index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /**
  2. * Plan mode is logged per-agent collaboration state: while active, a
  3. * deployment-owned guidance section shapes 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. Plan mode is independent of
  6. * sandbox mode and approval policy; those enforcement axes do not read or
  7. * write plan state.
  8. *
  9. * The state in force is folded from the session log (`plan/mode`, last one
  10. * wins), so resume and fork restore it without a live mirror. User selections
  11. * are held as pending intent until an in-turn request boundary because every
  12. * session event is turn-enclosed. The service flushes at `agent/step` before
  13. * the affected request assembly, including retry turns.
  14. *
  15. * The exit tool remains registered while plan mode is inactive so crossing a
  16. * boundary changes only the prompt section, not the request tool catalog.
  17. *
  18. * Agent Note:
  19. * - .agents/notes/implemented/simplification/2026-07-22-plan-specific-collaboration-state.md
  20. *
  21. * @module @deepseek-ai/dsh-plan-mode
  22. */
  23. import { Context, Service } from 'cordis'
  24. import { z as zod } from 'zod'
  25. import type { ZodType } from 'zod'
  26. import type { Agent } from '@deepseek-ai/dsh-agent'
  27. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  28. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  29. import { defineTool } from '@deepseek-ai/dsh-tools'
  30. import type {} from '@deepseek-ai/dsh-system-prompt'
  31. import type {} from '@deepseek-ai/dsh-user-interaction'
  32. // Type-only edge: resolves `ctx.commands` for the optional command child.
  33. import type {} from '@deepseek-ai/dsh-commands'
  34. // Type-only: resolves ctx.sessionProjections for the optional unit child.
  35. import type {} from '@deepseek-ai/dsh-session-projection'
  36. import type { PlanProjection } from './types.ts'
  37. // The `plan` projection-key declaration lives in src/types.ts (its one home);
  38. // this re-export projects the type face onto the package root AND keeps the
  39. // module edge in the emitted index.d.ts, so aggregate programs consuming the
  40. // declarations still receive the SessionProjectionMap merge.
  41. export type * from './types.ts'
  42. declare module '@deepseek-ai/dsh-session' {
  43. interface SessionEventMap {
  44. /**
  45. * Whether plan mode is in force from this point on: log-only, non-surface,
  46. * whole-value replace. The last `plan/mode` wins; a log with none folds to
  47. * inactive through {@link foldPlanMode}.
  48. */
  49. 'plan/mode': { active: boolean }
  50. }
  51. }
  52. declare module 'cordis' {
  53. interface Context {
  54. planMode: PlanModeService
  55. }
  56. }
  57. /**
  58. * The model-facing exit tool's name. It stays registered while plan mode is
  59. * inactive so the request tool catalog is stable across transitions.
  60. */
  61. export const EXIT_PLAN_MODE = 'exit_plan_mode'
  62. /** Deployment-owned plan guidance. */
  63. export interface PlanModeConfig {
  64. /** Guidance rendered as the `plan:policy` prompt section while plan mode is active. */
  65. section: string
  66. }
  67. /** The review question's approve option label. */
  68. const APPROVE_LABEL = 'Approve'
  69. /** The review question's keep-planning option label. */
  70. const KEEP_PLANNING_LABEL = 'Keep planning'
  71. const EXIT_DESCRIPTION
  72. = 'Use only in plan mode. Present your plan for the user\'s review and, on approval, leave plan mode. '
  73. + 'Send the COMPLETE plan as markdown, starting with a # heading that names it. '
  74. + 'The user may approve (carry out the plan from your next step) or keep '
  75. + 'planning — their feedback comes back in the tool result; revise and present again.'
  76. /** The plan's first markdown heading (any level), or `undefined` when it has none. */
  77. function firstHeading(plan: string): string | undefined {
  78. for (const line of plan.split('\n')) {
  79. const match = /^#{1,6}\s+(.+?)\s*$/.exec(line)
  80. if (match) return match[1]
  81. }
  82. return undefined
  83. }
  84. /**
  85. * Validate deployment-owned plan guidance. Missing, blank, non-string, or
  86. * unknown fields fail at plugin load rather than silently shaping nothing.
  87. *
  88. * @param config Raw plugin config.
  89. * @returns A detached validated config.
  90. */
  91. export function resolveConfig(config: PlanModeConfig): PlanModeConfig {
  92. const section = (config as Partial<PlanModeConfig>).section
  93. if (typeof section !== 'string') {
  94. throw new Error('PlanModeConfig needs a string `section`')
  95. }
  96. if (section.trim() === '') {
  97. throw new Error('PlanModeConfig needs a non-empty `section`')
  98. }
  99. const unknown = Object.keys(config).filter(key => key !== 'section')
  100. if (unknown.length > 0) {
  101. throw new Error(`PlanModeConfig has unknown key(s) ${unknown.join(', ')} — config is { section }`)
  102. }
  103. return { section }
  104. }
  105. /**
  106. * Whether plan mode is active after the first `end` events. The last
  107. * `plan/mode` wins; a prefix with none is inactive.
  108. *
  109. * @param events The session log or any prefix of it.
  110. * @param end Fold `events[0, end)`; defaults to the whole log.
  111. * @returns Whether plan mode is active.
  112. */
  113. export function foldPlanMode(events: readonly SessionEvent[], end = events.length): boolean {
  114. let active = false
  115. let index = 0
  116. for (const event of events) {
  117. if (index >= end) break
  118. index++
  119. if (event.type === 'plan/mode') active = event.data.active
  120. }
  121. return active
  122. }
  123. /**
  124. * Projection unit state: the logged mode plus the latest logged `/plan`
  125. * selection (`command/run`) not yet resolved by a `plan/mode` commit. Plain
  126. * JSON (persisted-cache precondition).
  127. */
  128. interface PlanUnitState {
  129. active: boolean
  130. /** The selection's target mode; null when no selection is outstanding. */
  131. wanted: boolean | null
  132. }
  133. /** Wire payload schema of the `plan` projection. */
  134. const planProjectionSchema: ZodType<PlanProjection> = zod.object({
  135. active: zod.boolean(),
  136. pending: zod.boolean(),
  137. })
  138. /** Whether the log holds an opened turn without its closing `turn/end`. */
  139. function hasOpenTurn(events: readonly SessionEvent[]): boolean {
  140. let open = false
  141. for (const event of events) {
  142. if (event.type === 'turn/start') open = true
  143. else if (event.type === 'turn/end') open = false
  144. }
  145. return open
  146. }
  147. /** Plan state at the last logged request header, or `undefined` before the first header. */
  148. function planModeAtLastHeader(events: readonly SessionEvent[]): boolean | undefined {
  149. let lastHeader = -1
  150. let index = 0
  151. for (const event of events) {
  152. if (event.type === 'request/header') lastHeader = index
  153. index++
  154. }
  155. if (lastHeader < 0) return undefined
  156. return foldPlanMode(events, lastHeader + 1)
  157. }
  158. /**
  159. * `ctx.planMode`: owns logged plan state, boundary application and narration,
  160. * the `plan:policy` section, the `/plan` command, and the stable exit tool.
  161. * UIs observe committed flips through `session/event`; there is no live mirror.
  162. */
  163. export class PlanModeService extends Service {
  164. static inject = ['tools', 'systemPrompt']
  165. /** Validated deployment-owned guidance. */
  166. private readonly section: string
  167. /**
  168. * Latest selection per session awaiting an in-turn request-boundary flush.
  169. * `narrate` is true for user selections and false for the exit tool, whose
  170. * result already narrates the transition.
  171. */
  172. private readonly pendingIntents = new WeakMap<Session, { active: boolean; narrate: boolean }>()
  173. constructor(ctx: Context, config: PlanModeConfig = { section: '' }) {
  174. super(ctx, 'planMode')
  175. this.section = resolveConfig(config).section
  176. let disposed = false
  177. // The boundary flush uses the loop's `agent/step` interception seam, not
  178. // post-commit `session/event` observation. `agent/step` runs inside the
  179. // open turn before every request derivation (including turn 1 step 1), so
  180. // it is the sole flush point: prompt admission happens pre-turn, where a
  181. // `plan/mode` append would land outside any open turn. Failures are
  182. // contained so policy cannot block a turn; a failed append remains
  183. // pending for a later boundary.
  184. ctx.on('agent/step', (agent) => {
  185. if (disposed) return
  186. try {
  187. this.onBoundary(agent)
  188. } catch (error) {
  189. ctx.logger.warn('dsh-plan-mode: boundary flush failed: %o', error)
  190. }
  191. }, { prepend: true })
  192. ctx.effect(() => () => { disposed = true }, 'dsh-plan-mode: close boundary lifetime')
  193. ctx.systemPrompt.section({
  194. name: 'plan:policy',
  195. order: 50,
  196. text: context => context.agent !== undefined && foldPlanMode(context.agent.session.events)
  197. ? this.section
  198. : '',
  199. })
  200. // The plan projection unit (session-projection RFC): a pure double-event
  201. // fold serving clients the whole {active, pending} value. `command/run`
  202. // records the user's logged /plan selection (the handler calls `set()`
  203. // before any failing path, so log and run-plane cannot fork); `plan/mode`
  204. // is the boundary commit that resolves it. Pending is thereby a pure
  205. // replay quantity: host restarts, other tabs, and cold reads all recover
  206. // it from the log alone. The unit child activates only when a projection
  207. // registry is composed (headless assemblies stay unaffected).
  208. ctx.inject(['sessionProjections'], (projectionCtx) => {
  209. projectionCtx.sessionProjections.register<'plan', PlanUnitState>({
  210. key: 'plan',
  211. schema: planProjectionSchema,
  212. init: () => ({ active: false, wanted: null }),
  213. apply: (state, event) => {
  214. if (event.type === 'command/run' && event.data.name === 'plan') {
  215. const wanted = event.data.args.trim() !== 'off'
  216. return wanted === state.wanted ? state : { active: state.active, wanted }
  217. }
  218. if (event.type === 'plan/mode') {
  219. return { active: event.data.active, wanted: null }
  220. }
  221. return state
  222. },
  223. view: state => ({
  224. active: state.active,
  225. pending: state.wanted !== null && state.wanted !== state.active,
  226. }),
  227. stateVersion: 1,
  228. })
  229. })
  230. // The command child activates only when a command registry is composed.
  231. ctx.inject(['commands'], (commandCtx) => {
  232. commandCtx.commands.register({
  233. name: 'plan',
  234. description: 'Enter or leave plan mode',
  235. input: { hint: '[off|message]' },
  236. handler: ({ agent, rawInput }) => {
  237. const message = rawInput.trim()
  238. if (message === 'off') {
  239. switch (this.set(agent, false)) {
  240. case 'committed':
  241. return { kind: 'success', text: 'Plan mode off.' }
  242. case 'queued':
  243. return { kind: 'success', text: 'Leaving plan mode (applies from the next step).' }
  244. case 'cancelled':
  245. return { kind: 'success', text: 'Plan mode entry cancelled.' }
  246. case 'noop':
  247. // Repeat the queued wording while an exit still awaits its
  248. // boundary; only a truly inactive session reads idempotent.
  249. return foldPlanMode(agent.session.events)
  250. ? { kind: 'success', text: 'Leaving plan mode (applies from the next step).' }
  251. : { kind: 'success', text: 'Plan mode is already inactive.' }
  252. }
  253. }
  254. const outcome = this.set(agent, true)
  255. if (message !== '') agent.steer(createUserMessage({ content: [{ type: 'text', text: message }], source: { kind: 'user' } }))
  256. return {
  257. kind: 'success',
  258. text: outcome === 'committed'
  259. ? 'Plan mode on. Use /plan off to leave.'
  260. : 'Entering plan mode (applies from the next step). Use /plan off to leave.',
  261. }
  262. },
  263. })
  264. })
  265. ctx.tools.register(defineTool({
  266. name: EXIT_PLAN_MODE,
  267. description: EXIT_DESCRIPTION,
  268. parameters: {
  269. plan: { type: 'string', required: true, description: 'The complete plan, as markdown, starting with a # heading that names it.' },
  270. },
  271. output: {
  272. schema: {
  273. type: 'object',
  274. additionalProperties: false,
  275. properties: {
  276. approved: { type: 'boolean', const: true, required: true },
  277. },
  278. },
  279. render: () => [{ type: 'text', text: 'Plan approved — plan mode exited; carry out the plan starting with your next step.' }],
  280. },
  281. execute: async (args, exec) => {
  282. const agent = exec.agent
  283. if (agent === undefined) throw new Error(`${EXIT_PLAN_MODE} requires a calling agent (no session to switch)`)
  284. if (!foldPlanMode(agent.session.events)) {
  285. throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`)
  286. }
  287. if (!/^#\s+\S/.test(args.plan.trim())) {
  288. throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`)
  289. }
  290. const interaction = ctx.get('userInteraction')
  291. if (interaction === undefined) {
  292. throw new Error('no user-interaction channel is available to review the plan; ask the user to switch the session mode instead')
  293. }
  294. const answer = await interaction.ask({
  295. questions: [{
  296. id: 'plan-review',
  297. header: 'Plan review',
  298. question: 'Approve this plan and leave plan mode?',
  299. detail: args.plan,
  300. options: [
  301. { label: APPROVE_LABEL, description: 'Leave plan mode; the plan is carried out from the next step.' },
  302. { label: KEEP_PLANNING_LABEL, description: 'Stay in plan mode; feedback goes back to the model.' },
  303. ],
  304. }],
  305. agent,
  306. signal: exec.signal,
  307. })
  308. // A review may outlive this plugin fiber. Without boundary listeners,
  309. // an approved result could never land, so fail and keep planning.
  310. if (disposed) {
  311. throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again')
  312. }
  313. const reviewItems = answer.answers.filter(entry => entry.id === 'plan-review')
  314. const item = reviewItems.length === 1 ? reviewItems[0] : undefined
  315. if (item?.selected.length !== 1 || item.selected[0] !== APPROVE_LABEL || item.custom !== undefined) {
  316. const feedback = item?.custom ?? ''
  317. throw new Error(feedback === ''
  318. ? 'The user chose to keep planning; revise the plan and present it again.'
  319. : `The user chose to keep planning; their feedback: ${feedback}`)
  320. }
  321. // Keep plan guidance for the rest of this assistant tool batch. The
  322. // silent intent flushes after the step, before the next 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. /**
  340. * Read the logged plan state and any selected state awaiting a boundary.
  341. *
  342. * @param agent The agent to read.
  343. * @returns Current logged state plus a pending selection, when present.
  344. */
  345. get(agent: Agent): { active: boolean; pending?: boolean } {
  346. const active = foldPlanMode(agent.session.events)
  347. const pending = this.pendingIntents.get(agent.session)
  348. return pending === undefined ? { active } : { active, pending: pending.active }
  349. }
  350. /**
  351. * Select whether plan mode should be active. Between turns the change
  352. * commits immediately — no request boundary would arrive until the next
  353. * prompt, so a queued intent would hang (the open-turn fold is the idle
  354. * signal: agent status stays `running` through post-turn checkpointing,
  355. * where a boundary equally never comes). During an open turn the
  356. * selection is held as pending intent for the next in-turn request
  357. * boundary. Repeated selection of the current or already-pending state is
  358. * a no-op.
  359. *
  360. * @param agent The agent to switch.
  361. * @param active Whether plan mode should be active.
  362. * @returns what happened: `committed` (logged now), `queued` (awaiting the
  363. * next boundary), `cancelled` (an opposite pending selection was cleared;
  364. * the logged state already matches), or `noop` (already in that state).
  365. */
  366. set(agent: Agent, active: boolean): 'committed' | 'queued' | 'cancelled' | 'noop' {
  367. const session = agent.session
  368. const pending = this.pendingIntents.get(session)
  369. const target = pending?.active ?? foldPlanMode(session.events)
  370. if (active === target) return 'noop'
  371. if (hasOpenTurn(session.events)) {
  372. this.pendingIntents.set(session, { active, narrate: true })
  373. return foldPlanMode(session.events) === active ? 'cancelled' : 'queued'
  374. }
  375. // No open turn: commit now. Delete only after append succeeds so a
  376. // failed durable write leaves the selection retryable, not dropped.
  377. if (active === foldPlanMode(session.events)) {
  378. this.pendingIntents.delete(session)
  379. return 'cancelled'
  380. }
  381. session.append('plan/mode', { active })
  382. this.pendingIntents.delete(session)
  383. this.narrate(session, active)
  384. return 'committed'
  385. }
  386. /** Flush one pending selection before the next request assembly. */
  387. private onBoundary(agent: Agent): void {
  388. const session = agent.session
  389. const pending = this.pendingIntents.get(session)
  390. if (pending === undefined) return
  391. const target = pending.active
  392. if (target === foldPlanMode(session.events)) {
  393. this.pendingIntents.delete(session)
  394. return
  395. }
  396. session.append('plan/mode', { active: target })
  397. // Delete only after append succeeds so a later boundary can retry a failed
  398. // durable write.
  399. this.pendingIntents.delete(session)
  400. if (pending.narrate) this.narrate(session, target)
  401. }
  402. /** Tell the model about a user switch when the last logged header described the other mode. */
  403. private narrate(session: Session, target: boolean): void {
  404. const told = planModeAtLastHeader(session.events)
  405. if (told === undefined || told === target) return
  406. const text = target
  407. ? 'The user switched this session to plan mode.'
  408. : 'The user switched this session back to the default mode.'
  409. session.append('user/message', createUserMessage({
  410. content: [{ type: 'text', text }],
  411. source: { kind: 'plugin', plugin: 'plan-mode' },
  412. }), { surfaceOp: 'append' })
  413. }
  414. }
  415. export default PlanModeService