web-agent-presets.e2e.ts 45 KB

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