plan-mode.spec.ts 48 KB

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