api-proxy-config.spec.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. /**
  2. * Settings/credentials/llm RPC domains and their host-stream frames over
  3. * createApiProxy: layered redacted describe, write-path rejection mapping,
  4. * value-free credential views, the directory/live-route merge, and the three
  5. * invalidation frames (settings/credentials/models changed).
  6. */
  7. import { describe, expect, it, vi } from 'vitest'
  8. import { Context } from 'cordis'
  9. import z from 'schemastery'
  10. import AgentRegistry from '@deepseek-ai/dsh-agent'
  11. import SessionStore from '@deepseek-ai/dsh-session'
  12. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  13. import ToolRegistry from '@deepseek-ai/dsh-tools'
  14. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  15. import LlmService, { LlmAdapter } from '@deepseek-ai/dsh-llm'
  16. import type { GenerateOptions, LlmModelInfo, LlmProviderInfo, StreamChunk } from '@deepseek-ai/dsh-llm'
  17. import { Settings, settingsNamespace } from '@deepseek-ai/dsh-settings'
  18. import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
  19. import { Credentials } from '@deepseek-ai/dsh-credentials'
  20. import type { CredentialInfo, CredentialRef, ResolvedCredential } from '@deepseek-ai/dsh-credentials'
  21. import type { HostFrame } from '../src/api/index.ts'
  22. import type { RpcRequest, RpcResponse } from '../src/api/rpc.ts'
  23. import { RpcId } from '../src/api/rpc.ts'
  24. import { AGENT_DEFAULT_MODEL_SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-agent-default-model'
  25. import { createApiProxy } from '../src/api-proxy.ts'
  26. const DEFAULTS = { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp', workspaceRoot: '/tmp' }
  27. let nextRpc = 1
  28. function request<P>(payload: P): RpcRequest<P> {
  29. return { rpcId: RpcId(`req-${String(nextRpc++)}`), payload }
  30. }
  31. function expectOk<T>(response: RpcResponse<T>): T {
  32. expect(response.result.ok).toBe(true)
  33. if (!response.result.ok) throw new Error('unreachable')
  34. return response.result.value
  35. }
  36. function expectErr<T>(response: RpcResponse<T>): { code: string; message: string; details: unknown } {
  37. expect(response.result.ok).toBe(false)
  38. if (response.result.ok) throw new Error('unreachable')
  39. return response.result.error
  40. }
  41. /** In-memory settings provider: the seam base class owns all tested behavior. */
  42. class MemorySettings extends Settings {
  43. doc: Record<string, unknown>
  44. constructor(ctx: ConstructorParameters<typeof Settings>[0], options?: {
  45. doc?: Record<string, unknown>
  46. readOnly?: boolean
  47. documentPath?: string
  48. preparedPath?: string
  49. }) {
  50. super(ctx)
  51. this.doc = structuredClone(options?.doc ?? {})
  52. this.readOnly = options?.readOnly ?? false
  53. this.path = options?.documentPath
  54. this.preparedPath = options?.preparedPath
  55. }
  56. private readonly readOnly: boolean
  57. private readonly path: string | undefined
  58. private readonly preparedPath: string | undefined
  59. get writable(): boolean {
  60. return !this.readOnly
  61. }
  62. override get documentPath(): string | undefined {
  63. return this.path
  64. }
  65. override prepareDocument(): Promise<string | undefined> {
  66. return Promise.resolve(this.preparedPath ?? this.documentPath)
  67. }
  68. protected load(): Promise<Record<string, unknown>> {
  69. return Promise.resolve(structuredClone(this.doc))
  70. }
  71. protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
  72. this.doc[ns] = structuredClone(section)
  73. return Promise.resolve()
  74. }
  75. }
  76. /** In-memory credential provider with an env-shadow double for the rejection path. */
  77. class MemoryCredentials extends Credentials {
  78. private readonly values = new Map<string, string>()
  79. constructor(ctx: ConstructorParameters<typeof Credentials>[0], options?: { shadowed?: string[] }) {
  80. super(ctx)
  81. this.shadowed = new Set(options?.shadowed ?? [])
  82. }
  83. private readonly shadowed: Set<string>
  84. resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined> {
  85. if (this.shadowed.has(ref)) return Promise.resolve({ value: 'from-env', source: 'env' })
  86. const value = this.values.get(ref)
  87. return Promise.resolve(value === undefined ? undefined : { value, source: 'file' })
  88. }
  89. describe(ref: CredentialRef): Promise<CredentialInfo> {
  90. if (this.shadowed.has(ref)) return Promise.resolve({ configured: true, source: 'env', writable: false })
  91. const configured = this.values.has(ref)
  92. return Promise.resolve({ configured, ...configured ? { source: 'file' } : {}, writable: true })
  93. }
  94. set(ref: CredentialRef, value: string): Promise<void> {
  95. if (this.shadowed.has(ref)) {
  96. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  97. }
  98. this.values.set(ref, value)
  99. this.ctx.emit('credentials/updated', ref)
  100. return Promise.resolve()
  101. }
  102. unset(ref: CredentialRef): Promise<void> {
  103. if (this.shadowed.has(ref)) {
  104. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  105. }
  106. this.values.delete(ref)
  107. this.ctx.emit('credentials/updated', ref)
  108. return Promise.resolve()
  109. }
  110. }
  111. /** Catalog-serving adapter stub for the llm.models path. */
  112. class CatalogAdapter extends LlmAdapter {
  113. constructor(private readonly name: string, private readonly models: readonly string[]) {
  114. super()
  115. }
  116. override providerInfo(provider: string): LlmProviderInfo {
  117. return { id: provider, name: this.name }
  118. }
  119. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  120. return Promise.resolve(this.models.map(id => ({ provider, id, name: id })))
  121. }
  122. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  123. throw new Error('not exercised')
  124. }
  125. }
  126. class BrokenCatalogAdapter extends CatalogAdapter {
  127. override listModels(): Promise<readonly LlmModelInfo[]> {
  128. return Promise.reject(new Error('catalog backend down'))
  129. }
  130. }
  131. const NS = settingsNamespace('llm-deepseek')
  132. const AdapterConfig = z.object({
  133. apiKey: z.string().role('secret'),
  134. apiKeyEnv: z.string().default('DEEPSEEK_API_KEY'),
  135. baseURL: z.string(),
  136. })
  137. async function harness(options?: {
  138. settings?: false | {
  139. doc?: Record<string, unknown>
  140. readOnly?: boolean
  141. documentPath?: string
  142. preparedPath?: string
  143. }
  144. credentials?: false | { shadowed?: string[] }
  145. /** Skip the directory registration to exercise a namespace the proxy does not expose. */
  146. configurableProviders?: false
  147. }): Promise<Context> {
  148. const ctx = new Context()
  149. await ctx.plugin(SessionStore)
  150. await ctx.plugin(SystemPrompt, { persona: '' })
  151. await ctx.plugin(ToolRegistry)
  152. await ctx.plugin(UserInteractionService)
  153. await ctx.plugin(AgentRegistry)
  154. await ctx.plugin(LlmService)
  155. if (options?.settings !== false) await ctx.plugin(MemorySettings, options?.settings)
  156. if (options?.credentials !== false) await ctx.plugin(MemoryCredentials, options?.credentials)
  157. // Model-provider namespaces plus the explicit Web preference and product
  158. // onboarding allowlists are the proxy's complete settings surface.
  159. if (options?.configurableProviders !== false) {
  160. ctx.llm.registerConfigurableProviders([
  161. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  162. ])
  163. }
  164. // Host-stream opener reads the committed-workspace baseline; the stub
  165. // suffices — the real workspace composition is api-proxy-workspace.spec's.
  166. ctx.provide('workspace', { list: () => [] } as never)
  167. return ctx
  168. }
  169. /** Drain `count` host frames matching `types`, then abort the stream. */
  170. async function collectHost(
  171. api: ReturnType<typeof createApiProxy>,
  172. types: string[],
  173. count: number,
  174. run: () => Promise<void>,
  175. ): Promise<HostFrame[]> {
  176. const abort = new AbortController()
  177. const frames: HostFrame[] = []
  178. const stream = api.events.host(request({}), abort.signal)
  179. const consume = (async () => {
  180. for await (const frame of stream) {
  181. if (!types.includes(frame.payload.type)) continue
  182. frames.push(frame.payload)
  183. if (frames.length >= count) abort.abort()
  184. }
  185. })()
  186. await run()
  187. await consume
  188. return frames
  189. }
  190. describe('settings domain', () => {
  191. it('reports an actionable error when no settings provider is mounted', async () => {
  192. const ctx = await harness({ settings: false })
  193. const api = createApiProxy(ctx, DEFAULTS)
  194. const error = expectErr(await api.settings.describe(request({})))
  195. expect(error.code).toBe('internal')
  196. expect(error.message).toContain('dsh-settings-local')
  197. })
  198. it('describes layered redacted namespaces with their secret slots', async () => {
  199. const ctx = await harness({ settings: {
  200. doc: { 'llm-deepseek': { apiKey: 'user-secret', baseURL: 'https://user' } },
  201. documentPath: '/tmp/custom-settings.yaml',
  202. } })
  203. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  204. const api = createApiProxy(ctx, DEFAULTS)
  205. const value = expectOk(await api.settings.describe(request({})))
  206. expect(value.writable).toBe(true)
  207. expect(value.hasDocument).toBe(true)
  208. expect(value.namespaces).toHaveLength(1)
  209. const view = value.namespaces[0]!
  210. expect(view.ns).toBe('llm-deepseek')
  211. expect(view.applies).toBe('live')
  212. expect((view.schema as { refs?: unknown }).refs).toBeDefined()
  213. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://user' })
  214. expect(view.base).toEqual({ baseURL: 'https://base' })
  215. expect(view.user).toEqual({ baseURL: 'https://user' })
  216. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  217. expect(JSON.stringify(value)).not.toContain('user-secret')
  218. })
  219. it('opens the provider-resolved document without accepting a browser path', async () => {
  220. const ctx = await harness({ settings: {
  221. documentPath: '/tmp/described-settings.yaml',
  222. preparedPath: '/tmp/custom-settings.yaml',
  223. } })
  224. const opened: string[] = []
  225. const api = createApiProxy(ctx, {
  226. ...DEFAULTS,
  227. openTextFile: (path) => {
  228. opened.push(path)
  229. return Promise.resolve()
  230. },
  231. })
  232. expect(expectOk(await api.settings.openDocument(request({}), new AbortController().signal)))
  233. .toEqual({ opened: true })
  234. expect(opened).toEqual(['/tmp/custom-settings.yaml'])
  235. })
  236. it('refuses to open settings when the provider has no local document', async () => {
  237. const ctx = await harness()
  238. const api = createApiProxy(ctx, DEFAULTS)
  239. expect(expectOk(await api.settings.describe(request({}))).hasDocument).toBe(false)
  240. const error = expectErr(await api.settings.openDocument(request({}), new AbortController().signal))
  241. expect(error.code).toBe('internal')
  242. expect(error.message).toContain('no local document')
  243. })
  244. it('does not prepare or open a settings document after cancellation', async () => {
  245. const ctx = await harness({ settings: { documentPath: '/tmp/settings.yaml' } })
  246. const opened: string[] = []
  247. const api = createApiProxy(ctx, {
  248. ...DEFAULTS,
  249. openTextFile: (path) => {
  250. opened.push(path)
  251. return Promise.resolve()
  252. },
  253. })
  254. const prepare = vi.spyOn(ctx.settings, 'prepareDocument')
  255. const cancelled = new AbortController()
  256. cancelled.abort()
  257. expect(expectErr(await api.settings.openDocument(request({}), cancelled.signal)).code)
  258. .toBe('cancelled')
  259. expect(prepare).not.toHaveBeenCalled()
  260. const pending = Promise.withResolvers<string | undefined>()
  261. prepare.mockReturnValueOnce(pending.promise)
  262. const duringPrepare = new AbortController()
  263. const opening = api.settings.openDocument(request({}), duringPrepare.signal)
  264. await vi.waitFor(() => { expect(prepare).toHaveBeenCalledOnce() })
  265. duringPrepare.abort()
  266. pending.resolve('/tmp/settings.yaml')
  267. expect(expectErr(await opening).code).toBe('cancelled')
  268. expect(opened).toEqual([])
  269. })
  270. it('serves model-provider and explicitly allowlisted Web namespaces only', async () => {
  271. // The settings seam is general: any plugin may register a namespace for
  272. // its own configuration. The Web configuration plane remains opt-in, so a
  273. // future internal plugin cannot become remotely configurable just by
  274. // registering; permission and the product onboarding namespace are the
  275. // non-model namespaces intentionally admitted by this surface.
  276. const ctx = await harness()
  277. ctx.settings.register(NS, AdapterConfig)
  278. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  279. ctx.settings.register(settingsNamespace('permission'), z.object({
  280. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  281. }), {
  282. base: { defaultPreset: 'read-only' },
  283. })
  284. const api = createApiProxy(ctx, DEFAULTS)
  285. const value = expectOk(await api.settings.describe(request({})))
  286. expect(value.namespaces.map(view => view.ns)).toEqual(['llm-deepseek', 'permission'])
  287. const permission = expectOk(await api.settings.mutate(request({
  288. ns: 'permission',
  289. ops: [{ op: 'set', path: ['defaultPreset'], value: 'workspace-write' }],
  290. })))
  291. expect(permission.value).toEqual({ defaultPreset: 'workspace-write' })
  292. for (const response of [
  293. await api.settings.update(request({ ns: 'some-other-plugin', patch: { secretPath: '/etc/shadow' } })),
  294. await api.settings.replace(request({ ns: 'some-other-plugin', section: {} })),
  295. ]) {
  296. const error = expectErr(response)
  297. expect(error.code).toBe('settings-not-exposed')
  298. expect(error.details).toEqual({ ns: 'some-other-plugin' })
  299. }
  300. // The write never reached the seam.
  301. expect(ctx.settings.describe().find(d => String(d.ns) === 'some-other-plugin')?.value).toEqual({})
  302. })
  303. it('serves the product onboarding namespace without invalidating the model catalog', async () => {
  304. const ctx = await harness()
  305. ctx.settings.register(settingsNamespace('ui-onboarding'), z.object({ welcomeNoticeVersion: z.string() }))
  306. const api = createApiProxy(ctx, DEFAULTS)
  307. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  308. .toEqual(['ui-onboarding'])
  309. const frames = await collectHost(api, ['host/settings-changed'], 1, async () => {
  310. expectOk(await api.settings.mutate(request({
  311. ns: 'ui-onboarding',
  312. ops: [{ op: 'set', path: ['welcomeNoticeVersion'], value: 'v1' }],
  313. })))
  314. })
  315. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'ui-onboarding' }])
  316. })
  317. it('refuses even a model-provider namespace once its directory entry is gone', async () => {
  318. const ctx = await harness({ configurableProviders: false })
  319. ctx.settings.register(NS, AdapterConfig)
  320. const api = createApiProxy(ctx, DEFAULTS)
  321. expect(expectOk(await api.settings.describe(request({}))).namespaces).toEqual([])
  322. expect(expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://x' } }))).code)
  323. .toBe('settings-not-exposed')
  324. })
  325. it('invalidates the model catalog when a provider namespace changes, and broadcasts a raw-only change', async () => {
  326. // Editing `models` changes no route, so llm/adapters-updated never fires
  327. // and an open model picker kept serving the old catalog. And storing an
  328. // override equal to the resolved value emits nothing on settings/updated,
  329. // so another tab never learned the field became overridden.
  330. const ctx = await harness()
  331. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  332. const api = createApiProxy(ctx, DEFAULTS)
  333. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 2, async () => {
  334. await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://base' } }))
  335. })
  336. expect(frames).toEqual([
  337. { type: 'host/settings-changed', ns: 'llm-deepseek' },
  338. { type: 'host/models-changed' },
  339. ])
  340. // The resolved value never moved: base already said https://base.
  341. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.value)
  342. .toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://base' })
  343. })
  344. it('broadcasts a permission change without invalidating the model catalog', async () => {
  345. const ctx = await harness()
  346. const permission = ctx.settings.register(settingsNamespace('permission'), z.object({
  347. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  348. }), {
  349. base: { defaultPreset: 'read-only' },
  350. })
  351. const api = createApiProxy(ctx, DEFAULTS)
  352. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 1, async () => {
  353. await permission.update({ defaultPreset: 'workspace-write' })
  354. })
  355. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'permission' }])
  356. })
  357. it('invalidates the model catalog when the Agent default selection changes', async () => {
  358. const ctx = await harness()
  359. const defaultModel = ctx.settings.register(AGENT_DEFAULT_MODEL_SETTINGS_NAMESPACE, z.object({
  360. provider: z.string().required(),
  361. model: z.string().required(),
  362. }), { base: { provider: 'deepseek-official', model: 'deepseek-v4-flash' } })
  363. const api = createApiProxy(ctx, DEFAULTS)
  364. // The shared section names the selection every blank session resolves to,
  365. // so an externally edited default — another tab, a
  366. // hand-edited settings.yaml — has to reach an open selector as well.
  367. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 2, async () => {
  368. await defaultModel.replace({ provider: 'deepseek-official', model: 'deepseek-reasoner' })
  369. })
  370. expect(frames).toEqual([
  371. { type: 'host/settings-changed', ns: 'agent-default-model' },
  372. { type: 'host/models-changed' },
  373. ])
  374. })
  375. it('maps a stale expectedRevision to settings-conflict carrying both revisions', async () => {
  376. const ctx = await harness()
  377. ctx.settings.register(NS, AdapterConfig)
  378. const api = createApiProxy(ctx, DEFAULTS)
  379. const opened = expectOk(await api.settings.describe(request({}))).namespaces[0]!.revision
  380. expect(expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://first' }, expectedRevision: opened })))
  381. .revision).toBe(opened + 1)
  382. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://second' }, expectedRevision: opened })))
  383. expect(error.code).toBe('settings-conflict')
  384. expect(error.details).toEqual({ ns: 'llm-deepseek', expected: opened, actual: opened + 1 })
  385. // The refused write changed nothing.
  386. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.user).toEqual({ baseURL: 'https://first' })
  387. })
  388. it('updates the user layer, answers with the new redacted view, and broadcasts the frame', async () => {
  389. const ctx = await harness()
  390. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  391. const api = createApiProxy(ctx, DEFAULTS)
  392. const frames = await collectHost(api, ['host/settings-changed'], 1, async () => {
  393. const view = expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { apiKey: 'sk-new', baseURL: 'https://next' } })))
  394. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://next' })
  395. expect(view.user).toEqual({ baseURL: 'https://next' })
  396. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  397. expect(JSON.stringify(view)).not.toContain('sk-new')
  398. })
  399. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'llm-deepseek' }])
  400. })
  401. it('replace resets the user layer wholesale', async () => {
  402. const ctx = await harness({ settings: { doc: { 'llm-deepseek': { baseURL: 'https://user' } } } })
  403. ctx.settings.register(NS, AdapterConfig)
  404. const api = createApiProxy(ctx, DEFAULTS)
  405. const view = expectOk(await api.settings.replace(request({ ns: 'llm-deepseek', section: {} })))
  406. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY' })
  407. expect(view.user).toEqual({})
  408. })
  409. it.each([
  410. ['an invalid namespace name', 'Not A Namespace', {}],
  411. ['a schema-invalid patch', 'llm-deepseek', { baseURL: 42 }],
  412. ])('rejects %s as settings-rejected', async (_case, ns, patch) => {
  413. const ctx = await harness()
  414. ctx.settings.register(NS, AdapterConfig)
  415. const api = createApiProxy(ctx, DEFAULTS)
  416. const error = expectErr(await api.settings.update(request({ ns, patch })))
  417. expect(error.code).toBe('settings-rejected')
  418. expect(error.details).toEqual({ ns })
  419. })
  420. it('answers an unregistered namespace exactly like an unexposed one', async () => {
  421. // Deliberately indistinguishable: separating "does not exist" from
  422. // "exists but is not yours to configure" would let a caller enumerate the
  423. // registered namespaces one probe at a time.
  424. const ctx = await harness()
  425. ctx.settings.register(NS, AdapterConfig)
  426. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  427. const api = createApiProxy(ctx, DEFAULTS)
  428. const unknown = expectErr(await api.settings.update(request({ ns: 'unknown-ns', patch: {} })))
  429. const unexposed = expectErr(await api.settings.update(request({ ns: 'some-other-plugin', patch: {} })))
  430. expect(unknown.code).toBe('settings-not-exposed')
  431. expect(unexposed.code).toBe(unknown.code)
  432. expect(unexposed.message.replace('some-other-plugin', 'unknown-ns')).toBe(unknown.message)
  433. })
  434. it('maps a read-only provider refusal onto the same rejection', async () => {
  435. const ctx = await harness({ settings: { readOnly: true } })
  436. ctx.settings.register(NS, AdapterConfig)
  437. const api = createApiProxy(ctx, DEFAULTS)
  438. const value = expectOk(await api.settings.describe(request({})))
  439. expect(value.writable).toBe(false)
  440. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: {} })))
  441. expect(error.code).toBe('settings-rejected')
  442. expect(error.message).toContain('read-only')
  443. })
  444. })
  445. describe('credentials domain', () => {
  446. it('reports an actionable error when no credential provider is mounted', async () => {
  447. const ctx = await harness({ credentials: false })
  448. const api = createApiProxy(ctx, DEFAULTS)
  449. const error = expectErr(await api.credentials.describe(request({ refs: ['A'] })))
  450. expect(error.code).toBe('internal')
  451. expect(error.message).toContain('dsh-credentials-local')
  452. })
  453. it('describes value-free views and flips state through set/unset with frames', async () => {
  454. const ctx = await harness()
  455. const api = createApiProxy(ctx, DEFAULTS)
  456. const before = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  457. expect(before.credentials).toEqual({ OPENAI_API_KEY: { configured: false, writable: true } })
  458. const frames = await collectHost(api, ['host/credentials-changed'], 2, async () => {
  459. expectOk(await api.credentials.set(request({ ref: 'OPENAI_API_KEY', value: 'sk-secret' })))
  460. const after = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  461. expect(after.credentials).toEqual({ OPENAI_API_KEY: { configured: true, source: 'file', writable: true } })
  462. expect(JSON.stringify(after)).not.toContain('sk-secret')
  463. expectOk(await api.credentials.unset(request({ ref: 'OPENAI_API_KEY' })))
  464. })
  465. expect(frames).toEqual([
  466. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  467. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  468. ])
  469. })
  470. it('maps a shadowed write onto credential-rejected for set and unset alike', async () => {
  471. const ctx = await harness({ credentials: { shadowed: ['DEEPSEEK_API_KEY'] } })
  472. const api = createApiProxy(ctx, DEFAULTS)
  473. const described = expectOk(await api.credentials.describe(request({ refs: ['DEEPSEEK_API_KEY'] })))
  474. expect(described.credentials['DEEPSEEK_API_KEY']).toEqual({ configured: true, source: 'env', writable: false })
  475. const setError = expectErr(await api.credentials.set(request({ ref: 'DEEPSEEK_API_KEY', value: 'x' })))
  476. expect(setError.code).toBe('credential-rejected')
  477. expect(setError.details).toEqual({ ref: 'DEEPSEEK_API_KEY' })
  478. const unsetError = expectErr(await api.credentials.unset(request({ ref: 'DEEPSEEK_API_KEY' })))
  479. expect(unsetError.code).toBe('credential-rejected')
  480. })
  481. })
  482. describe('llm domain', () => {
  483. it('merges the configurable directory with live routes and appends undeclared ones', async () => {
  484. const ctx = await harness({ configurableProviders: false })
  485. ctx.llm.registerConfigurableProviders([
  486. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  487. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'] },
  488. ])
  489. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash']))
  490. ctx.llm.registerAdapter(['undeclared'], new CatalogAdapter('Undeclared', ['u-1']))
  491. // Only one namespace can answer an interrogation, so the flag follows the
  492. // entry's namespace rather than being assumed for every row.
  493. ctx.llm.registerModelDiscovery('llm-pi-ai', () => Promise.resolve([]))
  494. const api = createApiProxy(ctx, DEFAULTS)
  495. const value = expectOk(await api.llm.providers(request({})))
  496. expect(value.providers).toEqual([
  497. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
  498. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: false },
  499. // An undeclared live route has no settings address, so nothing can be
  500. // interrogated on its behalf either.
  501. { provider: 'undeclared', displayName: 'Undeclared', settingsNs: '', settingsPath: [], active: true },
  502. ])
  503. })
  504. it('serves the host-scoped catalog with per-provider failures contained', async () => {
  505. const ctx = await harness()
  506. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash', 'deepseek-v4-pro']))
  507. ctx.llm.registerAdapter(['broken'], new BrokenCatalogAdapter('Broken', []))
  508. const api = createApiProxy(ctx, DEFAULTS)
  509. const value = expectOk(await api.llm.models(request({})))
  510. expect(value.groups).toEqual([{
  511. id: 'deepseek-official',
  512. name: 'DeepSeek',
  513. models: [
  514. { id: 'deepseek-v4-flash', name: 'deepseek-v4-flash' },
  515. { id: 'deepseek-v4-pro', name: 'deepseek-v4-pro' },
  516. ],
  517. }])
  518. expect(value.failures).toEqual([{ id: 'broken', name: 'Broken', message: 'catalog backend down' }])
  519. })
  520. it('broadcasts host/models-changed at every topology commit point', async () => {
  521. const ctx = await harness()
  522. const api = createApiProxy(ctx, DEFAULTS)
  523. const frames = await collectHost(api, ['host/models-changed'], 2, async () => {
  524. const dispose = ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', []))
  525. dispose()
  526. return Promise.resolve()
  527. })
  528. expect(frames).toEqual([{ type: 'host/models-changed' }, { type: 'host/models-changed' }])
  529. })
  530. })
  531. describe('llm.discoverModels', () => {
  532. it('carries a draft to its namespace and returns candidates without storing anything', async () => {
  533. const ctx = await harness()
  534. const seen: unknown[] = []
  535. ctx.llm.registerModelDiscovery('llm-pi-ai', (probe) => {
  536. seen.push({ baseURL: probe.baseURL, api: probe.api, apiKey: probe.apiKey })
  537. return Promise.resolve([
  538. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  539. { id: 'acme-small' },
  540. ])
  541. })
  542. const api = createApiProxy(ctx, DEFAULTS)
  543. const value = expectOk(await api.llm.discoverModels(request({
  544. settingsNs: 'llm-pi-ai',
  545. baseURL: 'https://gateway.acme.example/v1',
  546. api: 'openai-completions',
  547. apiKey: 'probe-key',
  548. })))
  549. expect(value.models).toEqual([
  550. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  551. { id: 'acme-small' },
  552. ])
  553. expect(seen).toEqual([{
  554. baseURL: 'https://gateway.acme.example/v1',
  555. api: 'openai-completions',
  556. apiKey: 'probe-key',
  557. }])
  558. // Interrogating a draft is a read: no namespace gained a section, and no
  559. // credential reference was written.
  560. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  561. .not.toContain('llm-pi-ai')
  562. })
  563. it('carries the route being edited so an adapter can answer from its own registry', async () => {
  564. const ctx = await harness()
  565. let probe: unknown
  566. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  567. probe = request_
  568. return Promise.resolve([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  569. })
  570. const api = createApiProxy(ctx, DEFAULTS)
  571. const value = expectOk(await api.llm.discoverModels(request({
  572. settingsNs: 'llm-pi-ai',
  573. provider: 'deepseek',
  574. })))
  575. // No endpoint at all: a route the adapter already describes needs none.
  576. expect(probe).toEqual({ provider: 'deepseek' })
  577. expect(value.models).toEqual([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  578. })
  579. it('omits a credential and protocol the draft does not name', async () => {
  580. const ctx = await harness()
  581. let probe: unknown
  582. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  583. probe = request_
  584. return Promise.resolve([])
  585. })
  586. const api = createApiProxy(ctx, DEFAULTS)
  587. expectOk(await api.llm.discoverModels(request({
  588. settingsNs: 'llm-pi-ai',
  589. baseURL: 'https://gateway.acme.example/v1',
  590. })))
  591. // Absent fields stay absent rather than crossing as explicit undefined:
  592. // the adapter distinguishes "no protocol named" from "protocol undefined".
  593. expect(probe).toEqual({ baseURL: 'https://gateway.acme.example/v1' })
  594. })
  595. it('reports a failed interrogation as the form\'s next move, naming no credential', async () => {
  596. const ctx = await harness()
  597. ctx.llm.registerModelDiscovery('llm-pi-ai', () =>
  598. Promise.reject(new Error('https://gateway.acme.example/v1/models answered 401; check the API key')))
  599. const api = createApiProxy(ctx, DEFAULTS)
  600. const error = expectErr(await api.llm.discoverModels(request({
  601. settingsNs: 'llm-pi-ai',
  602. baseURL: 'https://gateway.acme.example/v1',
  603. apiKey: 'wrong',
  604. })))
  605. expect(error.code).toBe('model-discovery-failed')
  606. expect(error.message).toContain('answered 401; check the API key')
  607. expect(error.details).toEqual({ settingsNs: 'llm-pi-ai', baseURL: 'https://gateway.acme.example/v1' })
  608. expect(JSON.stringify(error)).not.toContain('wrong')
  609. })
  610. it('reports a namespace no adapter family serves', async () => {
  611. const ctx = await harness()
  612. const api = createApiProxy(ctx, DEFAULTS)
  613. const error = expectErr(await api.llm.discoverModels(request({
  614. settingsNs: 'llm-deepseek',
  615. baseURL: 'https://api.deepseek.com',
  616. })))
  617. expect(error.code).toBe('model-discovery-failed')
  618. expect(error.message).toContain('no model discovery is registered')
  619. })
  620. })