web-agent-presets.e2e.ts 41 KB

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