web-agent-presets.e2e.ts 37 KB

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