web-agent-presets.e2e.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. import { randomUUID } from 'node:crypto'
  2. import { mkdir, mkdtemp, readFile, stat, 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 } from '@deepseek-ai/dsh-app-boot'
  8. import { SessionId } from '@deepseek-ai/dsh-session'
  9. import type { Agent } from '@deepseek-ai/dsh-agent'
  10. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  11. import { beforeAll, describe, expect, it } from 'vitest'
  12. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  13. import { resolveSessionPreset, SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-agent-presets'
  14. import { applyChildComposition, childSessionMeta } from '@deepseek-ai/dsh-subagent'
  15. import { CallId } from '@deepseek-ai/dsh-llm'
  16. import type { BasicCompactService } from '@deepseek-ai/dsh-compact-basic'
  17. import type {} from '@deepseek-ai/dsh-skill'
  18. import type {} from '@deepseek-ai/dsh-tools'
  19. const CONFIG_DIR = fileURLToPath(new URL('../config/', import.meta.url))
  20. const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  21. /** The shipped Web surface: the dsh-base and dsh-web-app bundle patches over an empty preset root. */
  22. const BASE_PATCH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  23. const WEB_PATCH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  24. /** The installation anchor whose dependency surface the preset module fallback mirrors. */
  25. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  26. const MINIMAL_PROMPT = 'You are a helpful software engineer assistant.'
  27. const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell
  28. * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.
  29. * You don't have access to the internet via this tool.
  30. * You do have access to a mirror of common linux and python packages via apt and pip.
  31. * State is persistent across command calls and discussions with the user.
  32. * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.
  33. * Please avoid commands that may produce a very large amount of output.
  34. * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.`
  35. /**
  36. * Boot the shipped Web composition, minus the rows that would bind a port,
  37. * touch the network, or write outside the test. Everything that decides an
  38. * agent's capabilities is the real thing, including both shipped presets.
  39. */
  40. async function bootWeb(settingsFile: string, extra: PatchOptions[] = []): Promise<Context> {
  41. const storageRoot = join(dirname(settingsFile), 'storages')
  42. const patches: PatchOptions[] = [
  43. ...loadOverlayPatches('dsh-test', BASE_PATCH),
  44. ...loadOverlayPatches('dsh-test', WEB_PATCH),
  45. // The settings row defaults to `$DSH_HOME/settings.yaml`. Left alone it
  46. // reads the developer's own document — and since the default preset is a
  47. // setting, a stored `agent-presets.default` would decide this file's
  48. // outcome. Point it at a temp file for the same reason the roster below
  49. // names only the shipped root.
  50. { id: 'settings', config: { path: settingsFile, watch: false } },
  51. // storage-json's root is anchored to the real $DSH_HOME. Unpinned, this
  52. // file writes the developer's own `~/.dsh/storages/` — and then reads it
  53. // back on the next run, so a stored document from any other build decides
  54. // this test's boot. Same reason the settings row above is pinned.
  55. { id: 'storage-json', config: { root: storageRoot } },
  56. // Host rows with side effects outside this process: a bound port, a served
  57. // asset tree, a telemetry exporter. `api-gateway` and `directory-picker`
  58. // stay ENABLED on purpose — the api-proxy is the host row that injects
  59. // `subagents`, `workspace`, and the rest of the agent plane, so disabling
  60. // it would hide exactly the breakage this file exists to catch: a service
  61. // moved into the presets that a host row still waits for. The boot audit
  62. // is that assertion.
  63. { id: 'webserver', disabled: true },
  64. // The web bundle's runtime row injects `httpServer`, so it cannot
  65. // activate without the bound port disabled above. It owns dist serving
  66. // and the URL prompt line — surface glue, not anything that decides an
  67. // agent's capabilities, which is all this file asserts.
  68. { id: 'web-runtime', disabled: true },
  69. { id: 'telemetry-otel', disabled: true },
  70. // A deployment-level skill on the host registry's GLOBAL layer — the same
  71. // registration shape a repository plugin's skill root uses. The layered
  72. // skills test below proves it reaches preset-composed agents.
  73. { id: 'skill-badge', disabled: false },
  74. { id: 'modules', disabled: true },
  75. { id: 'connection', disabled: true },
  76. // The shipped `-auto` chooser resolves its interaction from a running
  77. // host and so waits for the webserver disabled above; the browse variant
  78. // supplies `directoryPicker` without one.
  79. { id: 'directory-picker', disabled: true },
  80. { insert: [{ id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' }] },
  81. // The roster AppCLIEntry would patch in; only the shipped root, so a
  82. // developer's own `~/.dsh/.preset` cannot change this test's outcome.
  83. // `default` here is the COMPOSITION default — the base layer the settings
  84. // document overrides.
  85. {
  86. id: 'agent-presets',
  87. config: { default: 'standard', roots: [{ path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' }] },
  88. },
  89. ...extra,
  90. ]
  91. // The surface is patch layers over an empty preset root, so the root sits
  92. // outside this workspace and bare plugin names cannot resolve by Node's
  93. // upward walk. The flat fallback the preset boot maintains is what makes
  94. // them resolvable — the same mechanism, not a test-only shim.
  95. const home = dirname(settingsFile)
  96. healProfilesModuleFallback(INSTALL_ANCHOR, home)
  97. const profileDir = join(home, 'profiles', 'spec')
  98. await mkdir(profileDir, { recursive: true })
  99. const rootConfig = join(profileDir, 'cordis.yml')
  100. await writeFile(rootConfig, '[]\n')
  101. return await boot('dsh-test', rootConfig, patches)
  102. }
  103. const toolNames = (ctx: Context, agent?: Agent): string[] =>
  104. ctx.tools.schemas(agent).map(schema => schema.name).sort()
  105. let ctx: Context
  106. beforeAll(async () => {
  107. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-web-presets-')), 'settings.yaml')
  108. await writeFile(settingsFile, '{}\n')
  109. ctx = await bootWeb(settingsFile)
  110. }, 120_000)
  111. describe('the shipped Web composition', () => {
  112. it('leaves the global tool layer empty', () => {
  113. // Every model-facing tool belongs to a preset, `ask_user_question`
  114. // included: a tool in the global layer reaches EVERY agent regardless of
  115. // which preset composed it, so a two-tool benchmark surface would really
  116. // present three. A regression here means an agent-plane row came back to
  117. // the host composition.
  118. expect(toolNames(ctx)).toEqual([])
  119. })
  120. it('supplies both shipped presets, and only those, from the system root', async () => {
  121. const listed = await ctx.agentPresets.list()
  122. expect(listed.map(preset => preset.id).sort()).toEqual(['code', 'cordis', 'minimal', 'standard'])
  123. expect(listed.every(preset => preset.trust === 'system')).toBe(true)
  124. expect(ctx.agentPresets.defaultId).toBe('standard')
  125. })
  126. it('composes the full agent from `standard`', async () => {
  127. const handle = await ctx.agents.create({
  128. sessionId: SessionId('preset-standard'),
  129. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  130. })
  131. try {
  132. // The EXACT catalog, not a spot-check: an omission is this design's
  133. // quietest failure mode, because a row that registers into the wrong
  134. // layer mounts cleanly and simply contributes nothing. `glob`/`grep` are
  135. // excluded for the reason the TUI composition e2e excludes them — they
  136. // depend on ripgrep being present on the machine.
  137. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
  138. 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
  139. 'get_goal', 'interrupt_agent', 'list_agents', 'ralph', 'read', 'send_message', 'skill',
  140. 'subagent', 'subagent_fork', 'task_kill',
  141. 'task_list', 'task_output', 'todo_write', 'update_goal', 'web_search',
  142. 'workflow', 'write',
  143. ])
  144. } finally {
  145. await handle.dispose()
  146. }
  147. })
  148. it('composes the exact RL prompt and two tools from `minimal`', async () => {
  149. const handle = await ctx.agents.create({
  150. sessionId: SessionId('preset-minimal'),
  151. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  152. })
  153. try {
  154. const assembly = await ctx.systemPrompt.assemble({ scope: handle.agent })
  155. expect(assembly.sections).toEqual([
  156. { name: 'deployment:persona', text: MINIMAL_PROMPT },
  157. ])
  158. expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'str_replace_editor'])
  159. expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION)
  160. expect(JSON.stringify(assembly.tools.find(tool => tool.name === 'str_replace_editor')?.parameters))
  161. .toContain('Absolute path')
  162. const compact = ctx.agentPresets.serviceFor(handle.agent, 'compact')
  163. expect(compact).toBeDefined()
  164. expect((compact as BasicCompactService).config).toMatchObject({
  165. thresholdRatio: 0.8,
  166. retainTokens: 20480,
  167. summarizationProvider: '',
  168. summarizationModel: '',
  169. maxTokens: 8192,
  170. compactionRetries: 1,
  171. })
  172. } finally {
  173. await handle.dispose()
  174. }
  175. })
  176. it('keeps two differently composed sessions independent', async () => {
  177. const full = await ctx.agents.create({
  178. sessionId: SessionId('preset-both-full'),
  179. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  180. })
  181. const minimal = await ctx.agents.create({
  182. sessionId: SessionId('preset-both-minimal'),
  183. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  184. })
  185. try {
  186. expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'str_replace_editor'])
  187. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  188. await minimal.dispose()
  189. // Tearing the minimal session down leaves the full one whole.
  190. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  191. expect(toolNames(ctx)).toEqual([])
  192. } finally {
  193. await full.dispose()
  194. }
  195. })
  196. it('composes the cordis agent with its own toolset', async () => {
  197. const handle = await ctx.agents.create({
  198. sessionId: SessionId('preset-cordis'),
  199. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined),
  200. })
  201. try {
  202. const tools = toolNames(ctx, handle.agent)
  203. // The self-referential toolset is what distinguishes this preset.
  204. expect(tools).toEqual(expect.arrayContaining(['cordis_inspect', 'cordis_mount', 'cordis_unmount']))
  205. // And it keeps the standard agent's own tools rather than replacing them.
  206. expect(tools).toEqual(expect.arrayContaining(['bash', 'read', 'edit', 'skill']))
  207. expect(tools).not.toContain('str_replace_editor')
  208. // The preset's own authoring skill registers into ITS layer of the host
  209. // registry: the cordis agent's view carries it, the global view does not.
  210. const scoped = (await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)
  211. expect(scoped).toContain('editing-cordis-compositions')
  212. expect((await ctx.skills.list()).map(skill => skill.name)).not.toContain('editing-cordis-compositions')
  213. } finally {
  214. await handle.dispose()
  215. }
  216. })
  217. it('presents `code` as Code Mode without disturbing a native session beside it', async () => {
  218. const coded = await ctx.agents.create({
  219. sessionId: SessionId('preset-code'),
  220. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'code').then(() => undefined),
  221. })
  222. const native = await ctx.agents.create({
  223. sessionId: SessionId('preset-code-native'),
  224. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  225. })
  226. try {
  227. // One tool reaches the MODEL: the transport. The registry's catalog for
  228. // this agent is unchanged — a code mode collapses the presentation, not
  229. // the capabilities — so the assembly is what carries the claim.
  230. const assembly = await ctx.systemPrompt.assemble({ scope: coded.agent })
  231. expect(assembly.tools.map(tool => tool.name)).toEqual(['run_code'])
  232. expect(toolNames(ctx, coded.agent)).not.toContain('str_replace_editor')
  233. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  234. expect(sdk).not.toContain('str_replace_editor')
  235. expect(sdk).toContain('web_search')
  236. // The presentation is this agent's alone: the deployment default is
  237. // native, and the session composed from `standard` still sees it.
  238. const nativeAssembly = await ctx.systemPrompt.assemble({ scope: native.agent })
  239. expect(nativeAssembly.tools.map(tool => tool.name)).toContain('bash')
  240. expect(nativeAssembly.tools.map(tool => tool.name)).not.toContain('run_code')
  241. expect(nativeAssembly.sections.some(section => section.name === 'tools:sdk')).toBe(false)
  242. } finally {
  243. await native.dispose()
  244. await coded.dispose()
  245. }
  246. })
  247. it('keeps the self-referential toolset out of every other preset', async () => {
  248. const handle = await ctx.agents.create({
  249. sessionId: SessionId('preset-no-cordis'),
  250. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  251. })
  252. try {
  253. // Editing the live runtime is opt-in per session, not ambient.
  254. expect(toolNames(ctx, handle.agent)).not.toContain('cordis_mount')
  255. } finally {
  256. await handle.dispose()
  257. }
  258. })
  259. it('ships the composition-authoring skill inside the preset directory', async () => {
  260. // The preset's skill root is derived from its own `baseUrl`, so the skill
  261. // travels with the directory wherever the preset is installed.
  262. const skill = join(
  263. CONFIG_DIR, 'agent-presets', 'cordis', 'skills', 'editing-cordis-compositions', 'SKILL.md',
  264. )
  265. expect((await readFile(skill, 'utf8')).startsWith('---\nname: editing-cordis-compositions')).toBe(true)
  266. })
  267. it('merges the global skill layer into a preset agent\'s catalog, keeping local discovery preset-side', async () => {
  268. const proj = await mkdtemp(join(tmpdir(), 'dsh-preset-skill-proj-'))
  269. await mkdir(join(proj, '.dsh', 'skills', 'project-proof'), { recursive: true })
  270. await writeFile(join(proj, '.dsh', 'skills', 'project-proof', 'SKILL.md'), [
  271. '---',
  272. 'name: project-proof',
  273. 'description: Proves the preset layer discovers project skills beside global ones.',
  274. '---',
  275. '',
  276. 'Project proof body.',
  277. '',
  278. ].join('\n'))
  279. const handle = await ctx.agents.create({
  280. // Unique per run: the composition persists into the ambient DSH home,
  281. // and a fixed id would collide with a log an earlier run left there.
  282. sessionId: SessionId(`preset-skills-standard-${randomUUID()}`),
  283. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  284. })
  285. try {
  286. // The host (global) view carries the deployment-level provider alone:
  287. // local discovery moved behind the presets with `skill-local`.
  288. expect((await ctx.skills.list({ cwd: proj })).map(skill => skill.name)).toEqual(['dsh-badge'])
  289. // The standard agent's view merges the global layer with its preset's
  290. // own local discovery over the session cwd.
  291. const scoped = (await ctx.skills.list({ cwd: proj, scope: handle.agent })).map(skill => skill.name)
  292. expect(scoped).toContain('dsh-badge')
  293. expect(scoped).toContain('project-proof')
  294. // The preset's own loader tool resolves the global-layer skill.
  295. const loaded = await ctx.tools.execute({
  296. callId: CallId('preset-skills-load'),
  297. name: 'skill',
  298. arguments: { name: 'dsh-badge' },
  299. signal: new AbortController().signal,
  300. agent: handle.agent,
  301. })
  302. expect(loaded.isError).toBe(false)
  303. expect(JSON.stringify(loaded.content)).toContain('powered by dsh')
  304. } finally {
  305. await handle.dispose()
  306. }
  307. })
  308. it('shows a minimal agent the global layer but no loader tool', async () => {
  309. const handle = await ctx.agents.create({
  310. sessionId: SessionId(`preset-skills-minimal-${randomUUID()}`),
  311. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  312. })
  313. try {
  314. // Layer visibility is the registry's; whether an agent can USE skills
  315. // stays the preset's choice — minimal mounts no `tool-skill`, so its
  316. // tool table has no loader even though the global layer is readable.
  317. expect((await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)).toContain('dsh-badge')
  318. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  319. } finally {
  320. await handle.dispose()
  321. }
  322. })
  323. it('never rewrites the preset file it composed from', async () => {
  324. // The Loader persists a tree whose plugin self-disposed, and tearing an
  325. // agent down disposes its whole subtree. Inherited, that rewrote the
  326. // shipped composition — truncating it to `[]` the first time a session
  327. // ended — so `PresetTree` refuses to write at all.
  328. const path = join(CONFIG_DIR, 'agent-presets', 'standard', 'agent.cordis.yml')
  329. const before = await readFile(path, 'utf8')
  330. const handle = await ctx.agents.create({
  331. sessionId: SessionId('preset-readonly'),
  332. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  333. })
  334. await handle.dispose()
  335. // Slack, not a race the number has to win. The write is driven by the
  336. // Loader's fiber-unload listener, which fires as the subtree's fibers
  337. // settle rather than when `dispose()` resolves, and the Loader exposes no
  338. // flush to await. A regression writes synchronously inside that listener,
  339. // so any wait past settlement fails; a longer one only slows the test.
  340. await new Promise(resolve => setTimeout(resolve, 50))
  341. expect(await readFile(path, 'utf8')).toBe(before)
  342. })
  343. })
  344. describe('a switch survives the session', () => {
  345. it('records the choice so the log states what the agent runs', async () => {
  346. const handle = await ctx.agents.create({
  347. sessionId: SessionId('preset-switch-logged'),
  348. meta: { agentPreset: 'standard' },
  349. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  350. })
  351. try {
  352. // The api-proxy's select does exactly this pair while the session is blank.
  353. await ctx.agentPresets.recompose(handle.agent.ctx, 'minimal')
  354. handle.agent.session.append('agent-preset/selected', { agentPreset: 'minimal' })
  355. // The header keeps the creation fact; the log carries what it runs.
  356. expect(handle.agent.session.header.agentPreset).toBe('standard')
  357. expect(resolveSessionPreset(handle.agent.session)).toBe('minimal')
  358. } finally {
  359. await handle.dispose()
  360. }
  361. })
  362. it('rebuilds a switched session from the log, not the creation header', () => {
  363. // The exact shape a resume reads back from disk: the header says standard,
  364. // the log records the switch the user made while the session was blank.
  365. const rebuilt = resolveSessionPreset({
  366. header: { version: 0, id: SessionId('x'), createdAt: 0, agentPreset: 'standard' },
  367. events: [
  368. { type: 'agent-preset/selected', seq: 1, time: 0, data: { agentPreset: 'minimal' } },
  369. { type: 'turn/start', seq: 2, time: 0, data: { turn: 0, trigger: { kind: 'message', source: { kind: 'user' } } } },
  370. ] as never,
  371. })
  372. // Reading the header alone would compose the creation-time preset over a
  373. // history another one produced — the replay the blank-only lock prevents.
  374. expect(rebuilt).toBe('minimal')
  375. })
  376. })
  377. describe('a forked session', () => {
  378. it('inherits the composition its seeded history was produced under', async () => {
  379. const parent = await ctx.agents.create({
  380. sessionId: SessionId('preset-fork-parent'),
  381. meta: { agentPreset: 'minimal' },
  382. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  383. })
  384. const inherited = resolveSessionPreset(parent.agent.session)
  385. const child = await ctx.agents.create({
  386. sessionId: SessionId('preset-fork-child'),
  387. meta: {
  388. parentSession: SessionId('preset-fork-parent'),
  389. seedLength: 0,
  390. ...inherited === undefined ? {} : { agentPreset: inherited },
  391. },
  392. setup: agentCtx => ctx.agentPresets.mount(agentCtx, inherited).then(() => undefined),
  393. })
  394. try {
  395. // Composing nothing would leave the child empty: this layer moved every
  396. // model-facing row out of the host plane, so there is nothing to inherit
  397. // for free any more.
  398. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  399. expect(toolNames(ctx, child.agent).length).toBeGreaterThan(0)
  400. } finally {
  401. await child.dispose()
  402. await parent.dispose()
  403. }
  404. })
  405. })
  406. describe('a delegated child', () => {
  407. it('runs on the composition its parent runs on', async () => {
  408. const parent = await ctx.agents.create({
  409. sessionId: SessionId('preset-child-parent'),
  410. meta: { agentPreset: 'standard' },
  411. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  412. })
  413. // Exactly what an in-process subagent driver's creation window does.
  414. const child = await parent.agent.ctx.agents.create({
  415. sessionId: SessionId('preset-child'),
  416. meta: childSessionMeta(parent.agent, 1, 0),
  417. setup: (agentCtx) => {
  418. applyChildComposition(agentCtx, parent.agent, {})
  419. },
  420. })
  421. try {
  422. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  423. // The shipped `standard` preset is the whole coding agent; an empty
  424. // child here is the defect, and equality alone would not catch it.
  425. expect(toolNames(ctx, child.agent)).toContain('bash')
  426. expect(child.agent.session.header.agentPreset).toBe('standard')
  427. } finally {
  428. await child.dispose()
  429. await parent.dispose()
  430. }
  431. })
  432. it('follows a parent that switched preset while blank', async () => {
  433. const parent = await ctx.agents.create({
  434. sessionId: SessionId('preset-child-switch-parent'),
  435. meta: { agentPreset: 'standard' },
  436. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  437. })
  438. await ctx.agentPresets.recompose(parent.agent.ctx, 'minimal')
  439. const child = await parent.agent.ctx.agents.create({
  440. sessionId: SessionId('preset-child-switch'),
  441. meta: childSessionMeta(parent.agent, 1, 0),
  442. setup: (agentCtx) => {
  443. applyChildComposition(agentCtx, parent.agent, {})
  444. },
  445. })
  446. try {
  447. // The live scope chain is the authority, not the parent's creation
  448. // header — which still names `standard`.
  449. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  450. expect(child.agent.session.header.agentPreset).toBe('minimal')
  451. } finally {
  452. await child.dispose()
  453. await parent.dispose()
  454. }
  455. })
  456. })
  457. describe('authoring a preset on the shipped composition', () => {
  458. let authorCtx: Context
  459. let userRoot: string
  460. beforeAll(async () => {
  461. userRoot = join(await mkdtemp(join(tmpdir(), 'dsh-preset-authoring-')), 'profiles')
  462. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-preset-authoring-settings-')), 'settings.yaml')
  463. await writeFile(settingsFile, '{}\n')
  464. authorCtx = await bootWeb(settingsFile, [{
  465. id: 'agent-presets',
  466. config: {
  467. default: 'standard',
  468. roots: [
  469. { path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' },
  470. // The root does not exist yet: a deployment whose user has authored
  471. // nothing is the normal first-run state.
  472. { path: userRoot, trust: 'user' },
  473. ],
  474. },
  475. }])
  476. })
  477. it('refuses to copy over or delete a shipped preset', async () => {
  478. await expect(authorCtx.agentPresets.copy('minimal', 'standard')).rejects.toThrow(/already exists/)
  479. await expect(authorCtx.agentPresets.remove('standard')).rejects.toThrow(/ships with the deployment/)
  480. })
  481. it.each(['../escape', 'a/b', '/abs', 'Upper'])('refuses the uncontainable id %j', async (id) => {
  482. // The id becomes a directory name under the user root, so containment is
  483. // checked on the id rather than on the joined path afterwards.
  484. await expect(authorCtx.agentPresets.copy('minimal', id)).rejects.toThrow()
  485. })
  486. it('copies a shipped preset a session then really composes from', async () => {
  487. await authorCtx.agentPresets.copy('minimal', 'my-agent', '我的模式')
  488. // Round-trips through the roster as a `user` row carrying the given name
  489. // and the source's description, over the source's own composition text.
  490. const preset = await authorCtx.agentPresets.resolve('my-agent')
  491. const source = await authorCtx.agentPresets.resolve('minimal')
  492. expect(preset.trust).toBe('user')
  493. expect(preset.name).toBe('我的模式')
  494. expect(preset.description).toBe(source.description)
  495. expect(await authorCtx.agentPresets.read('my-agent')).toBe(await authorCtx.agentPresets.read('minimal'))
  496. // Owner-only, in an owner-only directory: a composition is executable
  497. // configuration on a machine that may have other users.
  498. expect((await stat(preset.path)).mode & 0o777).toBe(0o600)
  499. const handle = await authorCtx.agents.create({
  500. sessionId: SessionId('preset-authored'),
  501. setup: agentCtx => authorCtx.agentPresets.mount(agentCtx, 'my-agent').then(() => undefined),
  502. })
  503. try {
  504. // The same tools the shipped `minimal` composes, from a directory copied
  505. // through the service into a root outside the installed harness.
  506. expect(toolNames(authorCtx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  507. } finally {
  508. await handle.dispose()
  509. }
  510. })
  511. it('deletes what it copied', async () => {
  512. await authorCtx.agentPresets.copy('minimal', 'doomed')
  513. await authorCtx.agentPresets.remove('doomed')
  514. expect((await authorCtx.agentPresets.list()).map(preset => preset.id)).not.toContain('doomed')
  515. })
  516. })
  517. /**
  518. * Which preset an unnamed session gets is a user setting layered over the
  519. * composition's own default. The package suite proves the layering against a
  520. * hand-built context; this proves it through the shipped `cordis.yml` — that
  521. * the roster and the settings provider are actually wired to each other, and
  522. * that the id the setting names is the one a session composes from.
  523. */
  524. describe('the default preset as a user setting', () => {
  525. it('composes an unnamed session from the stored default, not the composed one', async () => {
  526. expect(ctx.agentPresets.defaultId).toBe('standard')
  527. await ctx.settings.update(settingsNamespace(SETTINGS_NAMESPACE), { default: 'minimal' })
  528. try {
  529. expect(ctx.agentPresets.defaultId).toBe('minimal')
  530. const handle = await ctx.agents.create({
  531. sessionId: SessionId('preset-user-default'),
  532. setup: agentCtx => ctx.agentPresets.mount(agentCtx).then(() => undefined),
  533. })
  534. try {
  535. // `mount()` with no id resolves the effective default. Two tools, not
  536. // `standard`'s catalog: the setting decided the composition.
  537. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  538. } finally {
  539. await handle.dispose()
  540. }
  541. } finally {
  542. // The context is shared with the rest of the file. `replace({})` drops
  543. // the user section wholesale so the field re-inherits the composition
  544. // base; `update` merges, and would leave the override standing.
  545. await ctx.settings.replace(settingsNamespace(SETTINGS_NAMESPACE), {})
  546. }
  547. expect(ctx.agentPresets.defaultId).toBe('standard')
  548. })
  549. })
  550. describe('a session keeps the preset it was created with', () => {
  551. it('refuses to adopt a live session under a different preset', async () => {
  552. const handle = await ctx.agents.create({
  553. sessionId: SessionId('preset-locked'),
  554. meta: { agentPreset: 'minimal' },
  555. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined),
  556. })
  557. try {
  558. // The api-proxy guard reads exactly this: the header records what the
  559. // session runs, so naming anything else is a caller error rather than a
  560. // switch. Its history was produced under `minimal`'s two tools.
  561. expect(handle.agent.session.header.agentPreset).toBe('minimal')
  562. } finally {
  563. await handle.dispose()
  564. }
  565. })
  566. })