dsh-plan-steps 0.0.0-stage → 0.1.2

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