plan-mode.spec.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { createUserMessage, CallId } from '@deepseek-ai/dsh-llm'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import ToolRegistry, { RUN_CODE_NAME, defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  6. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  7. import { agentEvents, type Agent } from '@deepseek-ai/dsh-agent'
  8. import { createScope } from '@deepseek-ai/dsh-scope'
  9. import UserInteractionService, { type AskUserQuestionRequest } from '@deepseek-ai/dsh-user-interaction'
  10. import CommandService from '@deepseek-ai/dsh-commands'
  11. import { CodeRuntime, type CodeRunRequest, type CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  12. import PlanModeService, { EXIT_PLAN_MODE, foldPlanMode, resolveConfig } from '../src/index.ts'
  13. import type { PlanModeConfig } from '../src/index.ts'
  14. const TEST_PLAN_SECTION = 'Test plan mode instructions.'
  15. const PLAN_CONFIG = { section: TEST_PLAN_SECTION } satisfies PlanModeConfig
  16. /**
  17. * Drives the REAL plugin: mounts `dsh-plan-mode` beside real `SystemPrompt` and
  18. * `ToolRegistry` services, with fake Agents carrying real `Session`s and a
  19. * real scoped `agent.ctx` minted through `createScope`.
  20. * Request boundaries are simulated by dispatching the real prompt-admission
  21. * and between-step seams used by the loop.
  22. */
  23. async function agentWithSession(ctx: Context, id = 'agent-1', { active }: { active?: boolean } = {}): Promise<Agent & { session: Session }> {
  24. // A live store session when a store is mounted (the command executor logs
  25. // lifecycle events through it); bare otherwise (fold/tool-only benches).
  26. const session = new Session(SessionId(id))
  27. const agent = { id: SessionId(id), session, options: {} } as unknown as Agent & { session: Session }
  28. let scoped!: Context
  29. await ctx.plugin(Object.assign((inner: Context) => { scoped = createScope(inner, agent).ctx }, {
  30. inject: ['tools'],
  31. }))
  32. ;(agent as { ctx?: Context }).ctx = scoped
  33. // Seeded plan state lands before the creation announcement, matching resume.
  34. if (active !== undefined) session.append('plan/mode', { active })
  35. // The loop announces creation after publication.
  36. ctx.emit('agent/created', agent)
  37. return agent
  38. }
  39. /** Assemble exactly as the loop does: the agent is both subject and scope. */
  40. function assembleFor(ctx: Context, agent: Agent) {
  41. return ctx.systemPrompt.assemble({ agent, scope: agent })
  42. }
  43. async function setup(config: PlanModeConfig = PLAN_CONFIG): Promise<Context> {
  44. const ctx = new Context()
  45. await ctx.plugin(SystemPrompt)
  46. await ctx.plugin(ToolRegistry)
  47. await ctx.plugin(PlanModeService, config)
  48. return ctx
  49. }
  50. /**
  51. * Dispatch either prompt admission or the between-step checkpoint.
  52. */
  53. async function boundary(ctx: Context, agent: Agent & { session: Session }, type: 'turn/start' | 'step/end'): Promise<void> {
  54. const events = agentEvents(ctx, agent)
  55. if (type === 'turn/start') {
  56. await events.waterfall(
  57. 'agent/prompt-submit',
  58. createUserMessage({
  59. content: [{ type: 'text', text: 'boundary probe' }],
  60. source: { kind: 'user' },
  61. }),
  62. new AbortController().signal,
  63. () => Promise.resolve({ kind: 'allow' }),
  64. )
  65. return
  66. }
  67. await events.serial('agent/step', 1, 2, new AbortController().signal)
  68. }
  69. /** Open a turn so a selection queues for the boundary flush (the mid-turn shape). */
  70. function openTurn(session: Session, turn = 0): void {
  71. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  72. }
  73. /** Close the open turn (the between-turns shape: selections commit immediately). */
  74. function closeTurn(session: Session, turn = 0): void {
  75. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  76. }
  77. /** Append a minimal `request/header` snapshot so the log has a "what the model was told" anchor. */
  78. function header(session: Session): void {
  79. session.append('request/header', { header: { config: { provider: 'test', model: 'test-model' } }, reason: 'initial' })
  80. }
  81. function noticeTexts(session: Session): string[] {
  82. return session.events
  83. .filter(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  84. .map(event => (event.data as { content: { type: string; text?: string }[] }).content.map(block => block.text ?? '').join(''))
  85. }
  86. function registerNamedTools(ctx: Context, names: string[]): void {
  87. for (const name of names) {
  88. ctx.tools.register(defineContentToolFixture({
  89. name,
  90. description: `test tool ${name}`,
  91. parameters: {},
  92. execute: () => Promise.resolve([{ type: 'text', text: `ran ${name}` }]),
  93. }))
  94. }
  95. }
  96. /** Assert the mapped Code Mode SDK includes the stable plan exit binding and test tools. */
  97. function expectPlanCodeSdkBindings(sdk: string): void {
  98. expect(sdk).toContain('interface ToolArgsMap {')
  99. expect(sdk).toContain('read: Record<string, JsonValue>;')
  100. expect(sdk).toContain('write: Record<string, JsonValue>;')
  101. expect(sdk).toContain('interface ToolOutputMap {')
  102. expect(sdk).toContain('exit_plan_mode: {\n approved: true;\n };')
  103. expect(sdk).toContain('[K in ToolName]: (args: ToolArgsMap[K]) => Promise<ToolOutputMap[K]>;')
  104. }
  105. let callCounter = 0
  106. function execute(ctx: Context, name: string, agent?: Agent) {
  107. return ctx.tools.execute({
  108. callId: CallId(`call-${++callCounter}`),
  109. name,
  110. arguments: {},
  111. signal: new AbortController().signal,
  112. ...agent ? { agent } : {},
  113. })
  114. }
  115. describe('resolveConfig', () => {
  116. it('requires string, non-empty plan instructions', () => {
  117. expect(() => resolveConfig({} as PlanModeConfig))
  118. .toThrow('needs a string `section`')
  119. expect(() => resolveConfig({ section: 5 } as unknown as PlanModeConfig))
  120. .toThrow('needs a string `section`')
  121. expect(() => resolveConfig({ section: ' ' }))
  122. .toThrow('needs a non-empty `section`')
  123. })
  124. it('returns a detached plan config', () => {
  125. const config = { section: TEST_PLAN_SECTION }
  126. const resolved = resolveConfig(config)
  127. expect(resolved).toEqual(config)
  128. expect(resolved).not.toBe(config)
  129. })
  130. it('rejects fields outside the plan policy config', () => {
  131. expect(() => resolveConfig({ section: TEST_PLAN_SECTION, tools: ['read'] } as unknown as PlanModeConfig))
  132. .toThrow('unknown key(s) tools — config is { section }')
  133. })
  134. })
  135. describe('foldPlanMode', () => {
  136. it('folds an empty log to inactive and takes the last plan/mode otherwise', () => {
  137. const session = new Session(SessionId('fold'))
  138. expect(foldPlanMode(session.events)).toBe(false)
  139. session.append('plan/mode', { active: true })
  140. session.append('plan/mode', { active: false })
  141. session.append('plan/mode', { active: true })
  142. expect(foldPlanMode(session.events)).toBe(true)
  143. })
  144. it('folds a prefix when `end` is given', () => {
  145. const session = new Session(SessionId('fold-prefix'))
  146. session.append('plan/mode', { active: true })
  147. session.append('plan/mode', { active: false })
  148. expect(foldPlanMode(session.events, 1)).toBe(true)
  149. expect(foldPlanMode(session.events, 0)).toBe(false)
  150. })
  151. })
  152. describe('ctx.planMode: get/set', () => {
  153. it('reads the folded state', async () => {
  154. const ctx = await setup()
  155. const agent = await agentWithSession(ctx)
  156. expect(ctx.planMode.get(agent)).toEqual({ active: false })
  157. agent.session.append('plan/mode', { active: true })
  158. expect(ctx.planMode.get(agent)).toEqual({ active: true })
  159. })
  160. it('selects inactive as the plan exit target during an open turn', async () => {
  161. const ctx = await setup()
  162. const agent = await agentWithSession(ctx)
  163. agent.session.append('plan/mode', { active: true })
  164. openTurn(agent.session)
  165. expect(ctx.planMode.set(agent, false)).toBe('queued')
  166. expect(ctx.planMode.get(agent)).toEqual({ active: true, pending: false })
  167. })
  168. it('drops a no-op set (target equals pending, else the current fold)', async () => {
  169. const ctx = await setup()
  170. const agent = await agentWithSession(ctx)
  171. openTurn(agent.session)
  172. expect(ctx.planMode.set(agent, false)).toBe('noop')
  173. expect(ctx.planMode.get(agent)).toEqual({ active: false })
  174. expect(ctx.planMode.set(agent, true)).toBe('queued')
  175. expect(ctx.planMode.set(agent, true)).toBe('noop')
  176. expect(ctx.planMode.get(agent)).toEqual({ active: false, pending: true })
  177. })
  178. it('a between-turns selection commits plan/mode immediately (no boundary would come)', async () => {
  179. const ctx = await setup()
  180. const agent = await agentWithSession(ctx, 'agent-idle')
  181. expect(ctx.planMode.set(agent, true)).toBe('committed')
  182. expect(foldPlanMode(agent.session.events)).toBe(true)
  183. expect(ctx.planMode.get(agent)).toEqual({ active: true })
  184. // Immediately reversible, still without a boundary.
  185. expect(ctx.planMode.set(agent, false)).toBe('committed')
  186. expect(foldPlanMode(agent.session.events)).toBe(false)
  187. // A later boundary finds nothing pending — no double append.
  188. await boundary(ctx, agent, 'step/end')
  189. expect(agent.session.events.filter(event => event.type === 'plan/mode')).toHaveLength(2)
  190. })
  191. it('a between-turns reversal of a mid-turn pending intent cancels without logging', async () => {
  192. const ctx = await setup()
  193. const agent = await agentWithSession(ctx)
  194. openTurn(agent.session)
  195. expect(ctx.planMode.set(agent, true)).toBe('queued')
  196. closeTurn(agent.session)
  197. // Back to the logged state: the pending intent clears, nothing lands.
  198. expect(ctx.planMode.set(agent, false)).toBe('cancelled')
  199. expect(agent.session.events.some(event => event.type === 'plan/mode')).toBe(false)
  200. expect(ctx.planMode.get(agent)).toEqual({ active: false })
  201. })
  202. it('a between-turns commit narrates when the last header told the model otherwise', async () => {
  203. const ctx = await setup()
  204. const agent = await agentWithSession(ctx, 'agent-idle-narrate')
  205. header(agent.session)
  206. ctx.planMode.set(agent, true)
  207. expect(noticeTexts(agent.session)).toEqual(['The user switched this session to plan mode.'])
  208. })
  209. })
  210. describe('the boundary flush', () => {
  211. it('does not flush at prompt admission — the seam is pre-turn, so the first step boundary lands it', async () => {
  212. const ctx = await setup()
  213. const agent = await agentWithSession(ctx)
  214. openTurn(agent.session)
  215. ctx.planMode.set(agent, true)
  216. // Prompt admission runs before any turn opens; a plan/mode appended there
  217. // would sit outside the turn. The pending intent survives admission and
  218. // the in-turn agent/step boundary flushes it before the request derives.
  219. await boundary(ctx, agent, 'turn/start')
  220. expect(agent.session.events.some(event => event.type === 'plan/mode')).toBe(false)
  221. expect(ctx.planMode.get(agent)).toEqual({ active: false, pending: true })
  222. await boundary(ctx, agent, 'step/end')
  223. expect(foldPlanMode(agent.session.events)).toBe(true)
  224. expect(ctx.planMode.get(agent)).toEqual({ active: true })
  225. })
  226. it('skips the flush after the plugin fiber is disposed (a captured wrapper must not write into a dead service)', async () => {
  227. const ctx = new Context()
  228. await ctx.plugin(SystemPrompt)
  229. await ctx.plugin(ToolRegistry)
  230. const fiber = await ctx.plugin(PlanModeService, PLAN_CONFIG)
  231. const agent = await agentWithSession(ctx)
  232. openTurn(agent.session)
  233. ctx.planMode.set(agent, true)
  234. // A listener captured in the same dispatch snapshot keeps the plan-mode
  235. // callback alive across the unload; the resumed wrapper must not append
  236. // through the disposed service. Registered prepended AFTER the plugin so
  237. // it runs before plan-mode's own prepended flush.
  238. ctx.on('agent/step', async () => {
  239. await fiber.dispose()
  240. }, { prepend: true })
  241. await agentEvents(ctx, agent).serial('agent/step', 1, 1, new AbortController().signal)
  242. expect(agent.session.events.some(event => event.type === 'plan/mode')).toBe(false)
  243. })
  244. it('skips the step-seam flush after the plugin fiber is disposed (a captured listener must not write into a dead service)', async () => {
  245. const ctx = new Context()
  246. await ctx.plugin(SystemPrompt)
  247. await ctx.plugin(ToolRegistry)
  248. const fiber = await ctx.plugin(PlanModeService, PLAN_CONFIG)
  249. const agent = await agentWithSession(ctx)
  250. openTurn(agent.session)
  251. ctx.planMode.set(agent, true)
  252. // Serial dispatch captures its listener list up front; prepending after
  253. // the plugin puts this listener ahead of the plugin's own prepended one,
  254. // so the plugin's captured callback still runs after the disposal below.
  255. ctx.on('agent/step', async () => {
  256. await fiber.dispose()
  257. }, { prepend: true })
  258. await agentEvents(ctx, agent).serial('agent/step', 1, 1, new AbortController().signal)
  259. expect(agent.session.events.some(event => event.type === 'plan/mode')).toBe(false)
  260. })
  261. it('flushes at the between-step seam too', async () => {
  262. const ctx = await setup()
  263. const agent = await agentWithSession(ctx)
  264. ctx.planMode.set(agent, true)
  265. await boundary(ctx, agent, 'step/end')
  266. expect(foldPlanMode(agent.session.events)).toBe(true)
  267. })
  268. it('nets out a flip sequence that returns to the folded mode (no append, no notice)', async () => {
  269. const ctx = await setup()
  270. const agent = await agentWithSession(ctx)
  271. openTurn(agent.session)
  272. ctx.planMode.set(agent, true)
  273. ctx.planMode.set(agent, false)
  274. await boundary(ctx, agent, 'turn/start')
  275. expect(agent.session.events.some(event => event.type === 'plan/mode')).toBe(false)
  276. expect(noticeTexts(agent.session)).toEqual([])
  277. })
  278. it('narrates nothing before the first request header (the section is the state statement)', async () => {
  279. const ctx = await setup()
  280. const agent = await agentWithSession(ctx)
  281. ctx.planMode.set(agent, true)
  282. await boundary(ctx, agent, 'turn/start')
  283. expect(noticeTexts(agent.session)).toEqual([])
  284. })
  285. it('narrates once when the flushed mode differs from what the last header told the model', async () => {
  286. const ctx = await setup()
  287. const agent = await agentWithSession(ctx)
  288. header(agent.session)
  289. ctx.planMode.set(agent, true)
  290. await boundary(ctx, agent, 'step/end')
  291. expect(noticeTexts(agent.session)).toEqual(['The user switched this session to plan mode.'])
  292. await boundary(ctx, agent, 'step/end')
  293. expect(noticeTexts(agent.session)).toEqual(['The user switched this session to plan mode.'])
  294. })
  295. it('narrates a switch back to the default mode with the default wording', async () => {
  296. const ctx = await setup()
  297. const agent = await agentWithSession(ctx)
  298. agent.session.append('plan/mode', { active: true })
  299. header(agent.session)
  300. ctx.planMode.set(agent, false)
  301. await boundary(ctx, agent, 'step/end')
  302. expect(noticeTexts(agent.session)).toEqual(['The user switched this session back to the default mode.'])
  303. })
  304. it('stays silent when the header already reflects the flushed mode', async () => {
  305. const ctx = await setup()
  306. const agent = await agentWithSession(ctx)
  307. agent.session.append('plan/mode', { active: true })
  308. header(agent.session)
  309. agent.session.append('plan/mode', { active: false })
  310. ctx.planMode.set(agent, true)
  311. await boundary(ctx, agent, 'step/end')
  312. expect(foldPlanMode(agent.session.events)).toBe(true)
  313. expect(noticeTexts(agent.session)).toEqual([])
  314. })
  315. it('contains an append failure instead of blocking the prompt or the turn', async () => {
  316. const ctx = await setup()
  317. const warn = vi.fn()
  318. ctx.logger.warn = warn as never
  319. const agent = await agentWithSession(ctx)
  320. openTurn(agent.session)
  321. ctx.planMode.set(agent, true)
  322. const original = agent.session.append.bind(agent.session)
  323. // Only the flush's own plan/mode append fails; the boundary event itself
  324. // lands (the loop appended it before the seam fires).
  325. agent.session.append = (((type: string, ...rest: unknown[]) => {
  326. if (type === 'plan/mode') throw new Error('backend gone')
  327. return (original as (...args: unknown[]) => unknown)(type, ...rest)
  328. }) as unknown) as typeof agent.session.append
  329. await boundary(ctx, agent, 'step/end')
  330. expect(warn).toHaveBeenCalledOnce()
  331. // The failed flush re-parks the intent (cleared only after a landed
  332. // append), so the next healthy boundary converges the log with the
  333. // picker's optimistic state instead of dropping the switch forever.
  334. expect(ctx.planMode.get(agent)).toEqual({ active: false, pending: true })
  335. agent.session.append = original
  336. await boundary(ctx, agent, 'step/end')
  337. expect(foldPlanMode(agent.session.events)).toBe(true)
  338. expect(ctx.planMode.get(agent).pending).toBeUndefined()
  339. })
  340. it('prompt admission never appends, so a broken backend surfaces only at the step boundary', async () => {
  341. const ctx = await setup()
  342. const warn = vi.fn()
  343. ctx.logger.warn = warn as never
  344. const agent = await agentWithSession(ctx)
  345. openTurn(agent.session)
  346. ctx.planMode.set(agent, true)
  347. const original = agent.session.append.bind(agent.session)
  348. agent.session.append = (((type: string, ...rest: unknown[]) => {
  349. if (type === 'plan/mode') throw new Error('backend gone')
  350. return (original as (...args: unknown[]) => unknown)(type, ...rest)
  351. }) as unknown) as typeof agent.session.append
  352. await boundary(ctx, agent, 'turn/start')
  353. expect(warn).not.toHaveBeenCalled()
  354. await boundary(ctx, agent, 'step/end')
  355. expect(warn).toHaveBeenCalledOnce()
  356. expect(ctx.planMode.get(agent)).toEqual({ active: false, pending: true })
  357. })
  358. })
  359. describe('the soft layer', () => {
  360. it('keeps the tool schemas identical across default and plan mode', async () => {
  361. const ctx = await setup()
  362. registerNamedTools(ctx, ['read', 'write'])
  363. const agent = await agentWithSession(ctx)
  364. const defaultAssembly = await assembleFor(ctx, agent)
  365. expect(defaultAssembly.tools.map(tool => tool.name)).toEqual([EXIT_PLAN_MODE, 'read', 'write'])
  366. expect(defaultAssembly.sections.find(section => section.name === 'plan:policy')?.text).toBe('')
  367. agent.session.append('plan/mode', { active: true })
  368. const planAssembly = await assembleFor(ctx, agent)
  369. expect(planAssembly.tools).toEqual(defaultAssembly.tools)
  370. expect(planAssembly.sections.find(section => section.name === 'plan:policy')?.text).toBe(TEST_PLAN_SECTION)
  371. })
  372. it('leaves an agent-less assembly untouched', async () => {
  373. const ctx = await setup()
  374. registerNamedTools(ctx, ['read'])
  375. const assembly = await ctx.systemPrompt.assemble()
  376. expect(assembly.tools.map(tool => tool.name)).toEqual([EXIT_PLAN_MODE, 'read'])
  377. expect(assembly.sections.find(section => section.name === 'plan:policy')?.text).toBe('')
  378. })
  379. it('keeps the full toolset in plan mode and renders the configured mode section', async () => {
  380. const ctx = await setup()
  381. registerNamedTools(ctx, ['read', 'write', 'todo_write'])
  382. const agent = await agentWithSession(ctx, 'agent-1', { active: true })
  383. const assembly = await assembleFor(ctx, agent)
  384. expect(assembly.tools.map(tool => tool.name).sort()).toEqual([EXIT_PLAN_MODE, 'read', 'todo_write', 'write'])
  385. expect(assembly.sections.find(section => section.name === 'plan:policy')?.text).toBe(TEST_PLAN_SECTION)
  386. })
  387. it('leaves foreign assemble additions alone (no assemble-layer filtering)', async () => {
  388. // Plan guidance does not filter the registry or later assembly additions.
  389. const ctx = new Context()
  390. await ctx.plugin(SystemPrompt)
  391. await ctx.plugin(ToolRegistry)
  392. ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
  393. const final = await next()
  394. final.tools = [...final.tools, { name: 'added-later', description: 'added after next()', parameters: {} }]
  395. return final
  396. })
  397. await ctx.plugin(PlanModeService, PLAN_CONFIG)
  398. registerNamedTools(ctx, ['read'])
  399. const planning = await agentWithSession(ctx, 'planning', { active: true })
  400. expect((await assembleFor(ctx, planning)).tools.map(tool => tool.name))
  401. .toEqual(['exit_plan_mode', 'read', 'added-later'])
  402. const defaulted = await agentWithSession(ctx, 'defaulted')
  403. expect((await assembleFor(ctx, defaulted)).tools.map(tool => tool.name))
  404. .toEqual(['exit_plan_mode', 'read', 'added-later'])
  405. })
  406. it('keeps run_code the only wire tool in plan mode under the registry Code Mode; the SDK gains the exit binding', async () => {
  407. // Minimal scriptable runtime: the SDK section resolves ctx.codeRuntime at
  408. // assembly time (the code-mode.spec fake's shape).
  409. class FakeRuntime extends CodeRuntime {
  410. readonly language = 'typescript'
  411. readonly isolation = 'fake'
  412. run(_request: CodeRunRequest): Promise<CodeRunResult> { return Promise.resolve({ logs: [] }) }
  413. }
  414. const ctx = new Context()
  415. await ctx.plugin(SystemPrompt)
  416. await ctx.plugin(ToolRegistry, { mode: 'code' })
  417. await ctx.plugin(FakeRuntime)
  418. await ctx.plugin(PlanModeService, PLAN_CONFIG)
  419. registerNamedTools(ctx, ['read', 'write'])
  420. const agent = await agentWithSession(ctx, 'agent-1', { active: true })
  421. const assembly = await assembleFor(ctx, agent)
  422. expect(assembly.tools.map(tool => tool.name)).toEqual(['run_code'])
  423. // The SDK documents the full binding set plus the exit; plan mode never
  424. // prunes capabilities and restrains through guidance alone.
  425. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  426. expectPlanCodeSdkBindings(sdk)
  427. })
  428. it('keeps native wire schemas and the SDK in step under mode both', async () => {
  429. class FakeRuntime extends CodeRuntime {
  430. readonly language = 'typescript'
  431. readonly isolation = 'fake'
  432. run(_request: CodeRunRequest): Promise<CodeRunResult> { return Promise.resolve({ logs: [] }) }
  433. }
  434. const ctx = new Context()
  435. await ctx.plugin(SystemPrompt)
  436. await ctx.plugin(ToolRegistry, { mode: 'both' })
  437. await ctx.plugin(FakeRuntime)
  438. await ctx.plugin(PlanModeService, PLAN_CONFIG)
  439. registerNamedTools(ctx, ['read', 'write'])
  440. const agent = await agentWithSession(ctx, 'agent-1', { active: true })
  441. const assembly = await assembleFor(ctx, agent)
  442. // The stable registry contribution reaches both surfaces: the exit tool
  443. // is present on the wire AND in the SDK alongside the untouched toolset.
  444. expect(assembly.tools.map(tool => tool.name).sort()).toEqual(['exit_plan_mode', 'read', 'run_code', 'write'])
  445. const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  446. expectPlanCodeSdkBindings(sdk)
  447. })
  448. it('keeps the Code Mode SDK byte-identical across mode switches', async () => {
  449. class FakeRuntime extends CodeRuntime {
  450. readonly language = 'typescript'
  451. readonly isolation = 'fake'
  452. run(_request: CodeRunRequest): Promise<CodeRunResult> { return Promise.resolve({ logs: [] }) }
  453. }
  454. const withPlanMode = new Context()
  455. await withPlanMode.plugin(SystemPrompt)
  456. await withPlanMode.plugin(ToolRegistry, { mode: 'code' })
  457. await withPlanMode.plugin(FakeRuntime)
  458. await withPlanMode.plugin(PlanModeService, PLAN_CONFIG)
  459. registerNamedTools(withPlanMode, ['read', 'write'])
  460. const agent = await agentWithSession(withPlanMode)
  461. const defaultSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  462. expectPlanCodeSdkBindings(defaultSdk)
  463. agent.session.append('plan/mode', { active: true })
  464. const planSdk = (await assembleFor(withPlanMode, agent)).sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  465. expect(planSdk).toBe(defaultSdk)
  466. // Loading the plan-mode plugin deliberately adds one stable binding compared
  467. // with a deployment that does not compose plan mode at all.
  468. const bare = new Context()
  469. await bare.plugin(SystemPrompt)
  470. await bare.plugin(ToolRegistry, { mode: 'code' })
  471. await bare.plugin(FakeRuntime)
  472. registerNamedTools(bare, ['read', 'write'])
  473. const bareSdk = (await bare.systemPrompt.assemble({ agent })).sections.find(section => section.name === 'tools:sdk')?.text ?? ''
  474. expect(bareSdk).not.toContain('exit_plan_mode:')
  475. expect(defaultSdk).not.toBe(bareSdk)
  476. })
  477. })
  478. describe('no execution gating beyond the exit tool', () => {
  479. it('passes agent-less and default-mode executions through', async () => {
  480. const ctx = await setup()
  481. registerNamedTools(ctx, ['write'])
  482. const agentless = await execute(ctx, 'write')
  483. expect(agentless.isError).toBe(false)
  484. const agent = await agentWithSession(ctx)
  485. const defaulted = await execute(ctx, 'write', agent)
  486. expect(defaulted.isError).toBe(false)
  487. })
  488. it('runs every call in plan mode untouched — guidance and enforcement are separate axes', async () => {
  489. const ctx = await setup()
  490. registerNamedTools(ctx, ['read', 'write', 'bash'])
  491. const agent = await agentWithSession(ctx, 'agent-1', { active: true })
  492. for (const name of ['read', 'write', 'bash']) {
  493. const result = await execute(ctx, name, agent)
  494. expect(result.isError).toBe(false)
  495. }
  496. })
  497. })
  498. describe('/plan', () => {
  499. it('registers only when a commands service is composed and optionally submits the next-step message', async () => {
  500. const bare = await setup()
  501. expect(bare.get('commands')).toBeUndefined()
  502. const ctx = await setup()
  503. await ctx.plugin(CommandService)
  504. // The `ctx.inject` child mounts asynchronously once `commands` resolves.
  505. await new Promise(resolve => setImmediate(resolve))
  506. const plainAgent = await agentWithSession(ctx, 'plain-plan-command')
  507. openTurn(plainAgent.session)
  508. const plainSteer = vi.fn()
  509. ;(plainAgent as unknown as { steer: typeof plainSteer }).steer = plainSteer
  510. expect(ctx.commands.list(plainAgent)).toEqual([
  511. { name: 'plan', description: 'Enter or leave plan mode', input: { hint: '[off|message]' } },
  512. ])
  513. const signal = new AbortController().signal
  514. expect(await ctx.commands.execute(plainAgent, '/mode', signal)).toBeUndefined()
  515. expect(await ctx.commands.execute(plainAgent, '/review', signal)).toBeUndefined()
  516. const plain = await ctx.commands.execute(plainAgent, '/plan', signal)
  517. expect(plain?.result).toEqual({
  518. kind: 'success',
  519. text: 'Entering plan mode (applies from the next step). Use /plan off to leave.',
  520. })
  521. expect(ctx.planMode.get(plainAgent)).toEqual({ active: false, pending: true })
  522. expect(plainSteer).not.toHaveBeenCalled()
  523. const messageAgent = await agentWithSession(ctx, 'message-plan-command')
  524. openTurn(messageAgent.session)
  525. const messageSteer = vi.fn()
  526. ;(messageAgent as unknown as { steer: typeof messageSteer }).steer = messageSteer
  527. const plan = await ctx.commands.execute(messageAgent, '/plan draft the migration ', signal)
  528. expect(plan?.result).toEqual({
  529. kind: 'success',
  530. text: 'Entering plan mode (applies from the next step). Use /plan off to leave.',
  531. })
  532. expect(ctx.planMode.get(messageAgent)).toEqual({ active: false, pending: true })
  533. expect(messageSteer).toHaveBeenCalledExactlyOnceWith({
  534. id: expect.any(String) as unknown,
  535. role: 'user',
  536. content: [{ type: 'text', text: 'draft the migration' }],
  537. source: { kind: 'user' },
  538. })
  539. })
  540. it('leaves active plan mode, cancels a pending entry, and treats inactive exit as idempotent', async () => {
  541. const ctx = await setup()
  542. await ctx.plugin(CommandService)
  543. await new Promise(resolve => setImmediate(resolve))
  544. const signal = new AbortController().signal
  545. const inactive = await agentWithSession(ctx, 'inactive-plan-command')
  546. expect((await ctx.commands.execute(inactive, '/plan off', signal))?.result)
  547. .toEqual({ kind: 'success', text: 'Plan mode is already inactive.' })
  548. expect(ctx.planMode.get(inactive)).toEqual({ active: false })
  549. const entering = await agentWithSession(ctx, 'entering-plan-command')
  550. openTurn(entering.session)
  551. const enteringSteer = vi.fn()
  552. ;(entering as unknown as { steer: typeof enteringSteer }).steer = enteringSteer
  553. await ctx.commands.execute(entering, '/plan', signal)
  554. expect((await ctx.commands.execute(entering, '/plan off', signal))?.result)
  555. .toEqual({ kind: 'success', text: 'Plan mode entry cancelled.' })
  556. expect(ctx.planMode.get(entering)).toEqual({ active: false, pending: false })
  557. expect(enteringSteer).not.toHaveBeenCalled()
  558. await boundary(ctx, entering, 'step/end')
  559. expect(ctx.planMode.get(entering)).toEqual({ active: false })
  560. expect(entering.session.events.some(event => event.type === 'plan/mode')).toBe(false)
  561. const active = await agentWithSession(ctx, 'active-plan-command', { active: true })
  562. openTurn(active.session)
  563. const activeSteer = vi.fn()
  564. ;(active as unknown as { steer: typeof activeSteer }).steer = activeSteer
  565. expect((await ctx.commands.execute(active, '/plan off', signal))?.result)
  566. .toEqual({ kind: 'success', text: 'Leaving plan mode (applies from the next step).' })
  567. expect(ctx.planMode.get(active)).toEqual({ active: true, pending: false })
  568. expect((await ctx.commands.execute(active, '/plan off', signal))?.result)
  569. .toEqual({ kind: 'success', text: 'Leaving plan mode (applies from the next step).' })
  570. expect(activeSteer).not.toHaveBeenCalled()
  571. await boundary(ctx, active, 'step/end')
  572. expect(ctx.planMode.get(active)).toEqual({ active: false })
  573. })
  574. it('idle sessions get the immediate-commit copy on both /plan and /plan off', async () => {
  575. const ctx = await setup()
  576. await ctx.plugin(CommandService)
  577. await new Promise(resolve => setImmediate(resolve))
  578. const signal = new AbortController().signal
  579. const agent = await agentWithSession(ctx, 'idle-plan-command')
  580. expect((await ctx.commands.execute(agent, '/plan', signal))?.result)
  581. .toEqual({ kind: 'success', text: 'Plan mode on. Use /plan off to leave.' })
  582. expect(foldPlanMode(agent.session.events)).toBe(true)
  583. expect((await ctx.commands.execute(agent, '/plan off', signal))?.result)
  584. .toEqual({ kind: 'success', text: 'Plan mode off.' })
  585. expect(foldPlanMode(agent.session.events)).toBe(false)
  586. })
  587. it('removes the contributed command when the plan-mode plugin is disposed', async () => {
  588. const ctx = new Context()
  589. await ctx.plugin(SystemPrompt)
  590. await ctx.plugin(ToolRegistry)
  591. await ctx.plugin(CommandService)
  592. const fiber = await ctx.plugin(PlanModeService, PLAN_CONFIG)
  593. await new Promise(resolve => setImmediate(resolve))
  594. const agent = await agentWithSession(ctx)
  595. expect(ctx.commands.list(agent).map(command => command.name)).toEqual(['plan'])
  596. await fiber.dispose()
  597. expect(ctx.commands.list(agent)).toEqual([])
  598. })
  599. })
  600. describe('exit_plan_mode', () => {
  601. async function setupWithReview(answer?: { selected: string[]; custom?: string }) {
  602. const ctx = await setup()
  603. await ctx.plugin(UserInteractionService)
  604. const asked: AskUserQuestionRequest[] = []
  605. if (answer !== undefined) {
  606. ctx.userInteraction.registerProvider({
  607. ask: (request) => {
  608. asked.push(request)
  609. return Promise.resolve({ answers: [{ id: 'plan-review', ...answer }] })
  610. },
  611. })
  612. }
  613. const agent = await agentWithSession(ctx, 'agent-1', { active: true })
  614. return { ctx, agent, asked }
  615. }
  616. function callExit(ctx: Context, agent: Agent | undefined, plan = '# The plan\n\ndo things') {
  617. return ctx.tools.execute({
  618. callId: CallId(`call-exit-${++callCounter}`),
  619. name: EXIT_PLAN_MODE,
  620. arguments: { plan },
  621. signal: new AbortController().signal,
  622. ...agent ? { agent } : {},
  623. })
  624. }
  625. it('registers the tool with one required plan argument', async () => {
  626. const ctx = await setup()
  627. const schema = ctx.tools.schemas().find(entry => entry.name === EXIT_PLAN_MODE)
  628. const parameters = schema?.parameters as { required?: string[]; properties?: Record<string, unknown> }
  629. expect(schema?.description).toMatch(/^Use only in plan mode\./)
  630. expect(Object.keys(parameters.properties ?? {})).toEqual(['plan'])
  631. expect(parameters.required).toEqual(['plan'])
  632. })
  633. it('rejects an agent-less call', async () => {
  634. const ctx = await setup()
  635. const result = await callExit(ctx, undefined)
  636. expect(result.isError).toBe(true)
  637. expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode requires a calling agent (no session to switch)' }])
  638. })
  639. it('rejects a call outside plan mode while remaining advertised', async () => {
  640. const ctx = await setup()
  641. const agent = await agentWithSession(ctx)
  642. expect(ctx.tools.schemas().map(tool => tool.name)).toContain(EXIT_PLAN_MODE)
  643. const result = await callExit(ctx, agent)
  644. expect(result.isError).toBe(true)
  645. expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }])
  646. })
  647. it('rejects an empty or heading-less plan before asking the reviewer', async () => {
  648. const { ctx, agent, asked } = await setupWithReview({ selected: ['Approve'] })
  649. for (const plan of ['', 'do things']) {
  650. const result = await callExit(ctx, agent, plan)
  651. expect(result.isError).toBe(true)
  652. expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode requires a non-empty markdown plan starting with a # heading' }])
  653. }
  654. expect(asked).toHaveLength(0)
  655. expect(foldPlanMode(agent.session.events)).toBe(true)
  656. })
  657. it('degrades to the manual exit when no user-interaction seam is composed', async () => {
  658. const ctx = await setup()
  659. const agent = await agentWithSession(ctx, 'agent-1', { active: true })
  660. const result = await callExit(ctx, agent)
  661. expect(result.isError).toBe(true)
  662. expect(result.content).toEqual([{ type: 'text', text: 'Error: no user-interaction channel is available to review the plan; ask the user to switch the session mode instead' }])
  663. expect(foldPlanMode(agent.session.events)).toBe(true)
  664. })
  665. it('degrades the same way when the seam has no provider (NO_PROVIDER)', async () => {
  666. const { ctx, agent } = await setupWithReview()
  667. const result = await callExit(ctx, agent)
  668. expect(result.isError).toBe(true)
  669. expect(result.content).toEqual([{ type: 'text', text: 'Error: no user-interaction provider is registered' }])
  670. expect(foldPlanMode(agent.session.events)).toBe(true)
  671. })
  672. it('approve: records the boundary-applied switch and confirms (the fold flips at the flush)', async () => {
  673. const { ctx, agent, asked } = await setupWithReview({ selected: ['Approve'] })
  674. const result = await callExit(ctx, agent)
  675. expect(result.isError).toBe(false)
  676. if (result.isError) throw new Error('expected approved plan result')
  677. expect(result.value).toEqual({ approved: true })
  678. expect(result.content).toEqual([{ type: 'text', text: 'Plan approved — plan mode exited; carry out the plan starting with your next step.' }])
  679. // Boundary-applied, not a direct append: the fold stays plan until the
  680. // step's end, so the plan policy covers any remaining call of the SAME batch.
  681. expect(foldPlanMode(agent.session.events)).toBe(true)
  682. expect(ctx.planMode.get(agent)).toEqual({ active: true, pending: false })
  683. await boundary(ctx, agent, 'step/end')
  684. expect(foldPlanMode(agent.session.events)).toBe(false)
  685. expect(asked).toHaveLength(1)
  686. expect(asked[0]?.agent).toBe(agent)
  687. expect(asked[0]?.questions[0]?.detail).toBe('# The plan\n\ndo things')
  688. expect(asked[0]?.questions[0]?.options?.map(option => option.label)).toEqual(['Approve', 'Keep planning'])
  689. })
  690. it('carries the exact plan through a Code Mode review and logs the nested dispatch', async () => {
  691. const plan = '# Code Mode plan\n\nUse the existing seam.'
  692. class ExitRuntime extends CodeRuntime {
  693. readonly language = 'typescript'
  694. readonly isolation = 'fake'
  695. async run(request: CodeRunRequest): Promise<CodeRunResult> {
  696. const exit = request.bindings[0]?.functions[EXIT_PLAN_MODE]
  697. if (exit === undefined) throw new Error('missing exit_plan_mode binding')
  698. return { logs: [], value: await exit({ plan }) }
  699. }
  700. }
  701. const ctx = new Context()
  702. await ctx.plugin(SystemPrompt)
  703. await ctx.plugin(ToolRegistry, { mode: 'code' })
  704. await ctx.plugin(ExitRuntime)
  705. await ctx.plugin(PlanModeService, PLAN_CONFIG)
  706. await ctx.plugin(UserInteractionService)
  707. const asked: AskUserQuestionRequest[] = []
  708. ctx.userInteraction.registerProvider({
  709. ask: (request) => {
  710. asked.push(request)
  711. return Promise.resolve({ answers: [{ id: 'plan-review', selected: ['Approve'] }] })
  712. },
  713. })
  714. const agent = await agentWithSession(ctx, 'code-mode-exit', { active: true })
  715. const result = await ctx.tools.execute({
  716. callId: CallId(`call-exit-${++callCounter}`),
  717. name: RUN_CODE_NAME,
  718. arguments: { code: `return await tools.${EXIT_PLAN_MODE}({ plan: ${JSON.stringify(plan)} })`, description: 'Submit the plan for review' },
  719. signal: new AbortController().signal,
  720. agent,
  721. })
  722. expect(result.isError).toBe(false)
  723. expect(asked).toHaveLength(1)
  724. expect(asked[0]?.questions[0]).toMatchObject({
  725. header: 'Plan review',
  726. question: 'Approve this plan and leave plan mode?',
  727. detail: plan,
  728. })
  729. expect(agent.session.events.find(event => event.type === 'tool/code-dispatch')?.data).toMatchObject({
  730. name: EXIT_PLAN_MODE,
  731. arguments: { plan },
  732. isError: false,
  733. })
  734. expect(ctx.planMode.get(agent)).toEqual({ active: true, pending: false })
  735. })
  736. it('an approved exit keeps plan guidance until the boundary and never removes the tool', async () => {
  737. const { ctx, agent } = await setupWithReview({ selected: ['Approve'] })
  738. const approved = await callExit(ctx, agent)
  739. expect(approved.isError).toBe(false)
  740. // Calls of the SAME assistant response (no boundary between) were
  741. // requested under the plan-shaped header — the fold stays plan for that
  742. // whole batch; the boundary flush is what flips the next step.
  743. expect(foldPlanMode(agent.session.events)).toBe(true)
  744. const assembly = await ctx.systemPrompt.assemble({ agent })
  745. expect(assembly.tools.some(tool => tool.name === EXIT_PLAN_MODE)).toBe(true)
  746. expect(assembly.sections.find(section => section.name === 'plan:policy')?.text).toBe(TEST_PLAN_SECTION)
  747. await boundary(ctx, agent, 'step/end')
  748. expect(foldPlanMode(agent.session.events)).toBe(false)
  749. const afterExit = await ctx.systemPrompt.assemble({ agent })
  750. expect(afterExit.tools).toEqual(assembly.tools)
  751. expect(afterExit.sections.find(section => section.name === 'plan:policy')?.text).toBe('')
  752. })
  753. it('the exit flush narrates nothing — the tool result is the narration', async () => {
  754. const { ctx, agent } = await setupWithReview({ selected: ['Approve'] })
  755. header(agent.session)
  756. await callExit(ctx, agent)
  757. await boundary(ctx, agent, 'step/end')
  758. expect(foldPlanMode(agent.session.events)).toBe(false)
  759. expect(noticeTexts(agent.session)).toEqual([])
  760. })
  761. it('keep planning returns the corrective error carrying the feedback verbatim', async () => {
  762. const { ctx, agent } = await setupWithReview({ selected: ['Keep planning'], custom: 'consider the resume path' })
  763. const result = await callExit(ctx, agent)
  764. expect(result.isError).toBe(true)
  765. expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: consider the resume path' }])
  766. expect(foldPlanMode(agent.session.events)).toBe(true)
  767. })
  768. it('keep planning without feedback returns the generic corrective error', async () => {
  769. const { ctx, agent } = await setupWithReview({ selected: ['Keep planning'] })
  770. const result = await callExit(ctx, agent)
  771. expect(result.isError).toBe(true)
  772. expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }])
  773. })
  774. it('a custom-text-only answer is feedback, never consent', async () => {
  775. const { ctx, agent } = await setupWithReview({ selected: [], custom: 'add tests first' })
  776. const result = await callExit(ctx, agent)
  777. expect(result.isError).toBe(true)
  778. expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: add tests first' }])
  779. expect(foldPlanMode(agent.session.events)).toBe(true)
  780. })
  781. it('requires exactly the single Approve selection', async () => {
  782. const { ctx, agent } = await setupWithReview({ selected: ['Approve', 'Keep planning'] })
  783. const result = await callExit(ctx, agent)
  784. expect(result.isError).toBe(true)
  785. expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }])
  786. expect(foldPlanMode(agent.session.events)).toBe(true)
  787. })
  788. it('treats custom text alongside Approve as feedback, not consent', async () => {
  789. const { ctx, agent } = await setupWithReview({ selected: ['Approve'], custom: 'change the tests' })
  790. const result = await callExit(ctx, agent)
  791. expect(result.isError).toBe(true)
  792. expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: change the tests' }])
  793. expect(foldPlanMode(agent.session.events)).toBe(true)
  794. })
  795. it('treats duplicate review answer items as non-consent', async () => {
  796. const { ctx, agent } = await setupWithReview()
  797. ctx.userInteraction.registerProvider({
  798. ask: () => Promise.resolve({ answers: [
  799. { id: 'plan-review', selected: ['Approve'] },
  800. { id: 'plan-review', selected: ['Keep planning'] },
  801. ] }),
  802. })
  803. const result = await callExit(ctx, agent)
  804. expect(result.isError).toBe(true)
  805. expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }])
  806. expect(foldPlanMode(agent.session.events)).toBe(true)
  807. })
  808. it('a missing answer item reads as keep-planning', async () => {
  809. const { ctx, agent } = await setupWithReview()
  810. ctx.userInteraction.registerProvider({ ask: () => Promise.resolve({ answers: [] }) })
  811. const result = await callExit(ctx, agent)
  812. expect(result.isError).toBe(true)
  813. expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }])
  814. })
  815. it('forwards the execution abort signal to the review question', async () => {
  816. const { ctx, agent, asked } = await setupWithReview({ selected: ['Approve'] })
  817. const controller = new AbortController()
  818. const result = await ctx.tools.execute({
  819. callId: CallId(`call-exit-${++callCounter}`),
  820. name: EXIT_PLAN_MODE,
  821. arguments: { plan: '# P' },
  822. agent,
  823. signal: controller.signal,
  824. })
  825. expect(result.isError).toBe(false)
  826. expect(asked[0]?.signal).toBe(controller.signal)
  827. })
  828. it('fails the call when the plugin is disposed while the review awaits (no phantom exit)', async () => {
  829. const ctx = new Context()
  830. await ctx.plugin(SystemPrompt)
  831. await ctx.plugin(ToolRegistry)
  832. const fiber = await ctx.plugin(PlanModeService, PLAN_CONFIG)
  833. await ctx.plugin(UserInteractionService)
  834. let answer!: (value: { answers: { id: string; selected: string[] }[] }) => void
  835. ctx.userInteraction.registerProvider({
  836. ask: () => new Promise((resolve) => { answer = resolve }),
  837. })
  838. const agent = await agentWithSession(ctx, 'agent-1', { active: true })
  839. const pending = callExit(ctx, agent)
  840. // Let execute reach the review await, then unload the plugin (HMR) and
  841. // only afterwards approve. The boundary listeners are gone, so a success
  842. // would claim an exit that can never flush — the call must fail instead.
  843. await new Promise(resolve => setImmediate(resolve))
  844. await fiber.dispose()
  845. answer({ answers: [{ id: 'plan-review', selected: ['Approve'] }] })
  846. const result = await pending
  847. expect(result.isError).toBe(true)
  848. expect(result.content).toEqual([{ type: 'text', text: 'Error: the plan-mode service was reloaded while the plan was under review; present the plan again' }])
  849. expect(foldPlanMode(agent.session.events)).toBe(true)
  850. })
  851. it('a throwing provider surfaces as the corrective isError and the mode stays plan', async () => {
  852. const { ctx, agent } = await setupWithReview()
  853. ctx.userInteraction.registerProvider({ ask: () => { throw new Error('review aborted') } })
  854. const result = await callExit(ctx, agent)
  855. expect(result.isError).toBe(true)
  856. expect(result.content).toEqual([{ type: 'text', text: 'Error: review aborted' }])
  857. expect(foldPlanMode(agent.session.events)).toBe(true)
  858. })
  859. it('presents the call as a generic card titled by the plan first heading', async () => {
  860. const ctx = await setup()
  861. const def = ctx.tools.get(EXIT_PLAN_MODE)!
  862. expect(def.presentCall?.({ plan: '## Fix the flake\n\nsteps' })).toEqual({
  863. card: 'generic',
  864. title: 'Fix the flake',
  865. kind: 'other',
  866. content: [{ type: 'text', text: '## Fix the flake\n\nsteps' }],
  867. })
  868. expect(def.presentCall?.({ plan: 'no heading here' })).toEqual({
  869. card: 'generic',
  870. title: 'Plan',
  871. kind: 'other',
  872. content: [{ type: 'text', text: 'no heading here' }],
  873. })
  874. })
  875. it('presents the result as a generic review card', async () => {
  876. const ctx = await setup()
  877. const def = ctx.tools.get(EXIT_PLAN_MODE)!
  878. const content = [{ type: 'text' as const, text: 'ok' }]
  879. expect(def.presentResult?.({ plan: '# P' }, { content, isError: false })).toEqual({
  880. card: 'generic',
  881. title: 'Plan review',
  882. content,
  883. })
  884. })
  885. })
  886. describe('HMR disposal', () => {
  887. it('unregisters the service, listeners, prompt section, and stable exit tool with the plugin fiber', async () => {
  888. const ctx = new Context()
  889. await ctx.plugin(SystemPrompt)
  890. await ctx.plugin(ToolRegistry)
  891. const fiber = await ctx.plugin(PlanModeService, PLAN_CONFIG)
  892. const agent = await agentWithSession(ctx, 'disposed-recovery')
  893. openTurn(agent.session)
  894. ctx.planMode.set(agent, true)
  895. expect(ctx.get('planMode')).toBeInstanceOf(PlanModeService)
  896. expect(ctx.tools.get(EXIT_PLAN_MODE)).toBeDefined()
  897. expect((await ctx.systemPrompt.assemble()).sections.map(section => section.name)).toContain('plan:policy')
  898. await fiber.dispose()
  899. expect(ctx.get('planMode')).toBeUndefined()
  900. expect(ctx.tools.get(EXIT_PLAN_MODE)).toBeUndefined()
  901. expect((await ctx.systemPrompt.assemble()).sections.map(section => section.name)).not.toContain('plan:policy')
  902. await boundary(ctx, agent, 'step/end')
  903. expect(agent.session.events.some(event => event.type === 'plan/mode')).toBe(false)
  904. })
  905. })