web-agent-presets.e2e.ts 45 KB

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