web-agent-presets.e2e.ts 45 KB

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