web-agent-presets.e2e.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { fileURLToPath } from 'node:url'
  4. import { dirname, join } from 'node:path'
  5. import { Context } from 'cordis'
  6. import { boot, healProfilesModuleFallback, loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
  7. import { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { Agent } from '@deepseek-ai/dsh-agent'
  9. import type { PatchOptions } from '@cordisjs/plugin-include'
  10. import { beforeAll, describe, expect, it } from 'vitest'
  11. import { settingsNamespace } from '@deepseek-ai/dsh-settings'
  12. import { resolveSessionPreset, SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-agent-presets'
  13. import type {} from '@deepseek-ai/dsh-tools'
  14. const CONFIG_DIR = fileURLToPath(new URL('../config/', import.meta.url))
  15. const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  16. /** The shipped Web surface: the dsh-base and dsh-web-app bundle patches over an empty preset root. */
  17. const BASE_PATCH = join(REPO_ROOT, 'packages/bundle/base/cordis.patch.yml')
  18. const WEB_PATCH = join(REPO_ROOT, 'packages/bundle/web-app/cordis.patch.yml')
  19. /** The installation anchor whose dependency surface the preset module fallback mirrors. */
  20. const INSTALL_ANCHOR = join(REPO_ROOT, 'apps/cli/package.json')
  21. /**
  22. * Boot the shipped Web composition, minus the rows that would bind a port,
  23. * touch the network, or write outside the test. Everything that decides an
  24. * agent's capabilities is the real thing, including both shipped presets.
  25. */
  26. async function bootWeb(settingsFile: string): Promise<Context> {
  27. const patches: PatchOptions[] = [
  28. ...loadOverlayPatches('dsh-test', BASE_PATCH),
  29. ...loadOverlayPatches('dsh-test', WEB_PATCH),
  30. // The settings row defaults to `$DSH_HOME/settings.yaml`. Left alone it
  31. // reads the developer's own document — and since the default preset is a
  32. // setting, a stored `agent-presets.default` would decide this file's
  33. // outcome. Point it at a temp file for the same reason the roster below
  34. // names only the shipped root.
  35. { id: 'settings', config: { path: settingsFile, watch: false } },
  36. // Host rows with side effects outside this process: a bound port, a
  37. // served asset tree, a telemetry exporter.
  38. { id: 'webserver', disabled: true },
  39. // Waits for `httpServer`, which the disabled webserver above provides.
  40. { id: 'web-runtime', disabled: true },
  41. { id: 'telemetry-otel', disabled: true },
  42. { id: 'modules', disabled: true },
  43. { id: 'connection', disabled: true },
  44. // `api-gateway` stays ENABLED on purpose — the api-proxy is the host row
  45. // that injects `subagents`, `workspace`, and the rest of the agent plane,
  46. // so disabling it would hide exactly the breakage this file exists to
  47. // catch: a service moved into the presets that a host row still waits for.
  48. // The boot audit is that assertion.
  49. // The shipped `-auto` chooser resolves its interaction from a running
  50. // host and so waits for the webserver disabled above; the browse variant
  51. // supplies `directoryPicker` without one.
  52. { id: 'directory-picker', disabled: true },
  53. { insert: [{ id: 'directory-picker-browse', name: '@deepseek-ai/dsh-host-directory-picker-browse' }] },
  54. // The roster AppCLIEntry would patch in; only the shipped root, so a
  55. // developer's own `~/.dsh/.preset` cannot change this test's outcome.
  56. // `default` here is the COMPOSITION default — the base layer the settings
  57. // document overrides.
  58. {
  59. id: 'agent-presets',
  60. config: { default: 'standard', roots: [{ path: join(CONFIG_DIR, 'agent-presets'), trust: 'system' }] },
  61. },
  62. ]
  63. // The composition boots from an empty preset root, exactly as `dsh web`
  64. // does: the root's own directory is outside this workspace, so bare plugin
  65. // names cannot resolve by Node's upward walk. The flat fallback the preset
  66. // boot maintains is what makes them resolvable — the same mechanism, not a
  67. // test-only shim. It links each package's published entry, so this file
  68. // consumes the ARTIFACT plane and lives in the lane that builds.
  69. const home = dirname(settingsFile)
  70. healProfilesModuleFallback(INSTALL_ANCHOR, home)
  71. const presetDir = join(home, 'profiles', 'spec')
  72. await mkdir(presetDir, { recursive: true })
  73. const rootConfig = join(presetDir, 'cordis.yml')
  74. await writeFile(rootConfig, '[]\n')
  75. return await boot('dsh-test', rootConfig, patches)
  76. }
  77. const toolNames = (ctx: Context, agent?: Agent): string[] =>
  78. ctx.tools.schemas(agent).map(schema => schema.name).sort()
  79. let ctx: Context
  80. beforeAll(async () => {
  81. const settingsFile = join(await mkdtemp(join(tmpdir(), 'dsh-web-presets-')), 'settings.yaml')
  82. await writeFile(settingsFile, '{}\n')
  83. ctx = await bootWeb(settingsFile)
  84. }, 120_000)
  85. describe('the shipped Web composition', () => {
  86. it('leaves the global tool layer empty', () => {
  87. // Every model-facing tool belongs to a preset, `ask_user_question`
  88. // included: a tool in the global layer reaches EVERY agent regardless of
  89. // which preset composed it, so a two-tool benchmark surface would really
  90. // present three. A regression here means an agent-plane row came back to
  91. // the host composition.
  92. expect(toolNames(ctx)).toEqual([])
  93. })
  94. it('supplies both shipped presets, and only those, from the system root', async () => {
  95. const listed = await ctx.agentPresets.list()
  96. expect(listed.map(preset => preset.id).sort()).toEqual(['cordis', 'core-web', 'standard'])
  97. expect(listed.every(preset => preset.trust === 'system')).toBe(true)
  98. expect(ctx.agentPresets.defaultId).toBe('standard')
  99. })
  100. it('composes the full agent from `standard`', async () => {
  101. const handle = await ctx.agents.create({
  102. sessionId: SessionId('preset-standard'),
  103. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  104. })
  105. try {
  106. // The EXACT catalog, not a spot-check: an omission is this design's
  107. // quietest failure mode, because a row that registers into the wrong
  108. // layer mounts cleanly and simply contributes nothing. `glob`/`grep` are
  109. // excluded for the reason the TUI composition e2e excludes them — they
  110. // depend on ripgrep being present on the machine.
  111. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
  112. 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
  113. 'get_goal', 'interrupt_agent', 'list_agents', 'ralph', 'read', 'send_message', 'skill',
  114. 'str_replace_editor', 'subagent', 'subagent_fork', 'task_kill',
  115. 'task_list', 'task_output', 'todo_write', 'update_goal', 'web_search',
  116. 'workflow', 'write',
  117. ])
  118. } finally {
  119. await handle.dispose()
  120. }
  121. })
  122. it('composes exactly two tools from `core-web`', async () => {
  123. const handle = await ctx.agents.create({
  124. sessionId: SessionId('preset-core-web'),
  125. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  126. })
  127. try {
  128. // Exactly what the preset lists — nothing arrives from the host.
  129. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  130. } finally {
  131. await handle.dispose()
  132. }
  133. })
  134. it('keeps two differently composed sessions independent', async () => {
  135. const full = await ctx.agents.create({
  136. sessionId: SessionId('preset-both-full'),
  137. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  138. })
  139. const minimal = await ctx.agents.create({
  140. sessionId: SessionId('preset-both-minimal'),
  141. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  142. })
  143. try {
  144. expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'str_replace_editor'])
  145. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  146. await minimal.dispose()
  147. // Tearing the minimal session down leaves the full one whole.
  148. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10)
  149. expect(toolNames(ctx)).toEqual([])
  150. } finally {
  151. await full.dispose()
  152. }
  153. })
  154. it('composes the cordis agent with its own toolset', async () => {
  155. const handle = await ctx.agents.create({
  156. sessionId: SessionId('preset-cordis'),
  157. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined),
  158. })
  159. try {
  160. const tools = toolNames(ctx, handle.agent)
  161. // The self-referential toolset is what distinguishes this preset.
  162. expect(tools).toEqual(expect.arrayContaining(['cordis_inspect', 'cordis_mount', 'cordis_unmount']))
  163. // And it keeps the standard agent's own tools rather than replacing them.
  164. expect(tools).toEqual(expect.arrayContaining(['bash', 'read', 'edit', 'skill']))
  165. // The skill registry sits in this preset's entry-local realm, so it is
  166. // invisible to the host AND to the agent's own scope — only the rows
  167. // inside that group resolve it, which is what makes `tool-skill` the
  168. // agent's own rather than a shared one.
  169. expect(ctx.get('skills')).toBeUndefined()
  170. } finally {
  171. await handle.dispose()
  172. }
  173. })
  174. it('keeps the self-referential toolset out of every other preset', async () => {
  175. const handle = await ctx.agents.create({
  176. sessionId: SessionId('preset-no-cordis'),
  177. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  178. })
  179. try {
  180. // Editing the live runtime is opt-in per session, not ambient.
  181. expect(toolNames(ctx, handle.agent)).not.toContain('cordis_mount')
  182. } finally {
  183. await handle.dispose()
  184. }
  185. })
  186. it('ships the composition-authoring skill inside the preset directory', async () => {
  187. // The preset's skill root is derived from its own `baseUrl`, so the skill
  188. // travels with the directory wherever the preset is installed.
  189. const skill = join(
  190. CONFIG_DIR, 'agent-presets', 'cordis', 'skills', 'editing-cordis-compositions', 'SKILL.md',
  191. )
  192. expect((await readFile(skill, 'utf8')).startsWith('---\nname: editing-cordis-compositions')).toBe(true)
  193. })
  194. it('never rewrites the preset file it composed from', async () => {
  195. // The Loader persists a tree whose plugin self-disposed, and tearing an
  196. // agent down disposes its whole subtree. Inherited, that rewrote the
  197. // shipped composition — truncating it to `[]` the first time a session
  198. // ended — so `PresetTree` refuses to write at all.
  199. const path = join(CONFIG_DIR, 'agent-presets', 'standard', 'agent.cordis.yml')
  200. const before = await readFile(path, 'utf8')
  201. const handle = await ctx.agents.create({
  202. sessionId: SessionId('preset-readonly'),
  203. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  204. })
  205. await handle.dispose()
  206. // Slack, not a race the number has to win. The write is driven by the
  207. // Loader's fiber-unload listener, which fires as the subtree's fibers
  208. // settle rather than when `dispose()` resolves, and the Loader exposes no
  209. // flush to await. A regression writes synchronously inside that listener,
  210. // so any wait past settlement fails; a longer one only slows the test.
  211. await new Promise(resolve => setTimeout(resolve, 50))
  212. expect(await readFile(path, 'utf8')).toBe(before)
  213. })
  214. it('gives each session its own persona', async () => {
  215. const handle = await ctx.agents.create({
  216. sessionId: SessionId('preset-persona'),
  217. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  218. })
  219. try {
  220. const assembly = await ctx.systemPrompt.assemble({ scope: handle.agent })
  221. expect(assembly.sections.find(section => section.name === 'deployment:persona')?.text)
  222. .toContain('You are a coding agent powered by')
  223. } finally {
  224. await handle.dispose()
  225. }
  226. })
  227. })
  228. describe('a switch survives the session', () => {
  229. it('records the choice so the log states what the agent runs', async () => {
  230. const handle = await ctx.agents.create({
  231. sessionId: SessionId('preset-switch-logged'),
  232. meta: { agentPreset: 'standard' },
  233. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'standard').then(() => undefined),
  234. })
  235. try {
  236. // The api-proxy's select does exactly this pair while the session is blank.
  237. await ctx.agentPresets.recompose(handle.agent.ctx, 'core-web')
  238. handle.agent.session.append('agent-preset/selected', { agentPreset: 'core-web' })
  239. // The header keeps the creation fact; the log carries what it runs.
  240. expect(handle.agent.session.header.agentPreset).toBe('standard')
  241. expect(resolveSessionPreset(handle.agent.session)).toBe('core-web')
  242. } finally {
  243. await handle.dispose()
  244. }
  245. })
  246. it('rebuilds a switched session from the log, not the creation header', () => {
  247. // The exact shape a resume reads back from disk: the header says standard,
  248. // the log records the switch the user made while the session was blank.
  249. const rebuilt = resolveSessionPreset({
  250. header: { version: 0, id: SessionId('x'), createdAt: 0, agentPreset: 'standard' },
  251. events: [
  252. { type: 'agent-preset/selected', seq: 1, time: 0, data: { agentPreset: 'core-web' } },
  253. { type: 'turn/start', seq: 2, time: 0, data: { turn: 0, trigger: { kind: 'message', source: { kind: 'user' } } } },
  254. ] as never,
  255. })
  256. // Reading the header alone would compose the creation-time preset over a
  257. // history another one produced — the replay the blank-only lock prevents.
  258. expect(rebuilt).toBe('core-web')
  259. })
  260. })
  261. describe('a forked session', () => {
  262. it('inherits the composition its seeded history was produced under', async () => {
  263. const parent = await ctx.agents.create({
  264. sessionId: SessionId('preset-fork-parent'),
  265. meta: { agentPreset: 'core-web' },
  266. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  267. })
  268. const inherited = resolveSessionPreset(parent.agent.session)
  269. const child = await ctx.agents.create({
  270. sessionId: SessionId('preset-fork-child'),
  271. meta: {
  272. parentSession: SessionId('preset-fork-parent'),
  273. seedLength: 0,
  274. ...inherited === undefined ? {} : { agentPreset: inherited },
  275. },
  276. setup: agentCtx => ctx.agentPresets.mount(agentCtx, inherited).then(() => undefined),
  277. })
  278. try {
  279. // Composing nothing would leave the child empty: this layer moved every
  280. // model-facing row out of the host plane, so there is nothing to inherit
  281. // for free any more.
  282. expect(toolNames(ctx, child.agent)).toEqual(toolNames(ctx, parent.agent))
  283. expect(toolNames(ctx, child.agent).length).toBeGreaterThan(0)
  284. } finally {
  285. await child.dispose()
  286. await parent.dispose()
  287. }
  288. })
  289. })
  290. /**
  291. * Which preset an unnamed session gets is a user setting layered over the
  292. * composition's own default. The package suite proves the layering against a
  293. * hand-built context; this proves it through the shipped `cordis.yml` — that
  294. * the roster and the settings provider are actually wired to each other, and
  295. * that the id the setting names is the one a session composes from.
  296. */
  297. describe('the default preset as a user setting', () => {
  298. it('composes an unnamed session from the stored default, not the composed one', async () => {
  299. expect(ctx.agentPresets.defaultId).toBe('standard')
  300. await ctx.settings.update(settingsNamespace(SETTINGS_NAMESPACE), { default: 'core-web' })
  301. try {
  302. expect(ctx.agentPresets.defaultId).toBe('core-web')
  303. const handle = await ctx.agents.create({
  304. sessionId: SessionId('preset-user-default'),
  305. setup: agentCtx => ctx.agentPresets.mount(agentCtx).then(() => undefined),
  306. })
  307. try {
  308. // `mount()` with no id resolves the effective default. Two tools, not
  309. // `standard`'s catalog: the setting decided the composition.
  310. expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'str_replace_editor'])
  311. } finally {
  312. await handle.dispose()
  313. }
  314. } finally {
  315. // The context is shared with the rest of the file. `replace({})` drops
  316. // the user section wholesale so the field re-inherits the composition
  317. // base; `update` merges, and would leave the override standing.
  318. await ctx.settings.replace(settingsNamespace(SETTINGS_NAMESPACE), {})
  319. }
  320. expect(ctx.agentPresets.defaultId).toBe('standard')
  321. })
  322. })
  323. describe('a session keeps the preset it was created with', () => {
  324. it('records the preset the gateway guard reads', async () => {
  325. const handle = await ctx.agents.create({
  326. sessionId: SessionId('preset-locked'),
  327. meta: { agentPreset: 'core-web' },
  328. setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'core-web').then(() => undefined),
  329. })
  330. try {
  331. // The api-proxy guard reads exactly this: the header records what the
  332. // session runs, so naming anything else is a caller error rather than a
  333. // switch. Its history was produced under `core-web`'s two tools.
  334. expect(handle.agent.session.header.agentPreset).toBe('core-web')
  335. } finally {
  336. await handle.dispose()
  337. }
  338. })
  339. })