api-proxy-config.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 } 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?: { doc?: Record<string, unknown>; readOnly?: boolean }) {
  44. super(ctx)
  45. this.doc = structuredClone(options?.doc ?? {})
  46. this.readOnly = options?.readOnly ?? false
  47. }
  48. private readonly readOnly: boolean
  49. get writable(): boolean {
  50. return !this.readOnly
  51. }
  52. protected load(): Promise<Record<string, unknown>> {
  53. return Promise.resolve(structuredClone(this.doc))
  54. }
  55. protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
  56. this.doc[ns] = structuredClone(section)
  57. return Promise.resolve()
  58. }
  59. }
  60. /** In-memory credential provider with an env-shadow double for the rejection path. */
  61. class MemoryCredentials extends Credentials {
  62. private readonly values = new Map<string, string>()
  63. constructor(ctx: ConstructorParameters<typeof Credentials>[0], options?: { shadowed?: string[] }) {
  64. super(ctx)
  65. this.shadowed = new Set(options?.shadowed ?? [])
  66. }
  67. private readonly shadowed: Set<string>
  68. resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined> {
  69. if (this.shadowed.has(ref)) return Promise.resolve({ value: 'from-env', source: 'env' })
  70. const value = this.values.get(ref)
  71. return Promise.resolve(value === undefined ? undefined : { value, source: 'file' })
  72. }
  73. describe(ref: CredentialRef): Promise<CredentialInfo> {
  74. if (this.shadowed.has(ref)) return Promise.resolve({ configured: true, source: 'env', writable: false })
  75. const configured = this.values.has(ref)
  76. return Promise.resolve({ configured, ...configured ? { source: 'file' } : {}, writable: true })
  77. }
  78. set(ref: CredentialRef, value: string): Promise<void> {
  79. if (this.shadowed.has(ref)) {
  80. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  81. }
  82. this.values.set(ref, value)
  83. this.ctx.emit('credentials/updated', ref)
  84. return Promise.resolve()
  85. }
  86. unset(ref: CredentialRef): Promise<void> {
  87. if (this.shadowed.has(ref)) {
  88. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  89. }
  90. this.values.delete(ref)
  91. this.ctx.emit('credentials/updated', ref)
  92. return Promise.resolve()
  93. }
  94. }
  95. /** Catalog-serving adapter stub for the llm.models path. */
  96. class CatalogAdapter extends LlmAdapter {
  97. constructor(private readonly name: string, private readonly models: readonly string[]) {
  98. super()
  99. }
  100. override providerInfo(provider: string): LlmProviderInfo {
  101. return { id: provider, name: this.name }
  102. }
  103. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  104. return Promise.resolve(this.models.map(id => ({ provider, id, name: id })))
  105. }
  106. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  107. throw new Error('not exercised')
  108. }
  109. }
  110. class BrokenCatalogAdapter extends CatalogAdapter {
  111. override listModels(): Promise<readonly LlmModelInfo[]> {
  112. return Promise.reject(new Error('catalog backend down'))
  113. }
  114. }
  115. const NS = settingsNamespace('llm-deepseek')
  116. const AdapterConfig = z.object({
  117. apiKey: z.string().role('secret'),
  118. apiKeyEnv: z.string().default('DEEPSEEK_API_KEY'),
  119. baseURL: z.string(),
  120. })
  121. async function harness(options?: {
  122. settings?: false | { doc?: Record<string, unknown>; readOnly?: boolean }
  123. credentials?: false | { shadowed?: string[] }
  124. /** Skip the directory registration to exercise a namespace the proxy does not expose. */
  125. configurableProviders?: false
  126. }): Promise<Context> {
  127. const ctx = new Context()
  128. await ctx.plugin(SessionStore)
  129. await ctx.plugin(SystemPrompt, { persona: '' })
  130. await ctx.plugin(ToolRegistry)
  131. await ctx.plugin(UserInteractionService)
  132. await ctx.plugin(AgentRegistry)
  133. await ctx.plugin(LlmService)
  134. if (options?.settings !== false) await ctx.plugin(MemorySettings, options?.settings)
  135. if (options?.credentials !== false) await ctx.plugin(MemoryCredentials, options?.credentials)
  136. // The proxy serves only namespaces a configurable provider addresses, which
  137. // is what the real LLM plugins declare at load; the tests mirror that.
  138. if (options?.configurableProviders !== false) {
  139. ctx.llm.registerConfigurableProviders([
  140. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  141. ])
  142. }
  143. // Host-stream opener reads the committed-workspace baseline; the stub
  144. // suffices — the real workspace composition is api-proxy-workspace.spec's.
  145. ctx.provide('workspace', { list: () => [] } as never)
  146. return ctx
  147. }
  148. /** Drain `count` host frames matching `types`, then abort the stream. */
  149. async function collectHost(
  150. api: ReturnType<typeof createApiProxy>,
  151. types: string[],
  152. count: number,
  153. run: () => Promise<void>,
  154. ): Promise<HostFrame[]> {
  155. const abort = new AbortController()
  156. const frames: HostFrame[] = []
  157. const stream = api.events.host(request({}), abort.signal)
  158. const consume = (async () => {
  159. for await (const frame of stream) {
  160. if (!types.includes(frame.payload.type)) continue
  161. frames.push(frame.payload)
  162. if (frames.length >= count) abort.abort()
  163. }
  164. })()
  165. await run()
  166. await consume
  167. return frames
  168. }
  169. describe('settings domain', () => {
  170. it('reports an actionable error when no settings provider is mounted', async () => {
  171. const ctx = await harness({ settings: false })
  172. const api = createApiProxy(ctx, DEFAULTS)
  173. const error = expectErr(await api.settings.describe(request({})))
  174. expect(error.code).toBe('internal')
  175. expect(error.message).toContain('dsh-settings-local')
  176. })
  177. it('describes layered redacted namespaces with their secret slots', async () => {
  178. const ctx = await harness({ settings: { doc: { 'llm-deepseek': { apiKey: 'user-secret', baseURL: 'https://user' } } } })
  179. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  180. const api = createApiProxy(ctx, DEFAULTS)
  181. const value = expectOk(await api.settings.describe(request({})))
  182. expect(value.writable).toBe(true)
  183. expect(value.namespaces).toHaveLength(1)
  184. const view = value.namespaces[0]!
  185. expect(view.ns).toBe('llm-deepseek')
  186. expect(view.applies).toBe('live')
  187. expect((view.schema as { refs?: unknown }).refs).toBeDefined()
  188. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://user' })
  189. expect(view.base).toEqual({ baseURL: 'https://base' })
  190. expect(view.user).toEqual({ baseURL: 'https://user' })
  191. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  192. expect(JSON.stringify(value)).not.toContain('user-secret')
  193. })
  194. it('serves only namespaces a registered model provider addresses', async () => {
  195. // The settings seam is general: any plugin may register a namespace for
  196. // its own configuration. The Web configuration plane is not — it is the
  197. // model-provider surface, and a namespace nothing in the provider
  198. // directory addresses must be invisible and unwritable here, so a future
  199. // plugin cannot become remotely configurable just by registering.
  200. const ctx = await harness()
  201. ctx.settings.register(NS, AdapterConfig)
  202. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  203. const api = createApiProxy(ctx, DEFAULTS)
  204. const value = expectOk(await api.settings.describe(request({})))
  205. expect(value.namespaces.map(view => view.ns)).toEqual(['llm-deepseek'])
  206. for (const response of [
  207. await api.settings.update(request({ ns: 'some-other-plugin', patch: { secretPath: '/etc/shadow' } })),
  208. await api.settings.replace(request({ ns: 'some-other-plugin', section: {} })),
  209. ]) {
  210. const error = expectErr(response)
  211. expect(error.code).toBe('settings-not-exposed')
  212. expect(error.details).toEqual({ ns: 'some-other-plugin' })
  213. }
  214. // The write never reached the seam.
  215. expect(ctx.settings.describe().find(d => String(d.ns) === 'some-other-plugin')?.value).toEqual({})
  216. })
  217. it('refuses even a model-provider namespace once its directory entry is gone', async () => {
  218. const ctx = await harness({ configurableProviders: false })
  219. ctx.settings.register(NS, AdapterConfig)
  220. const api = createApiProxy(ctx, DEFAULTS)
  221. expect(expectOk(await api.settings.describe(request({}))).namespaces).toEqual([])
  222. expect(expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://x' } }))).code)
  223. .toBe('settings-not-exposed')
  224. })
  225. it('invalidates the model catalog when a provider namespace changes, and broadcasts a raw-only change', async () => {
  226. // Editing `models` changes no route, so llm/adapters-updated never fires
  227. // and an open model picker kept serving the old catalog. And storing an
  228. // override equal to the resolved value emits nothing on settings/updated,
  229. // so another tab never learned the field became overridden.
  230. const ctx = await harness()
  231. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  232. const api = createApiProxy(ctx, DEFAULTS)
  233. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 2, async () => {
  234. await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://base' } }))
  235. })
  236. expect(frames).toEqual([
  237. { type: 'host/settings-changed', ns: 'llm-deepseek' },
  238. { type: 'host/models-changed' },
  239. ])
  240. // The resolved value never moved: base already said https://base.
  241. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.value)
  242. .toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://base' })
  243. })
  244. it('maps a stale expectedRevision to settings-conflict carrying both revisions', async () => {
  245. const ctx = await harness()
  246. ctx.settings.register(NS, AdapterConfig)
  247. const api = createApiProxy(ctx, DEFAULTS)
  248. const opened = expectOk(await api.settings.describe(request({}))).namespaces[0]!.revision
  249. expect(expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://first' }, expectedRevision: opened })))
  250. .revision).toBe(opened + 1)
  251. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://second' }, expectedRevision: opened })))
  252. expect(error.code).toBe('settings-conflict')
  253. expect(error.details).toEqual({ ns: 'llm-deepseek', expected: opened, actual: opened + 1 })
  254. // The refused write changed nothing.
  255. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.user).toEqual({ baseURL: 'https://first' })
  256. })
  257. it('updates the user layer, answers with the new redacted view, and broadcasts the frame', async () => {
  258. const ctx = await harness()
  259. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  260. const api = createApiProxy(ctx, DEFAULTS)
  261. const frames = await collectHost(api, ['host/settings-changed'], 1, async () => {
  262. const view = expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { apiKey: 'sk-new', baseURL: 'https://next' } })))
  263. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://next' })
  264. expect(view.user).toEqual({ baseURL: 'https://next' })
  265. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  266. expect(JSON.stringify(view)).not.toContain('sk-new')
  267. })
  268. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'llm-deepseek' }])
  269. })
  270. it('replace resets the user layer wholesale', async () => {
  271. const ctx = await harness({ settings: { doc: { 'llm-deepseek': { baseURL: 'https://user' } } } })
  272. ctx.settings.register(NS, AdapterConfig)
  273. const api = createApiProxy(ctx, DEFAULTS)
  274. const view = expectOk(await api.settings.replace(request({ ns: 'llm-deepseek', section: {} })))
  275. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY' })
  276. expect(view.user).toEqual({})
  277. })
  278. it.each([
  279. ['an invalid namespace name', 'Not A Namespace', {}],
  280. ['a schema-invalid patch', 'llm-deepseek', { baseURL: 42 }],
  281. ])('rejects %s as settings-rejected', async (_case, ns, patch) => {
  282. const ctx = await harness()
  283. ctx.settings.register(NS, AdapterConfig)
  284. const api = createApiProxy(ctx, DEFAULTS)
  285. const error = expectErr(await api.settings.update(request({ ns, patch })))
  286. expect(error.code).toBe('settings-rejected')
  287. expect(error.details).toEqual({ ns })
  288. })
  289. it('answers an unregistered namespace exactly like an unexposed one', async () => {
  290. // Deliberately indistinguishable: separating "does not exist" from
  291. // "exists but is not yours to configure" would let a caller enumerate the
  292. // registered namespaces one probe at a time.
  293. const ctx = await harness()
  294. ctx.settings.register(NS, AdapterConfig)
  295. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  296. const api = createApiProxy(ctx, DEFAULTS)
  297. const unknown = expectErr(await api.settings.update(request({ ns: 'unknown-ns', patch: {} })))
  298. const unexposed = expectErr(await api.settings.update(request({ ns: 'some-other-plugin', patch: {} })))
  299. expect(unknown.code).toBe('settings-not-exposed')
  300. expect(unexposed.code).toBe(unknown.code)
  301. expect(unexposed.message.replace('some-other-plugin', 'unknown-ns')).toBe(unknown.message)
  302. })
  303. it('maps a read-only provider refusal onto the same rejection', async () => {
  304. const ctx = await harness({ settings: { readOnly: true } })
  305. ctx.settings.register(NS, AdapterConfig)
  306. const api = createApiProxy(ctx, DEFAULTS)
  307. const value = expectOk(await api.settings.describe(request({})))
  308. expect(value.writable).toBe(false)
  309. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: {} })))
  310. expect(error.code).toBe('settings-rejected')
  311. expect(error.message).toContain('read-only')
  312. })
  313. })
  314. describe('credentials domain', () => {
  315. it('reports an actionable error when no credential provider is mounted', async () => {
  316. const ctx = await harness({ credentials: false })
  317. const api = createApiProxy(ctx, DEFAULTS)
  318. const error = expectErr(await api.credentials.describe(request({ refs: ['A'] })))
  319. expect(error.code).toBe('internal')
  320. expect(error.message).toContain('dsh-credentials-local')
  321. })
  322. it('describes value-free views and flips state through set/unset with frames', async () => {
  323. const ctx = await harness()
  324. const api = createApiProxy(ctx, DEFAULTS)
  325. const before = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  326. expect(before.credentials).toEqual({ OPENAI_API_KEY: { configured: false, writable: true } })
  327. const frames = await collectHost(api, ['host/credentials-changed'], 2, async () => {
  328. expectOk(await api.credentials.set(request({ ref: 'OPENAI_API_KEY', value: 'sk-secret' })))
  329. const after = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  330. expect(after.credentials).toEqual({ OPENAI_API_KEY: { configured: true, source: 'file', writable: true } })
  331. expect(JSON.stringify(after)).not.toContain('sk-secret')
  332. expectOk(await api.credentials.unset(request({ ref: 'OPENAI_API_KEY' })))
  333. })
  334. expect(frames).toEqual([
  335. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  336. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  337. ])
  338. })
  339. it('maps a shadowed write onto credential-rejected for set and unset alike', async () => {
  340. const ctx = await harness({ credentials: { shadowed: ['DEEPSEEK_API_KEY'] } })
  341. const api = createApiProxy(ctx, DEFAULTS)
  342. const described = expectOk(await api.credentials.describe(request({ refs: ['DEEPSEEK_API_KEY'] })))
  343. expect(described.credentials['DEEPSEEK_API_KEY']).toEqual({ configured: true, source: 'env', writable: false })
  344. const setError = expectErr(await api.credentials.set(request({ ref: 'DEEPSEEK_API_KEY', value: 'x' })))
  345. expect(setError.code).toBe('credential-rejected')
  346. expect(setError.details).toEqual({ ref: 'DEEPSEEK_API_KEY' })
  347. const unsetError = expectErr(await api.credentials.unset(request({ ref: 'DEEPSEEK_API_KEY' })))
  348. expect(unsetError.code).toBe('credential-rejected')
  349. })
  350. })
  351. describe('llm domain', () => {
  352. it('merges the configurable directory with live routes and appends undeclared ones', async () => {
  353. const ctx = await harness({ configurableProviders: false })
  354. ctx.llm.registerConfigurableProviders([
  355. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  356. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'] },
  357. ])
  358. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash']))
  359. ctx.llm.registerAdapter(['undeclared'], new CatalogAdapter('Undeclared', ['u-1']))
  360. const api = createApiProxy(ctx, DEFAULTS)
  361. const value = expectOk(await api.llm.providers(request({})))
  362. expect(value.providers).toEqual([
  363. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
  364. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: false },
  365. { provider: 'undeclared', displayName: 'Undeclared', settingsNs: '', settingsPath: [], active: true },
  366. ])
  367. })
  368. it('serves the host-scoped catalog with per-provider failures contained', async () => {
  369. const ctx = await harness()
  370. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash', 'deepseek-v4-pro']))
  371. ctx.llm.registerAdapter(['broken'], new BrokenCatalogAdapter('Broken', []))
  372. const api = createApiProxy(ctx, DEFAULTS)
  373. const value = expectOk(await api.llm.models(request({})))
  374. expect(value.groups).toEqual([{
  375. id: 'deepseek-official',
  376. name: 'DeepSeek',
  377. models: [
  378. { id: 'deepseek-v4-flash', name: 'deepseek-v4-flash' },
  379. { id: 'deepseek-v4-pro', name: 'deepseek-v4-pro' },
  380. ],
  381. }])
  382. expect(value.failures).toEqual([{ id: 'broken', name: 'Broken', message: 'catalog backend down' }])
  383. })
  384. it('broadcasts host/models-changed at every topology commit point', async () => {
  385. const ctx = await harness()
  386. const api = createApiProxy(ctx, DEFAULTS)
  387. const frames = await collectHost(api, ['host/models-changed'], 2, async () => {
  388. const dispose = ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', []))
  389. dispose()
  390. return Promise.resolve()
  391. })
  392. expect(frames).toEqual([{ type: 'host/models-changed' }, { type: 'host/models-changed' }])
  393. })
  394. })