plan-mode.spec.ts 55 KB

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