api-proxy-config.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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 ToolRegistry from '@deepseek-ai/dsh-tools'
  14. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  15. import LlmService, { LlmAdapter } from '@deepseek-ai/dsh-llm'
  16. import type { GenerateOptions, LlmModelInfo, LlmProviderInfo, StreamChunk } from '@deepseek-ai/dsh-llm'
  17. import { Settings, settingsNamespace } from '@deepseek-ai/dsh-settings'
  18. import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
  19. import { Credentials } from '@deepseek-ai/dsh-credentials'
  20. import type { CredentialInfo, CredentialRef, ResolvedCredential } from '@deepseek-ai/dsh-credentials'
  21. import type { HostFrame } from '../src/api/index.ts'
  22. import type { RpcRequest, RpcResponse } from '../src/api/rpc.ts'
  23. import { RpcId } from '../src/api/rpc.ts'
  24. import { AGENT_DEFAULT_MODEL_SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-agent-default-model'
  25. import { createApiProxy } from '../src/api-proxy.ts'
  26. const DEFAULTS = { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' }
  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 Settings {
  43. doc: Record<string, unknown>
  44. constructor(ctx: ConstructorParameters<typeof Settings>[0], options?: {
  45. doc?: Record<string, unknown>
  46. readOnly?: boolean
  47. documentPath?: string
  48. preparedPath?: string
  49. }) {
  50. super(ctx)
  51. this.doc = structuredClone(options?.doc ?? {})
  52. this.readOnly = options?.readOnly ?? false
  53. this.path = options?.documentPath
  54. this.preparedPath = options?.preparedPath
  55. }
  56. private readonly readOnly: boolean
  57. private readonly path: string | undefined
  58. private readonly preparedPath: string | undefined
  59. get writable(): boolean {
  60. return !this.readOnly
  61. }
  62. override get documentPath(): string | undefined {
  63. return this.path
  64. }
  65. override prepareDocument(): Promise<string | undefined> {
  66. return Promise.resolve(this.preparedPath ?? this.documentPath)
  67. }
  68. protected load(): Promise<Record<string, unknown>> {
  69. return Promise.resolve(structuredClone(this.doc))
  70. }
  71. protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
  72. this.doc[ns] = structuredClone(section)
  73. return Promise.resolve()
  74. }
  75. }
  76. /** In-memory credential provider with an env-shadow double for the rejection path. */
  77. class MemoryCredentials extends Credentials {
  78. private readonly values = new Map<string, string>()
  79. constructor(ctx: ConstructorParameters<typeof Credentials>[0], options?: { shadowed?: string[] }) {
  80. super(ctx)
  81. this.shadowed = new Set(options?.shadowed ?? [])
  82. }
  83. private readonly shadowed: Set<string>
  84. resolve(ref: CredentialRef): Promise<ResolvedCredential | undefined> {
  85. if (this.shadowed.has(ref)) return Promise.resolve({ value: 'from-env', source: 'env' })
  86. const value = this.values.get(ref)
  87. return Promise.resolve(value === undefined ? undefined : { value, source: 'file' })
  88. }
  89. describe(ref: CredentialRef): Promise<CredentialInfo> {
  90. if (this.shadowed.has(ref)) return Promise.resolve({ configured: true, source: 'env', writable: false })
  91. const configured = this.values.has(ref)
  92. return Promise.resolve({ configured, ...configured ? { source: 'file' } : {}, writable: true })
  93. }
  94. set(ref: CredentialRef, value: string): Promise<void> {
  95. if (this.shadowed.has(ref)) {
  96. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  97. }
  98. this.values.set(ref, value)
  99. this.ctx.emit('credentials/updated', ref)
  100. return Promise.resolve()
  101. }
  102. unset(ref: CredentialRef): Promise<void> {
  103. if (this.shadowed.has(ref)) {
  104. return Promise.reject(new Error(`credentials: ${ref} is shadowed by the read-only environment`))
  105. }
  106. this.values.delete(ref)
  107. this.ctx.emit('credentials/updated', ref)
  108. return Promise.resolve()
  109. }
  110. }
  111. /** Catalog-serving adapter stub for the llm.models path. */
  112. class CatalogAdapter extends LlmAdapter {
  113. constructor(private readonly name: string, private readonly models: readonly string[]) {
  114. super()
  115. }
  116. override providerInfo(provider: string): LlmProviderInfo {
  117. return { id: provider, name: this.name }
  118. }
  119. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  120. return Promise.resolve(this.models.map(id => ({ provider, id, name: id })))
  121. }
  122. async * stream(_options: GenerateOptions): AsyncIterable<StreamChunk> {
  123. throw new Error('not exercised')
  124. }
  125. }
  126. class BrokenCatalogAdapter extends CatalogAdapter {
  127. override listModels(): Promise<readonly LlmModelInfo[]> {
  128. return Promise.reject(new Error('catalog backend down'))
  129. }
  130. }
  131. const NS = settingsNamespace('llm-deepseek')
  132. const AdapterConfig = z.object({
  133. apiKey: z.string().role('secret'),
  134. apiKeyEnv: z.string().default('DEEPSEEK_API_KEY'),
  135. baseURL: z.string(),
  136. })
  137. async function harness(options?: {
  138. settings?: false | {
  139. doc?: Record<string, unknown>
  140. readOnly?: boolean
  141. documentPath?: string
  142. preparedPath?: string
  143. }
  144. credentials?: false | { shadowed?: string[] }
  145. /** Skip the directory registration to exercise a namespace the proxy does not expose. */
  146. configurableProviders?: false
  147. }): Promise<Context> {
  148. const ctx = new Context()
  149. await ctx.plugin(SessionStore)
  150. await ctx.plugin(SystemPrompt, { persona: '' })
  151. await ctx.plugin(ToolRegistry)
  152. await ctx.plugin(UserInteractionService)
  153. await ctx.plugin(AgentRegistry)
  154. await ctx.plugin(LlmService)
  155. if (options?.settings !== false) await ctx.plugin(MemorySettings, options?.settings)
  156. if (options?.credentials !== false) await ctx.plugin(MemoryCredentials, options?.credentials)
  157. // Model-provider namespaces plus the explicit Web preference and product
  158. // onboarding allowlists are the proxy's complete settings surface.
  159. if (options?.configurableProviders !== false) {
  160. ctx.llm.registerConfigurableProviders([
  161. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  162. ])
  163. }
  164. // Host-stream opener reads the committed-workspace baseline; the stub
  165. // suffices — the real workspace composition is api-proxy-workspace.spec's.
  166. ctx.provide('workspace', { list: () => [] } as never)
  167. return ctx
  168. }
  169. /** Drain `count` host frames matching `types`, then abort the stream. */
  170. async function collectHost(
  171. api: ReturnType<typeof createApiProxy>,
  172. types: string[],
  173. count: number,
  174. run: () => Promise<void>,
  175. ): Promise<HostFrame[]> {
  176. const abort = new AbortController()
  177. const frames: HostFrame[] = []
  178. const stream = api.events.host(request({}), abort.signal)
  179. const consume = (async () => {
  180. for await (const frame of stream) {
  181. if (!types.includes(frame.payload.type)) continue
  182. frames.push(frame.payload)
  183. if (frames.length >= count) abort.abort()
  184. }
  185. })()
  186. await run()
  187. await consume
  188. return frames
  189. }
  190. /**
  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-local')
  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 model-provider and explicitly allowlisted Web namespaces only', async () => {
  286. // The settings seam is general: any plugin may register a namespace for
  287. // its own configuration. The Web configuration plane remains opt-in, so a
  288. // future internal plugin cannot become remotely configurable just by
  289. // registering; locale, permission, conversation, theme, and the product
  290. // onboarding namespace are intentionally admitted by this surface.
  291. const ctx = await harness()
  292. ctx.settings.register(NS, AdapterConfig)
  293. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  294. ctx.settings.register(settingsNamespace('permission'), z.object({
  295. defaultPreset: z.union(['read-only', 'workspace-write']).required(),
  296. }), {
  297. base: { defaultPreset: 'read-only' },
  298. })
  299. ctx.settings.register(settingsNamespace('ui-theme'), z.object({
  300. preference: z.union(['light', 'dark', 'system']).default('system'),
  301. }))
  302. ctx.settings.register(settingsNamespace('locale'), z.object({
  303. preference: z.union(['zh', 'en']).required(false),
  304. }))
  305. ctx.settings.register(settingsNamespace('ui-conversation'), z.object({
  306. busyEnter: z.union(['queue', 'steer']).default('queue'),
  307. }))
  308. ctx.settings.register(settingsNamespace('bash'), z.object({
  309. timeoutMs: z.number().default(120_000),
  310. }))
  311. ctx.settings.register(settingsNamespace('agent-loop'), z.object({
  312. maxParallelToolCalls: z.number().default(10),
  313. }))
  314. ctx.settings.register(settingsNamespace('web-search-deepseek'), z.object({
  315. baseURL: z.string(),
  316. }))
  317. const api = createApiProxy(ctx, DEFAULTS)
  318. const value = expectOk(await api.settings.describe(request({})))
  319. expect(value.namespaces.map(view => view.ns)).toEqual([
  320. 'llm-deepseek', 'permission', 'ui-theme', 'locale', 'ui-conversation',
  321. 'bash', 'agent-loop', 'web-search-deepseek',
  322. ])
  323. const permission = expectOk(await api.settings.mutate(request({
  324. ns: 'permission',
  325. ops: [{ op: 'set', path: ['defaultPreset'], value: 'workspace-write' }],
  326. })))
  327. expect(permission.value).toEqual({ defaultPreset: 'workspace-write' })
  328. const theme = expectOk(await api.settings.mutate(request({
  329. ns: 'ui-theme',
  330. ops: [{ op: 'set', path: ['preference'], value: 'dark' }],
  331. })))
  332. expect(theme.value).toEqual({ preference: 'dark' })
  333. const locale = expectOk(await api.settings.mutate(request({
  334. ns: 'locale',
  335. ops: [{ op: 'set', path: ['preference'], value: 'en' }],
  336. })))
  337. expect(locale.value).toEqual({ preference: 'en' })
  338. const conversation = expectOk(await api.settings.mutate(request({
  339. ns: 'ui-conversation',
  340. ops: [{ op: 'set', path: ['busyEnter'], value: 'steer' }],
  341. })))
  342. expect(conversation.value).toEqual({ busyEnter: 'steer' })
  343. const bash = expectOk(await api.settings.mutate(request({
  344. ns: 'bash',
  345. ops: [{ op: 'set', path: ['timeoutMs'], value: 5_000 }],
  346. })))
  347. expect(bash.value).toEqual({ timeoutMs: 5_000 })
  348. const agentLoop = expectOk(await api.settings.mutate(request({
  349. ns: 'agent-loop',
  350. ops: [{ op: 'set', path: ['maxParallelToolCalls'], value: 2 }],
  351. })))
  352. expect(agentLoop.value).toEqual({ maxParallelToolCalls: 2 })
  353. const webSearch = expectOk(await api.settings.mutate(request({
  354. ns: 'web-search-deepseek',
  355. ops: [{ op: 'set', path: ['baseURL'], value: 'https://search.test/v1' }],
  356. })))
  357. expect(webSearch.value).toEqual({ baseURL: 'https://search.test/v1' })
  358. for (const response of [
  359. await api.settings.update(request({ ns: 'some-other-plugin', patch: { secretPath: '/etc/shadow' } })),
  360. await api.settings.replace(request({ ns: 'some-other-plugin', section: {} })),
  361. ]) {
  362. const error = expectErr(response)
  363. expect(error.code).toBe('settings-not-exposed')
  364. expect(error.details).toEqual({ ns: 'some-other-plugin' })
  365. }
  366. // The write never reached the seam.
  367. expect(ctx.settings.describe().find(d => String(d.ns) === 'some-other-plugin')?.value).toEqual({})
  368. })
  369. it('serves product preference namespaces without invalidating the model catalog', async () => {
  370. const ctx = await harness()
  371. ctx.settings.register(settingsNamespace('ui-onboarding'), z.object({ welcomeNoticeVersion: z.string() }))
  372. ctx.settings.register(settingsNamespace('ui-theme'), z.object({
  373. preference: z.union(['light', 'dark', 'system']).default('system'),
  374. }))
  375. const api = createApiProxy(ctx, DEFAULTS)
  376. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  377. .toEqual(['ui-onboarding', 'ui-theme'])
  378. const frames = await collectHost(api, ['host/remote-event'], 2, async () => {
  379. expectOk(await api.settings.mutate(request({
  380. ns: 'ui-onboarding',
  381. ops: [{ op: 'set', path: ['welcomeNoticeVersion'], value: 'v1' }],
  382. })))
  383. expectOk(await api.settings.mutate(request({
  384. ns: 'ui-theme',
  385. ops: [{ op: 'set', path: ['preference'], value: 'dark' }],
  386. })))
  387. })
  388. expect(frames).toEqual([forwardedSettings('ui-onboarding'), forwardedSettings('ui-theme')])
  389. })
  390. it('serves the agent-preset namespace, so a browser preset picker can persist its choice', async () => {
  391. const ctx = await harness()
  392. ctx.settings.register(settingsNamespace('agent-presets'), z.object({ default: z.string() }))
  393. const api = createApiProxy(ctx, DEFAULTS)
  394. expectOk(await api.settings.update(request({ ns: 'agent-presets', patch: { default: 'minimal' } })))
  395. // Both browser surfaces that offer the choice — the General row and the
  396. // management section — write the default through `settings.update`, so a
  397. // namespace outside this boundary makes the picker move and then silently
  398. // forget, which is worse than refusing the control.
  399. expect(ctx.settings.describe().find(view => String(view.ns) === 'agent-presets')?.value)
  400. .toEqual({ default: 'minimal' })
  401. })
  402. it('refuses even a model-provider namespace once its directory entry is gone', async () => {
  403. const ctx = await harness({ configurableProviders: false })
  404. ctx.settings.register(NS, AdapterConfig)
  405. const api = createApiProxy(ctx, DEFAULTS)
  406. expect(expectOk(await api.settings.describe(request({}))).namespaces).toEqual([])
  407. expect(expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: { baseURL: 'https://x' } }))).code)
  408. .toBe('settings-not-exposed')
  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 exactly like an unexposed one', async () => {
  501. // Deliberately indistinguishable: separating "does not exist" from
  502. // "exists but is not yours to configure" would let a caller enumerate the
  503. // registered namespaces one probe at a time.
  504. const ctx = await harness()
  505. ctx.settings.register(NS, AdapterConfig)
  506. ctx.settings.register(settingsNamespace('some-other-plugin'), z.object({ secretPath: z.string() }))
  507. const api = createApiProxy(ctx, DEFAULTS)
  508. const unknown = expectErr(await api.settings.update(request({ ns: 'unknown-ns', patch: {} })))
  509. const unexposed = expectErr(await api.settings.update(request({ ns: 'some-other-plugin', patch: {} })))
  510. expect(unknown.code).toBe('settings-not-exposed')
  511. expect(unexposed.code).toBe(unknown.code)
  512. expect(unexposed.message.replace('some-other-plugin', 'unknown-ns')).toBe(unknown.message)
  513. })
  514. it('maps a read-only provider refusal onto the same rejection', async () => {
  515. const ctx = await harness({ settings: { readOnly: true } })
  516. ctx.settings.register(NS, AdapterConfig)
  517. const api = createApiProxy(ctx, DEFAULTS)
  518. const value = expectOk(await api.settings.describe(request({})))
  519. expect(value.writable).toBe(false)
  520. const error = expectErr(await api.settings.update(request({ ns: 'llm-deepseek', patch: {} })))
  521. expect(error.code).toBe('settings-rejected')
  522. expect(error.message).toContain('read-only')
  523. })
  524. })
  525. describe('credentials domain', () => {
  526. it('reports an actionable error when no credential provider is mounted', async () => {
  527. const ctx = await harness({ credentials: false })
  528. const api = createApiProxy(ctx, DEFAULTS)
  529. const error = expectErr(await api.credentials.describe(request({ refs: ['A'] })))
  530. expect(error.code).toBe('internal')
  531. expect(error.message).toContain('dsh-credentials-local')
  532. })
  533. it('describes value-free views and flips state through set/unset with frames', async () => {
  534. const ctx = await harness()
  535. const api = createApiProxy(ctx, DEFAULTS)
  536. const before = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  537. expect(before.credentials).toEqual({ OPENAI_API_KEY: { configured: false, writable: true } })
  538. const frames = await collectHost(api, ['host/remote-event'], 2, async () => {
  539. expectOk(await api.credentials.set(request({ ref: 'OPENAI_API_KEY', value: 'sk-secret' })))
  540. const after = expectOk(await api.credentials.describe(request({ refs: ['OPENAI_API_KEY'] })))
  541. expect(after.credentials).toEqual({ OPENAI_API_KEY: { configured: true, source: 'file', writable: true } })
  542. expect(JSON.stringify(after)).not.toContain('sk-secret')
  543. expectOk(await api.credentials.unset(request({ ref: 'OPENAI_API_KEY' })))
  544. })
  545. expect(frames).toEqual([
  546. { type: 'host/remote-event', event: 'credentials/updated', args: ['OPENAI_API_KEY'] },
  547. { type: 'host/remote-event', event: 'credentials/updated', args: ['OPENAI_API_KEY'] },
  548. ])
  549. })
  550. it('maps a shadowed write onto credential-rejected for set and unset alike', async () => {
  551. const ctx = await harness({ credentials: { shadowed: ['DEEPSEEK_API_KEY'] } })
  552. const api = createApiProxy(ctx, DEFAULTS)
  553. const described = expectOk(await api.credentials.describe(request({ refs: ['DEEPSEEK_API_KEY'] })))
  554. expect(described.credentials['DEEPSEEK_API_KEY']).toEqual({ configured: true, source: 'env', writable: false })
  555. const setError = expectErr(await api.credentials.set(request({ ref: 'DEEPSEEK_API_KEY', value: 'x' })))
  556. expect(setError.code).toBe('credential-rejected')
  557. expect(setError.details).toEqual({ ref: 'DEEPSEEK_API_KEY' })
  558. const unsetError = expectErr(await api.credentials.unset(request({ ref: 'DEEPSEEK_API_KEY' })))
  559. expect(unsetError.code).toBe('credential-rejected')
  560. })
  561. })
  562. describe('llm domain', () => {
  563. it('merges the configurable directory with live routes and appends undeclared ones', async () => {
  564. const ctx = await harness({ configurableProviders: false })
  565. ctx.llm.registerConfigurableProviders([
  566. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [] },
  567. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'] },
  568. ])
  569. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash']))
  570. ctx.llm.registerAdapter(['undeclared'], new CatalogAdapter('Undeclared', ['u-1']))
  571. // Only one namespace can answer an interrogation, so the flag follows the
  572. // entry's namespace rather than being assumed for every row.
  573. ctx.llm.registerModelDiscovery('llm-pi-ai', () => Promise.resolve([]))
  574. const api = createApiProxy(ctx, DEFAULTS)
  575. const value = expectOk(await api.llm.providers(request({})))
  576. expect(value.providers).toEqual([
  577. { provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
  578. { provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: false },
  579. // An undeclared live route has no settings address, so nothing can be
  580. // interrogated on its behalf either.
  581. { provider: 'undeclared', displayName: 'Undeclared', settingsNs: '', settingsPath: [], active: true },
  582. ])
  583. })
  584. it('serves the host-scoped catalog with per-provider failures contained', async () => {
  585. const ctx = await harness()
  586. ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', ['deepseek-v4-flash', 'deepseek-v4-pro']))
  587. ctx.llm.registerAdapter(['broken'], new BrokenCatalogAdapter('Broken', []))
  588. const api = createApiProxy(ctx, DEFAULTS)
  589. const value = expectOk(await api.llm.models(request({})))
  590. expect(value.groups).toEqual([{
  591. id: 'deepseek-official',
  592. name: 'DeepSeek',
  593. models: [
  594. { id: 'deepseek-v4-flash', name: 'deepseek-v4-flash' },
  595. { id: 'deepseek-v4-pro', name: 'deepseek-v4-pro' },
  596. ],
  597. }])
  598. expect(value.failures).toEqual([{ id: 'broken', name: 'Broken', message: 'catalog backend down' }])
  599. })
  600. it('forwards llm/adapters-updated at every topology commit point', async () => {
  601. const ctx = await harness()
  602. const api = createApiProxy(ctx, DEFAULTS)
  603. const frames = await collectHost(api, ['host/remote-event'], 2, async () => {
  604. const dispose = ctx.llm.registerAdapter(['deepseek-official'], new CatalogAdapter('DeepSeek', []))
  605. dispose()
  606. return Promise.resolve()
  607. })
  608. expect(frames).toEqual([
  609. { type: 'host/remote-event', event: 'llm/adapters-updated', args: [] },
  610. { type: 'host/remote-event', event: 'llm/adapters-updated', args: [] },
  611. ])
  612. })
  613. })
  614. describe('llm.discoverModels', () => {
  615. it('carries a draft to its namespace and returns candidates without storing anything', async () => {
  616. const ctx = await harness()
  617. const seen: unknown[] = []
  618. ctx.llm.registerModelDiscovery('llm-pi-ai', (probe) => {
  619. seen.push({ baseURL: probe.baseURL, api: probe.api, apiKey: probe.apiKey })
  620. return Promise.resolve([
  621. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  622. { id: 'acme-small' },
  623. ])
  624. })
  625. const api = createApiProxy(ctx, DEFAULTS)
  626. const value = expectOk(await api.llm.discoverModels(request({
  627. settingsNs: 'llm-pi-ai',
  628. baseURL: 'https://gateway.acme.example/v1',
  629. api: 'openai-completions',
  630. apiKey: 'probe-key',
  631. })))
  632. expect(value.models).toEqual([
  633. { id: 'acme-large', name: 'Acme Large', contextWindow: 65_536, maxTokens: 4096 },
  634. { id: 'acme-small' },
  635. ])
  636. expect(seen).toEqual([{
  637. baseURL: 'https://gateway.acme.example/v1',
  638. api: 'openai-completions',
  639. apiKey: 'probe-key',
  640. }])
  641. // Interrogating a draft is a read: no namespace gained a section, and no
  642. // credential reference was written.
  643. expect(expectOk(await api.settings.describe(request({}))).namespaces.map(view => view.ns))
  644. .not.toContain('llm-pi-ai')
  645. })
  646. it('carries the route being edited so an adapter can answer from its own registry', async () => {
  647. const ctx = await harness()
  648. let probe: unknown
  649. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  650. probe = request_
  651. return Promise.resolve([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  652. })
  653. const api = createApiProxy(ctx, DEFAULTS)
  654. const value = expectOk(await api.llm.discoverModels(request({
  655. settingsNs: 'llm-pi-ai',
  656. provider: 'deepseek',
  657. })))
  658. // No endpoint at all: a route the adapter already describes needs none.
  659. expect(probe).toEqual({ provider: 'deepseek' })
  660. expect(value.models).toEqual([{ id: 'from-registry', contextWindow: 65_536, maxTokens: 4096 }])
  661. })
  662. it('omits a credential and protocol the draft does not name', async () => {
  663. const ctx = await harness()
  664. let probe: unknown
  665. ctx.llm.registerModelDiscovery('llm-pi-ai', (request_) => {
  666. probe = request_
  667. return Promise.resolve([])
  668. })
  669. const api = createApiProxy(ctx, DEFAULTS)
  670. expectOk(await api.llm.discoverModels(request({
  671. settingsNs: 'llm-pi-ai',
  672. baseURL: 'https://gateway.acme.example/v1',
  673. })))
  674. // Absent fields stay absent rather than crossing as explicit undefined:
  675. // the adapter distinguishes "no protocol named" from "protocol undefined".
  676. expect(probe).toEqual({ baseURL: 'https://gateway.acme.example/v1' })
  677. })
  678. it('reports a failed interrogation as the form\'s next move, naming no credential', async () => {
  679. const ctx = await harness()
  680. ctx.llm.registerModelDiscovery('llm-pi-ai', () =>
  681. Promise.reject(new Error('https://gateway.acme.example/v1/models answered 401; check the API key')))
  682. const api = createApiProxy(ctx, DEFAULTS)
  683. const error = expectErr(await api.llm.discoverModels(request({
  684. settingsNs: 'llm-pi-ai',
  685. baseURL: 'https://gateway.acme.example/v1',
  686. apiKey: 'wrong',
  687. })))
  688. expect(error.code).toBe('model-discovery-failed')
  689. expect(error.message).toContain('answered 401; check the API key')
  690. expect(error.details).toEqual({ settingsNs: 'llm-pi-ai', baseURL: 'https://gateway.acme.example/v1' })
  691. expect(JSON.stringify(error)).not.toContain('wrong')
  692. })
  693. it('reports a namespace no adapter family serves', async () => {
  694. const ctx = await harness()
  695. const api = createApiProxy(ctx, DEFAULTS)
  696. const error = expectErr(await api.llm.discoverModels(request({
  697. settingsNs: 'llm-deepseek',
  698. baseURL: 'https://api.deepseek.com',
  699. })))
  700. expect(error.code).toBe('model-discovery-failed')
  701. expect(error.message).toContain('no model discovery is registered')
  702. })
  703. })