api-proxy-config.spec.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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('serves the agent-preset namespace, so a browser preset picker can persist its choice', async () => {
  317. const ctx = await harness()
  318. ctx.settings.register(settingsNamespace('agent-presets'), z.object({ default: z.string() }))
  319. const api = createApiProxy(ctx, DEFAULTS)
  320. expectOk(await api.settings.update(request({ ns: 'agent-presets', patch: { default: 'minimal' } })))
  321. // Both browser surfaces that offer the choice — the General row and the
  322. // management section — write the default through `settings.update`, so a
  323. // namespace outside this boundary makes the picker move and then silently
  324. // forget, which is worse than refusing the control.
  325. expect(ctx.settings.describe().find(view => String(view.ns) === 'agent-presets')?.value)
  326. .toEqual({ default: 'minimal' })
  327. })
  328. it('refuses even a model-provider namespace once its directory entry is gone', async () => {
  329. const ctx = await harness({ configurableProviders: false })
  330. ctx.settings.register(NS, AdapterConfig)
  331. const api = createApiProxy(ctx, DEFAULTS)
  332. expect(expectOk(await api.settings.describe(request({}))).namespaces).toEqual([])
  333. expect(expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://x' } }))).code)
  334. .toBe('settings-not-exposed')
  335. })
  336. it('invalidates the model catalog when a provider namespace changes, and broadcasts a raw-only change', async () => {
  337. // Editing `models` changes no route, so llm/adapters-updated never fires
  338. // and an open model picker kept serving the old catalog. And storing an
  339. // override equal to the resolved value emits nothing on settings/updated,
  340. // so another tab never learned the field became overridden.
  341. const ctx = await harness()
  342. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  343. const api = createApiProxy(ctx, DEFAULTS)
  344. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 2, async () => {
  345. await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://base' } }))
  346. })
  347. expect(frames).toEqual([
  348. { type: 'host/settings-changed', ns: 'llm-deepseek' },
  349. { type: 'host/models-changed' },
  350. ])
  351. // The resolved value never moved: base already said https://base.
  352. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.value)
  353. .toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://base' })
  354. })
  355. it('broadcasts a permission change without invalidating the model catalog', async () => {
  356. const ctx = await harness()
  357. const permission = ctx.settings.register(settingsNamespace('permission'), z.object({
  358. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  359. }), {
  360. base: { defaultPreset: 'read-only' },
  361. })
  362. const api = createApiProxy(ctx, DEFAULTS)
  363. const frames = await collectHost(api, ['host/settings-changed', 'host/models-changed'], 1, async () => {
  364. await permission.update({ defaultPreset: 'workspace-write' })
  365. })
  366. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'permission' }])
  367. })
  368. it('maps a stale expectedRevision to settings-conflict carrying both revisions', async () => {
  369. const ctx = await harness()
  370. ctx.settings.register(NS, AdapterConfig)
  371. const api = createApiProxy(ctx, DEFAULTS)
  372. const opened = expectOk(await api.settings.describe(request({}))).namespaces[0]!.revision
  373. expect(expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://first' }, expectedRevision: opened })))
  374. .revision).toBe(opened + 1)
  375. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://second' }, expectedRevision: opened })))
  376. expect(error.code).toBe('settings-conflict')
  377. expect(error.details).toEqual({ ns: 'llm-deepseek', expected: opened, actual: opened + 1 })
  378. // The refused write changed nothing.
  379. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.user).toEqual({ baseURL: 'https://first' })
  380. })
  381. it('updates the user layer, answers with the new redacted view, and broadcasts the frame', async () => {
  382. const ctx = await harness()
  383. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  384. const api = createApiProxy(ctx, DEFAULTS)
  385. const frames = await collectHost(api, ['host/settings-changed'], 1, async () => {
  386. const view = expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { apiKey: 'sk-new', baseURL: 'https://next' } })))
  387. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://next' })
  388. expect(view.user).toEqual({ baseURL: 'https://next' })
  389. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  390. expect(JSON.stringify(view)).not.toContain('sk-new')
  391. })
  392. expect(frames).toEqual([{ type: 'host/settings-changed', ns: 'llm-deepseek' }])
  393. })
  394. it('replace resets the user layer wholesale', async () => {
  395. const ctx = await harness({ settings: { doc: { 'llm-deepseek': { baseURL: 'https://user' } } } })
  396. ctx.settings.register(NS, AdapterConfig)
  397. const api = createApiProxy(ctx, DEFAULTS)
  398. const view = expectOk(await api.settings.replace(request({ ns: 'llm-deepseek', section: {} })))
  399. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY' })
  400. expect(view.user).toEqual({})
  401. })
  402. it.each([
  403. ['an invalid namespace name', 'Not A Namespace', {}],
  404. ['a schema-invalid patch', 'llm-deepseek', { baseURL: 42 }],
  405. ])('rejects %s as settings-rejected', async (_case, ns, patch) => {
  406. const ctx = await harness()
  407. ctx.settings.register(NS, AdapterConfig)
  408. const api = createApiProxy(ctx, DEFAULTS)
  409. const error = expectErr(await api.settings.update(request({ ns, patch })))
  410. expect(error.code).toBe('settings-rejected')
  411. expect(error.details).toEqual({ ns })
  412. })
  413. it('answers an unregistered namespace exactly like an unexposed one', async () => {
  414. // Deliberately indistinguishable: separating "does not exist" from
  415. // "exists but is not yours to configure" would let a caller enumerate the
  416. // registered namespaces one probe at a time.
  417. const ctx = await harness()
  418. ctx.settings.register(NS, AdapterConfig)
  419. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  420. const api = createApiProxy(ctx, DEFAULTS)
  421. const unknown = expectErr(await api.settings.update(request({ ns: 'unknown-ns', patch: {} })))
  422. const unexposed = expectErr(await api.settings.update(request({ ns: 'some-other-plugin', patch: {} })))
  423. expect(unknown.code).toBe('settings-not-exposed')
  424. expect(unexposed.code).toBe(unknown.code)
  425. expect(unexposed.message.replace('some-other-plugin', 'unknown-ns')).toBe(unknown.message)
  426. })
  427. it('maps a read-only provider refusal onto the same rejection', async () => {
  428. const ctx = await harness({ settings: { readOnly: true } })
  429. ctx.settings.register(NS, AdapterConfig)
  430. const api = createApiProxy(ctx, DEFAULTS)
  431. const value = expectOk(await api.settings.describe(request({})))
  432. expect(value.writable).toBe(false)
  433. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: {} })))
  434. expect(error.code).toBe('settings-rejected')
  435. expect(error.message).toContain('read-only')
  436. })
  437. })
  438. describe('credentials domain', () => {
  439. it('reports an actionable error when no credential provider is mounted', async () => {
  440. const ctx = await harness({ credentials: false })
  441. const api = createApiProxy(ctx, DEFAULTS)
  442. const error = expectErr(await api.credentials.describe(request({ refs: ['A'] })))
  443. expect(error.code).toBe('internal')
  444. expect(error.message).toContain('dsh-credentials-local')
  445. })
  446. it('describes value-free views and flips state through set/unset with frames', async () => {
  447. const ctx = await harness()
  448. const api = createApiProxy(ctx, DEFAULTS)
  449. const before = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  450. expect(before.credentials).toEqual({ OPENAI_API_KEY: { configured: false, writable: true } })
  451. const frames = await collectHost(api, ['host/credentials-changed'], 2, async () => {
  452. expectOk(await api.credentials.set(request({ ref: 'OPENAI_API_KEY', value: 'sk-secret' })))
  453. const after = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  454. expect(after.credentials).toEqual({ OPENAI_API_KEY: { configured: true, source: 'file', writable: true } })
  455. expect(JSON.stringify(after)).not.toContain('sk-secret')
  456. expectOk(await api.credentials.unset(request({ ref: 'OPENAI_API_KEY' })))
  457. })
  458. expect(frames).toEqual([
  459. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  460. { type: 'host/credentials-changed', ref: 'OPENAI_API_KEY' },
  461. ])
  462. })
  463. it('maps a shadowed write onto credential-rejected for set and unset alike', async () => {
  464. const ctx = await harness({ credentials: { shadowed: ['DEEPSEEK_API_KEY'] } })
  465. const api = createApiProxy(ctx, DEFAULTS)
  466. const described = expectOk(await api.credentials.describe(request({ refs: ['DEEPSEEK_API_KEY'] })))
  467. expect(described.credentials['DEEPSEEK_API_KEY']).toEqual({ configured: true, source: 'env', writable: false })
  468. const setError = expectErr(await api.credentials.set(request({ ref: 'DEEPSEEK_API_KEY', value: 'x' })))
  469. expect(setError.code).toBe('credential-rejected')
  470. expect(setError.details).toEqual({ ref: 'DEEPSEEK_API_KEY' })
  471. const unsetError = expectErr(await api.credentials.unset(request({ ref: 'DEEPSEEK_API_KEY' })))
  472. expect(unsetError.code).toBe('credential-rejected')
  473. })
  474. })
  475. describe('llm domain', () => {
  476. it('merges the configurable directory with live routes and appends undeclared ones', async () => {
  477. const ctx = await harness({ configurableProviders: false })
  478. ctx.llm.registerConfigurableProviders([
  479. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  480. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'] },
  481. ])
  482. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash']))
  483. ctx.llm.registerAdapter(['undeclared'], new CatalogAdapter('Undeclared', ['u-1']))
  484. // Only one namespace can answer an interrogation, so the flag follows the
  485. // entry's namespace rather than being assumed for every row.
  486. ctx.llm.registerModelDiscovery('llm-pi-ai', () => Promise.resolve([]))
  487. const api = createApiProxy(ctx, DEFAULTS)
  488. const value = expectOk(await api.llm.providers(request({})))
  489. expect(value.providers).toEqual([
  490. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
  491. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: false },
  492. // An undeclared live route has no settings address, so nothing can be
  493. // interrogated on its behalf either.
  494. { provider: 'undeclared', displayName: 'Undeclared', settingsNs: '', settingsPath: [], active: true },
  495. ])
  496. })
  497. it('serves the host-scoped catalog with per-provider failures contained', async () => {
  498. const ctx = await harness()
  499. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash', 'deepseek-v4-pro']))
  500. ctx.llm.registerAdapter(['broken'], new BrokenCatalogAdapter('Broken', []))
  501. const api = createApiProxy(ctx, DEFAULTS)
  502. const value = expectOk(await api.llm.models(request({})))
  503. expect(value.groups).toEqual([{
  504. id: 'deepseek-official',
  505. name: 'DeepSeek',
  506. models: [
  507. { id: 'deepseek-v4-flash', name: 'deepseek-v4-flash' },
  508. { id: 'deepseek-v4-pro', name: 'deepseek-v4-pro' },
  509. ],
  510. }])
  511. expect(value.failures).toEqual([{ id: 'broken', name: 'Broken', message: 'catalog backend down' }])
  512. })
  513. it('broadcasts host/models-changed at every topology commit point', async () => {
  514. const ctx = await harness()
  515. const api = createApiProxy(ctx, DEFAULTS)
  516. const frames = await collectHost(api, ['host/models-changed'], 2, async () => {
  517. const dispose = ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', []))
  518. dispose()
  519. return Promise.resolve()
  520. })
  521. expect(frames).toEqual([{ type: 'host/models-changed' }, { type: 'host/models-changed' }])
  522. })
  523. })
  524. describe('llm.discoverModels', () => {
  525. it('carries a draft to its namespace and returns candidates without storing anything', async () => {
  526. const ctx = await harness()
  527. const seen: unknown[] = []
  528. ctx.llm.registerModelDiscovery('llm-pi-ai', (probe) => {
  529. seen.push({ baseURL: probe.baseURL, api: probe.api, apiKey: probe.apiKey })
  530. return Promise.resolve([
  531. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  532. { id: 'acme-small' },
  533. ])
  534. })
  535. const api = createApiProxy(ctx, DEFAULTS)
  536. const value = expectOk(await api.llm.discoverModels(request({
  537. settingsNs: 'llm-pi-ai',
  538. baseURL: 'https://gateway.acme.example/v1',
  539. api: 'openai-completions',
  540. apiKey: 'probe-key',
  541. })))
  542. expect(value.models).toEqual([
  543. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  544. { id: 'acme-small' },
  545. ])
  546. expect(seen).toEqual([{
  547. baseURL: 'https://gateway.acme.example/v1',
  548. api: 'openai-completions',
  549. apiKey: 'probe-key',
  550. }])
  551. // Interrogating a draft is a read: no namespace gained a section, and no
  552. // credential reference was written.
  553. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  554. .not.toContain('llm-pi-ai')
  555. })
  556. it('carries the route being edited so an adapter can answer from its own registry', async () => {
  557. const ctx = await harness()
  558. let probe: unknown
  559. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  560. probe = request_
  561. return Promise.resolve([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  562. })
  563. const api = createApiProxy(ctx, DEFAULTS)
  564. const value = expectOk(await api.llm.discoverModels(request({
  565. settingsNs: 'llm-pi-ai',
  566. provider: 'deepseek',
  567. })))
  568. // No endpoint at all: a route the adapter already describes needs none.
  569. expect(probe).toEqual({ provider: 'deepseek' })
  570. expect(value.models).toEqual([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  571. })
  572. it('omits a credential and protocol the draft does not name', async () => {
  573. const ctx = await harness()
  574. let probe: unknown
  575. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  576. probe = request_
  577. return Promise.resolve([])
  578. })
  579. const api = createApiProxy(ctx, DEFAULTS)
  580. expectOk(await api.llm.discoverModels(request({
  581. settingsNs: 'llm-pi-ai',
  582. baseURL: 'https://gateway.acme.example/v1',
  583. })))
  584. // Absent fields stay absent rather than crossing as explicit undefined:
  585. // the adapter distinguishes "no protocol named" from "protocol undefined".
  586. expect(probe).toEqual({ baseURL: 'https://gateway.acme.example/v1' })
  587. })
  588. it('reports a failed interrogation as the form\'s next move, naming no credential', async () => {
  589. const ctx = await harness()
  590. ctx.llm.registerModelDiscovery('llm-pi-ai', () =>
  591. Promise.reject(new Error('https://gateway.acme.example/v1/models answered 401; check the API key')))
  592. const api = createApiProxy(ctx, DEFAULTS)
  593. const error = expectErr(await api.llm.discoverModels(request({
  594. settingsNs: 'llm-pi-ai',
  595. baseURL: 'https://gateway.acme.example/v1',
  596. apiKey: 'wrong',
  597. })))
  598. expect(error.code).toBe('model-discovery-failed')
  599. expect(error.message).toContain('answered 401; check the API key')
  600. expect(error.details).toEqual({ settingsNs: 'llm-pi-ai', baseURL: 'https://gateway.acme.example/v1' })
  601. expect(JSON.stringify(error)).not.toContain('wrong')
  602. })
  603. it('reports a namespace no adapter family serves', async () => {
  604. const ctx = await harness()
  605. const api = createApiProxy(ctx, DEFAULTS)
  606. const error = expectErr(await api.llm.discoverModels(request({
  607. settingsNs: 'llm-deepseek',
  608. baseURL: 'https://api.deepseek.com',
  609. })))
  610. expect(error.code).toBe('model-discovery-failed')
  611. expect(error.message).toContain('no model discovery is registered')
  612. })
  613. })