web-agent-presets.e2e.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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-compact-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 `httpServer`, 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: '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: [{ id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' }] },
  88. // The roster AppCLIEntry would patch in; only the shipped root, so a
  89. // developer's own `~/.dsh/.preset` cannot change this test's outcome.
  90. // `default` here is the COMPOSITION default — the base layer the settings
  91. // document overrides.
  92. {
  93. id: 'agent-presets',
  94. config: { default: 'standard', roots: [{ path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' }] },
  95. },
  96. ...extra,
  97. ]
  98. // The surface is patch layers over an empty preset root, so the root sits
  99. // outside this workspace and bare plugin names cannot resolve by Node's
  100. // upward walk. The flat fallback the preset boot maintains is what makes
  101. // them resolvable — the same mechanism, not a test-only shim.
  102. const home = dirname(settingsFile)
  103. healProfilesModuleFallback(INSTALL_ANCHOR, home)
  104. const profileDir = join(home, 'profiles', 'spec')
  105. await mkdir(profileDir, { recursive: true })
  106. const rootConfig = join(profileDir, 'cordis.yml')
  107. await writeFile(rootConfig, '[]\n')
  108. return await boot('dsh-test', rootConfig, patches, (bootCtx) => {
  109. provideCmdline(bootCtx, { args: [], exit: () => {} })
  110. })
  111. }
  112. const toolNames = (ctx: Context, agent?: Agent): string[] =>
  113. ctx.tools.schemas(agent).map(schema => schema.name).sort()
  114. function enablePresetTool(composition: string, id: string): string {
  115. const row = ` - id: ${id}\n`
  116. const start = composition.indexOf(row)
  117. if (start < 0) throw new Error(`missing preset row ${id}`)
  118. const end = composition.indexOf('\n - id:', start + row.length)
  119. const disabled = composition.indexOf(' disabled: true\n', start)
  120. if (disabled < 0 || (end >= 0 && disabled > end)) {
  121. throw new Error(`preset row ${id} is not disabled`)
  122. }
  123. return composition.slice(0, disabled) + composition.slice(disabled + ' disabled: true\n'.length)
  124. }
  125. let ctx: Context
  126. beforeAll(async () => {
  127. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-web-presets-')), 'settings.yaml')
  128. await writeFile(settingsFile, '{}\n')
  129. ctx = await bootWeb(settingsFile)
  130. }, 120_000)
  131. describe('the shipped Web composition', () => {
  132. it('leaves the global tool layer empty', () => {
  133. // Every model-facing tool belongs to a preset, `ask_user_question`
  134. // included: a tool in the global layer reaches EVERY agent regardless of
  135. // which preset composed it, so a two-tool benchmark surface would really
  136. // present three. A regression here means an agent-plane row came back to
  137. // the host composition.
  138. expect(toolNames(ctx)).toEqual([])
  139. })
  140. it('keeps the token meter and its context-meter projections on the host plane', async () => {
  141. // Read before any preset in this file mounts, which is what makes this an
  142. // ownership assertion rather than a mount-order coincidence: a preset-side
  143. // meter sits behind an `isolate` realm and is invisible to `ctx.get`.
  144. //
  145. // The projection registry is process-wide rather than scope-layered, so a
  146. // preset-side meter would also make the browser's context meter appear for
  147. // a `minimal` session the moment some OTHER session mounted a preset that
  148. // carries one, and vanish entirely in a process that only ever ran
  149. // `minimal`. Host ownership is what makes the meter a per-session fact.
  150. expect(ctx.get('tokenMeter')).toBeDefined()
  151. const projections = ctx.get('sessionProjections')
  152. if (projections === undefined) throw new Error('the Web composition must compose a projection registry')
  153. const handle = await ctx.agents.create({
  154. sessionId: SessionId('preset-minimal-meter'),
  155. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  156. })
  157. try {
  158. // A subset assertion: `tasks`, `goal`, and the rest register into the
  159. // same process-wide table, and this is about the meter's three units.
  160. expect(Object.keys(projections.snapshot(handle.agent.session).values))
  161. .toEqual(expect.arrayContaining(['contextBreakdown', 'contextPressure', 'tokenUsage']))
  162. } finally {
  163. await handle.dispose()
  164. }
  165. })
  166. it('supplies both shipped presets, and only those, from the system root', async () => {
  167. const listed = await ctx.agentPresets.list()
  168. expect(listed.map(preset => preset.id).sort()).toEqual(['code', 'cordis', 'minimal', 'standard'])
  169. expect(listed.every(preset => preset.trust === 'system')).toBe(true)
  170. expect(ctx.agentPresets.defaultId).toBe('standard')
  171. })
  172. it('composes the full agent from `standard`', async () => {
  173. const handle = await ctx.agents.create({
  174. sessionId: SessionId('preset-standard'),
  175. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  176. })
  177. try {
  178. // The EXACT catalog, not a spot-check: an omission is this design's
  179. // quietest failure mode, because a row that registers into the wrong
  180. // layer mounts cleanly and simply contributes nothing. `glob`/`grep` are
  181. // excluded for the reason the TUI composition e2e excludes them — they
  182. // depend on ripgrep being present on the machine.
  183. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
  184. 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
  185. 'get_goal', 'interrupt_agent', 'list_agents', 'ralph', 'read', 'read_image', 'send_message', 'skill',
  186. 'subagent', 'subagent_fork', 'task_kill',
  187. 'task_list', 'task_output', 'todo_write', 'update_goal', 'web_search',
  188. 'workflow', 'write',
  189. ])
  190. } finally {
  191. await handle.dispose()
  192. }
  193. })
  194. it('composes the exact RL prompt and two tools from `minimal`', async () => {
  195. const handle = await ctx.agents.create({
  196. sessionId: SessionId('preset-minimal'),
  197. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  198. })
  199. try {
  200. const assembly = await ctx.systemPrompt.assemble({ scope: handle.agent })
  201. expect(assembly.sections).toEqual([
  202. { name: 'deployment:persona', text: MINIMAL_PROMPT },
  203. ])
  204. expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'str_replace_editor'])
  205. expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION)
  206. expect(JSON.stringify(assembly.tools.find(tool => tool.name === 'str_replace_editor')?.parameters))
  207. .toContain('Absolute path')
  208. expect(ctx.agentPresets.serviceFor(handle.agent, 'compact')).toBeUndefined()
  209. expect(handle.agent.ctx.get('compact')).toBeUndefined()
  210. } finally {
  211. await handle.dispose()
  212. }
  213. })
  214. it('keeps two differently composed sessions independent', async () => {
  215. const full = await ctx.agents.create({
  216. sessionId: SessionId('preset-both-full'),
  217. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  218. })
  219. const minimal = await ctx.agents.create({
  220. sessionId: SessionId('preset-both-minimal'),
  221. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  222. })
  223. try {
  224. expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'str_replace_editor'])
  225. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  226. await minimal.dispose()
  227. // Tearing the minimal session down leaves the full one whole.
  228. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  229. expect(toolNames(ctx)).toEqual([])
  230. } finally {
  231. await full.dispose()
  232. }
  233. })
  234. it('composes the cordis agent with its own toolset', async () => {
  235. const handle = await ctx.agents.create({
  236. sessionId: SessionId('preset-cordis'),
  237. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined),
  238. })
  239. try {
  240. const tools = toolNames(ctx, handle.agent)
  241. // The self-referential toolset is what distinguishes this preset.
  242. expect(tools).toEqual(expect.arrayContaining(['cordis_inspect', 'cordis_mount', 'cordis_unmount']))
  243. // And it keeps the standard agent's own tools rather than replacing them.
  244. expect(tools).toEqual(expect.arrayContaining(['bash', 'read', 'edit', 'skill']))
  245. expect(tools).not.toContain('str_replace_editor')
  246. // The preset's own authoring skill registers into ITS layer of the host
  247. // registry: the cordis agent's view carries it, the global view does not.
  248. const scoped = (await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)
  249. expect(scoped).toContain('editing-cordis-compositions')
  250. expect((await ctx.skills.list()).map(skill => skill.name)).not.toContain('editing-cordis-compositions')
  251. } finally {
  252. await handle.dispose()
  253. }
  254. })
  255. it('presents `code` as Code Mode without disturbing a native session beside it', async () => {
  256. const coded = await ctx.agents.create({
  257. sessionId: SessionId('preset-code'),
  258. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'code').then(() => undefined),
  259. })
  260. const native = await ctx.agents.create({
  261. sessionId: SessionId('preset-code-native'),
  262. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  263. })
  264. try {
  265. // One tool reaches the MODEL: the transport. The registry's catalog for
  266. // this agent is unchanged — a code mode collapses the presentation, not
  267. // the capabilities — so the assembly is what carries the claim.
  268. const assembly = await ctx.systemPrompt.assemble({ scope: coded.agent })
  269. expect(assembly.tools.map(tool => tool.name)).toEqual(['run_code'])
  270. expect(toolNames(ctx, coded.agent)).not.toContain('str_replace_editor')
  271. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  272. expect(sdk).not.toContain('str_replace_editor')
  273. expect(sdk).toContain('web_search')
  274. // The presentation is this agent's alone: the deployment default is
  275. // native, and the session composed from `standard` still sees it.
  276. const nativeAssembly = await ctx.systemPrompt.assemble({ scope: native.agent })
  277. expect(nativeAssembly.tools.map(tool => tool.name)).toContain('bash')
  278. expect(nativeAssembly.tools.map(tool => tool.name)).not.toContain('run_code')
  279. expect(nativeAssembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  280. } finally {
  281. await native.dispose()
  282. await coded.dispose()
  283. }
  284. })
  285. it('keeps the self-referential toolset out of every other preset', async () => {
  286. const handle = await ctx.agents.create({
  287. sessionId: SessionId('preset-no-cordis'),
  288. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  289. })
  290. try {
  291. // Editing the live runtime is opt-in per session, not ambient.
  292. expect(toolNames(ctx, handle.agent)).not.toContain('cordis_mount')
  293. } finally {
  294. await handle.dispose()
  295. }
  296. })
  297. it('ships the composition-authoring skill inside the preset directory', async () => {
  298. // The preset's skill root is derived from its own `baseUrl`, so the skill
  299. // travels with the directory wherever the preset is installed.
  300. const skill = join(
  301. CONFIG_DIR, 'agent-presets', 'cordis', 'skills', 'editing-cordis-compositions', 'SKILL.md',
  302. )
  303. expect((await readFile(skill, 'utf8')).startsWith('---\nname: editing-cordis-compositions')).toBe(true)
  304. })
  305. it('merges the global skill layer into a preset agent\'s catalog, keeping local discovery preset-side', async () => {
  306. const proj = await mkdtemp(join(tmpdir(), 'dsh-preset-skill-proj-'))
  307. await mkdir(join(proj, '.dsh', 'skills', 'project-proof'), { recursive: true })
  308. await writeFile(join(proj, '.dsh', 'skills', 'project-proof', 'SKILL.md'), [
  309. '---',
  310. 'name: project-proof',
  311. 'description: Proves the preset layer discovers project skills beside global ones.',
  312. '---',
  313. '',
  314. 'Project proof body.',
  315. '',
  316. ].join('\n'))
  317. const handle = await ctx.agents.create({
  318. // Unique per run: the composition persists into the ambient DSH home,
  319. // and a fixed id would collide with a log an earlier run left there.
  320. sessionId: SessionId(`preset-skills-standard-${randomUUID()}`),
  321. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  322. })
  323. try {
  324. // The host (global) view carries the deployment-level provider alone:
  325. // local discovery moved behind the presets with `skill-local`.
  326. expect((await ctx.skills.list({ cwd: proj })).map(skill => skill.name)).toEqual(['dsh-badge'])
  327. // The standard agent's view merges the global layer with its preset's
  328. // own local discovery over the session cwd.
  329. const scoped = (await ctx.skills.list({ cwd: proj, scope: handle.agent })).map(skill => skill.name)
  330. expect(scoped).toContain('dsh-badge')
  331. expect(scoped).toContain('project-proof')
  332. // The preset's own loader tool resolves the global-layer skill.
  333. const loaded = await ctx.tools.execute({
  334. callId: CallId('preset-skills-load'),
  335. name: 'skill',
  336. arguments: { name: 'dsh-badge' },
  337. signal: new AbortController().signal,
  338. agent: handle.agent,
  339. })
  340. expect(loaded.isError).toBe(false)
  341. expect(JSON.stringify(loaded.content)).toContain('powered by dsh')
  342. } finally {
  343. await handle.dispose()
  344. }
  345. })
  346. it('shows a minimal agent the global layer but no loader tool', async () => {
  347. const handle = await ctx.agents.create({
  348. sessionId: SessionId(`preset-skills-minimal-${randomUUID()}`),
  349. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  350. })
  351. try {
  352. // Layer visibility is the registry's; whether an agent can USE skills
  353. // stays the preset's choice — minimal mounts no `tool-skill`, so its
  354. // tool table has no loader even though the global layer is readable.
  355. expect((await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)).toContain('dsh-badge')
  356. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  357. } finally {
  358. await handle.dispose()
  359. }
  360. })
  361. it('never rewrites the preset file it composed from', async () => {
  362. // The Loader persists a tree whose plugin self-disposed, and tearing an
  363. // agent down disposes its whole subtree. Inherited, that rewrote the
  364. // shipped composition — truncating it to `[]` the first time a session
  365. // ended — so `PresetTree` refuses to write at all.
  366. const path = join(CONFIG_DIR, 'agent-presets', 'standard', 'agent.cordis.yml')
  367. const before = await readFile(path, 'utf8')
  368. const handle = await ctx.agents.create({
  369. sessionId: SessionId('preset-readonly'),
  370. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  371. })
  372. await handle.dispose()
  373. // Slack, not a race the number has to win. The write is driven by the
  374. // Loader's fiber-unload listener, which fires as the subtree's fibers
  375. // settle rather than when `dispose()` resolves, and the Loader exposes no
  376. // flush to await. A regression writes synchronously inside that listener,
  377. // so any wait past settlement fails; a longer one only slows the test.
  378. await new Promise(resolve => setTimeout(resolve, 50))
  379. expect(await readFile(path, 'utf8')).toBe(before)
  380. })
  381. })
  382. describe('product subagent rows in user presets', () => {
  383. let productCtx: Context
  384. const ids = ['products-none', 'products-codex', 'products-claude', 'products-both'] as const
  385. beforeAll(async () => {
  386. const root = await mkdtemp(join(tmpdir(), 'dsh-product-presets-'))
  387. const userRoot = join(root, 'presets')
  388. const settingsFile = join(root, 'settings.yaml')
  389. const standard = await readFile(join(CONFIG_DIR, 'agent-presets', 'standard', 'agent.cordis.yml'), 'utf8')
  390. await writeFile(settingsFile, '{}\n')
  391. for (const id of ids) {
  392. let composition = standard
  393. if (id === 'products-codex' || id === 'products-both') {
  394. composition = enablePresetTool(composition, 'tool-subagent-codex')
  395. }
  396. if (id === 'products-claude' || id === 'products-both') {
  397. composition = enablePresetTool(composition, 'tool-subagent-claude-code')
  398. }
  399. const directory = join(userRoot, id)
  400. await mkdir(directory, { recursive: true })
  401. await writeFile(join(directory, 'agent.cordis.yml'), composition)
  402. }
  403. productCtx = await bootWeb(settingsFile, [{
  404. id: 'agent-presets',
  405. config: {
  406. default: 'standard',
  407. roots: [
  408. { path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' },
  409. { path: userRoot, trust: 'user' },
  410. ],
  411. },
  412. }])
  413. }, 120_000)
  414. afterAll(async () => {
  415. await productCtx.fiber.dispose()
  416. })
  417. it('composes none, either product, or both without changing the shared host registry', async () => {
  418. const expected = new Map<string, string[]>([
  419. ['products-none', []],
  420. ['products-codex', ['subagent_codex']],
  421. ['products-claude', ['subagent_claude_code']],
  422. ['products-both', ['subagent_claude_code', 'subagent_codex']],
  423. ])
  424. expect(productCtx.subagents.list()).toEqual(expect.arrayContaining([
  425. 'spawn', 'fork', 'codex', 'claude-code',
  426. ]))
  427. for (const [id, productTools] of expected) {
  428. const handle = await productCtx.agents.create({
  429. sessionId: SessionId(`preset-${id}`),
  430. setup: agentCtx => productCtx.agentPresets.mount(agentCtx, id).then(() => undefined),
  431. })
  432. try {
  433. const tools = toolNames(productCtx, handle.agent)
  434. expect(tools.filter(name => name === 'subagent_codex' || name === 'subagent_claude_code'))
  435. .toEqual(productTools)
  436. } finally {
  437. await handle.dispose()
  438. }
  439. }
  440. })
  441. it('applies a product-row edit only to later sessions on the preset', async () => {
  442. const preset = await productCtx.agentPresets.resolve('products-none')
  443. const original = await readFile(preset.path, 'utf8')
  444. const existing = await productCtx.agents.create({
  445. sessionId: SessionId('preset-product-generation-existing'),
  446. setup: agentCtx => productCtx.agentPresets.mount(agentCtx, 'products-none').then(() => undefined),
  447. })
  448. try {
  449. expect(toolNames(productCtx, existing.agent)).not.toContain('subagent_codex')
  450. await writeFile(preset.path, enablePresetTool(original, 'tool-subagent-codex'))
  451. const later = await productCtx.agents.create({
  452. sessionId: SessionId('preset-product-generation-later'),
  453. setup: agentCtx => productCtx.agentPresets.mount(agentCtx, 'products-none').then(() => undefined),
  454. })
  455. try {
  456. expect(toolNames(productCtx, existing.agent)).not.toContain('subagent_codex')
  457. expect(toolNames(productCtx, later.agent)).toContain('subagent_codex')
  458. } finally {
  459. await later.dispose()
  460. }
  461. } finally {
  462. await existing.dispose()
  463. await writeFile(preset.path, original)
  464. }
  465. })
  466. })
  467. describe('a switch survives the session', () => {
  468. it('records the choice so the log states what the agent runs', async () => {
  469. const handle = await ctx.agents.create({
  470. sessionId: SessionId('preset-switch-logged'),
  471. meta: { agentPreset: 'standard' },
  472. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  473. })
  474. try {
  475. // The api-proxy's select does exactly this pair while the session is blank.
  476. await ctx.agentPresets.recompose(handle.agent.ctx, 'minimal')
  477. handle.agent.session.append('agent-preset/selected', { agentPreset: 'minimal' })
  478. // The header keeps the creation fact; the log carries what it runs.
  479. expect(handle.agent.session.header.agentPreset).toBe('standard')
  480. expect(resolveSessionPreset(handle.agent.session)).toBe('minimal')
  481. } finally {
  482. await handle.dispose()
  483. }
  484. })
  485. it('rebuilds a switched session from the log, not the creation header', () => {
  486. // The exact shape a resume reads back from disk: the header says standard,
  487. // the log records the switch the user made while the session was blank.
  488. const rebuilt = resolveSessionPreset({
  489. header: { version: 0, id: SessionId('x'), createdAt: 0, agentPreset: 'standard' },
  490. events: [
  491. { type: 'agent-preset/selected', seq: 1, time: 0, data: { agentPreset: 'minimal' } },
  492. { type: 'turn/start', seq: 2, time: 0, data: { turn: 0, trigger: { kind: 'message', source: { kind: 'user' } } } },
  493. ] as never,
  494. })
  495. // Reading the header alone would compose the creation-time preset over a
  496. // history another one produced — the replay the blank-only lock prevents.
  497. expect(rebuilt).toBe('minimal')
  498. })
  499. })
  500. describe('a forked session', () => {
  501. it('inherits the composition its seeded history was produced under', async () => {
  502. const parent = await ctx.agents.create({
  503. sessionId: SessionId('preset-fork-parent'),
  504. meta: { agentPreset: 'minimal' },
  505. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  506. })
  507. const inherited = resolveSessionPreset(parent.agent.session)
  508. const child = await ctx.agents.create({
  509. sessionId: SessionId('preset-fork-child'),
  510. meta: {
  511. parentSession: SessionId('preset-fork-parent'),
  512. seedLength: 0,
  513. ...inherited === undefined ? {} : { agentPreset: inherited },
  514. },
  515. setup: agentCtx => ctx.agentPresets.mount(agentCtx, inherited).then(() => undefined),
  516. })
  517. try {
  518. // Composing nothing would leave the child empty: this layer moved every
  519. // model-facing row out of the host plane, so there is nothing to inherit
  520. // for free any more.
  521. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  522. expect(toolNames(ctx, child.agent).length).toBeGreaterThan(0)
  523. } finally {
  524. await child.dispose()
  525. await parent.dispose()
  526. }
  527. })
  528. })
  529. describe('a delegated child', () => {
  530. it('runs on the composition its parent runs on', async () => {
  531. const parent = await ctx.agents.create({
  532. sessionId: SessionId('preset-child-parent'),
  533. meta: { agentPreset: 'standard' },
  534. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  535. })
  536. // Exactly what an in-process subagent driver's creation window does.
  537. const child = await parent.agent.ctx.agents.create({
  538. sessionId: SessionId('preset-child'),
  539. meta: childSessionMeta(parent.agent, 1, 0),
  540. setup: (agentCtx) => {
  541. applyChildComposition(agentCtx, parent.agent, {})
  542. },
  543. })
  544. try {
  545. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  546. // The shipped `standard` preset is the whole coding agent; an empty
  547. // child here is the defect, and equality alone would not catch it.
  548. expect(toolNames(ctx, child.agent)).toContain('bash')
  549. expect(child.agent.session.header.agentPreset).toBe('standard')
  550. } finally {
  551. await child.dispose()
  552. await parent.dispose()
  553. }
  554. })
  555. it('follows a parent that switched preset while blank', async () => {
  556. const parent = await ctx.agents.create({
  557. sessionId: SessionId('preset-child-switch-parent'),
  558. meta: { agentPreset: 'standard' },
  559. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  560. })
  561. await ctx.agentPresets.recompose(parent.agent.ctx, 'minimal')
  562. const child = await parent.agent.ctx.agents.create({
  563. sessionId: SessionId('preset-child-switch'),
  564. meta: childSessionMeta(parent.agent, 1, 0),
  565. setup: (agentCtx) => {
  566. applyChildComposition(agentCtx, parent.agent, {})
  567. },
  568. })
  569. try {
  570. // The live scope chain is the authority, not the parent's creation
  571. // header — which still names `standard`.
  572. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  573. expect(child.agent.session.header.agentPreset).toBe('minimal')
  574. } finally {
  575. await child.dispose()
  576. await parent.dispose()
  577. }
  578. })
  579. })
  580. describe('authoring a preset on the shipped composition', () => {
  581. let authorCtx: Context
  582. let userRoot: string
  583. beforeAll(async () => {
  584. userRoot = join(await mkdtemp(join(tmpdir(), 'dsh-preset-authoring-')), 'profiles')
  585. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-preset-authoring-settings-')), 'settings.yaml')
  586. await writeFile(settingsFile, '{}\n')
  587. authorCtx = await bootWeb(settingsFile, [{
  588. id: 'agent-presets',
  589. config: {
  590. default: 'standard',
  591. roots: [
  592. { path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' },
  593. // The root does not exist yet: a deployment whose user has authored
  594. // nothing is the normal first-run state.
  595. { path: userRoot, trust: 'user' },
  596. ],
  597. },
  598. }])
  599. })
  600. it('refuses to copy over or delete a shipped preset', async () => {
  601. await expect(authorCtx.agentPresets.copy('minimal', 'standard')).rejects.toThrow(/already exists/)
  602. await expect(authorCtx.agentPresets.remove('standard')).rejects.toThrow(/ships with the deployment/)
  603. })
  604. it.each(['../escape', 'a/b', '/abs', 'Upper'])('refuses the uncontainable id %j', async (id) => {
  605. // The id becomes a directory name under the user root, so containment is
  606. // checked on the id rather than on the joined path afterwards.
  607. await expect(authorCtx.agentPresets.copy('minimal', id)).rejects.toThrow()
  608. })
  609. it('copies a shipped preset a session then really composes from', async () => {
  610. await authorCtx.agentPresets.copy('minimal', 'my-agent', '我的模式')
  611. // Round-trips through the roster as a `user` row carrying the given name
  612. // and the source's description, over the source's own composition text.
  613. const preset = await authorCtx.agentPresets.resolve('my-agent')
  614. const source = await authorCtx.agentPresets.resolve('minimal')
  615. expect(preset.trust).toBe('user')
  616. expect(preset.name).toBe('我的模式')
  617. expect(preset.description).toBe(source.description)
  618. expect(await authorCtx.agentPresets.read('my-agent')).toBe(await authorCtx.agentPresets.read('minimal'))
  619. // Owner-only, in an owner-only directory: a composition is executable
  620. // configuration on a machine that may have other users.
  621. expect((await stat(preset.path)).mode & 0o777).toBe(0o600)
  622. const handle = await authorCtx.agents.create({
  623. sessionId: SessionId('preset-authored'),
  624. setup: agentCtx => authorCtx.agentPresets.mount(agentCtx, 'my-agent').then(() => undefined),
  625. })
  626. try {
  627. // The same tools the shipped `minimal` composes, from a directory copied
  628. // through the service into a root outside the installed harness.
  629. expect(toolNames(authorCtx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  630. } finally {
  631. await handle.dispose()
  632. }
  633. })
  634. it('deletes what it copied', async () => {
  635. await authorCtx.agentPresets.copy('minimal', 'doomed')
  636. await authorCtx.agentPresets.remove('doomed')
  637. expect((await authorCtx.agentPresets.list()).map(preset => preset.id)).not.toContain('doomed')
  638. })
  639. })
  640. /**
  641. * Which preset an unnamed session gets is a user setting layered over the
  642. * composition's own default. The package suite proves the layering against a
  643. * hand-built context; this proves it through the shipped `cordis.yml` — that
  644. * the roster and the settings provider are actually wired to each other, and
  645. * that the id the setting names is the one a session composes from.
  646. */
  647. describe('the default preset as a user setting', () => {
  648. it('composes an unnamed session from the stored default, not the composed one', async () => {
  649. expect(ctx.agentPresets.defaultId).toBe('standard')
  650. await ctx.settings.update(settingsNamespace(SETTINGS_NAMESPACE), { default: 'minimal' })
  651. try {
  652. expect(ctx.agentPresets.defaultId).toBe('minimal')
  653. const handle = await ctx.agents.create({
  654. sessionId: SessionId('preset-user-default'),
  655. setup: agentCtx => ctx.agentPresets.mount(agentCtx).then(() => undefined),
  656. })
  657. try {
  658. // `mount()` with no id resolves the effective default. Two tools, not
  659. // `standard`'s catalog: the setting decided the composition.
  660. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  661. } finally {
  662. await handle.dispose()
  663. }
  664. } finally {
  665. // The context is shared with the rest of the file. `replace({})` drops
  666. // the user section wholesale so the field re-inherits the composition
  667. // base; `update` merges, and would leave the override standing.
  668. await ctx.settings.replace(settingsNamespace(SETTINGS_NAMESPACE), {})
  669. }
  670. expect(ctx.agentPresets.defaultId).toBe('standard')
  671. })
  672. })
  673. describe('a session keeps the preset it was created with', () => {
  674. it('refuses to adopt a live session under a different preset', async () => {
  675. const handle = await ctx.agents.create({
  676. sessionId: SessionId('preset-locked'),
  677. meta: { agentPreset: 'minimal' },
  678. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  679. })
  680. try {
  681. // The api-proxy guard reads exactly this: the header records what the
  682. // session runs, so naming anything else is a caller error rather than a
  683. // switch. Its history was produced under `minimal`'s two tools.
  684. expect(handle.agent.session.header.agentPreset).toBe('minimal')
  685. } finally {
  686. await handle.dispose()
  687. }
  688. })
  689. })