model-selection-settings.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /** Default-off settings and per-session model-selection decisions. */
  2. import { describe, expect, it, vi } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  5. import { Session, SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
  6. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  7. import { bindScopeParent, createScope, scopeOf, scopeTarget } from '@deepseek-ai/dsh-scope'
  8. import { SettingsProvider } from '@deepseek-ai/dsh-settings'
  9. import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
  10. import InvariantRegistry from '@deepseek-ai/dsh-invariants'
  11. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  12. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  13. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  14. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  15. import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process'
  16. import * as tool from '../src/index.ts'
  17. import * as ToolInvariant from '../src/invariant.ts'
  18. import SubagentModelSelectionConfig, {
  19. SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE,
  20. } from '../src/model-selection-settings.ts'
  21. import {
  22. subagentModelSelectionPolicy,
  23. subagentModelSelectionProjectionDefinition,
  24. } from '../src/model-selection-state.ts'
  25. import { text } from './harness.ts'
  26. const ALLOWED_MODELS = [{ provider: 'alpha', model: 'fast-model' }]
  27. /** Writable in-memory settings provider for the package integration. */
  28. class MemorySettings extends SettingsProvider {
  29. doc: Record<string, unknown> = {}
  30. get writable(): boolean {
  31. return true
  32. }
  33. protected load(): Promise<Record<string, unknown>> {
  34. return Promise.resolve(structuredClone(this.doc))
  35. }
  36. protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
  37. this.doc = { ...this.doc, [ns]: structuredClone(section) }
  38. return Promise.resolve()
  39. }
  40. }
  41. /** Read whether one Agent's delegation definition contains route fields. */
  42. function selectable(ctx: Context, agent: Awaited<ReturnType<Context['agents']['create']>>['agent']): boolean {
  43. const schema = ctx.tools.schemas(agent).find(candidate => candidate.name === 'subagent')
  44. const properties = (schema?.parameters as { properties?: Record<string, unknown> } | undefined)?.properties
  45. return properties?.['provider'] !== undefined
  46. && properties['model'] !== undefined
  47. && properties['reasoning_effort'] !== undefined
  48. && ctx.tools.schemas(agent).some(candidate => candidate.name === 'list_subagent_models')
  49. }
  50. const modelSelectionPresets = new WeakMap<Context, ReturnType<typeof createScope>>()
  51. /** Mount the real settings, Agent, provider, and optional preset tool services. */
  52. async function boot(withPreset = true): Promise<Context> {
  53. const ctx = new Context()
  54. await ctx.plugin(MemorySettings)
  55. await ctx.plugin(SubagentModelSelectionConfig)
  56. await mountAgentLoopTestDependencies(ctx)
  57. await ctx.plugin(AgentLoop, { agents: [] })
  58. await ctx.plugin(SubagentRuntime)
  59. await ctx.plugin(SubagentSpawn, { providerName: 'spawn' })
  60. if (withPreset) {
  61. const preset = createScope(ctx, { preset: 'model-selection-test' })
  62. await preset.ctx.plugin(tool, {
  63. provider: 'spawn',
  64. modelSelectionSettings: true,
  65. backgroundMode: 'continuable',
  66. })
  67. modelSelectionPresets.set(ctx, preset)
  68. }
  69. return ctx
  70. }
  71. /** Create one Agent joined to the test's standing preset. */
  72. async function createAgent(ctx: Context, id: string, options: {
  73. meta?: { parentSession: SessionId; origin: 'subagent' }
  74. seed?: readonly SessionEvent[]
  75. } = {}) {
  76. const preset = modelSelectionPresets.get(ctx)
  77. if (preset === undefined) throw new Error('context has no model-selection preset')
  78. const handle = await ctx.agents.create({
  79. sessionId: SessionId(id),
  80. ...options,
  81. setup: (agentCtx) => {
  82. bindScopeParent(scopeOf(agentCtx)!, scopeOf(preset.ctx)!)
  83. },
  84. })
  85. return handle.agent
  86. }
  87. describe('SubagentModelSelectionConfig', () => {
  88. it('uses the composed default without a settings provider', async () => {
  89. const ctx = new Context()
  90. await ctx.plugin(SubagentModelSelectionConfig, { enabled: true, allowedModels: ALLOWED_MODELS })
  91. expect(ctx.subagentModelSelection.current()).toEqual({ enabled: true, allowedModels: ALLOWED_MODELS })
  92. await ctx.fiber.dispose()
  93. })
  94. it('defaults off and follows the validated user layer', async () => {
  95. const ctx = new Context()
  96. await ctx.plugin(MemorySettings)
  97. await ctx.plugin(SubagentModelSelectionConfig)
  98. expect(ctx.subagentModelSelection.current()).toEqual({ enabled: false, allowedModels: [] })
  99. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  100. enabled: true,
  101. allowedModels: ALLOWED_MODELS,
  102. })
  103. expect(ctx.subagentModelSelection.current()).toEqual({ enabled: true, allowedModels: ALLOWED_MODELS })
  104. await ctx.fiber.dispose()
  105. })
  106. it('rejects duplicate routes, enabled empty settings, and an empty durable policy', async () => {
  107. const ctx = new Context()
  108. await ctx.plugin(MemorySettings)
  109. await ctx.plugin(SubagentModelSelectionConfig)
  110. await ctx.plugin(SessionProjectionRegistry)
  111. ctx.sessionProjections.register(subagentModelSelectionProjectionDefinition)
  112. await expect(ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  113. allowedModels: [...ALLOWED_MODELS, ...ALLOWED_MODELS],
  114. })).rejects.toThrow('repeats route "alpha/fast-model"')
  115. await expect(ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  116. enabled: true,
  117. allowedModels: [],
  118. })).rejects.toThrow('enabled subagent model selection requires at least one allowed model')
  119. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  120. enabled: false,
  121. allowedModels: ALLOWED_MODELS,
  122. })
  123. expect(ctx.subagentModelSelection.current()).toEqual({ enabled: false, allowedModels: ALLOWED_MODELS })
  124. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { allowedModels: [] })
  125. expect(ctx.subagentModelSelection.current()).toEqual({ enabled: false, allowedModels: [] })
  126. const invalid = Session.create(SessionId('empty-policy'))
  127. invalid.append('subagent/model-selection-policy', { allowedModels: [] })
  128. expect(() => subagentModelSelectionPolicy(ctx.sessionProjections, invalid)).toThrow('requires at least one route')
  129. const malformed = Session.create(SessionId('malformed-policy'))
  130. malformed.append('subagent/model-selection-policy', {
  131. allowedModels: [{ provider: 1, model: 'fast-model' }],
  132. } as never)
  133. expect(() => subagentModelSelectionPolicy(ctx.sessionProjections, malformed))
  134. .toThrow('requires non-empty provider and model ids')
  135. await ctx.fiber.dispose()
  136. })
  137. it('samples each new root Session without changing existing definitions', async () => {
  138. const ctx = await boot()
  139. const disabled = await createAgent(ctx, 'disabled')
  140. expect(selectable(ctx, disabled)).toBe(false)
  141. expect(subagentModelSelectionPolicy(ctx.sessionProjections, disabled.session)).toBeUndefined()
  142. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  143. enabled: true,
  144. allowedModels: ALLOWED_MODELS,
  145. })
  146. const enabled = await createAgent(ctx, 'enabled')
  147. expect(subagentModelSelectionPolicy(ctx.sessionProjections, enabled.session)).toEqual(ALLOWED_MODELS)
  148. expect(selectable(ctx, enabled)).toBe(true)
  149. expect(selectable(ctx, disabled)).toBe(false)
  150. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false })
  151. const disabledAgain = await createAgent(ctx, 'disabled-again')
  152. expect(selectable(ctx, disabledAgain)).toBe(false)
  153. expect(selectable(ctx, enabled)).toBe(true)
  154. await ctx.fiber.dispose()
  155. })
  156. it('installs a direct Agent setup before Session publication', async () => {
  157. const ctx = await boot(false)
  158. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  159. enabled: true,
  160. allowedModels: ALLOWED_MODELS,
  161. })
  162. let prepared: Awaited<ReturnType<Context['agents']['create']>>['agent'] | undefined
  163. let visibleAtSessionCreated = false
  164. ctx.on('session/created', () => {
  165. visibleAtSessionCreated = prepared !== undefined && selectable(ctx, prepared)
  166. })
  167. const handle = await ctx.agents.create({
  168. sessionId: SessionId('direct-agent-setup'),
  169. setup: async (agentCtx, agent) => {
  170. prepared = agent
  171. const fiber = agentCtx.inject(tool.inject, (runtimeCtx) => {
  172. tool.apply(runtimeCtx, {
  173. provider: 'spawn',
  174. modelSelectionSettings: true,
  175. backgroundMode: 'continuable',
  176. }, agent.session)
  177. })
  178. await fiber.await()
  179. },
  180. })
  181. expect(visibleAtSessionCreated).toBe(true)
  182. expect(selectable(ctx, handle.agent)).toBe(true)
  183. await handle.dispose()
  184. await ctx.fiber.dispose()
  185. })
  186. it('rejects a forced route outside the Session policy before child creation', async () => {
  187. const ctx = await boot()
  188. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  189. enabled: true,
  190. allowedModels: ALLOWED_MODELS,
  191. })
  192. const agent = await createAgent(ctx, 'enforced')
  193. const result = await ctx.tools.execute({
  194. signal: new AbortController().signal,
  195. callId: ToolCallId('disallowed-session-route'),
  196. name: 'subagent',
  197. arguments: {
  198. description: 'forced route',
  199. prompt: 'do it',
  200. provider: 'alpha',
  201. model: 'other-model',
  202. },
  203. agent,
  204. })
  205. expect(result.isError).toBe(true)
  206. expect(text(result)).toContain('is not allowed for this Session')
  207. await ctx.fiber.dispose()
  208. })
  209. it('installs per-Agent definitions for a shared preset scope', async () => {
  210. const ctx = await boot(false)
  211. await ctx.plugin(InvariantRegistry, { enabled: true })
  212. await ctx.plugin(ToolInvariant)
  213. const preset = createScope(ctx, { preset: 'standard' })
  214. const other = createScope(ctx, { preset: 'minimal' })
  215. await preset.ctx.plugin(tool, {
  216. provider: 'spawn',
  217. modelSelectionSettings: true,
  218. backgroundMode: 'continuable',
  219. })
  220. let enabledBinding: ReturnType<typeof bindScopeParent> | undefined
  221. const createComposed = async (id: string) => ctx.agents.create({
  222. sessionId: SessionId(id),
  223. setup: (agentCtx) => {
  224. const binding = bindScopeParent(scopeOf(agentCtx)!, scopeOf(preset.ctx)!)
  225. if (id === 'preset-enabled') enabledBinding = binding
  226. },
  227. })
  228. const disabled = await createComposed('preset-disabled')
  229. expect(selectable(ctx, disabled.agent)).toBe(false)
  230. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  231. enabled: true,
  232. allowedModels: ALLOWED_MODELS,
  233. })
  234. const enabled = await createComposed('preset-enabled')
  235. expect(selectable(ctx, enabled.agent)).toBe(true)
  236. expect(selectable(ctx, disabled.agent)).toBe(false)
  237. enabledBinding!.rebind(scopeOf(other.ctx)!)
  238. ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change')
  239. await vi.waitFor(() => { expect(selectable(ctx, enabled.agent)).toBe(false) })
  240. const next = () => Promise.resolve({ kind: 'enter' as const, messages: [] })
  241. const payload = {
  242. agent: enabled.agent,
  243. messages: [],
  244. turn: 1,
  245. step: 1,
  246. signal: new AbortController().signal,
  247. }
  248. await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next))
  249. .resolves.toEqual({ kind: 'enter', messages: [] })
  250. enabledBinding!.rebind(scopeOf(preset.ctx)!)
  251. ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change')
  252. await vi.waitFor(() => { expect(selectable(ctx, enabled.agent)).toBe(true) })
  253. await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next))
  254. .resolves.toEqual({ kind: 'enter', messages: [] })
  255. await enabled.dispose()
  256. ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change')
  257. await disabled.dispose()
  258. await ctx.fiber.dispose()
  259. })
  260. it('releases a shared-preset installation reservation after policy selection fails', async () => {
  261. const ctx = await boot(false)
  262. const preset = createScope(ctx, { preset: 'standard' })
  263. const other = createScope(ctx, { preset: 'minimal' })
  264. await preset.ctx.plugin(tool, {
  265. provider: 'spawn',
  266. modelSelectionSettings: true,
  267. backgroundMode: 'continuable',
  268. })
  269. let binding: ReturnType<typeof bindScopeParent> | undefined
  270. const handle = await ctx.agents.create({
  271. sessionId: SessionId('preset-policy-retry'),
  272. setup: (agentCtx) => {
  273. binding = bindScopeParent(scopeOf(agentCtx)!, scopeOf(preset.ctx)!)
  274. },
  275. })
  276. expect(selectable(ctx, handle.agent)).toBe(false)
  277. binding!.rebind(scopeOf(other.ctx)!)
  278. ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change')
  279. binding!.rebind(scopeOf(preset.ctx)!)
  280. vi.spyOn(ctx.subagentModelSelection, 'current')
  281. .mockImplementationOnce(() => { throw new Error('transient settings read') })
  282. .mockReturnValue({ enabled: true, allowedModels: ALLOWED_MODELS })
  283. expect(() => { ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change') })
  284. .toThrow('transient settings read')
  285. ctx.emit(scopeTarget({}, scopeOf(preset.ctx)), 'tools/change')
  286. await vi.waitFor(() => { expect(selectable(ctx, handle.agent)).toBe(true) })
  287. await handle.dispose()
  288. await ctx.fiber.dispose()
  289. })
  290. it('inherits the parent decision and preserves seeded decisions across composition', async () => {
  291. const ctx = await boot()
  292. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  293. enabled: true,
  294. allowedModels: ALLOWED_MODELS,
  295. })
  296. const parent = await createAgent(ctx, 'parent')
  297. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false })
  298. const child = await createAgent(ctx, 'child', {
  299. meta: { parentSession: parent.id, origin: 'subagent' },
  300. })
  301. expect(selectable(ctx, child)).toBe(true)
  302. expect(subagentModelSelectionPolicy(ctx.sessionProjections, child.session)).toEqual(ALLOWED_MODELS)
  303. const orphan = await createAgent(ctx, 'orphan', {
  304. meta: { parentSession: SessionId('missing-parent'), origin: 'subagent' },
  305. })
  306. expect(selectable(ctx, orphan)).toBe(false)
  307. const enabledSeed = Session.create(SessionId('enabled-seed'))
  308. enabledSeed.append('subagent/model-selection-policy', { allowedModels: ALLOWED_MODELS })
  309. const resumedEnabled = await createAgent(ctx, 'resumed-enabled', { seed: enabledSeed.snapshotEvents() })
  310. expect(selectable(ctx, resumedEnabled)).toBe(true)
  311. const oldSeed = Session.create(SessionId('old-seed'), [])
  312. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  313. enabled: true,
  314. allowedModels: ALLOWED_MODELS,
  315. })
  316. const resumedEmpty = await createAgent(ctx, 'resumed-empty', { seed: [] })
  317. expect(selectable(ctx, resumedEmpty)).toBe(false)
  318. expect(subagentModelSelectionPolicy(ctx.sessionProjections, resumedEmpty.session)).toBeUndefined()
  319. const resumedDisabled = await createAgent(ctx, 'resumed-disabled', { seed: oldSeed.snapshotEvents() })
  320. expect(selectable(ctx, resumedDisabled)).toBe(false)
  321. expect(subagentModelSelectionPolicy(ctx.sessionProjections, resumedDisabled.session)).toBeUndefined()
  322. await ctx.fiber.dispose()
  323. })
  324. it('requires both the Host setting owner and a scoped standing preset', async () => {
  325. const withoutSettings = new Context()
  326. await mountAgentLoopTestDependencies(withoutSettings)
  327. await withoutSettings.plugin(SubagentRuntime)
  328. expect(() => {
  329. tool.apply(withoutSettings, {
  330. provider: 'missing',
  331. modelSelectionSettings: true,
  332. maxDepth: 'provider-managed',
  333. })
  334. }).toThrow('requires @deepseek-ai/dsh-tool-subagent/model-selection-settings')
  335. await withoutSettings.fiber.dispose()
  336. const withoutAgent = await boot(false)
  337. expect(() => {
  338. tool.apply(withoutAgent, {
  339. provider: 'spawn',
  340. modelSelectionSettings: true,
  341. backgroundMode: 'continuable',
  342. })
  343. }).toThrow('requires a scoped preset Context')
  344. await withoutAgent.fiber.dispose()
  345. })
  346. it('requires the Session registry when a child inherits its parent policy', async () => {
  347. const ctx = new Context()
  348. try {
  349. await ctx.plugin(SubagentModelSelectionConfig)
  350. await ctx.plugin(SessionProjectionRegistry)
  351. await ctx.plugin(SubagentRuntime)
  352. const childId = SessionId('child-without-session-registry')
  353. const child = Session.create(childId, undefined, {
  354. version: SESSION_FORMAT_VERSION,
  355. id: childId,
  356. createdAt: 1,
  357. isSeeded: false,
  358. origin: 'subagent',
  359. parentSession: SessionId('missing-parent'),
  360. })
  361. expect(() => {
  362. tool.apply(ctx, {
  363. provider: 'missing',
  364. modelSelectionSettings: true,
  365. maxDepth: 'provider-managed',
  366. }, child)
  367. }).toThrow('child model-selection inheritance requires the Session registry')
  368. } finally {
  369. await ctx.fiber.dispose()
  370. }
  371. })
  372. it('checks model-selectable definitions without rejecting a policy-only preset', async () => {
  373. const ctx = await boot()
  374. await ctx.plugin(InvariantRegistry, { enabled: true })
  375. await ctx.plugin(ToolInvariant)
  376. const disabled = await createAgent(ctx, 'invariant-disabled')
  377. const next = () => Promise.resolve({ kind: 'enter' as const, messages: [] })
  378. const payload = {
  379. agent: disabled,
  380. messages: [],
  381. turn: 1,
  382. step: 1,
  383. signal: new AbortController().signal,
  384. }
  385. await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next)).resolves.toEqual({
  386. kind: 'enter', messages: [],
  387. })
  388. disabled.session.append('subagent/model-selection-policy', { allowedModels: ALLOWED_MODELS })
  389. await expect(ctx.waterfall(ctx as never, 'agent/pre-step', payload, next))
  390. .resolves.toEqual({ kind: 'enter', messages: [] })
  391. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, {
  392. enabled: true,
  393. allowedModels: ALLOWED_MODELS,
  394. })
  395. const enabled = await createAgent(ctx, 'invariant-enabled')
  396. await expect(ctx.waterfall(ctx as never, 'agent/pre-step', { ...payload, agent: enabled }, next))
  397. .resolves.toEqual({ kind: 'enter', messages: [] })
  398. const enabledSchemas = ctx.tools.schemas(enabled)
  399. const schemas = vi.spyOn(ctx.tools, 'schemas')
  400. schemas.mockReturnValue(enabledSchemas.filter(schema => schema.name !== 'list_subagent_models'))
  401. await expect(ctx.waterfall(ctx as never, 'agent/pre-step', { ...payload, agent: enabled }, next))
  402. .rejects.toThrow('require a durable policy, route fields, and list_subagent_models')
  403. schemas.mockReturnValue(enabledSchemas)
  404. await ctx.settings.update(SUBAGENT_MODEL_SELECTION_SETTINGS_NAMESPACE, { enabled: false })
  405. const withoutPolicy = await createAgent(ctx, 'invariant-without-policy')
  406. await expect(ctx.waterfall(ctx as never, 'agent/pre-step', { ...payload, agent: withoutPolicy }, next))
  407. .rejects.toThrow('require a durable policy, route fields, and list_subagent_models')
  408. await ctx.fiber.dispose()
  409. })
  410. })