web-agent-presets.e2e.ts 45 KB

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