web-agent-presets.e2e.ts 44 KB

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