web-agent-presets.e2e.ts 25 KB

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