api-proxy-config.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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 '@deepseek-ai/cordis'
  9. import z from '@deepseek-ai/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 ToolRuntime from '@deepseek-ai/dsh-tools'
  14. import UserQuestionService from '@deepseek-ai/dsh-user-questions'
  15. import LlmRuntime, { LlmAdapter } from '@deepseek-ai/dsh-llm'
  16. import type { GenerateOptions, LlmModelInfo, LlmProviderInfo, StreamChunk } from '@deepseek-ai/dsh-llm'
  17. import { SettingsProvider, settingsNamespace } from '@deepseek-ai/dsh-settings'
  18. import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
  19. import { CredentialProvider } 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' }
  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 Service Definition base class owns all tested behavior. */
  42. class MemorySettings extends SettingsProvider {
  43. doc: Record<string, unknown>
  44. constructor(ctx: ConstructorParameters<typeof SettingsProvider>[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 CredentialProvider {
  78. private readonly values = new Map<string, string>()
  79. constructor(ctx: ConstructorParameters<typeof CredentialProvider>[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(ToolRuntime)
  152. await ctx.plugin(UserQuestionService)
  153. await ctx.plugin(AgentRegistry)
  154. await ctx.plugin(LlmRuntime)
  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('workspaceRegistry', { 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. /**
  191. * One forwarded `settings/document-updated` frame for `ns`. The revision rides
  192. * the host's own argument list, so it is matched by shape rather than pinned to
  193. * a per-test count.
  194. * @param ns - the namespace whose stored section changed.
  195. * @returns the expected wrapper frame.
  196. */
  197. function forwardedSettings(ns: string): HostFrame {
  198. return {
  199. type: 'host/remote-event',
  200. event: 'settings/document-updated',
  201. // The revision is the Host's own counter, so the matcher is the assertion.
  202. args: [ns, expect.any(Number)], // oxlint-disable-line typescript/no-unsafe-assignment
  203. }
  204. }
  205. describe('settings domain', () => {
  206. it('reports an actionable error when no settings provider is mounted', async () => {
  207. const ctx = await harness({ settings: false })
  208. const api = createApiProxy(ctx, DEFAULTS)
  209. const error = expectErr(await api.settings.describe(request({})))
  210. expect(error.code).toBe('internal')
  211. expect(error.message).toContain('dsh-settings-file')
  212. })
  213. it('describes layered redacted namespaces with their secret slots', async () => {
  214. const ctx = await harness({ settings: {
  215. doc: { 'llm-deepseek': { apiKey: 'user-secret', baseURL: 'https://user' } },
  216. documentPath: '/tmp/custom-settings.yaml',
  217. } })
  218. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  219. const api = createApiProxy(ctx, DEFAULTS)
  220. const value = expectOk(await api.settings.describe(request({})))
  221. expect(value.writable).toBe(true)
  222. expect(value.hasDocument).toBe(true)
  223. expect(value.namespaces).toHaveLength(1)
  224. const view = value.namespaces[0]!
  225. expect(view.ns).toBe('llm-deepseek')
  226. expect(view.applies).toBe('live')
  227. expect((view.schema as { refs?: unknown }).refs).toBeDefined()
  228. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://user' })
  229. expect(view.base).toEqual({ baseURL: 'https://base' })
  230. expect(view.user).toEqual({ baseURL: 'https://user' })
  231. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  232. expect(JSON.stringify(value)).not.toContain('user-secret')
  233. })
  234. it('opens the provider-resolved document without accepting a browser path', async () => {
  235. const ctx = await harness({ settings: {
  236. documentPath: '/tmp/described-settings.yaml',
  237. preparedPath: '/tmp/custom-settings.yaml',
  238. } })
  239. const opened: string[] = []
  240. const api = createApiProxy(ctx, {
  241. ...DEFAULTS,
  242. openTextFile: (path) => {
  243. opened.push(path)
  244. return Promise.resolve()
  245. },
  246. })
  247. expect(expectOk(await api.settings.openDocument(request({}), new AbortController().signal)))
  248. .toEqual({ opened: true })
  249. expect(opened).toEqual(['/tmp/custom-settings.yaml'])
  250. })
  251. it('refuses to open settings when the provider has no local document', async () => {
  252. const ctx = await harness()
  253. const api = createApiProxy(ctx, DEFAULTS)
  254. expect(expectOk(await api.settings.describe(request({}))).hasDocument).toBe(false)
  255. const error = expectErr(await api.settings.openDocument(request({}), new AbortController().signal))
  256. expect(error.code).toBe('internal')
  257. expect(error.message).toContain('no local document')
  258. })
  259. it('does not prepare or open a settings document after cancellation', async () => {
  260. const ctx = await harness({ settings: { documentPath: '/tmp/settings.yaml' } })
  261. const opened: string[] = []
  262. const api = createApiProxy(ctx, {
  263. ...DEFAULTS,
  264. openTextFile: (path) => {
  265. opened.push(path)
  266. return Promise.resolve()
  267. },
  268. })
  269. const prepare = vi.spyOn(ctx.settings, 'prepareDocument')
  270. const cancelled = new AbortController()
  271. cancelled.abort()
  272. expect(expectErr(await api.settings.openDocument(request({}), cancelled.signal)).code)
  273. .toBe('cancelled')
  274. expect(prepare).not.toHaveBeenCalled()
  275. const pending = Promise.withResolvers<string | undefined>()
  276. prepare.mockReturnValueOnce(pending.promise)
  277. const duringPrepare = new AbortController()
  278. const opening = api.settings.openDocument(request({}), duringPrepare.signal)
  279. await vi.waitFor(() => { expect(prepare).toHaveBeenCalledOnce() })
  280. duringPrepare.abort()
  281. pending.resolve('/tmp/settings.yaml')
  282. expect(expectErr(await opening).code).toBe('cancelled')
  283. expect(opened).toEqual([])
  284. })
  285. it('serves every registered namespace, including one this repository never named', async () => {
  286. // Registering IS the exposure: a plugin distributed outside this
  287. // repository configures itself from the browser without a change here.
  288. // The plane stays loopback-only and secret-redacted, and which surface
  289. // renders a namespace is the browser's decision, not this proxy's.
  290. const ctx = await harness()
  291. ctx.settings.register(NS, AdapterConfig)
  292. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  293. ctx.settings.register(settingsNamespace('permission'), z.object({
  294. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  295. }), {
  296. base: { defaultPreset: 'read-only' },
  297. })
  298. ctx.settings.register(settingsNamespace('ui-theme'), z.object({
  299. preference: z.union(['light', 'dark', 'system']).default('system'),
  300. }))
  301. ctx.settings.register(settingsNamespace('locale'), z.object({
  302. preference: z.union(['zh', 'en']).required(false),
  303. }))
  304. ctx.settings.register(settingsNamespace('ui-conversation'), z.object({
  305. busyEnter: z.union(['queue', 'steer']).default('queue'),
  306. }))
  307. ctx.settings.register(settingsNamespace('shell'), z.object({
  308. timeoutMs: z.number().default(120_000),
  309. }))
  310. ctx.settings.register(settingsNamespace('agent-loop'), z.object({
  311. maxParallelToolCalls: z.number().default(10),
  312. }))
  313. ctx.settings.register(settingsNamespace('web-search-deepseek'), z.object({
  314. baseURL: z.string(),
  315. }))
  316. const api = createApiProxy(ctx, DEFAULTS)
  317. const value = expectOk(await api.settings.describe(request({})))
  318. expect(value.namespaces.map(view => view.ns)).toEqual([
  319. 'llm-deepseek', 'some-other-plugin', 'permission', 'ui-theme', 'locale',
  320. 'ui-conversation', 'shell', 'agent-loop', 'web-search-deepseek',
  321. ])
  322. const permission = expectOk(await api.settings.mutate(request({
  323. ns: 'permission',
  324. ops: [{ op: 'set', path: ['defaultPreset'], value: 'workspace-write' }],
  325. })))
  326. expect(permission.value).toEqual({ defaultPreset: 'workspace-write' })
  327. const theme = expectOk(await api.settings.mutate(request({
  328. ns: 'ui-theme',
  329. ops: [{ op: 'set', path: ['preference'], value: 'dark' }],
  330. })))
  331. expect(theme.value).toEqual({ preference: 'dark' })
  332. const locale = expectOk(await api.settings.mutate(request({
  333. ns: 'locale',
  334. ops: [{ op: 'set', path: ['preference'], value: 'en' }],
  335. })))
  336. expect(locale.value).toEqual({ preference: 'en' })
  337. const conversation = expectOk(await api.settings.mutate(request({
  338. ns: 'ui-conversation',
  339. ops: [{ op: 'set', path: ['busyEnter'], value: 'steer' }],
  340. })))
  341. expect(conversation.value).toEqual({ busyEnter: 'steer' })
  342. const bash = expectOk(await api.settings.mutate(request({
  343. ns: 'shell',
  344. ops: [{ op: 'set', path: ['timeoutMs'], value: 5_000 }],
  345. })))
  346. expect(bash.value).toEqual({ timeoutMs: 5_000 })
  347. const agentLoop = expectOk(await api.settings.mutate(request({
  348. ns: 'agent-loop',
  349. ops: [{ op: 'set', path: ['maxParallelToolCalls'], value: 2 }],
  350. })))
  351. expect(agentLoop.value).toEqual({ maxParallelToolCalls: 2 })
  352. const webSearch = expectOk(await api.settings.mutate(request({
  353. ns: 'web-search-deepseek',
  354. ops: [{ op: 'set', path: ['baseURL'], value: 'https://search.test/v1' }],
  355. })))
  356. expect(webSearch.value).toEqual({ baseURL: 'https://search.test/v1' })
  357. const other = expectOk(await api.settings.update(request({
  358. ns: 'some-other-plugin',
  359. patch: { secretPath: '/etc/shadow' },
  360. })))
  361. expect(other.value).toEqual({ secretPath: '/etc/shadow' })
  362. expect(ctx.settings.describe().find(d => String(d.ns) === 'some-other-plugin')?.value)
  363. .toEqual({ secretPath: '/etc/shadow' })
  364. })
  365. it('serves product preference namespaces without invalidating the model catalog', async () => {
  366. const ctx = await harness()
  367. ctx.settings.register(settingsNamespace('ui-onboarding'), z.object({ welcomeNoticeVersion: z.string() }))
  368. ctx.settings.register(settingsNamespace('ui-theme'), z.object({
  369. preference: z.union(['light', 'dark', 'system']).default('system'),
  370. }))
  371. const api = createApiProxy(ctx, DEFAULTS)
  372. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  373. .toEqual(['ui-onboarding', 'ui-theme'])
  374. const frames = await collectHost(api, ['host/remote-event'], 2, async () => {
  375. expectOk(await api.settings.mutate(request({
  376. ns: 'ui-onboarding',
  377. ops: [{ op: 'set', path: ['welcomeNoticeVersion'], value: 'v1' }],
  378. })))
  379. expectOk(await api.settings.mutate(request({
  380. ns: 'ui-theme',
  381. ops: [{ op: 'set', path: ['preference'], value: 'dark' }],
  382. })))
  383. })
  384. expect(frames).toEqual([forwardedSettings('ui-onboarding'), forwardedSettings('ui-theme')])
  385. })
  386. it('serves the agent-preset namespace, so a browser preset picker can persist its choice', async () => {
  387. const ctx = await harness()
  388. ctx.settings.register(settingsNamespace('agent-presets'), z.object({ default: z.string() }))
  389. const api = createApiProxy(ctx, DEFAULTS)
  390. expectOk(await api.settings.update(request({ ns: 'agent-presets', patch: { default: 'minimal' } })))
  391. // Both browser surfaces that offer the choice — the General row and the
  392. // management section — write the default through `settings.update`, so a
  393. // namespace outside this boundary makes the picker move and then silently
  394. // forget, which is worse than refusing the control.
  395. expect(ctx.settings.describe().find(view => String(view.ns) === 'agent-presets')?.value)
  396. .toEqual({ default: 'minimal' })
  397. })
  398. it('keeps serving a provider namespace whose directory entry is gone', async () => {
  399. // The configurable-provider directory says what the Models page can offer,
  400. // not what a user may configure: a dormant route's stored section is still
  401. // theirs to edit, and losing the entry must not strand it.
  402. const ctx = await harness({ configurableProviders: false })
  403. ctx.settings.register(NS, AdapterConfig)
  404. const api = createApiProxy(ctx, DEFAULTS)
  405. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  406. .toEqual(['llm-deepseek'])
  407. expect(expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://x' } }))).value)
  408. .toMatchObject({ baseURL: 'https://x' })
  409. })
  410. it('forwards a provider settings change for model-catalog consumers', async () => {
  411. // Editing `models` changes no route, so llm/adapters-updated never fires
  412. // and an open model picker would keep serving the stale catalog. Storing
  413. // an override equal to the resolved value emits nothing on
  414. // settings/updated, so another tab would never learn the field became
  415. // overridden.
  416. const ctx = await harness()
  417. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  418. const api = createApiProxy(ctx, DEFAULTS)
  419. const frames = await collectHost(api, ['host/remote-event'], 1, async () => {
  420. await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://base' } }))
  421. })
  422. expect(frames).toEqual([forwardedSettings('llm-deepseek')])
  423. // The resolved value never moved: base already said https://base.
  424. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.value)
  425. .toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://base' })
  426. })
  427. it('broadcasts a permission change without invalidating the model catalog', async () => {
  428. const ctx = await harness()
  429. const permission = ctx.settings.register(settingsNamespace('permission'), z.object({
  430. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  431. }), {
  432. base: { defaultPreset: 'read-only' },
  433. })
  434. const api = createApiProxy(ctx, DEFAULTS)
  435. const frames = await collectHost(api, ['host/remote-event'], 1, async () => {
  436. await permission.update({ defaultPreset: 'workspace-write' })
  437. })
  438. expect(frames).toEqual([forwardedSettings('permission')])
  439. })
  440. it('forwards an Agent-default settings change for model-catalog consumers', async () => {
  441. const ctx = await harness()
  442. const defaultModel = ctx.settings.register(AGENT_DEFAULT_MODEL_SETTINGS_NAMESPACE, z.object({
  443. provider: z.string().required(),
  444. model: z.string().required(),
  445. }), { base: { provider: 'deepseek-official', model: 'deepseek-v4-flash' } })
  446. const api = createApiProxy(ctx, DEFAULTS)
  447. // The shared section names the selection every blank session resolves to,
  448. // so an externally edited default — another tab, a
  449. // hand-edited settings.yaml — has to reach an open selector as well.
  450. const frames = await collectHost(api, ['host/remote-event'], 1, async () => {
  451. await defaultModel.replace({ provider: 'deepseek-official', model: 'deepseek-reasoner' })
  452. })
  453. expect(frames).toEqual([forwardedSettings('agent-default-model')])
  454. })
  455. it('maps a stale expectedRevision to settings-conflict carrying both revisions', async () => {
  456. const ctx = await harness()
  457. ctx.settings.register(NS, AdapterConfig)
  458. const api = createApiProxy(ctx, DEFAULTS)
  459. const opened = expectOk(await api.settings.describe(request({}))).namespaces[0]!.revision
  460. expect(expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://first' }, expectedRevision: opened })))
  461. .revision).toBe(opened + 1)
  462. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://second' }, expectedRevision: opened })))
  463. expect(error.code).toBe('settings-conflict')
  464. expect(error.details).toEqual({ ns: 'llm-deepseek', expected: opened, actual: opened + 1 })
  465. // The refused write changed nothing.
  466. expect(expectOk(await api.settings.describe(request({}))).namespaces[0]!.user).toEqual({ baseURL: 'https://first' })
  467. })
  468. it('updates the user layer, answers with the new redacted view, and broadcasts the frame', async () => {
  469. const ctx = await harness()
  470. ctx.settings.register(NS, AdapterConfig, { base: { baseURL: 'https://base' } })
  471. const api = createApiProxy(ctx, DEFAULTS)
  472. const frames = await collectHost(api, ['host/remote-event'], 1, async () => {
  473. const view = expectOk(await api.settings.update(request({ ns: 'llm-deepseek', patch: { apiKey: 'sk-new', baseURL: 'https://next' } })))
  474. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://next' })
  475. expect(view.user).toEqual({ baseURL: 'https://next' })
  476. expect(view.secrets).toEqual([{ path: ['apiKey'], set: true }])
  477. expect(JSON.stringify(view)).not.toContain('sk-new')
  478. })
  479. expect(frames).toEqual([forwardedSettings('llm-deepseek')])
  480. })
  481. it('replace resets the user layer wholesale', async () => {
  482. const ctx = await harness({ settings: { doc: { 'llm-deepseek': { baseURL: 'https://user' } } } })
  483. ctx.settings.register(NS, AdapterConfig)
  484. const api = createApiProxy(ctx, DEFAULTS)
  485. const view = expectOk(await api.settings.replace(request({ ns: 'llm-deepseek', section: {} })))
  486. expect(view.value).toEqual({ apiKeyEnv: 'DEEPSEEK_API_KEY' })
  487. expect(view.user).toEqual({})
  488. })
  489. it.each([
  490. ['an invalid namespace name', 'Not A Namespace', {}],
  491. ['a schema-invalid patch', 'llm-deepseek', { baseURL: 42 }],
  492. ])('rejects %s as settings-rejected', async (_case, ns, patch) => {
  493. const ctx = await harness()
  494. ctx.settings.register(NS, AdapterConfig)
  495. const api = createApiProxy(ctx, DEFAULTS)
  496. const error = expectErr(await api.settings.update(request({ ns, patch })))
  497. expect(error.code).toBe('settings-rejected')
  498. expect(error.details).toEqual({ ns })
  499. })
  500. it('answers an unregistered namespace as the seam does, and a malformed one alike', async () => {
  501. // A name no registration answers and a name no registration could answer
  502. // fold into the same rejection: the proxy adds no boundary of its own, so
  503. // the seam's own refusal is the whole answer.
  504. const ctx = await harness()
  505. ctx.settings.register(NS, AdapterConfig)
  506. const api = createApiProxy(ctx, DEFAULTS)
  507. const unknown = expectErr(await api.settings.update(request({ ns: 'unknown-ns', patch: {} })))
  508. const malformed = expectErr(await api.settings.update(request({ ns: 'Not A Namespace', patch: {} })))
  509. expect(unknown.code).toBe('settings-rejected')
  510. expect(unknown.message).toContain('is not registered')
  511. expect(malformed.code).toBe(unknown.code)
  512. })
  513. it('maps a read-only provider refusal onto the same rejection', async () => {
  514. const ctx = await harness({ settings: { readOnly: true } })
  515. ctx.settings.register(NS, AdapterConfig)
  516. const api = createApiProxy(ctx, DEFAULTS)
  517. const value = expectOk(await api.settings.describe(request({})))
  518. expect(value.writable).toBe(false)
  519. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: {} })))
  520. expect(error.code).toBe('settings-rejected')
  521. expect(error.message).toContain('read-only')
  522. })
  523. })
  524. describe('credentials domain', () => {
  525. it('reports an actionable error when no credential provider is mounted', async () => {
  526. const ctx = await harness({ credentials: false })
  527. const api = createApiProxy(ctx, DEFAULTS)
  528. const error = expectErr(await api.credentials.describe(request({ refs: ['A'] })))
  529. expect(error.code).toBe('internal')
  530. expect(error.message).toContain('dsh-credentials-local')
  531. })
  532. it('describes value-free views and flips state through set/unset with frames', async () => {
  533. const ctx = await harness()
  534. const api = createApiProxy(ctx, DEFAULTS)
  535. const before = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  536. expect(before.credentials).toEqual({ OPENAI_API_KEY: { configured: false, writable: true } })
  537. const frames = await collectHost(api, ['host/remote-event'], 2, async () => {
  538. expectOk(await api.credentials.set(request({ ref: 'OPENAI_API_KEY', value: 'sk-secret' })))
  539. const after = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  540. expect(after.credentials).toEqual({ OPENAI_API_KEY: { configured: true, source: 'file', writable: true } })
  541. expect(JSON.stringify(after)).not.toContain('sk-secret')
  542. expectOk(await api.credentials.unset(request({ ref: 'OPENAI_API_KEY' })))
  543. })
  544. expect(frames).toEqual([
  545. { type: 'host/remote-event', event: 'credentials/updated', args: ['OPENAI_API_KEY'] },
  546. { type: 'host/remote-event', event: 'credentials/updated', args: ['OPENAI_API_KEY'] },
  547. ])
  548. })
  549. it('maps a shadowed write onto credential-rejected for set and unset alike', async () => {
  550. const ctx = await harness({ credentials: { shadowed: ['DEEPSEEK_API_KEY'] } })
  551. const api = createApiProxy(ctx, DEFAULTS)
  552. const described = expectOk(await api.credentials.describe(request({ refs: ['DEEPSEEK_API_KEY'] })))
  553. expect(described.credentials['DEEPSEEK_API_KEY']).toEqual({ configured: true, source: 'env', writable: false })
  554. const setError = expectErr(await api.credentials.set(request({ ref: 'DEEPSEEK_API_KEY', value: 'x' })))
  555. expect(setError.code).toBe('credential-rejected')
  556. expect(setError.details).toEqual({ ref: 'DEEPSEEK_API_KEY' })
  557. const unsetError = expectErr(await api.credentials.unset(request({ ref: 'DEEPSEEK_API_KEY' })))
  558. expect(unsetError.code).toBe('credential-rejected')
  559. })
  560. })
  561. describe('llm domain', () => {
  562. it('merges the configurable directory with live routes and appends undeclared ones', async () => {
  563. const ctx = await harness({ configurableProviders: false })
  564. ctx.llm.registerConfigurableProviders([
  565. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  566. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'] },
  567. ])
  568. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash']))
  569. ctx.llm.registerAdapter(['undeclared'], new CatalogAdapter('Undeclared', ['u-1']))
  570. // Only one namespace can answer an interrogation, so the flag follows the
  571. // entry's namespace rather than being assumed for every row.
  572. ctx.llm.registerModelDiscovery('llm-pi-ai', () => Promise.resolve([]))
  573. const api = createApiProxy(ctx, DEFAULTS)
  574. const value = expectOk(await api.llm.providers(request({})))
  575. expect(value.providers).toEqual([
  576. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
  577. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: false },
  578. // An undeclared live route has no settings address, so nothing can be
  579. // interrogated on its behalf either.
  580. { provider: 'undeclared', displayName: 'Undeclared', settingsNs: '', settingsPath: [], active: true },
  581. ])
  582. })
  583. it('serves the host-scoped catalog with per-provider failures contained', async () => {
  584. const ctx = await harness()
  585. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash', 'deepseek-v4-pro']))
  586. ctx.llm.registerAdapter(['broken'], new BrokenCatalogAdapter('Broken', []))
  587. const api = createApiProxy(ctx, DEFAULTS)
  588. const value = expectOk(await api.llm.models(request({})))
  589. expect(value.groups).toEqual([{
  590. id: 'deepseek-official',
  591. name: 'DeepSeek',
  592. models: [
  593. { id: 'deepseek-v4-flash', name: 'deepseek-v4-flash' },
  594. { id: 'deepseek-v4-pro', name: 'deepseek-v4-pro' },
  595. ],
  596. }])
  597. expect(value.failures).toEqual([{ id: 'broken', name: 'Broken', message: 'catalog backend down' }])
  598. })
  599. it('forwards llm/adapters-updated at every topology commit point', async () => {
  600. const ctx = await harness()
  601. const api = createApiProxy(ctx, DEFAULTS)
  602. const frames = await collectHost(api, ['host/remote-event'], 2, async () => {
  603. const dispose = ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', []))
  604. dispose()
  605. return Promise.resolve()
  606. })
  607. expect(frames).toEqual([
  608. { type: 'host/remote-event', event: 'llm/adapters-updated', args: [] },
  609. { type: 'host/remote-event', event: 'llm/adapters-updated', args: [] },
  610. ])
  611. })
  612. })
  613. describe('llm.discoverModels', () => {
  614. it('carries a draft to its namespace and returns candidates without storing anything', async () => {
  615. const ctx = await harness()
  616. const seen: unknown[] = []
  617. ctx.llm.registerModelDiscovery('llm-pi-ai', (probe) => {
  618. seen.push({ baseURL: probe.baseURL, api: probe.api, apiKey: probe.apiKey })
  619. return Promise.resolve([
  620. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  621. { id: 'acme-small' },
  622. ])
  623. })
  624. const api = createApiProxy(ctx, DEFAULTS)
  625. const value = expectOk(await api.llm.discoverModels(request({
  626. settingsNs: 'llm-pi-ai',
  627. baseURL: 'https://gateway.acme.example/v1',
  628. api: 'openai-completions',
  629. apiKey: 'probe-key',
  630. })))
  631. expect(value.models).toEqual([
  632. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  633. { id: 'acme-small' },
  634. ])
  635. expect(seen).toEqual([{
  636. baseURL: 'https://gateway.acme.example/v1',
  637. api: 'openai-completions',
  638. apiKey: 'probe-key',
  639. }])
  640. // Interrogating a draft is a read: no namespace gained a section, and no
  641. // credential reference was written.
  642. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  643. .not.toContain('llm-pi-ai')
  644. })
  645. it('carries the route being edited so an adapter can answer from its own registry', async () => {
  646. const ctx = await harness()
  647. let probe: unknown
  648. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  649. probe = request_
  650. return Promise.resolve([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  651. })
  652. const api = createApiProxy(ctx, DEFAULTS)
  653. const value = expectOk(await api.llm.discoverModels(request({
  654. settingsNs: 'llm-pi-ai',
  655. provider: 'deepseek',
  656. })))
  657. // No endpoint at all: a route the adapter already describes needs none.
  658. expect(probe).toEqual({ provider: 'deepseek' })
  659. expect(value.models).toEqual([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  660. })
  661. it('omits a credential and protocol the draft does not name', async () => {
  662. const ctx = await harness()
  663. let probe: unknown
  664. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  665. probe = request_
  666. return Promise.resolve([])
  667. })
  668. const api = createApiProxy(ctx, DEFAULTS)
  669. expectOk(await api.llm.discoverModels(request({
  670. settingsNs: 'llm-pi-ai',
  671. baseURL: 'https://gateway.acme.example/v1',
  672. })))
  673. // Absent fields stay absent rather than crossing as explicit undefined:
  674. // the adapter distinguishes "no protocol named" from "protocol undefined".
  675. expect(probe).toEqual({ baseURL: 'https://gateway.acme.example/v1' })
  676. })
  677. it('reports a failed interrogation as the form\'s next move, naming no credential', async () => {
  678. const ctx = await harness()
  679. ctx.llm.registerModelDiscovery('llm-pi-ai', () =>
  680. Promise.reject(new Error('https://gateway.acme.example/v1/models answered 401; check the API key')))
  681. const api = createApiProxy(ctx, DEFAULTS)
  682. const error = expectErr(await api.llm.discoverModels(request({
  683. settingsNs: 'llm-pi-ai',
  684. baseURL: 'https://gateway.acme.example/v1',
  685. apiKey: 'wrong',
  686. })))
  687. expect(error.code).toBe('model-discovery-failed')
  688. expect(error.message).toContain('answered 401; check the API key')
  689. expect(error.details).toEqual({ settingsNs: 'llm-pi-ai', baseURL: 'https://gateway.acme.example/v1' })
  690. expect(JSON.stringify(error)).not.toContain('wrong')
  691. })
  692. it('reports a namespace no adapter family serves', async () => {
  693. const ctx = await harness()
  694. const api = createApiProxy(ctx, DEFAULTS)
  695. const error = expectErr(await api.llm.discoverModels(request({
  696. settingsNs: 'llm-deepseek',
  697. baseURL: 'https://api.deepseek.com',
  698. })))
  699. expect(error.code).toBe('model-discovery-failed')
  700. expect(error.message).toContain('no model discovery is registered')
  701. })
  702. })