dsh-plan-steps 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,958 @@
1
+ /**
2
+ * Host-owned task-list steps.
3
+ *
4
+ * The shipped `todo_write` tool records a whole-list snapshot and nothing else:
5
+ * a completed item exists only because the model remembered to re-send the table
6
+ * with a different status. This plugin adds the missing half — `complete_step`
7
+ * signs exactly one item off and the host advances the list — plus the guard
8
+ * that refuses a `todo_write` marking a new item completed with no sign-off, and
9
+ * a turn-stopping hold that steers the model back while the list is still open.
10
+ *
11
+ * The canonical list is rebuilt the way the host rebuilds any derived state:
12
+ * by replaying the session log (the latest successful `todo_write` call, then
13
+ * every successful `complete_step` after it). Nothing is cached in plugin
14
+ * memory, so a fold, a fork, or a restarted process still reads the same list.
15
+ *
16
+ * Zero external runtime dependencies on purpose: a profile copy of
17
+ * `@deepseek-ai/dsh-tools` is a different module instance from the one the host
18
+ * registry is built on, so this hands the registry a plain object whose
19
+ * parameters and output already use standard JSON Schema.
20
+ *
21
+ * @module dsh-plan-steps
22
+ */
23
+
24
+ import { randomUUID } from 'node:crypto'
25
+ import Schema from '@deepseek-ai/schemastery'
26
+
27
+ export const name = 'plan-steps'
28
+ export const inject = ['tools']
29
+
30
+ /** Marks a level-1 sub-step inside content, which every projection keeps. */
31
+ const SUB_STEP_MARK = '​'
32
+
33
+ /** The shipped task list's snapshot event: one whole-list write per update. */
34
+ const TODO_WRITE = 'todo/write'
35
+
36
+ /** The switches this plugin exposes on its row in the plugin page. */
37
+ export const Config = Schema.object({
38
+ // `.volatile()` is what makes a field editable from the plugin page without a
39
+ // remount; an ordinary field is validated but never rendered.
40
+ guardUnsignedCompletions: Schema.boolean().default(true).volatile(),
41
+ holdOpenList: Schema.boolean().default(true).volatile(),
42
+ restorePanel: Schema.boolean().default(true).volatile(),
43
+ })
44
+
45
+ /** Turns already held once, so a model that will not update its list still ends. */
46
+ const heldTurn = new WeakMap()
47
+
48
+ /** Sessions that declared they are waiting on the user this turn. */
49
+ const waitingSessions = new WeakSet()
50
+
51
+ /** The turn whose panel snapshot was already re-written, per session. */
52
+ const restoredTurns = new WeakMap()
53
+
54
+ /** The step whose one sign-off was already claimed, per session. */
55
+ const claimedStep = new WeakMap()
56
+
57
+ /** Sessions whose turn-start restore failure was already reported. */
58
+ const restoreWarned = new WeakSet()
59
+
60
+ /** Declarations that say nothing: a test word or a placeholder is not a need. */
61
+ const PLACEHOLDER_NEED = /^(?:test|testing|todo|tbd|n\/a|none|foo|bar|baz|asdf|xxx)[.!]?$/i
62
+
63
+ /** One plugin-authored context message: host-authored, so no user bubble. */
64
+ function makeMessage(text) {
65
+ return {
66
+ id: randomUUID(),
67
+ role: 'user',
68
+ content: [{ type: 'text', text }],
69
+ source: { kind: 'system-prompt' },
70
+ }
71
+ }
72
+
73
+ /** Step names compared after trimming and collapsing runs of whitespace. */
74
+ function normalize(text) {
75
+ return String(text ?? '').trim().replace(/\s+/g, ' ')
76
+ }
77
+
78
+ /**
79
+ * One stored item. The mirrored fields — `level` and `stepId` — are the ones a
80
+ * two-level plan needs; a flat list simply has neither.
81
+ */
82
+ function toItem(todo) {
83
+ let content = String(todo?.content ?? '')
84
+ // The shipped projection keeps only content and status, so a sub-step carries
85
+ // a leading zero-width space: it survives every reader and is invisible.
86
+ let marker = false
87
+ if (content.startsWith(SUB_STEP_MARK)) {
88
+ marker = true
89
+ content = content.slice(SUB_STEP_MARK.length)
90
+ }
91
+ const item = { content, status: todo?.status ?? 'pending' }
92
+ if (marker || Number(todo?.level) === 1) item.level = 1
93
+ const id = String(todo?.step_id ?? todo?.stepId ?? '').trim()
94
+ if (id !== '') item.stepId = id
95
+ return item
96
+ }
97
+
98
+ /**
99
+ * Validate one stored projection value. The unit starts as `null`, so the
100
+ * schema has to accept that state as well as a list.
101
+ * @param value - a stored snapshot.
102
+ * @returns the normalized list, or null before the first write.
103
+ */
104
+ function parseTodos(value) {
105
+ if (value === null || value === undefined) return null
106
+ if (!Array.isArray(value)) throw new Error('plan-steps: a stored task list must be an array or null')
107
+ return value.map(toItem)
108
+ }
109
+
110
+ /** One logged call's arguments, or undefined when the log holds no parseable ones. */
111
+ function callArgs(event) {
112
+ const raw = event?.data?.arguments
113
+ if (typeof raw !== 'string' || raw.trim() === '') return undefined
114
+ try {
115
+ return JSON.parse(raw)
116
+ } catch {
117
+ return undefined
118
+ }
119
+ }
120
+
121
+ /**
122
+ * The session's events, as a stable frozen snapshot.
123
+ * @param session - the session to read.
124
+ * @returns the log snapshot, or undefined when this host exposes none.
125
+ */
126
+ function sessionEvents(session) {
127
+ if (session === undefined) return undefined
128
+ if (typeof session.snapshotEvents === 'function') {
129
+ try {
130
+ const snapshot = session.snapshotEvents()
131
+ if (Array.isArray(snapshot)) return snapshot
132
+ } catch {
133
+ return undefined
134
+ }
135
+ }
136
+ return Array.isArray(session.events) ? session.events : undefined
137
+ }
138
+
139
+ /**
140
+ * Read the list through the plugin's own projection when the host handed one
141
+ * back, and fall back to a log scan otherwise. The projection is the sanctioned
142
+ * incremental read; the scan is what a host without the seam can still serve.
143
+ */
144
+ let readProjected = null
145
+
146
+ /**
147
+ * Rebuild the host list from the session log. The `todo/write` event is the
148
+ * canonical snapshot — the shipped tool appends one per write, and so does
149
+ * `complete_step` — so the last event is the whole answer. A host whose todo
150
+ * tool writes no event falls back to replaying the tool calls.
151
+ * @param session - the session to read.
152
+ * @returns the current items, or null before a successful `todo_write`.
153
+ */
154
+ function listOf(session) {
155
+ if (session === undefined) return null
156
+ if (readProjected !== null) {
157
+ try {
158
+ const projected = readProjected(session)
159
+ if (Array.isArray(projected)) return projected.map(toItem)
160
+ } catch {
161
+ // A session the projection has not materialized falls through to the scan.
162
+ }
163
+ }
164
+ const events = sessionEvents(session)
165
+ if (events === undefined) return null
166
+ let written = null
167
+ let sawWrite = false
168
+ for (const event of events) {
169
+ if (event?.type !== TODO_WRITE) continue
170
+ sawWrite = true
171
+ if (Array.isArray(event.data?.todos)) written = event.data.todos.map(toItem)
172
+ }
173
+ if (sawWrite) return written
174
+ return replayCalls(events)
175
+ }
176
+
177
+ /**
178
+ * Fallback: the same list, rebuilt from the tool calls when the host stores no
179
+ * `todo/write` event. Only settled calls count, and only a successful one.
180
+ * @param events - the session log snapshot.
181
+ * @returns the current items, or null.
182
+ */
183
+ function replayCalls(events) {
184
+ const settled = new Set()
185
+ const failed = new Set()
186
+ for (const event of events) {
187
+ const message = event?.type === 'tool/result' ? event.data?.message : undefined
188
+ if (message === undefined) continue
189
+ settled.add(message.toolCallId)
190
+ if (message.isError === true) failed.add(message.toolCallId)
191
+ }
192
+ let list = null
193
+ for (const event of events) {
194
+ if (event?.type !== 'tool/call') continue
195
+ const call = event.data
196
+ if (call === undefined) continue
197
+ if (!settled.has(call.callId) || failed.has(call.callId)) continue
198
+ const args = callArgs(event)
199
+ if (call.name === 'todo_write') {
200
+ if (Array.isArray(args?.todos)) list = args.todos.map(toItem)
201
+ continue
202
+ }
203
+ if (call.name !== 'complete_step' || list === null) continue
204
+ const at = locate(list, args?.step_id, args?.step, args?.index)
205
+ if (at !== -1 && list[at].status === 'in_progress') list = advance(list, at)
206
+ }
207
+ return list
208
+ }
209
+
210
+ /** The model-facing inventory a citation error names. */
211
+ function inventory(items) {
212
+ return items
213
+ .map((item, index) => {
214
+ const id = item.stepId === undefined ? '' : ` ${item.stepId}`
215
+ const indent = (item.level ?? 0) === 1 ? ' ' : ''
216
+ return `${index + 1}.${indent}${id} ${JSON.stringify(item.content)} [${item.status}]`
217
+ })
218
+ .join(', ')
219
+ }
220
+
221
+ /**
222
+ * The list as host state for the request, in the reading order a sign-off uses.
223
+ * @param items - the current list.
224
+ * @returns the block, or an empty string when there is nothing to carry.
225
+ */
226
+ function renderTaskState(items) {
227
+ if (items === null || items.length === 0) return ''
228
+ const lines = items.map((item, index) => {
229
+ const id = item.stepId === undefined ? '' : ` ${item.stepId}`
230
+ const indent = (item.level ?? 0) === 1 ? ' ' : ''
231
+ return `${index + 1}.${indent}${id} ${JSON.stringify(item.content)} [${item.status}]`
232
+ })
233
+ return (
234
+ "Host task state. This list is the host's, not a message you sent; sign a step off with complete_step once it is finished.\n" +
235
+ lines.join('\n')
236
+ )
237
+ }
238
+
239
+ /** Whether the visible history already carries a host task-state block. */
240
+ function alreadyStated(agent) {
241
+ try {
242
+ const messages = agent.session.deriveMessages()
243
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
244
+ const parts = Array.isArray(messages[i]?.content) ? messages[i].content : []
245
+ if (parts.some((part) => part?.type === 'text' && typeof part.text === 'string' && part.text.startsWith('Host task state.'))) {
246
+ return true
247
+ }
248
+ }
249
+ return false
250
+ } catch {
251
+ return false
252
+ }
253
+ }
254
+
255
+ /** The only item a sign-off may cite right now: the current one, if any. */
256
+ function currentItem(items) {
257
+ return items.find((item) => item.status === 'in_progress')
258
+ }
259
+
260
+ /**
261
+ * Resolve the cited step against the list, most stable identity first: a
262
+ * `step_id` survives a replan, a 1-based position survives a retitle, a title
263
+ * survives neither.
264
+ * @param items - the current list.
265
+ * @param stepId - the cited stable id, when one was given.
266
+ * @param step - the cited name, when one was given.
267
+ * @param index - the cited 1-based position, when one was given.
268
+ * @returns the 0-based index, or -1.
269
+ */
270
+ function locate(items, stepId, step, index) {
271
+ const wantedId = normalize(stepId)
272
+ if (wantedId !== '') {
273
+ const hit = items.findIndex((item) => normalize(item.stepId) === wantedId)
274
+ if (hit !== -1) return hit
275
+ }
276
+ const wanted = normalize(step)
277
+ if (wanted !== '') {
278
+ const exact = items.findIndex((item) => normalize(item.content) === wanted)
279
+ if (exact !== -1) return exact
280
+ const folded = wanted.toLowerCase()
281
+ const foldedHit = items.findIndex((item) => normalize(item.content).toLowerCase() === folded)
282
+ if (foldedHit !== -1) return foldedHit
283
+ }
284
+ if (Number.isInteger(index) && index > 0) return index <= items.length ? index - 1 : -1
285
+ return -1
286
+ }
287
+
288
+ /**
289
+ * Split a list into serial units: a level-0 phase owns the level-1 items
290
+ * directly after it; every other item is its own single-step unit.
291
+ * @param items - the current list.
292
+ * @returns the segments, each `{ head, end }` (end exclusive).
293
+ */
294
+ function segmentsOf(items) {
295
+ const segments = []
296
+ for (let i = 0; i < items.length; ) {
297
+ let end = i + 1
298
+ if ((items[i].level ?? 0) === 0) {
299
+ while (end < items.length && (items[end].level ?? 0) === 1) end += 1
300
+ }
301
+ segments.push({ head: i, end })
302
+ i = end
303
+ }
304
+ return segments
305
+ }
306
+
307
+ /**
308
+ * The first unfinished sub-step of the phase at `index`, when that item is a
309
+ * phase with sub-steps.
310
+ * @param items - the current list.
311
+ * @param index - 0-based index of a candidate phase.
312
+ * @returns the 0-based index of the first unfinished sub-step, or -1.
313
+ */
314
+ function firstUnfinishedSubStep(items, index) {
315
+ if ((items[index]?.level ?? 0) !== 0) return -1
316
+ for (let i = index + 1; i < items.length && (items[i].level ?? 0) === 1; i += 1) {
317
+ if (items[i].status !== 'completed') return i
318
+ }
319
+ return -1
320
+ }
321
+
322
+ /**
323
+ * Sign one item off and promote the next serial unit, mirroring Reasonix's
324
+ * `AdvanceSerialTodo`: a sub-step promotes its next pending sibling, or hands
325
+ * the phase back for sign-off once every sibling is done; a phase (or a plain
326
+ * step) promotes the next unit — a phase's first pending sub-step, or the
327
+ * phase itself. A phase with unfinished sub-steps does not complete.
328
+ * @param items - the current list.
329
+ * @param at - 0-based index of the item being signed off.
330
+ * @returns the advanced list, as a new array.
331
+ */
332
+ function advance(items, at) {
333
+ const next = items.map((item) => ({ ...item }))
334
+ if (next[at] === undefined || next[at].status !== 'in_progress') return next
335
+ if (firstUnfinishedSubStep(next, at) >= 0) return next
336
+ next[at].status = 'completed'
337
+ if ((next[at].level ?? 0) === 1) {
338
+ for (let i = at + 1; i < next.length && (next[i].level ?? 0) === 1; i += 1) {
339
+ if (next[i].status === 'pending') {
340
+ next[i].status = 'in_progress'
341
+ return next
342
+ }
343
+ }
344
+ let head = at - 1
345
+ while (head >= 0 && (next[head].level ?? 0) === 1) head -= 1
346
+ if (head >= 0) {
347
+ if (next[head].status !== 'completed') next[head].status = 'in_progress'
348
+ return next
349
+ }
350
+ }
351
+ if (next.some((item) => item.status === 'in_progress')) return next
352
+ for (let i = 0; i < next.length; i += 1) {
353
+ if (next[i].status !== 'pending') continue
354
+ const sub = firstUnfinishedSubStep(next, i)
355
+ if (sub >= 0) {
356
+ if (next[sub].status === 'pending') next[sub].status = 'in_progress'
357
+ return next
358
+ }
359
+ next[i].status = 'in_progress'
360
+ return next
361
+ }
362
+ return next
363
+ }
364
+
365
+ /**
366
+ * Find the same item in a rewrite: by step_id when both carry one, else by
367
+ * normalized content.
368
+ * @param item - the item to look for.
369
+ * @param list - the submitted list.
370
+ * @returns the match and its index, or null.
371
+ */
372
+ function findSame(item, list) {
373
+ if (item.stepId !== undefined) {
374
+ const byId = list.findIndex((candidate) => candidate.stepId === item.stepId)
375
+ if (byId !== -1) return { item: list[byId], index: byId }
376
+ }
377
+ const key = normalize(item.content)
378
+ const byName = list.findIndex((candidate) => normalize(candidate.content) === key)
379
+ return byName === -1 ? null : { item: list[byName], index: byName }
380
+ }
381
+
382
+ /**
383
+ * The three continuity rules a rewrite must respect, mirroring Reasonix's
384
+ * `verifyStepIDsPreserved`, `verifyTodoCurrentContinuity` and
385
+ * `verifyCompletedTodoPositions`: an id is never dropped, the current item is
386
+ * never removed or moved back to pending, and completed history keeps its
387
+ * position.
388
+ * @param previous - the list the host holds, or null before the first write.
389
+ * @param next - the submitted list.
390
+ * @returns an error message, or null when the rewrite is coherent.
391
+ */
392
+ function continuityProblem(previous, next) {
393
+ if (previous === null || previous.length === 0) return null
394
+ for (const item of previous) {
395
+ if (item.stepId === undefined) continue
396
+ if (next.some((candidate) => candidate.stepId === item.stepId)) continue
397
+ return (
398
+ `step_id ${JSON.stringify(item.stepId)} (${JSON.stringify(item.content)}) was dropped; ` +
399
+ 'copy every existing step_id verbatim so a completion stays attached to its step'
400
+ )
401
+ }
402
+ const current = previous.find((item) => item.status === 'in_progress')
403
+ if (current !== undefined) {
404
+ const match = findSame(current, next)
405
+ if (match === null) {
406
+ return (
407
+ `the current item ${JSON.stringify(current.content)} cannot be removed or replaced while it is in progress; ` +
408
+ 'sign it off with complete_step first'
409
+ )
410
+ }
411
+ if (match.item.status === 'pending') {
412
+ return (
413
+ `the current item ${JSON.stringify(current.content)} cannot move back to pending; ` +
414
+ 'keep it in_progress or sign it off with complete_step'
415
+ )
416
+ }
417
+ }
418
+ for (let i = 0; i < previous.length; i += 1) {
419
+ if (previous[i].status !== 'completed') continue
420
+ const match = findSame(previous[i], next)
421
+ if (match === null || match.index !== i) {
422
+ return (
423
+ `completed item ${JSON.stringify(previous[i].content)} must keep its position; ` +
424
+ 'completed history cannot be removed, renamed or reordered while the plan is active'
425
+ )
426
+ }
427
+ }
428
+ return null
429
+ }
430
+
431
+ /**
432
+ * Validate a submitted list against the serial state machine: at most one
433
+ * current item, completed work as a prefix, pending work after the current
434
+ * item, sub-steps in order, and a phase that is current only once its
435
+ * sub-steps are all done. Mirrors Reasonix's `ValidateSerialTodos`.
436
+ * @param items - the submitted list.
437
+ * @returns an error message, or null when the list is valid.
438
+ */
439
+ function validateSerial(items) {
440
+ let currentSeen = false
441
+ for (let i = 0; i < items.length; i += 1) {
442
+ const status = items[i].status
443
+ if (status !== 'completed' && status !== 'pending' && status !== 'in_progress') {
444
+ return `todo ${i + 1} has invalid status ${JSON.stringify(status)}`
445
+ }
446
+ if (status === 'in_progress') {
447
+ if (currentSeen) return `todo ${i + 1} ${JSON.stringify(items[i].content)} is a second in_progress item; a serial list allows exactly one current item`
448
+ currentSeen = true
449
+ }
450
+ }
451
+ if (items.length > 0 && (items[0].level ?? 0) === 1) {
452
+ return `todo 1 ${JSON.stringify(items[0].content)} is a level-1 sub-step with no phase above it; add a level-0 phase header or use level 0`
453
+ }
454
+ let seenCurrent = false
455
+ let seenPending = false
456
+ for (const segment of segmentsOf(items)) {
457
+ const head = items[segment.head]
458
+ const headStatus = head.status
459
+ let subCurrent = false
460
+ let subPending = false
461
+ let completedSubs = 0
462
+ let unfinished = -1
463
+ for (let i = segment.head + 1; i < segment.end; i += 1) {
464
+ const sub = items[i]
465
+ if (sub.status === 'completed') {
466
+ if (subCurrent || subPending) return `todo ${i + 1} ${JSON.stringify(sub.content)} is completed after unfinished work; completed items must form a prefix`
467
+ completedSubs += 1
468
+ } else if (sub.status === 'in_progress') {
469
+ if (subPending) return `todo ${i + 1} ${JSON.stringify(sub.content)} is in_progress after pending work; the current item must be the first unfinished one`
470
+ subCurrent = true
471
+ if (unfinished < 0) unfinished = i
472
+ } else {
473
+ subPending = true
474
+ if (unfinished < 0) unfinished = i
475
+ }
476
+ }
477
+ if (headStatus === 'completed') {
478
+ if (unfinished >= 0) {
479
+ return `phase ${segment.head + 1} ${JSON.stringify(head.content)} is completed but sub-step ${unfinished + 1} ${JSON.stringify(items[unfinished].content)} is unfinished`
480
+ }
481
+ if (seenCurrent || seenPending) return `phase ${segment.head + 1} ${JSON.stringify(head.content)} is completed after unfinished work; completed items must form a prefix`
482
+ } else if (headStatus === 'in_progress') {
483
+ if (unfinished >= 0) {
484
+ return `phase ${segment.head + 1} ${JSON.stringify(head.content)} cannot be in_progress while sub-step ${unfinished + 1} ${JSON.stringify(items[unfinished].content)} is unfinished; keep the phase pending, finish its sub-steps, then mark it in_progress`
485
+ }
486
+ if (seenPending) return `phase ${segment.head + 1} ${JSON.stringify(head.content)} is in_progress after pending work; the current item must be the first unfinished one`
487
+ seenCurrent = true
488
+ } else if (subCurrent) {
489
+ if (seenPending) return `phase ${segment.head + 1} ${JSON.stringify(head.content)} holds the current item after pending work`
490
+ seenCurrent = true
491
+ } else if (completedSubs > 0) {
492
+ if (seenCurrent) return `phase ${segment.head + 1} ${JSON.stringify(head.content)} has completed sub-steps after unfinished work`
493
+ seenPending = true
494
+ } else {
495
+ seenPending = true
496
+ }
497
+ }
498
+ if (items.length > 0 && seenPending && !seenCurrent) return 'the list has pending work but no in_progress item'
499
+ return null
500
+ }
501
+
502
+ /**
503
+ * The seq of the step this call belongs to: the last `step/start` in the log.
504
+ * @param events - the session log snapshot, when the host exposes one.
505
+ * @returns the step's seq, or null when the step cannot be identified.
506
+ */
507
+ function stepSeqOf(events) {
508
+ if (events === undefined) return null
509
+ for (let i = events.length - 1; i >= 0; i -= 1) {
510
+ if (events[i]?.type === 'step/start') return events[i].seq ?? -1
511
+ }
512
+ return null
513
+ }
514
+
515
+ const DESCRIPTION =
516
+ 'Sign off ONE step of the current task list as done. The host marks that item completed and moves the next ' +
517
+ 'serial unit to in_progress — a sub-step promotes its next sibling, and a phase only becomes current after ' +
518
+ 'every sub-step is done. Cite the item by its step_id (preferred), by name, or by 1-based position. A plan ' +
519
+ 'write that marks a new item completed without a complete_step sign-off is refused.'
520
+
521
+ export function apply(ctx, config = {}) {
522
+ // Settings come from the plugin row; an unset key keeps the mechanism on.
523
+ const guardEnabled = config.guardUnsignedCompletions !== false
524
+ const holdEnabled = config.holdOpenList !== false
525
+ const restoreEnabled = config.restorePanel !== false
526
+
527
+ // The plan writer. The shipped `todo_write` stores a flat name list; a
528
+ // two-level plan needs a phase header, ordered sub-steps and stable step ids,
529
+ // so this tool owns the structured form and writes the same `todo/write`
530
+ // snapshot the panel already reads.
531
+ ctx.tools.register({
532
+ name: 'plan_write',
533
+ description:
534
+ 'Record and update a structured task list for the current work. Send the COMPLETE list every call — it replaces ' +
535
+ 'the previous one. The list is two-level: a `level` 0 item is a PHASE (a milestone) and the `level` 1 items ' +
536
+ 'after it are its concrete sub-steps. Keep exactly one item in_progress: a phase stays pending while its ' +
537
+ 'sub-steps run and becomes the current item only after all of them are done, so the phase signs off last. ' +
538
+ 'COPY `step_id` VERBATIM for every item that already has one: it is how a completion stays attached across ' +
539
+ 'retitles and reordering. Give a new item a fresh unique id (e.g. "plan_step_07"). Sign finished items off ' +
540
+ 'with complete_step; do not mark a new item completed here.',
541
+ parameters: {
542
+ type: 'object',
543
+ additionalProperties: false,
544
+ properties: {
545
+ todos: {
546
+ type: 'array',
547
+ description: 'The complete task list, in order. Replaces any previous list.',
548
+ items: {
549
+ type: 'object',
550
+ additionalProperties: false,
551
+ properties: {
552
+ content: { type: 'string', description: 'Imperative description of the task.' },
553
+ status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
554
+ level: { type: 'integer', description: '0 = phase/milestone, 1 = a sub-step of the phase above it.' },
555
+ step_id: { type: 'string', description: 'Stable identity for this item, copied verbatim on every rewrite.' },
556
+ activeForm: { type: 'string', description: 'Present-continuous form shown while the item is in progress.' },
557
+ },
558
+ required: ['content', 'status'],
559
+ },
560
+ },
561
+ },
562
+ required: ['todos'],
563
+ },
564
+ output: {
565
+ schema: {
566
+ type: 'object',
567
+ additionalProperties: false,
568
+ properties: {
569
+ message: { type: 'string' },
570
+ },
571
+ required: ['message'],
572
+ },
573
+ render: (_args, value) => [{ type: 'text', text: String(value?.message ?? '') }],
574
+ },
575
+ execute: async (args, exec) => {
576
+ const agent = exec.agent
577
+ if (agent === undefined) throw new Error('plan_write requires an owning agent session')
578
+ const raw = args?.todos
579
+ if (!Array.isArray(raw)) throw new Error('`todos` must be the complete list')
580
+ const items = []
581
+ const seenContent = new Set()
582
+ const seenId = new Set()
583
+ for (let i = 0; i < raw.length; i += 1) {
584
+ const entry = raw[i] ?? {}
585
+ const content = String(entry.content ?? '').trim()
586
+ if (content === '') throw new Error(`todo ${i + 1}: content is required`)
587
+ const key = normalize(content)
588
+ if (seenContent.has(key)) throw new Error(`todo ${i + 1} ${JSON.stringify(content)} repeats an earlier item`)
589
+ seenContent.add(key)
590
+ const status = entry.status ?? 'pending'
591
+ if (status !== 'pending' && status !== 'in_progress' && status !== 'completed') {
592
+ throw new Error(`todo ${i + 1}: invalid status ${JSON.stringify(status)}`)
593
+ }
594
+ const level = Number(entry.level) === 1 ? 1 : 0
595
+ const stepId = String(entry.step_id ?? '').trim()
596
+ if (stepId !== '') {
597
+ if (seenId.has(stepId)) throw new Error(`todo ${i + 1} reuses step_id ${JSON.stringify(stepId)}`)
598
+ seenId.add(stepId)
599
+ }
600
+ const item = { content, status }
601
+ if (level === 1) item.level = 1
602
+ if (stepId !== '') item.stepId = stepId
603
+ items.push(item)
604
+ }
605
+ const problem = validateSerial(items)
606
+ if (problem !== null) throw new Error(problem)
607
+ const continuity = continuityProblem(listOf(agent.session), items)
608
+ if (continuity !== null) throw new Error(continuity)
609
+ agent.session.append(TODO_WRITE, {
610
+ todos: items.map((item) => ({
611
+ content: item.level === 1 ? SUB_STEP_MARK + item.content : item.content,
612
+ status: item.status,
613
+ ...(item.level === 1 ? { level: 1 } : {}),
614
+ ...(item.stepId === undefined ? {} : { step_id: item.stepId }),
615
+ })),
616
+ })
617
+ const done = items.filter((item) => item.status === 'completed').length
618
+ const active = items.filter((item) => item.status === 'in_progress').length
619
+ const pending = items.length - done - active
620
+ return { message: `Plan updated: ${items.length} items — ${done} completed, ${active} in progress, ${pending} pending.` }
621
+ },
622
+ presentCall: (args) => ({
623
+ card: 'generic',
624
+ title: 'Update plan',
625
+ kind: 'other',
626
+ content: [{ type: 'text', text: Array.isArray(args?.todos) ? `${args.todos.length} items` : 'plan' }],
627
+ }),
628
+ })
629
+
630
+ ctx.tools.register({
631
+ name: 'complete_step',
632
+ description: DESCRIPTION,
633
+ parameters: {
634
+ type: 'object',
635
+ additionalProperties: false,
636
+ properties: {
637
+ step_id: {
638
+ type: 'string',
639
+ description:
640
+ 'PREFERRED: the stable step_id of the task-list item this completes, e.g. "plan_step_02". Unlike a title or a number it survives retitles, insertions and reordering.',
641
+ },
642
+ step: {
643
+ type: 'string',
644
+ description: 'The task-list item this completes, by name. Use when the item has no step_id.',
645
+ },
646
+ index: {
647
+ type: 'number',
648
+ description: 'The 1-based task-list position, used when the item has neither a step_id nor a unique name.',
649
+ },
650
+ result: {
651
+ type: 'string',
652
+ description: 'What is now true or changed as a result of finishing this step.',
653
+ },
654
+ },
655
+ required: ['result'],
656
+ },
657
+ output: {
658
+ schema: {
659
+ type: 'object',
660
+ additionalProperties: false,
661
+ properties: {
662
+ message: { type: 'string' },
663
+ },
664
+ required: ['message'],
665
+ },
666
+ render: (_args, value) => [{ type: 'text', text: String(value?.message ?? '') }],
667
+ },
668
+ execute: async (args, exec) => {
669
+ const agent = exec.agent
670
+ if (agent === undefined) throw new Error('complete_step requires an owning agent session')
671
+ const items = listOf(agent.session)
672
+ if (items === null || items.length === 0) {
673
+ const unreadable = readProjected === null && sessionEvents(agent.session) === undefined
674
+ throw new Error(
675
+ 'this session holds no task list yet; call plan_write with the plan, then sign each step off as you finish it' +
676
+ (unreadable ? ' (this host exposes neither a projection nor a session log to the plugin)' : ''),
677
+ )
678
+ }
679
+ const said = String(args?.result ?? '').trim()
680
+ if (said === '') {
681
+ throw new Error('`result` is required — state what is now true after finishing this step')
682
+ }
683
+ const cited = args?.step ?? args?.step_id ?? ''
684
+ const at = locate(items, args?.step_id, args?.step, args?.index)
685
+ if (at === -1) {
686
+ throw new Error(
687
+ `${cited === '' ? 'no step was cited and no in_progress item is current' : `step ${JSON.stringify(cited)} matches no task-list item`}; the list is: ${inventory(items)}`,
688
+ )
689
+ }
690
+ if (firstUnfinishedSubStep(items, at) >= 0) {
691
+ const sub = firstUnfinishedSubStep(items, at)
692
+ throw new Error(
693
+ `${JSON.stringify(items[at].content)} is a phase whose sub-steps are unfinished; complete sub-step ` +
694
+ `${JSON.stringify(items[sub].content)} first, then sign the phase off`,
695
+ )
696
+ }
697
+ const target = items[at]
698
+ if (target.status === 'completed') {
699
+ return { message: `Step ${JSON.stringify(target.content)} was already completed; the list is unchanged.` }
700
+ }
701
+ if (target.status !== 'in_progress') {
702
+ const current = currentItem(items)
703
+ throw new Error(
704
+ `step ${JSON.stringify(target.content)} is ${target.status}; complete_step only signs the current in_progress item` +
705
+ (current === undefined
706
+ ? ' — mark the item you are working on with todo_write first'
707
+ : ` — finish ${JSON.stringify(current.content)} first`),
708
+ )
709
+ }
710
+ // One sign-off per step. The claim is taken before the append and before
711
+ // any await, so a second call in the same parallel batch is refused
712
+ // instead of signing a list the first call already moved.
713
+ const stepSeq = stepSeqOf(sessionEvents(agent.session))
714
+ if (stepSeq !== null) {
715
+ if (claimedStep.get(agent.session) === stepSeq) {
716
+ throw new Error(
717
+ 'only one complete_step per step: a second sign-off in the same batch signs against the list as it stood ' +
718
+ 'before the first one advanced it. Sign the next item in your next step.',
719
+ )
720
+ }
721
+ claimedStep.set(agent.session, stepSeq)
722
+ }
723
+ const advanced = advance(items, at)
724
+ // Persist the advance as the same snapshot the shipped tool writes, so
725
+ // the task panel and every log reader see the step close here and now.
726
+ agent.session.append(TODO_WRITE, { todos: advanced })
727
+ const next = currentItem(advanced)
728
+ const remaining = advanced.filter((item) => item.status !== 'completed').length
729
+ const tail =
730
+ next === undefined
731
+ ? 'Every step in the task list is now complete. Do not open new work under this plan.'
732
+ : `The host advanced the list; the next step is ${advanced.indexOf(next) + 1} ${JSON.stringify(next.content)}.`
733
+ return {
734
+ message: `Step ${JSON.stringify(target.content)} done: ${said} ${tail} (${remaining} open)`,
735
+ }
736
+ },
737
+ presentCall: (args) => ({
738
+ card: 'generic',
739
+ title: 'Complete step',
740
+ kind: 'other',
741
+ content: [
742
+ {
743
+ type: 'text',
744
+ text:
745
+ args && typeof args.step === 'string' && args.step !== ''
746
+ ? `Signing off ${args.step}`
747
+ : 'Signing off the current step',
748
+ },
749
+ ],
750
+ }),
751
+ })
752
+
753
+ ctx.tools.register({
754
+ name: 'wait_for_user',
755
+ description:
756
+ 'Declare that the current task-list item cannot go on without the user: their decision, material only they have, ' +
757
+ 'or their view on what you just showed them. The turn may then end with that item still in progress and the host ' +
758
+ 'will not pull the turn back for it. Name what you need in one line; the substance belongs in your reply. ' +
759
+ 'Use ask_user_question instead when you can offer the choices yourself and want the answer in this turn.',
760
+ parameters: {
761
+ type: 'object',
762
+ additionalProperties: false,
763
+ properties: {
764
+ need: {
765
+ type: 'string',
766
+ description: 'One short line saying what you are waiting for, addressed to the user.',
767
+ },
768
+ },
769
+ required: ['need'],
770
+ },
771
+ output: {
772
+ schema: {
773
+ type: 'object',
774
+ additionalProperties: false,
775
+ properties: {
776
+ message: { type: 'string' },
777
+ },
778
+ required: ['message'],
779
+ },
780
+ render: (_args, value) => [{ type: 'text', text: String(value?.message ?? '') }],
781
+ },
782
+ execute: async (args, exec) => {
783
+ const agent = exec.agent
784
+ if (agent === undefined) throw new Error('wait_for_user requires an owning agent session')
785
+ const need = String(args?.need ?? '').trim()
786
+ if (need === '') throw new Error('`need` is required — say in one line what you are waiting for')
787
+ if (need.length < 2 || PLACEHOLDER_NEED.test(need)) {
788
+ throw new Error(
789
+ '`need` must name the actual thing you are waiting for — a bare test word or a placeholder leaves the user ' +
790
+ 'nothing to answer; write the decision, the material, or the confirmation you need',
791
+ )
792
+ }
793
+ waitingSessions.add(agent.session)
794
+ return {
795
+ message:
796
+ `Recorded: waiting on the user for ${JSON.stringify(need)}. The task list is kept as it stands, ` +
797
+ 'and the host will not pull this turn back for it.',
798
+ }
799
+ },
800
+ presentCall: (args) => ({
801
+ card: 'generic',
802
+ title: 'Waiting on you',
803
+ kind: 'other',
804
+ content: [{ type: 'text', text: String(args?.need ?? 'Waiting for your input.') }],
805
+ }),
806
+ })
807
+
808
+ // The canonical list as a projection: the incremental read the host keeps for
809
+ // every session, so a read no longer rescans the log. A host without the seam
810
+ // falls back to the scan in `listOf`.
811
+ ctx.inject(['sessionProjections'], (projectionCtx) => {
812
+ try {
813
+ const pending = projectionCtx.sessionProjections.register({
814
+ key: 'plan-steps/todos',
815
+ stateSchema: { parse: parseTodos },
816
+ init: () => null,
817
+ apply: (state, event) =>
818
+ event?.type === TODO_WRITE && Array.isArray(event.data?.todos) ? event.data.todos.map(toItem) : state,
819
+ stateVersion: 1,
820
+ })
821
+ Promise.resolve(pending)
822
+ .then((handle) => {
823
+ readProjected = (session) => handle.stateOf(session)
824
+ })
825
+ .catch(() => {})
826
+ } catch {
827
+ // Without a usable seam the log scan stays the reader.
828
+ }
829
+ })
830
+
831
+ if (guardEnabled) {
832
+ ctx.tools.guard((exec) => {
833
+ if ((exec.name !== 'todo_write' && exec.name !== 'plan_write') || exec.agent === undefined) return undefined
834
+ const items = listOf(exec.agent.session)
835
+ if (items === null || items.length === 0) return undefined
836
+ const submitted = exec.arguments?.todos
837
+ if (!Array.isArray(submitted)) return undefined
838
+ // A rewrite that does not add a completion is a relabel or a replan, not a
839
+ // claim about work: names are the only identity a shipped item has, so a
840
+ // completed item renamed must not read as a fresh completion.
841
+ const done = items.filter((item) => item.status === 'completed').length
842
+ const nextDone = submitted.filter((item) => item?.status === 'completed').length
843
+ if (nextDone <= done) return undefined
844
+ const already = new Set(
845
+ items.filter((item) => item.status === 'completed').map((item) => normalize(item.content)),
846
+ )
847
+ for (const item of submitted) {
848
+ if (item?.status !== 'completed') continue
849
+ const key = normalize(item.content)
850
+ if (already.has(key)) continue
851
+ return {
852
+ reason:
853
+ `blocked: todo ${JSON.stringify(item.content)} is newly completed with no complete_step sign-off. ` +
854
+ 'Call complete_step for it first — the host marks it completed and advances the list for you — ' +
855
+ 'or send todo_write again leaving that item in_progress.',
856
+ }
857
+ }
858
+ return undefined
859
+ })
860
+ }
861
+
862
+ // The turn is about to close with the list still open. Steering is the only
863
+ // thing that reopens a step: the loop re-reads its inbox, finds this message,
864
+ // and runs another step instead of committing the boundary. One hold per turn
865
+ // bounds a model that will not update the list — it ends on the second stop.
866
+ if (holdEnabled) {
867
+ ctx.on('agent/turn-stopping', ({ agent, turn, signal }) => {
868
+ if (agent === undefined || signal?.aborted === true) return
869
+ if (waitingSessions.has(agent.session)) return
870
+ const items = listOf(agent.session)
871
+ if (items === null || items.length === 0) return
872
+ const open = items.filter((item) => item.status !== 'completed')
873
+ if (open.length === 0) return
874
+ if (heldTurn.get(agent.session) === turn) return
875
+ heldTurn.set(agent.session, turn)
876
+ const current = open.find((item) => item.status === 'in_progress') ?? open[0]
877
+ try {
878
+ agent.steer(
879
+ makeMessage(
880
+ `Your task list still has ${open.length} open step(s); the current one is ${JSON.stringify(current.content)}. ` +
881
+ 'Keep working on it, and call complete_step the moment a step is finished. ' +
882
+ 'If you are waiting on the user, call wait_for_user with one line naming what you need — that is what lets ' +
883
+ 'the turn end with the item still open. Do not end a turn that still has work you can do.',
884
+ ),
885
+ )
886
+ } catch {
887
+ // A host that refuses steering simply lets the turn close.
888
+ }
889
+ })
890
+ }
891
+
892
+ // The list rides the request as host state once per visible window: a fold
893
+ // takes the model's own todo_write out of view, and this puts the list back
894
+ // where a sign-off can be judged against it. It is not re-sent while the
895
+ // window already carries one.
896
+ ctx.on('agent/pre-step', async (payload, next) => {
897
+ const decision = await next()
898
+ if (decision?.kind !== 'enter' || payload?.agent === undefined) return decision
899
+ const session = payload.agent.session
900
+ const items = listOf(session)
901
+ if (items === null || items.length === 0) return decision
902
+ if (!items.some((item) => item.status !== 'completed')) return decision
903
+ // The shipped task projection resets at `turn/start`, so the first step of
904
+ // a turn writes the open list back as its own snapshot: the panel is there
905
+ // when the turn starts instead of after the model happens to re-send it.
906
+ const restored = restoredTurns.get(session)
907
+ if (restoreEnabled && restored !== payload.turn) {
908
+ restoredTurns.set(session, payload.turn)
909
+ try {
910
+ session.append(TODO_WRITE, { todos: items })
911
+ } catch {
912
+ // A read-only or closing session keeps its own behaviour.
913
+ }
914
+ }
915
+ if (alreadyStated(payload.agent)) return decision
916
+ const text = renderTaskState(items)
917
+ if (text === '') return decision
918
+ try {
919
+ return { ...decision, messages: [...decision.messages, makeMessage(text)] }
920
+ } catch {
921
+ return decision
922
+ }
923
+ })
924
+
925
+ // A declaration lasts one turn: the next turn's work has to earn its own.
926
+ // The shipped task projection also resets here, so an open list is written
927
+ // back as a snapshot of its own — otherwise the panel is blank until the
928
+ // model happens to write a table it already owns.
929
+ ctx.on('session/event', (session, event) => {
930
+ if (event?.type !== 'turn/start') return
931
+ waitingSessions.delete(session)
932
+ if (restoreEnabled !== true) return
933
+ // Appending inside the turn/start dispatch does not land, so the snapshot is
934
+ // written on the next macrotask, once the boundary has committed. The
935
+ // pre-step restore stays as the fallback when this one does not run.
936
+ const turn = event.data?.turn
937
+ setTimeout(() => {
938
+ const items = listOf(session)
939
+ if (items === null || items.length === 0) return
940
+ if (!items.some((item) => item.status !== 'completed')) return
941
+ try {
942
+ session.append(TODO_WRITE, { todos: items })
943
+ restoredTurns.set(session, turn)
944
+ } catch (error) {
945
+ // The pre-step restore still runs for this turn, so the panel is not
946
+ // lost; say it once, because this path is expected to work on this host
947
+ // and a silent fallback would hide a host change.
948
+ if (!restoreWarned.has(session)) {
949
+ restoreWarned.add(session)
950
+ ctx.logger?.warn?.('plan-steps: could not restore the task panel at turn start; falling back to the pre-step restore', error)
951
+ }
952
+ }
953
+ }, 0)
954
+ })
955
+ }
956
+
957
+ /** Pure helpers, exposed for the regression tests in test/. */
958
+ export const __testing = { normalize, locate, advance, replayCalls, renderTaskState, stepSeqOf, parseTodos, validateSerial, segmentsOf, firstUnfinishedSubStep, continuityProblem }