web-agent-presets.e2e.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. import { randomUUID } from 'node:crypto'
  2. import { mkdir, mkdtemp, readFile, stat, writeFile } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { fileURLToPath } from 'node:url'
  5. import { dirname, join } from 'node:path'
  6. import { Context } from '@deepseek-ai/cordis'
  7. import { boot, healProfilesModuleFallback, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
  8. import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
  9. import { SessionId } from '@deepseek-ai/dsh-session'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  12. import { afterAll, beforeAll, describe, expect, it } from 'vitest'
  13. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  14. import { resolveSessionPreset, SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-agent-presets'
  15. import { applyChildComposition, childSessionMeta } from '@deepseek-ai/dsh-subagent'
  16. import { CallId } from '@deepseek-ai/dsh-llm'
  17. import type { BasicCompactService } from '@deepseek-ai/dsh-compact-basic'
  18. import type {} from '@deepseek-ai/dsh-skill'
  19. import type {} from '@deepseek-ai/dsh-tools'
  20. const CONFIG_DIR = fileURLToPath(new URL('../config/', import.meta.url))
  21. const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  22. /** The shipped Web surface: the dsh-base and dsh-web-app bundle patches over an empty preset root. */
  23. const BASE_PATCH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  24. const WEB_PATCH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  25. /** The installation anchor whose dependency surface the preset module fallback mirrors. */
  26. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  27. const MINIMAL_PROMPT = 'You are a helpful software engineer assistant.'
  28. const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell
  29. * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.
  30. * You don't have access to the internet via this tool.
  31. * You do have access to a mirror of common linux and python packages via apt and pip.
  32. * State is persistent across command calls and discussions with the user.
  33. * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.
  34. * Please avoid commands that may produce a very large amount of output.
  35. * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.`
  36. /**
  37. * Boot the shipped Web composition, minus the rows that would bind a port,
  38. * touch the network, or write outside the test. Everything that decides an
  39. * agent's capabilities is the real thing, including both shipped presets.
  40. */
  41. async function bootWeb(settingsFile: string, extra: PatchOptions[] = []): Promise<Context> {
  42. const storageRoot = join(dirname(settingsFile), 'storages')
  43. const patches: PatchOptions[] = [
  44. ...loadOverlayPatches('dsh-test', BASE_PATCH),
  45. ...loadOverlayPatches('dsh-test', WEB_PATCH),
  46. // The settings row defaults to `$DSH_HOME/settings.yaml`. Left alone it
  47. // reads the developer's own document — and since the default preset is a
  48. // setting, a stored `agent-presets.default` would decide this file's
  49. // outcome. Point it at a temp file for the same reason the roster below
  50. // names only the shipped root.
  51. { id: 'settings', config: { path: settingsFile, watch: false } },
  52. // storage-json's root is anchored to the real $DSH_HOME. Unpinned, this
  53. // file writes the developer's own `~/.dsh/storages/` — and then reads it
  54. // back on the next run, so a stored document from any other build decides
  55. // this test's boot. Same reason the settings row above is pinned.
  56. { id: 'storage-json', config: { root: storageRoot } },
  57. // Host rows with side effects outside this process: a bound port, a served
  58. // asset tree, a telemetry exporter. `api-gateway` and `directory-picker`
  59. // stay ENABLED on purpose — the api-proxy is the host row that injects
  60. // `subagents`, `workspace`, and the rest of the agent plane, so disabling
  61. // it would hide exactly the breakage this file exists to catch: a service
  62. // moved into the presets that a host row still waits for. The boot audit
  63. // is that assertion.
  64. { id: 'webserver', disabled: true },
  65. // The web bundle's runtime row injects `httpServer`, so it cannot
  66. // activate without the bound port disabled above. It owns dist serving
  67. // and the URL prompt line — surface glue, not anything that decides an
  68. // agent's capabilities, which is all this file asserts.
  69. { id: 'web-runtime', disabled: true },
  70. { id: 'telemetry-otel', disabled: true },
  71. // A deployment-level skill on the host registry's GLOBAL layer — the same
  72. // registration shape a repository plugin's skill root uses. The layered
  73. // skills test below proves it reaches preset-composed agents.
  74. { id: 'skill-badge', disabled: false },
  75. { id: 'modules', disabled: true },
  76. { id: 'connection', disabled: true },
  77. // The shipped `-auto` chooser resolves its interaction from a running
  78. // host and so waits for the webserver disabled above; the browse variant
  79. // supplies `directoryPicker` without one.
  80. { id: 'directory-picker', disabled: true },
  81. { insert: [{ id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' }] },
  82. // The roster AppCLIEntry would patch in; only the shipped root, so a
  83. // developer's own `~/.dsh/.preset` cannot change this test's outcome.
  84. // `default` here is the COMPOSITION default — the base layer the settings
  85. // document overrides.
  86. {
  87. id: 'agent-presets',
  88. config: { default: 'standard', roots: [{ path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' }] },
  89. },
  90. ...extra,
  91. ]
  92. // The surface is patch layers over an empty preset root, so the root sits
  93. // outside this workspace and bare plugin names cannot resolve by Node's
  94. // upward walk. The flat fallback the preset boot maintains is what makes
  95. // them resolvable — the same mechanism, not a test-only shim.
  96. const home = dirname(settingsFile)
  97. healProfilesModuleFallback(INSTALL_ANCHOR, home)
  98. const profileDir = join(home, 'profiles', 'spec')
  99. await mkdir(profileDir, { recursive: true })
  100. const rootConfig = join(profileDir, 'cordis.yml')
  101. await writeFile(rootConfig, '[]\n')
  102. return await boot('dsh-test', rootConfig, patches, (bootCtx) => {
  103. provideCmdline(bootCtx, { args: [], exit: () => {} })
  104. })
  105. }
  106. const toolNames = (ctx: Context, agent?: Agent): string[] =>
  107. ctx.tools.schemas(agent).map(schema => schema.name).sort()
  108. function enablePresetTool(composition: string, id: string): string {
  109. const row = ` - id: ${id}\n`
  110. const start = composition.indexOf(row)
  111. if (start < 0) throw new Error(`missing preset row ${id}`)
  112. const end = composition.indexOf('\n - id:', start + row.length)
  113. const disabled = composition.indexOf(' disabled: true\n', start)
  114. if (disabled < 0 || (end >= 0 && disabled > end)) {
  115. throw new Error(`preset row ${id} is not disabled`)
  116. }
  117. return composition.slice(0, disabled) + composition.slice(disabled + ' disabled: true\n'.length)
  118. }
  119. let ctx: Context
  120. beforeAll(async () => {
  121. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-web-presets-')), 'settings.yaml')
  122. await writeFile(settingsFile, '{}\n')
  123. ctx = await bootWeb(settingsFile)
  124. }, 120_000)
  125. describe('the shipped Web composition', () => {
  126. it('leaves the global tool layer empty', () => {
  127. // Every model-facing tool belongs to a preset, `ask_user_question`
  128. // included: a tool in the global layer reaches EVERY agent regardless of
  129. // which preset composed it, so a two-tool benchmark surface would really
  130. // present three. A regression here means an agent-plane row came back to
  131. // the host composition.
  132. expect(toolNames(ctx)).toEqual([])
  133. })
  134. it('supplies both shipped presets, and only those, from the system root', async () => {
  135. const listed = await ctx.agentPresets.list()
  136. expect(listed.map(preset => preset.id).sort()).toEqual(['code', 'cordis', 'minimal', 'standard'])
  137. expect(listed.every(preset => preset.trust === 'system')).toBe(true)
  138. expect(ctx.agentPresets.defaultId).toBe('standard')
  139. })
  140. it('composes the full agent from `standard`', async () => {
  141. const handle = await ctx.agents.create({
  142. sessionId: SessionId('preset-standard'),
  143. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  144. })
  145. try {
  146. // The EXACT catalog, not a spot-check: an omission is this design's
  147. // quietest failure mode, because a row that registers into the wrong
  148. // layer mounts cleanly and simply contributes nothing. `glob`/`grep` are
  149. // excluded for the reason the TUI composition e2e excludes them — they
  150. // depend on ripgrep being present on the machine.
  151. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
  152. 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
  153. 'get_goal', 'interrupt_agent', 'list_agents', 'ralph', 'read', 'send_message', 'skill',
  154. 'subagent', 'subagent_fork', 'task_kill',
  155. 'task_list', 'task_output', 'todo_write', 'update_goal', 'web_search',
  156. 'workflow', 'write',
  157. ])
  158. } finally {
  159. await handle.dispose()
  160. }
  161. })
  162. it('composes the exact RL prompt and two tools from `minimal`', async () => {
  163. const handle = await ctx.agents.create({
  164. sessionId: SessionId('preset-minimal'),
  165. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  166. })
  167. try {
  168. const assembly = await ctx.systemPrompt.assemble({ scope: handle.agent })
  169. expect(assembly.sections).toEqual([
  170. { name: 'deployment:persona', text: MINIMAL_PROMPT },
  171. ])
  172. expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'str_replace_editor'])
  173. expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION)
  174. expect(JSON.stringify(assembly.tools.find(tool => tool.name === 'str_replace_editor')?.parameters))
  175. .toContain('Absolute path')
  176. const compact = ctx.agentPresets.serviceFor(handle.agent, 'compact')
  177. expect(compact).toBeDefined()
  178. expect((compact as BasicCompactService).config).toMatchObject({
  179. thresholdRatio: 0.8,
  180. retainTokens: 20480,
  181. summarizationProvider: '',
  182. summarizationModel: '',
  183. maxTokens: 8192,
  184. compactionRetries: 1,
  185. })
  186. } finally {
  187. await handle.dispose()
  188. }
  189. })
  190. it('keeps two differently composed sessions independent', async () => {
  191. const full = await ctx.agents.create({
  192. sessionId: SessionId('preset-both-full'),
  193. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  194. })
  195. const minimal = await ctx.agents.create({
  196. sessionId: SessionId('preset-both-minimal'),
  197. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  198. })
  199. try {
  200. expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'str_replace_editor'])
  201. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  202. await minimal.dispose()
  203. // Tearing the minimal session down leaves the full one whole.
  204. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  205. expect(toolNames(ctx)).toEqual([])
  206. } finally {
  207. await full.dispose()
  208. }
  209. })
  210. it('composes the cordis agent with its own toolset', async () => {
  211. const handle = await ctx.agents.create({
  212. sessionId: SessionId('preset-cordis'),
  213. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined),
  214. })
  215. try {
  216. const tools = toolNames(ctx, handle.agent)
  217. // The self-referential toolset is what distinguishes this preset.
  218. expect(tools).toEqual(expect.arrayContaining(['cordis_inspect', 'cordis_mount', 'cordis_unmount']))
  219. // And it keeps the standard agent's own tools rather than replacing them.
  220. expect(tools).toEqual(expect.arrayContaining(['bash', 'read', 'edit', 'skill']))
  221. expect(tools).not.toContain('str_replace_editor')
  222. // The preset's own authoring skill registers into ITS layer of the host
  223. // registry: the cordis agent's view carries it, the global view does not.
  224. const scoped = (await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)
  225. expect(scoped).toContain('editing-cordis-compositions')
  226. expect((await ctx.skills.list()).map(skill => skill.name)).not.toContain('editing-cordis-compositions')
  227. } finally {
  228. await handle.dispose()
  229. }
  230. })
  231. it('presents `code` as Code Mode without disturbing a native session beside it', async () => {
  232. const coded = await ctx.agents.create({
  233. sessionId: SessionId('preset-code'),
  234. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'code').then(() => undefined),
  235. })
  236. const native = await ctx.agents.create({
  237. sessionId: SessionId('preset-code-native'),
  238. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  239. })
  240. try {
  241. // One tool reaches the MODEL: the transport. The registry's catalog for
  242. // this agent is unchanged — a code mode collapses the presentation, not
  243. // the capabilities — so the assembly is what carries the claim.
  244. const assembly = await ctx.systemPrompt.assemble({ scope: coded.agent })
  245. expect(assembly.tools.map(tool => tool.name)).toEqual(['run_code'])
  246. expect(toolNames(ctx, coded.agent)).not.toContain('str_replace_editor')
  247. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  248. expect(sdk).not.toContain('str_replace_editor')
  249. expect(sdk).toContain('web_search')
  250. // The presentation is this agent's alone: the deployment default is
  251. // native, and the session composed from `standard` still sees it.
  252. const nativeAssembly = await ctx.systemPrompt.assemble({ scope: native.agent })
  253. expect(nativeAssembly.tools.map(tool => tool.name)).toContain('bash')
  254. expect(nativeAssembly.tools.map(tool => tool.name)).not.toContain('run_code')
  255. expect(nativeAssembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  256. } finally {
  257. await native.dispose()
  258. await coded.dispose()
  259. }
  260. })
  261. it('keeps the self-referential toolset out of every other preset', async () => {
  262. const handle = await ctx.agents.create({
  263. sessionId: SessionId('preset-no-cordis'),
  264. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  265. })
  266. try {
  267. // Editing the live runtime is opt-in per session, not ambient.
  268. expect(toolNames(ctx, handle.agent)).not.toContain('cordis_mount')
  269. } finally {
  270. await handle.dispose()
  271. }
  272. })
  273. it('ships the composition-authoring skill inside the preset directory', async () => {
  274. // The preset's skill root is derived from its own `baseUrl`, so the skill
  275. // travels with the directory wherever the preset is installed.
  276. const skill = join(
  277. CONFIG_DIR, 'agent-presets', 'cordis', 'skills', 'editing-cordis-compositions', 'SKILL.md',
  278. )
  279. expect((await readFile(skill, 'utf8')).startsWith('---\nname: editing-cordis-compositions')).toBe(true)
  280. })
  281. it('merges the global skill layer into a preset agent\'s catalog, keeping local discovery preset-side', async () => {
  282. const proj = await mkdtemp(join(tmpdir(), 'dsh-preset-skill-proj-'))
  283. await mkdir(join(proj, '.dsh', 'skills', 'project-proof'), { recursive: true })
  284. await writeFile(join(proj, '.dsh', 'skills', 'project-proof', 'SKILL.md'), [
  285. '---',
  286. 'name: project-proof',
  287. 'description: Proves the preset layer discovers project skills beside global ones.',
  288. '---',
  289. '',
  290. 'Project proof body.',
  291. '',
  292. ].join('\n'))
  293. const handle = await ctx.agents.create({
  294. // Unique per run: the composition persists into the ambient DSH home,
  295. // and a fixed id would collide with a log an earlier run left there.
  296. sessionId: SessionId(`preset-skills-standard-${randomUUID()}`),
  297. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  298. })
  299. try {
  300. // The host (global) view carries the deployment-level provider alone:
  301. // local discovery moved behind the presets with `skill-local`.
  302. expect((await ctx.skills.list({ cwd: proj })).map(skill => skill.name)).toEqual(['dsh-badge'])
  303. // The standard agent's view merges the global layer with its preset's
  304. // own local discovery over the session cwd.
  305. const scoped = (await ctx.skills.list({ cwd: proj, scope: handle.agent })).map(skill => skill.name)
  306. expect(scoped).toContain('dsh-badge')
  307. expect(scoped).toContain('project-proof')
  308. // The preset's own loader tool resolves the global-layer skill.
  309. const loaded = await ctx.tools.execute({
  310. callId: CallId('preset-skills-load'),
  311. name: 'skill',
  312. arguments: { name: 'dsh-badge' },
  313. signal: new AbortController().signal,
  314. agent: handle.agent,
  315. })
  316. expect(loaded.isError).toBe(false)
  317. expect(JSON.stringify(loaded.content)).toContain('powered by dsh')
  318. } finally {
  319. await handle.dispose()
  320. }
  321. })
  322. it('shows a minimal agent the global layer but no loader tool', async () => {
  323. const handle = await ctx.agents.create({
  324. sessionId: SessionId(`preset-skills-minimal-${randomUUID()}`),
  325. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  326. })
  327. try {
  328. // Layer visibility is the registry's; whether an agent can USE skills
  329. // stays the preset's choice — minimal mounts no `tool-skill`, so its
  330. // tool table has no loader even though the global layer is readable.
  331. expect((await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)).toContain('dsh-badge')
  332. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  333. } finally {
  334. await handle.dispose()
  335. }
  336. })
  337. it('never rewrites the preset file it composed from', async () => {
  338. // The Loader persists a tree whose plugin self-disposed, and tearing an
  339. // agent down disposes its whole subtree. Inherited, that rewrote the
  340. // shipped composition — truncating it to `[]` the first time a session
  341. // ended — so `PresetTree` refuses to write at all.
  342. const path = join(CONFIG_DIR, 'agent-presets', 'standard', 'agent.cordis.yml')
  343. const before = await readFile(path, 'utf8')
  344. const handle = await ctx.agents.create({
  345. sessionId: SessionId('preset-readonly'),
  346. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  347. })
  348. await handle.dispose()
  349. // Slack, not a race the number has to win. The write is driven by the
  350. // Loader's fiber-unload listener, which fires as the subtree's fibers
  351. // settle rather than when `dispose()` resolves, and the Loader exposes no
  352. // flush to await. A regression writes synchronously inside that listener,
  353. // so any wait past settlement fails; a longer one only slows the test.
  354. await new Promise(resolve => setTimeout(resolve, 50))
  355. expect(await readFile(path, 'utf8')).toBe(before)
  356. })
  357. })
  358. describe('product subagent rows in user presets', () => {
  359. let productCtx: Context
  360. const ids = ['products-none', 'products-codex', 'products-claude', 'products-both'] as const
  361. beforeAll(async () => {
  362. const root = await mkdtemp(join(tmpdir(), 'dsh-product-presets-'))
  363. const userRoot = join(root, 'presets')
  364. const settingsFile = join(root, 'settings.yaml')
  365. const standard = await readFile(join(CONFIG_DIR, 'agent-presets', 'standard', 'agent.cordis.yml'), 'utf8')
  366. await writeFile(settingsFile, '{}\n')
  367. for (const id of ids) {
  368. let composition = standard
  369. if (id === 'products-codex' || id === 'products-both') {
  370. composition = enablePresetTool(composition, 'tool-subagent-codex')
  371. }
  372. if (id === 'products-claude' || id === 'products-both') {
  373. composition = enablePresetTool(composition, 'tool-subagent-claude-code')
  374. }
  375. const directory = join(userRoot, id)
  376. await mkdir(directory, { recursive: true })
  377. await writeFile(join(directory, 'agent.cordis.yml'), composition)
  378. }
  379. productCtx = await bootWeb(settingsFile, [{
  380. id: 'agent-presets',
  381. config: {
  382. default: 'standard',
  383. roots: [
  384. { path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' },
  385. { path: userRoot, trust: 'user' },
  386. ],
  387. },
  388. }])
  389. }, 120_000)
  390. afterAll(async () => {
  391. await productCtx.fiber.dispose()
  392. })
  393. it('composes none, either product, or both without changing the shared host registry', async () => {
  394. const expected = new Map<string, string[]>([
  395. ['products-none', []],
  396. ['products-codex', ['subagent_codex']],
  397. ['products-claude', ['subagent_claude_code']],
  398. ['products-both', ['subagent_claude_code', 'subagent_codex']],
  399. ])
  400. expect(productCtx.subagents.list()).toEqual(expect.arrayContaining([
  401. 'spawn', 'fork', 'codex', 'claude-code',
  402. ]))
  403. for (const [id, productTools] of expected) {
  404. const handle = await productCtx.agents.create({
  405. sessionId: SessionId(`preset-${id}`),
  406. setup: agentCtx => productCtx.agentPresets.mount(agentCtx, id).then(() => undefined),
  407. })
  408. try {
  409. const tools = toolNames(productCtx, handle.agent)
  410. expect(tools.filter(name => name === 'subagent_codex' || name === 'subagent_claude_code'))
  411. .toEqual(productTools)
  412. } finally {
  413. await handle.dispose()
  414. }
  415. }
  416. })
  417. it('applies a product-row edit only to later sessions on the preset', async () => {
  418. const preset = await productCtx.agentPresets.resolve('products-none')
  419. const original = await readFile(preset.path, 'utf8')
  420. const existing = await productCtx.agents.create({
  421. sessionId: SessionId('preset-product-generation-existing'),
  422. setup: agentCtx => productCtx.agentPresets.mount(agentCtx, 'products-none').then(() => undefined),
  423. })
  424. try {
  425. expect(toolNames(productCtx, existing.agent)).not.toContain('subagent_codex')
  426. await writeFile(preset.path, enablePresetTool(original, 'tool-subagent-codex'))
  427. const later = await productCtx.agents.create({
  428. sessionId: SessionId('preset-product-generation-later'),
  429. setup: agentCtx => productCtx.agentPresets.mount(agentCtx, 'products-none').then(() => undefined),
  430. })
  431. try {
  432. expect(toolNames(productCtx, existing.agent)).not.toContain('subagent_codex')
  433. expect(toolNames(productCtx, later.agent)).toContain('subagent_codex')
  434. } finally {
  435. await later.dispose()
  436. }
  437. } finally {
  438. await existing.dispose()
  439. await writeFile(preset.path, original)
  440. }
  441. })
  442. })
  443. describe('a switch survives the session', () => {
  444. it('records the choice so the log states what the agent runs', async () => {
  445. const handle = await ctx.agents.create({
  446. sessionId: SessionId('preset-switch-logged'),
  447. meta: { agentPreset: 'standard' },
  448. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  449. })
  450. try {
  451. // The api-proxy's select does exactly this pair while the session is blank.
  452. await ctx.agentPresets.recompose(handle.agent.ctx, 'minimal')
  453. handle.agent.session.append('agent-preset/selected', { agentPreset: 'minimal' })
  454. // The header keeps the creation fact; the log carries what it runs.
  455. expect(handle.agent.session.header.agentPreset).toBe('standard')
  456. expect(resolveSessionPreset(handle.agent.session)).toBe('minimal')
  457. } finally {
  458. await handle.dispose()
  459. }
  460. })
  461. it('rebuilds a switched session from the log, not the creation header', () => {
  462. // The exact shape a resume reads back from disk: the header says standard,
  463. // the log records the switch the user made while the session was blank.
  464. const rebuilt = resolveSessionPreset({
  465. header: { version: 0, id: SessionId('x'), createdAt: 0, agentPreset: 'standard' },
  466. events: [
  467. { type: 'agent-preset/selected', seq: 1, time: 0, data: { agentPreset: 'minimal' } },
  468. { type: 'turn/start', seq: 2, time: 0, data: { turn: 0, trigger: { kind: 'message', source: { kind: 'user' } } } },
  469. ] as never,
  470. })
  471. // Reading the header alone would compose the creation-time preset over a
  472. // history another one produced — the replay the blank-only lock prevents.
  473. expect(rebuilt).toBe('minimal')
  474. })
  475. })
  476. describe('a forked session', () => {
  477. it('inherits the composition its seeded history was produced under', async () => {
  478. const parent = await ctx.agents.create({
  479. sessionId: SessionId('preset-fork-parent'),
  480. meta: { agentPreset: 'minimal' },
  481. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  482. })
  483. const inherited = resolveSessionPreset(parent.agent.session)
  484. const child = await ctx.agents.create({
  485. sessionId: SessionId('preset-fork-child'),
  486. meta: {
  487. parentSession: SessionId('preset-fork-parent'),
  488. seedLength: 0,
  489. ...inherited === undefined ? {} : { agentPreset: inherited },
  490. },
  491. setup: agentCtx => ctx.agentPresets.mount(agentCtx, inherited).then(() => undefined),
  492. })
  493. try {
  494. // Composing nothing would leave the child empty: this layer moved every
  495. // model-facing row out of the host plane, so there is nothing to inherit
  496. // for free any more.
  497. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  498. expect(toolNames(ctx, child.agent).length).toBeGreaterThan(0)
  499. } finally {
  500. await child.dispose()
  501. await parent.dispose()
  502. }
  503. })
  504. })
  505. describe('a delegated child', () => {
  506. it('runs on the composition its parent runs on', async () => {
  507. const parent = await ctx.agents.create({
  508. sessionId: SessionId('preset-child-parent'),
  509. meta: { agentPreset: 'standard' },
  510. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  511. })
  512. // Exactly what an in-process subagent driver's creation window does.
  513. const child = await parent.agent.ctx.agents.create({
  514. sessionId: SessionId('preset-child'),
  515. meta: childSessionMeta(parent.agent, 1, 0),
  516. setup: (agentCtx) => {
  517. applyChildComposition(agentCtx, parent.agent, {})
  518. },
  519. })
  520. try {
  521. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  522. // The shipped `standard` preset is the whole coding agent; an empty
  523. // child here is the defect, and equality alone would not catch it.
  524. expect(toolNames(ctx, child.agent)).toContain('bash')
  525. expect(child.agent.session.header.agentPreset).toBe('standard')
  526. } finally {
  527. await child.dispose()
  528. await parent.dispose()
  529. }
  530. })
  531. it('follows a parent that switched preset while blank', async () => {
  532. const parent = await ctx.agents.create({
  533. sessionId: SessionId('preset-child-switch-parent'),
  534. meta: { agentPreset: 'standard' },
  535. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  536. })
  537. await ctx.agentPresets.recompose(parent.agent.ctx, 'minimal')
  538. const child = await parent.agent.ctx.agents.create({
  539. sessionId: SessionId('preset-child-switch'),
  540. meta: childSessionMeta(parent.agent, 1, 0),
  541. setup: (agentCtx) => {
  542. applyChildComposition(agentCtx, parent.agent, {})
  543. },
  544. })
  545. try {
  546. // The live scope chain is the authority, not the parent's creation
  547. // header — which still names `standard`.
  548. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  549. expect(child.agent.session.header.agentPreset).toBe('minimal')
  550. } finally {
  551. await child.dispose()
  552. await parent.dispose()
  553. }
  554. })
  555. })
  556. describe('authoring a preset on the shipped composition', () => {
  557. let authorCtx: Context
  558. let userRoot: string
  559. beforeAll(async () => {
  560. userRoot = join(await mkdtemp(join(tmpdir(), 'dsh-preset-authoring-')), 'profiles')
  561. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-preset-authoring-settings-')), 'settings.yaml')
  562. await writeFile(settingsFile, '{}\n')
  563. authorCtx = await bootWeb(settingsFile, [{
  564. id: 'agent-presets',
  565. config: {
  566. default: 'standard',
  567. roots: [
  568. { path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' },
  569. // The root does not exist yet: a deployment whose user has authored
  570. // nothing is the normal first-run state.
  571. { path: userRoot, trust: 'user' },
  572. ],
  573. },
  574. }])
  575. })
  576. it('refuses to copy over or delete a shipped preset', async () => {
  577. await expect(authorCtx.agentPresets.copy('minimal', 'standard')).rejects.toThrow(/already exists/)
  578. await expect(authorCtx.agentPresets.remove('standard')).rejects.toThrow(/ships with the deployment/)
  579. })
  580. it.each(['../escape', 'a/b', '/abs', 'Upper'])('refuses the uncontainable id %j', async (id) => {
  581. // The id becomes a directory name under the user root, so containment is
  582. // checked on the id rather than on the joined path afterwards.
  583. await expect(authorCtx.agentPresets.copy('minimal', id)).rejects.toThrow()
  584. })
  585. it('copies a shipped preset a session then really composes from', async () => {
  586. await authorCtx.agentPresets.copy('minimal', 'my-agent', '我的模式')
  587. // Round-trips through the roster as a `user` row carrying the given name
  588. // and the source's description, over the source's own composition text.
  589. const preset = await authorCtx.agentPresets.resolve('my-agent')
  590. const source = await authorCtx.agentPresets.resolve('minimal')
  591. expect(preset.trust).toBe('user')
  592. expect(preset.name).toBe('我的模式')
  593. expect(preset.description).toBe(source.description)
  594. expect(await authorCtx.agentPresets.read('my-agent')).toBe(await authorCtx.agentPresets.read('minimal'))
  595. // Owner-only, in an owner-only directory: a composition is executable
  596. // configuration on a machine that may have other users.
  597. expect((await stat(preset.path)).mode & 0o777).toBe(0o600)
  598. const handle = await authorCtx.agents.create({
  599. sessionId: SessionId('preset-authored'),
  600. setup: agentCtx => authorCtx.agentPresets.mount(agentCtx, 'my-agent').then(() => undefined),
  601. })
  602. try {
  603. // The same tools the shipped `minimal` composes, from a directory copied
  604. // through the service into a root outside the installed harness.
  605. expect(toolNames(authorCtx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  606. } finally {
  607. await handle.dispose()
  608. }
  609. })
  610. it('deletes what it copied', async () => {
  611. await authorCtx.agentPresets.copy('minimal', 'doomed')
  612. await authorCtx.agentPresets.remove('doomed')
  613. expect((await authorCtx.agentPresets.list()).map(preset => preset.id)).not.toContain('doomed')
  614. })
  615. })
  616. /**
  617. * Which preset an unnamed session gets is a user setting layered over the
  618. * composition's own default. The package suite proves the layering against a
  619. * hand-built context; this proves it through the shipped `cordis.yml` — that
  620. * the roster and the settings provider are actually wired to each other, and
  621. * that the id the setting names is the one a session composes from.
  622. */
  623. describe('the default preset as a user setting', () => {
  624. it('composes an unnamed session from the stored default, not the composed one', async () => {
  625. expect(ctx.agentPresets.defaultId).toBe('standard')
  626. await ctx.settings.update(settingsNamespace(SETTINGS_NAMESPACE), { default: 'minimal' })
  627. try {
  628. expect(ctx.agentPresets.defaultId).toBe('minimal')
  629. const handle = await ctx.agents.create({
  630. sessionId: SessionId('preset-user-default'),
  631. setup: agentCtx => ctx.agentPresets.mount(agentCtx).then(() => undefined),
  632. })
  633. try {
  634. // `mount()` with no id resolves the effective default. Two tools, not
  635. // `standard`'s catalog: the setting decided the composition.
  636. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  637. } finally {
  638. await handle.dispose()
  639. }
  640. } finally {
  641. // The context is shared with the rest of the file. `replace({})` drops
  642. // the user section wholesale so the field re-inherits the composition
  643. // base; `update` merges, and would leave the override standing.
  644. await ctx.settings.replace(settingsNamespace(SETTINGS_NAMESPACE), {})
  645. }
  646. expect(ctx.agentPresets.defaultId).toBe('standard')
  647. })
  648. })
  649. describe('a session keeps the preset it was created with', () => {
  650. it('refuses to adopt a live session under a different preset', async () => {
  651. const handle = await ctx.agents.create({
  652. sessionId: SessionId('preset-locked'),
  653. meta: { agentPreset: 'minimal' },
  654. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  655. })
  656. try {
  657. // The api-proxy guard reads exactly this: the header records what the
  658. // session runs, so naming anything else is a caller error rather than a
  659. // switch. Its history was produced under `minimal`'s two tools.
  660. expect(handle.agent.session.header.agentPreset).toBe('minimal')
  661. } finally {
  662. await handle.dispose()
  663. }
  664. })
  665. })