index.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /**
  2. * Plan mode is logged per-agent collaboration state: while active, a
  3. * deployment-owned guidance section is included in each model request, and
  4. * `exit_plan_mode` presents the completed plan for user review, while the
  5. * `/plan off` command lets a user leave directly. Sandbox mode and approval
  6. * policy enforce restrictions independently and do not read or write plan
  7. * state.
  8. *
  9. * The `plan` projection folds the session log, so resume and fork restore the
  10. * state. User selections remain pending until the next accepted in-turn
  11. * pre-step. The service includes the selected state in the proposed step
  12. * assembly, then appends `plan/mode` from `agent/pre-step` only when the step
  13. * is accepted. Same-step request retries reuse their assembly.
  14. *
  15. * The exit tool remains registered while plan mode is inactive, so entering
  16. * or leaving plan mode changes only the prompt section, not the request tool
  17. * catalog.
  18. *
  19. * Agent Note:
  20. * - .agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md
  21. *
  22. * @module @deepseek-ai/dsh-plan-mode
  23. */
  24. import { Context, Service } from '@deepseek-ai/cordis'
  25. import { z as zod } from 'zod'
  26. import type { ZodType } from 'zod'
  27. import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent'
  28. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  29. import type { Session, UserMessage } from '@deepseek-ai/dsh-session'
  30. import { defineTool } from '@deepseek-ai/dsh-tools'
  31. import { UserQuestionError } from '@deepseek-ai/dsh-user-questions'
  32. import type { CommandId } from '@deepseek-ai/dsh-commands'
  33. import type {} from '@deepseek-ai/dsh-session-projection'
  34. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  35. import type { PlanProjection, PlanUnitState } from './types.ts'
  36. export type * from './types.ts'
  37. declare module '@deepseek-ai/dsh-session/types' {
  38. interface SessionEventMap {
  39. /**
  40. * Whether plan mode is in force from this point on: log-only, non-surface,
  41. * whole-value replace. The last `plan/mode` wins; a log with none folds to
  42. * inactive through the projection unit's fold.
  43. */
  44. 'plan/mode': { active: boolean }
  45. }
  46. }
  47. declare module '@deepseek-ai/cordis' {
  48. interface Context {
  49. planMode: PlanModeController
  50. }
  51. }
  52. /**
  53. * The model-facing exit tool's name. It stays registered while plan mode is
  54. * inactive so the request tool catalog is stable across transitions.
  55. */
  56. export const EXIT_PLAN_MODE = 'exit_plan_mode'
  57. /** Deployment-owned plan guidance. */
  58. export interface PlanModeConfig {
  59. /** Guidance rendered as the `plan:policy` prompt section while plan mode is active. */
  60. section: string
  61. }
  62. /** The review question's id, echoed in the answer this tool reads. */
  63. const REVIEW_ID = 'plan-review'
  64. /** The review question's approve option label. */
  65. const APPROVE_LABEL = 'Approve'
  66. /** The review question's keep-planning option label. */
  67. const KEEP_PLANNING_LABEL = 'Keep planning'
  68. const EXIT_DESCRIPTION
  69. = 'Use only in plan mode. Present your plan for the user\'s review and, on approval, leave plan mode. '
  70. + 'Send the COMPLETE plan as markdown, starting with a # heading that names it. '
  71. + 'The user may approve (carry out the plan from your next step) or keep '
  72. + 'planning — their feedback comes back in the tool result; revise and present again.'
  73. /** The plan's first markdown heading (any level), or `undefined` when it has none. */
  74. function firstHeading(plan: string): string | undefined {
  75. for (const line of plan.split('\n')) {
  76. const match = /^#{1,6}\s+(.+?)\s*$/.exec(line)
  77. if (match) return match[1]
  78. }
  79. return undefined
  80. }
  81. /**
  82. * Validate deployment-owned plan guidance. Missing, blank, non-string, or
  83. * unknown fields fail at plugin load rather than being ignored.
  84. *
  85. * @param config Raw plugin config.
  86. * @returns A detached validated config.
  87. */
  88. export function resolveConfig(config: PlanModeConfig): PlanModeConfig {
  89. const section = (config as Partial<PlanModeConfig>).section
  90. if (typeof section !== 'string') {
  91. throw new Error('PlanModeConfig needs a string `section`')
  92. }
  93. if (section.trim() === '') {
  94. throw new Error('PlanModeConfig needs a non-empty `section`')
  95. }
  96. const unknown = Object.keys(config).filter(key => key !== 'section')
  97. if (unknown.length > 0) {
  98. throw new Error(`PlanModeConfig has unknown key(s) ${unknown.join(', ')} — config is { section }`)
  99. }
  100. return { section }
  101. }
  102. const planUnitStateSchema: ZodType<PlanUnitState> = zod.object({
  103. active: zod.boolean(),
  104. wanted: zod.boolean().nullable(),
  105. running: zod.object({
  106. commandId: zod.string() as unknown as ZodType<CommandId>,
  107. wanted: zod.boolean(),
  108. }).strict().nullable(),
  109. activeAtLastHeader: zod.boolean().nullable(),
  110. }).strict()
  111. /** Wire payload schema of the `plan` projection. */
  112. const planProjectionSchema: ZodType<PlanProjection> = zod.object({
  113. active: zod.boolean(),
  114. pending: zod.boolean(),
  115. })
  116. /** Projection of logged plan selections and committed mode. */
  117. export const planProjectionDefinition = {
  118. key: 'plan',
  119. stateVersion: 3,
  120. stateSchema: planUnitStateSchema,
  121. init: () => ({ active: false, wanted: null, running: null, activeAtLastHeader: null }),
  122. apply: (state, event) => {
  123. if (event.type === 'command/run' && event.data.name === 'plan') {
  124. if (event.data.args === undefined) return state
  125. const wanted = event.data.args.trim() !== 'off'
  126. return { ...state, running: { commandId: event.data.commandId, wanted } }
  127. }
  128. if (event.type === 'command/done' && event.data.commandId === state.running?.commandId) {
  129. const wanted = event.data.kind === 'success' && state.running.wanted !== state.active
  130. ? state.running.wanted
  131. : null
  132. return { ...state, wanted, running: null }
  133. }
  134. if (event.type === 'plan/mode') {
  135. return { ...state, active: event.data.active, wanted: null }
  136. }
  137. if (event.type === 'request/header') {
  138. return { ...state, activeAtLastHeader: state.active }
  139. }
  140. return state
  141. },
  142. wire: {
  143. viewSchema: planProjectionSchema,
  144. view: (state) => {
  145. const wanted = state.running?.wanted ?? state.wanted
  146. return { active: state.active, pending: wanted !== null && wanted !== state.active }
  147. },
  148. },
  149. } satisfies ProjectionDefinition<'plan', PlanUnitState>
  150. /**
  151. * `ctx.planMode`: owns logged plan state, applies and narrates selected state at step start,
  152. * the `plan:policy` section, the `/plan` command, and the stable exit tool.
  153. * Client carriers expose the projection's cropped `{ active, pending }` view.
  154. */
  155. export class PlanModeController extends Service {
  156. static inject = ['tools', 'systemPrompt', 'sessionProjections']
  157. /** Validated deployment-owned guidance. */
  158. private readonly section: string
  159. /**
  160. * Latest selection per session awaiting the next accepted in-turn pre-step.
  161. * `narrate` is true for user selections and false for the exit tool, whose
  162. * result already narrates the transition.
  163. */
  164. private readonly pendingIntents = new WeakMap<Session, { active: boolean; narrate: boolean }>()
  165. constructor(ctx: Context, config: PlanModeConfig = { section: '' }) {
  166. super(ctx, 'planMode')
  167. this.section = resolveConfig(config).section
  168. let disposed = false
  169. // Pre-step is outside Session.append publication, so it can append the
  170. // log-only mode event inside an open turn without re-entering the session.
  171. // A failed append remains pending for a later accepted in-turn pre-step,
  172. // and policy cannot block the step.
  173. ctx.on('agent/pre-step', async (
  174. { agent, signal },
  175. next,
  176. ): Promise<PreStepDecision> => {
  177. const decision = await next()
  178. const pending = this.pendingIntents.get(agent.session)
  179. if (decision.kind === 'reject' || signal.aborted || pending === undefined) return decision
  180. const narration = this.narration(agent.session, pending.active)
  181. try {
  182. this.onBoundary(agent.session)
  183. } catch (error) {
  184. ctx.logger.warn('dsh-plan-mode: failed to append selected plan mode at step start: %o', error)
  185. return decision
  186. }
  187. return !pending.narrate || narration === undefined
  188. ? decision
  189. : { ...decision, messages: [...decision.messages, narration] }
  190. })
  191. ctx.effect(() => () => { disposed = true }, 'dsh-plan-mode: close service lifetime')
  192. ctx.systemPrompt.section({
  193. name: 'plan:policy',
  194. order: ctx.systemPrompt.getSectionOrder('PLAN_POLICY'),
  195. text: (context) => {
  196. if (context.agent === undefined) return ''
  197. const pending = this.pendingIntents.get(context.agent.session)
  198. return (pending?.active ?? this.loggedActive(context.agent.session)) ? this.section : ''
  199. },
  200. })
  201. ctx.sessionProjections.register(planProjectionDefinition)
  202. // The command child activates only when a command registry is composed.
  203. ctx.inject(['commands'], (commandCtx) => {
  204. commandCtx.commands.register({
  205. name: 'plan',
  206. description: 'Enter or leave plan mode',
  207. input: { hint: '[off|message]', attachments: true },
  208. handler: ({ agent, rawInput, attachments }) => {
  209. const message = rawInput.trim()
  210. if (message === 'off' && attachments.length > 0) {
  211. return { kind: 'error', text: 'Attachments cannot accompany /plan off.' }
  212. }
  213. if (message === 'off') {
  214. switch (this.set(agent, false)) {
  215. case 'committed':
  216. return { kind: 'success', text: 'Plan mode off.' }
  217. case 'queued':
  218. return { kind: 'success', text: 'Leaving plan mode (applies from the next step).' }
  219. case 'cancelled':
  220. return { kind: 'success', text: 'Plan mode entry cancelled.' }
  221. case 'noop':
  222. // Repeat the queued wording while an exit still awaits the
  223. // next accepted pre-step; only a truly inactive session reads
  224. // idempotent.
  225. return this.loggedActive(agent.session)
  226. ? { kind: 'success', text: 'Leaving plan mode (applies from the next step).' }
  227. : { kind: 'success', text: 'Plan mode is already inactive.' }
  228. }
  229. }
  230. const outcome = this.set(agent, true)
  231. if (message !== '' || attachments.length > 0) {
  232. agent.steer(createUserMessage({
  233. content: [
  234. ...attachments,
  235. ...(message === '' ? [] : [{ type: 'text' as const, text: message }]),
  236. ],
  237. source: { kind: 'user' },
  238. }))
  239. }
  240. return {
  241. kind: 'success',
  242. text: outcome === 'committed'
  243. ? 'Plan mode on. Use /plan off to leave.'
  244. : 'Entering plan mode (applies from the next step). Use /plan off to leave.',
  245. }
  246. },
  247. })
  248. })
  249. ctx.tools.register(defineTool({
  250. name: EXIT_PLAN_MODE,
  251. description: EXIT_DESCRIPTION,
  252. parameters: {
  253. plan: { type: 'string', required: true, description: 'The complete plan, as markdown, starting with a # heading that names it.' },
  254. },
  255. output: {
  256. schema: {
  257. type: 'object',
  258. additionalProperties: false,
  259. properties: {
  260. approved: { type: 'boolean', const: true, required: true },
  261. },
  262. },
  263. render: () => [{ type: 'text', text: 'Plan approved — plan mode exited; carry out the plan starting with your next step.' }],
  264. },
  265. execute: async (args, exec) => {
  266. const agent = exec.agent
  267. if (agent === undefined) throw new Error(`${EXIT_PLAN_MODE} requires a calling agent (no session to switch)`)
  268. if (!this.loggedActive(agent.session)) {
  269. throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`)
  270. }
  271. if (!/^#\s+\S/.test(args.plan.trim())) {
  272. throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`)
  273. }
  274. const interaction = ctx.get('userQuestions')
  275. if (interaction === undefined) {
  276. throw new Error('no user-questions channel is available to review the plan; ask the user to switch the session mode instead')
  277. }
  278. const answer = await interaction.ask({
  279. questions: [{
  280. id: REVIEW_ID,
  281. header: 'Plan review',
  282. question: 'Approve this plan and leave plan mode?',
  283. detail: args.plan,
  284. options: [
  285. { label: APPROVE_LABEL, description: 'Leave plan mode; the plan is carried out from the next step.' },
  286. { label: KEEP_PLANNING_LABEL, description: 'Stay in plan mode; feedback goes back to the model.' },
  287. ],
  288. // Presentation only: a capable UI renders the plan as a review
  289. // decision instead of a generic question, and answers with one of
  290. // the labels above either way.
  291. intent: { kind: 'plan-review', approve: APPROVE_LABEL },
  292. }],
  293. agent,
  294. signal: exec.signal,
  295. }).catch((cause: unknown) => {
  296. // A dismissed review is not a failed one: the user took the turn back
  297. // to say something the two options do not cover. Say so, because the
  298. // generic channel message names ask_user_question, which the model
  299. // never called. An abort (turn cancel, provider teardown) keeps its
  300. // own message — there is no user to wait for.
  301. if (cause instanceof UserQuestionError && cause.code === 'ASK_CANCELLED') {
  302. throw new Error('The user dismissed the plan review to speak instead; '
  303. + 'stay in plan mode, stop here, and wait for their message.')
  304. }
  305. throw cause
  306. })
  307. // A review may outlive this plugin fiber. Without its pre-step listener,
  308. // an approved selection could never be appended, so fail and keep planning.
  309. if (disposed) {
  310. throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again')
  311. }
  312. const reviewItems = answer.answers.filter(entry => entry.id === REVIEW_ID)
  313. const item = reviewItems.length === 1 ? reviewItems[0] : undefined
  314. if (item?.selected.length !== 1 || item.selected[0] !== APPROVE_LABEL || item.custom !== undefined) {
  315. const feedback = item?.custom ?? ''
  316. throw new Error(feedback === ''
  317. ? 'The user chose to keep planning; revise the plan and present it again.'
  318. : `The user chose to keep planning; their feedback: ${feedback}`)
  319. }
  320. // Keep plan guidance for the rest of this assistant tool batch. The
  321. // silent selection is appended at the next accepted in-turn pre-step,
  322. // before its request assembly.
  323. this.pendingIntents.set(agent.session, { active: false, narrate: false })
  324. return { approved: true }
  325. },
  326. presentCall: args => ({
  327. card: 'generic',
  328. title: firstHeading(args.plan) ?? 'Plan',
  329. kind: 'other',
  330. content: [{ type: 'text', text: args.plan }],
  331. }),
  332. presentResult: (_args, result) => ({
  333. card: 'generic',
  334. title: 'Plan review',
  335. content: result.content,
  336. }),
  337. }))
  338. }
  339. private loggedActive(session: Session): boolean {
  340. return this.planState(session).active
  341. }
  342. private hasOpenTurn(session: Session): boolean {
  343. const state = this.ctx.sessionProjections.stateOf(session, 'turnBoundary')
  344. if (state === undefined) throw new Error('plan-mode requires the turnBoundary session projection')
  345. return state.openTurnStartSeq !== null
  346. }
  347. private loggedActiveAtLastHeader(session: Session): boolean | undefined {
  348. return this.planState(session).activeAtLastHeader ?? undefined
  349. }
  350. /** Read the required plan projection state or fail at the first service access. */
  351. private planState(session: Session): PlanUnitState {
  352. const state = this.ctx.sessionProjections.stateOf(session, 'plan')
  353. if (state === undefined) throw new Error('plan-mode requires the plan session projection')
  354. return state
  355. }
  356. /**
  357. * Read the logged plan state and any selected state awaiting the next
  358. * accepted in-turn pre-step.
  359. *
  360. * @param agent The agent to read.
  361. * @returns Current logged state plus a pending selection, when present.
  362. */
  363. get(agent: Agent): { active: boolean; pending?: boolean } {
  364. const active = this.loggedActive(agent.session)
  365. const pending = this.pendingIntents.get(agent.session)
  366. return pending === undefined ? { active } : { active, pending: pending.active }
  367. }
  368. /**
  369. * Select whether plan mode should be active. Between turns the method
  370. * appends the change immediately because no in-turn pre-step will run until
  371. * another prompt starts a turn. The open-turn fold is the idle signal:
  372. * agent status stays `running` through post-turn checkpointing, when no
  373. * further in-turn pre-step runs. During an open turn the selection remains
  374. * pending until the next accepted in-turn pre-step. Repeated selection of
  375. * the current or already-pending state is a no-op.
  376. *
  377. * @param agent The agent to switch.
  378. * @param active Whether plan mode should be active.
  379. * @returns what happened: `committed` (logged now), `queued` (awaiting the
  380. * next accepted in-turn pre-step), `cancelled` (an opposite pending selection
  381. * was cleared; the logged state already matches), or `noop` (already in that
  382. * state).
  383. */
  384. set(agent: Agent, active: boolean): 'committed' | 'queued' | 'cancelled' | 'noop' {
  385. const session = agent.session
  386. const pending = this.pendingIntents.get(session)
  387. const target = pending?.active ?? this.loggedActive(session)
  388. if (active === target) return 'noop'
  389. if (this.hasOpenTurn(session)) {
  390. this.pendingIntents.set(session, { active, narrate: true })
  391. return this.loggedActive(session) === active ? 'cancelled' : 'queued'
  392. }
  393. // No open turn: commit now. Delete only after append succeeds so a
  394. // failed durable write leaves the selection retryable, not dropped.
  395. if (active === this.loggedActive(session)) {
  396. this.pendingIntents.delete(session)
  397. return 'cancelled'
  398. }
  399. session.append('plan/mode', { active })
  400. this.pendingIntents.delete(session)
  401. const narration = this.narration(session, active)
  402. if (narration !== undefined) agent.inject(narration)
  403. return 'committed'
  404. }
  405. /** Append one pending selection before the next request assembly. */
  406. private onBoundary(session: Session): void {
  407. const pending = this.pendingIntents.get(session)
  408. if (pending === undefined) return
  409. const target = pending.active
  410. if (target === this.loggedActive(session)) {
  411. this.pendingIntents.delete(session)
  412. return
  413. }
  414. session.append('plan/mode', { active: target })
  415. // Delete only after append succeeds so a later accepted in-turn pre-step
  416. // can retry a failed durable write.
  417. this.pendingIntents.delete(session)
  418. }
  419. /** Build a user-switch notice when the last logged header described the other mode. */
  420. private narration(session: Session, target: boolean): UserMessage | undefined {
  421. const told = this.loggedActiveAtLastHeader(session)
  422. if (told === undefined || told === target) return
  423. const text = target
  424. ? 'The user switched this session to plan mode.'
  425. : 'The user switched this session back to the default mode.'
  426. return createUserMessage({
  427. content: [{ type: 'text', text }],
  428. // The narration is already one sentence, so it is its own summary.
  429. source: { kind: 'plugin', plugin: 'plan-mode', form: 'notice', summary: text },
  430. })
  431. }
  432. }
  433. export default PlanModeController