web-agent-presets.e2e.ts 45 KB

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