web-agent-presets.e2e.ts 46 KB

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