api-proxy-config.spec.ts 25 KB

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