dsh-as-aistudio 0.2.13 → 0.3.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.
@@ -0,0 +1,2784 @@
1
+ // dsh-rerun-turn host half (dsh-rerun-turn.js), VENDORED by tools/vendor.mjs - DO NOT EDIT.
2
+ //
3
+ // Source: ../dsh-rerun-turn/lib/index.js (v0.2.5, sha256 1955b5db5e5262ee)
4
+ // Regenerate with `npm run vendor`; test/sync.test.js fails when this is stale.
5
+ //
6
+ // src/shell.js imports the copy named after the component, which is why the
7
+ // studio installs with no runtime dependency on the component package.
8
+ // dsh-rerun-turn - host half.
9
+ //
10
+ // Loopback-only JSON routes:
11
+ //
12
+ // GET /dsh-rerun-turn/state?sessionId=<id>
13
+ // POST /dsh-rerun-turn/apply { sessionId, seq|messageId }
14
+ // POST /dsh-rerun-turn/replay { sessionId, rerunId? }
15
+ // GET /dsh-rerun-turn/debug
16
+ //
17
+ // WHAT A RERUN IS
18
+ //
19
+ // The model context is re-derived from the session surface on every call, so
20
+ // re-running turn C is a *splice*: the surface loses the old reply and keeps
21
+ // every later turn, and the next call reads A B C1 D E F G. DSH's official
22
+ // surface-replace contract cannot express that directly - an assistant message
23
+ // may never carry `sourceEventSeqs`, so a reply can never be the replacement
24
+ // carrier (checked against the real validator, not assumed). A rerun is
25
+ // therefore three official operations, in order:
26
+ //
27
+ // 1. SHADOW - one replace event whose window runs from the turn's prompt to
28
+ // the last surface node. The window always ends at the tail, so a reply
29
+ // and the tool calls/results it produced always leave together. The
30
+ // carrier is a `user/message` that opens no turn at all: the format reads
31
+ // `user/message` without any open turn or step (the only surface type it
32
+ // does), and it carries no readable text, so the model never reads it
33
+ // either. Its exact content shape is decided ONCE at load from the
34
+ // installed adapter (`dropsEmptyUserContent`): an empty list where the
35
+ // adapter is proven to drop a user message whose content converts to
36
+ // nothing, otherwise one zero-width space - an unpatched adapter turns
37
+ // `content: []` into `{ role: 'user', content: '' }`, which the provider
38
+ // refuses with HTTP 400 and which aborts the whole turn (0.1.27, see
39
+ // {@link ADAPTER_DROPS_EMPTY_USER_CONTENT}). A carrier that opened its own
40
+ // turn would spend a turn number on bookkeeping - an empty "completed"
41
+ // strip in the conversation view and a hole in the trajectory numbering -
42
+ // and the agent loop's process-local turn counter would have to be
43
+ // re-pointed at it (the 0.1.0/0.1.1 incident, see README).
44
+ //
45
+ // 2. REGENERATE - the official prompt path (`sessionController.prompt`),
46
+ // re-sending the turn's own prompt text/images. The model sees the
47
+ // surviving prefix plus the re-sent prompt and answers fresh, with the
48
+ // session's real tools.
49
+ //
50
+ // 3. REPLAY - every shadowed event after the prompt is appended back,
51
+ // verbatim except for: fresh turn numbers (the log requires them
52
+ // contiguous), fresh message ids, remapped `sourceEventSeqs` on tool
53
+ // results, dropped usage numbers and embedded streams, and a source
54
+ // marker (`rerunBy`/`rerunId`/`originalSeq`) that lets this plugin - or
55
+ // a sibling - tell a replayed event from its retired original. The
56
+ // replayed turns go into the log as ordinary turns, so cold reads,
57
+ // exports and other instances see exactly what the model sees.
58
+ //
59
+ // The append-only log is never rewritten. Uninstalling the plugin keeps every
60
+ // landed rerun: the operations are official events.
61
+ //
62
+ // RECOVERY
63
+ //
64
+ // Generation can take minutes; a crash mid-rerun is a real state. The carrier
65
+ // names the operation (`rerunId`), the fold records exactly which surface
66
+ // nodes it shadowed, and every replayed event cites its `originalSeq` - so
67
+ // "which copies are missing" is always computable from the log alone, and the
68
+ // missing suffix can be replayed later without the model. `/state` reports
69
+ // incomplete reruns and, by default, resumes them automatically when the
70
+ // session is live, idle and its inbox is empty.
71
+ import { randomUUID } from 'node:crypto'
72
+ import { readFileSync } from 'node:fs'
73
+ import { createRequire } from 'node:module'
74
+ import { dirname } from 'node:path'
75
+
76
+ const nodeRequire = createRequire(import.meta.url)
77
+ const schemaPackage = (() => {
78
+ try {
79
+ return nodeRequire('@deepseek-ai/schemastery')
80
+ } catch {
81
+ return null
82
+ }
83
+ })()
84
+ const z = schemaPackage === null ? null : (schemaPackage.default ?? schemaPackage)
85
+
86
+ /** Plugin id shared by the host and browser halves. */
87
+ export const PLUGIN_ID = 'dsh-rerun-turn'
88
+
89
+ /** Cordis plugin name. */
90
+ export const name = PLUGIN_ID
91
+
92
+ /** Keep in sync with package.json and lib/client.js. */
93
+ export const PLUGIN_VERSION = '0.2.5'
94
+
95
+ const ROUTE_PREFIX = '/dsh-rerun-turn'
96
+ // A session id is an OPAQUE string to DSH: the host's own schema is
97
+ // `z.string().min(1)`, and a named session created in the GUI (`bili-whale`,
98
+ // stored as ~/.dsh/storages/<profile>/sessions/bili-whale.json) is exactly as
99
+ // real as a UUID one. A UUID-only test rejected those with a 400, so the panel
100
+ // answered "status failed to load" for a session that plainly exists. The
101
+ // character class still refuses everything that could leave a path or a URL:
102
+ // `/`, `\`, `..` (the first character must be alphanumeric, so a leading dot
103
+ // is already out), whitespace and control characters.
104
+ const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
105
+ const PROMPT_DEADLINE_MS = 30_000
106
+ const FLUSH_DEADLINE_MS = 5_000
107
+ const DEFAULT_IDLE_TIMEOUT_MS = 10 * 60_000
108
+ const REPLAY_DEFER_MS = 2_000
109
+ const REPLAY_DEFER_MAX = 30
110
+ // The auto-resume no-progress gate: a replay that leaves the same missing set
111
+ // behind is not retried within this window (see the /state handler).
112
+ const RESUME_STALL_MS = 10_000
113
+
114
+ /**
115
+ * Surface types the replay walk reproduces as fresh copies. Anything else a
116
+ * rerun shadows is retired without replacement - notably `system/message`,
117
+ * loop-owned machinery the next request rebuilds, and this plugin's own
118
+ * bookkeeping carriers ({@link isRerunCarrier}) - and must never hold the
119
+ * ledger incomplete: an eternally missing seq would make every `/state` poll
120
+ * append the replay batch again, growing the log without bound.
121
+ */
122
+ const REPLAYED_SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result'])
123
+
124
+ // A ring of the last few requests, answering "did the browser half even ask,
125
+ // and what did it get?" without needing its console.
126
+ const REQUEST_LOG_LIMIT = 40
127
+ const requestLog = []
128
+
129
+ /** Record one request for the diagnostic route. */
130
+ export function noteRequest(entry) {
131
+ requestLog.push({ at: Date.now(), ...entry })
132
+ if (requestLog.length > REQUEST_LOG_LIMIT) requestLog.shift()
133
+ }
134
+
135
+ /** The recorded requests, oldest first. */
136
+ export function recentRequests() {
137
+ return requestLog.slice()
138
+ }
139
+
140
+ export const Config =
141
+ z === null
142
+ ? undefined
143
+ : z.object({
144
+ /**
145
+ * Whether the client asks for a second confirmation before rerunning.
146
+ * Off by default: the button is an explicit action, and its tooltip
147
+ * states what it does.
148
+ */
149
+ confirm: z.boolean().default(false),
150
+ /**
151
+ * Whether `/state` resumes an interrupted rerun's replay on its own
152
+ * (session live, idle, inbox empty). On by default: a rerun that died
153
+ * mid-flight would otherwise leave the later turns out of the model
154
+ * context until someone pressed "complete replay".
155
+ */
156
+ autoResume: z.boolean().default(true),
157
+ /**
158
+ * How long the rerun waits for the regenerated turn to settle before
159
+ * giving up on in-process replay (the replay then waits for a resume).
160
+ */
161
+ idleTimeoutMs: z.number().default(DEFAULT_IDLE_TIMEOUT_MS),
162
+ /**
163
+ * Whether the loopback dev routes are mounted: `POST /dev/scratch`
164
+ * creates a throwaway session and drives a few short turns, and
165
+ * `GET /dev/derived` reports the live derived context. They exist for
166
+ * end-to-end verification and spend real model calls, so they stay off
167
+ * unless a deployment explicitly turns them on.
168
+ */
169
+ devTools: z.boolean().default(false),
170
+ })
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // pure session-log logic (no DSH SDK imports; unit-testable under node --test)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /** The five event types that may carry `surfaceOp` (official surface contract). */
177
+ const SURFACE_TYPES = new Set([
178
+ 'system/message',
179
+ 'developer/message',
180
+ 'user/message',
181
+ 'assistant/message',
182
+ 'tool/result',
183
+ ])
184
+
185
+ /**
186
+ * Whether one event participates in the model-visible surface.
187
+ * @param event - raw session event.
188
+ * @returns true for a message-producing event type.
189
+ */
190
+ export function isSurfaceEvent(event) {
191
+ const type = event && event.type
192
+ return typeof type === 'string' && SURFACE_TYPES.has(type)
193
+ }
194
+
195
+ /**
196
+ * Replay the surface operations of a complete log.
197
+ *
198
+ * Mirrors the official fold: `append` pushes the event onto the tail; a
199
+ * `replace` swaps the inclusive window between its two surface nodes for the
200
+ * replacing event. Replacements whose anchors are no longer present are
201
+ * skipped defensively - a corrupt log must not throw inside an HTTP handler.
202
+ *
203
+ * @param events - complete contiguous raw event log in seq order.
204
+ * @returns current surface seqs in model order plus every landed replacement.
205
+ */
206
+ export function foldSurface(events) {
207
+ const nodes = []
208
+ const replacements = []
209
+ for (const event of events) {
210
+ const op = event.surfaceOp
211
+ if (op === undefined) continue
212
+ if (op === 'append') {
213
+ nodes.push(event.seq)
214
+ continue
215
+ }
216
+ if (op === null || typeof op !== 'object' || op.op !== 'replace') continue
217
+ const startIdx = nodes.indexOf(op.startSeq)
218
+ const endIdx = nodes.indexOf(op.endSeq)
219
+ if (startIdx === -1 || endIdx === -1 || startIdx > endIdx) continue
220
+ const shadowed = nodes.slice(startIdx, endIdx + 1)
221
+ nodes.splice(startIdx, endIdx - startIdx + 1, event.seq)
222
+ replacements.push({ seq: event.seq, startSeq: op.startSeq, endSeq: op.endSeq, shadowed })
223
+ }
224
+ return { nodes, replacements }
225
+ }
226
+
227
+ /**
228
+ * Map every event seq to the turn that encloses it.
229
+ *
230
+ * Turn brackets are the durable source for user messages (their payload has no
231
+ * turn field); assistant and tool events carry their own turn and override the
232
+ * bracket reading.
233
+ *
234
+ * @param events - complete contiguous raw event log.
235
+ * @returns seq -> turn number (undefined outside any turn).
236
+ */
237
+ export function turnIndex(events) {
238
+ const turnOf = new Map()
239
+ let current
240
+ for (const event of events) {
241
+ if (event.type === 'turn/start') {
242
+ current = event.data && event.data.turn
243
+ turnOf.set(event.seq, current)
244
+ continue
245
+ }
246
+ if (event.type === 'turn/end') {
247
+ turnOf.set(event.seq, current)
248
+ current = undefined
249
+ continue
250
+ }
251
+ const data = event.data
252
+ const explicit =
253
+ (event.type === 'assistant/message' || event.type === 'tool/result' || event.type === 'tool/call') &&
254
+ data &&
255
+ typeof data.turn === 'number'
256
+ ? data.turn
257
+ : undefined
258
+ turnOf.set(event.seq, explicit !== undefined ? explicit : current)
259
+ }
260
+ return turnOf
261
+ }
262
+
263
+ /**
264
+ * Index an event list by the seq each event carries.
265
+ *
266
+ * A caller hands in a LIST, not a dense vector. The session log leads with a
267
+ * header record that the platform's scanner strips before handing events over,
268
+ * and a resumed log can inherit its head from another file, so the first event's
269
+ * \`seq\` is not necessarily 0 — which makes \`events[seq]\` the wrong event (or
270
+ * undefined) even though the list is perfectly valid. Every read that means "the
271
+ * event with this seq" goes through this map instead.
272
+ *
273
+ * @param events - raw event list in seq order.
274
+ * @returns seq -> event, for every event carrying a numeric seq.
275
+ */
276
+ export function eventIndex(events) {
277
+ const bySeq = new Map()
278
+ for (const event of events) if (event !== null && typeof event === 'object' && typeof event.seq === 'number') bySeq.set(event.seq, event)
279
+ return bySeq
280
+ }
281
+
282
+ /**
283
+ * The turn bracket that OWNS one reply.
284
+ *
285
+ * A turn NUMBER can appear in more than one bracket. Rerunning replays the tail,
286
+ * and a replay opens bookkeeping brackets that reuse a number while carrying no
287
+ * user message at all, so the first bracket holding a number is not necessarily
288
+ * the one a reply belongs to. Picking it blindly reported "the turn has no
289
+ * prompt to re-send" for replies that were plainly on screen and genuinely
290
+ * rerunnable — the failing case was a session with four reruns in it, where the
291
+ * user's ↻ on turn 49/51 answered "this reply cannot be rerun".
292
+ *
293
+ * The owning bracket is the one whose range contains the reply; a bracket that
294
+ * carries a prompt is the fallback, then the first with the number.
295
+ *
296
+ * @param brackets - \`turnSpans(events)\`, computed once by the caller.
297
+ * @param turn - the turn number the reply reports.
298
+ * @param targetSeq - the reply's seq.
299
+ * @returns the owning bracket, or undefined when the number is unknown.
300
+ */
301
+ function bracketOwning(brackets, turn, targetSeq) {
302
+ const owning = brackets.find(
303
+ (entry) => entry.turn === turn && entry.startSeq <= targetSeq && (entry.endSeq === null || entry.endSeq >= targetSeq),
304
+ )
305
+ return (
306
+ owning ??
307
+ brackets.find((entry) => entry.turn === turn && typeof entry.promptSeq === 'number') ??
308
+ brackets.find((entry) => entry.turn === turn)
309
+ )
310
+ }
311
+
312
+ /**
313
+ * The replacement chains of a log: shadowed seq -> the seq that stands in for it.
314
+ *
315
+ * A sibling plugin editing a prompt in place (dsh-edit-turn replaces one node
316
+ * with the new wording) shadows the original and lands a carrier in its place;
317
+ * compaction does the same. Following the chain is a documented cross-plugin
318
+ * contract, and both the planner and the rerunnable list need it, so it is built
319
+ * in one place.
320
+ *
321
+ * @param events - raw event log.
322
+ * @returns a map from a shadowed seq to its live stand-in.
323
+ */
324
+ function replacementChains(events) {
325
+ const revisions = new Map()
326
+ for (const replacement of foldSurface(events).replacements) {
327
+ for (const seq of replacement.shadowed) revisions.set(seq, replacement.seq)
328
+ }
329
+ return revisions
330
+ }
331
+
332
+ /**
333
+ * Follow a seq to the node the surface shows in its place.
334
+ *
335
+ * @param startSeq - the logged seq to follow.
336
+ * @param nodeIndex - seq -> surface position for the current surface.
337
+ * @param revisions - replacement chains from {@link replacementChains}.
338
+ * @returns the live seq, or undefined when the chain dies off the surface.
339
+ */
340
+ function followToSurface(startSeq, nodeIndex, revisions) {
341
+ let live = startSeq
342
+ const seen = new Set()
343
+ while (!nodeIndex.has(live)) {
344
+ const next = revisions.get(live)
345
+ if (next === undefined || seen.has(live)) return undefined
346
+ seen.add(live)
347
+ live = next
348
+ }
349
+ return live
350
+ }
351
+
352
+ /**
353
+ * Resolve the prompt a rerun of one reply would re-send, or the reason it
354
+ * cannot. This is THE single definition of "rerunnable": `rerunnableReplies`
355
+ * (which advertises the ↻ button) and `planRerun` (which executes it) both go
356
+ * through it, so a button is never offered for a reply the planner would refuse.
357
+ *
358
+ * A prompt replaced in place still counts when the chain lands on a live
359
+ * `user/message` (the dsh-edit-turn contract, whose carrier keeps the human
360
+ * `kind: 'user'` and adds `editedBy`). A chain that lands on anything else
361
+ * does not: dsh-delete-turn retires a deleted prompt to its own carrier, and a
362
+ * plugin carrier - `source.kind` starting with `plugin:`, whether the sibling's
363
+ * or our own silent replacement - is not a prompt a rerun can re-send. Re-sending
364
+ * one would re-ask a question that is no longer there (the carrier has no text,
365
+ * so the prompt admission fails). The advertisement used to accept any live
366
+ * node, so such a reply was offered and then answered "this reply cannot be
367
+ * rerun" - the exact complaint this function exists to prevent.
368
+ *
369
+ * @param bySeq - `eventIndex(events)`, so no read is ever `events[seq]`.
370
+ * @param nodeIndex - seq -> surface position.
371
+ * @param brackets - `turnSpans(events)`.
372
+ * @param revisions - `replacementChains(events)`.
373
+ * @param head - the surface's first seq (the system prompt head); never rerunnable.
374
+ * @param turn - the turn number the reply reports.
375
+ * @param targetSeq - the reply's seq.
376
+ * @returns `{ reason: null, promptSeq, span }` when rerunnable; otherwise
377
+ * `{ reason: 'no-prompt' | 'retired' | 'not-user' | 'carrier' | 'head' }`.
378
+ */
379
+ function resolveRerunPrompt(bySeq, nodeIndex, brackets, revisions, head, turn, targetSeq) {
380
+ const span = bracketOwning(brackets, turn, targetSeq)
381
+ if (!span || typeof span.promptSeq !== 'number') return { reason: 'no-prompt' }
382
+ const promptSeq = followToSurface(span.promptSeq, nodeIndex, revisions)
383
+ if (promptSeq === undefined) return { reason: 'retired' }
384
+ const promptEvent = bySeq.get(promptSeq)
385
+ if (!promptEvent || promptEvent.type !== 'user/message') return { reason: 'not-user' }
386
+ // A silent plugin carrier standing where the prompt used to be is not a
387
+ // prompt: it marks a deletion or an earlier rerun's shadow, and re-sending it
388
+ // would re-ask a question that no longer exists (its empty content would fail
389
+ // prompt admission anyway).
390
+ if (isSilentPluginCarrier(promptEvent)) return { reason: 'carrier' }
391
+ if (promptSeq === head) return { reason: 'head' }
392
+ return { reason: null, promptSeq, span }
393
+ }
394
+
395
+ /**
396
+ * One turn bracket: its number, log range, first prompt and reply count.
397
+ * @param events - complete contiguous raw event log.
398
+ * @returns one entry per `turn/start`, in log order.
399
+ */
400
+ export function turnSpans(events) {
401
+ const spans = []
402
+ let open = null
403
+ for (const event of events) {
404
+ if (event.type === 'turn/start') {
405
+ open = {
406
+ turn: event.data && event.data.turn,
407
+ startSeq: event.seq,
408
+ endSeq: null,
409
+ promptSeq: null,
410
+ replies: 0,
411
+ }
412
+ spans.push(open)
413
+ continue
414
+ }
415
+ if (open === null) continue
416
+ if (event.type === 'turn/end') {
417
+ open.endSeq = event.seq
418
+ open = null
419
+ continue
420
+ }
421
+ if (event.type === 'user/message' && open.promptSeq === null) open.promptSeq = event.seq
422
+ if (event.type === 'assistant/message') open.replies += 1
423
+ }
424
+ return spans
425
+ }
426
+
427
+ /** The turn still awaiting its `turn/end`, or null when every turn closed. */
428
+ export function openTurn(events) {
429
+ let open = null
430
+ for (const event of events) {
431
+ if (event.type === 'turn/start') open = event.data && event.data.turn
432
+ else if (event.type === 'turn/end' && (open === null || event.data.turn === open)) open = null
433
+ }
434
+ return open
435
+ }
436
+
437
+ /**
438
+ * Whether the trailing open turn is a crash-orphan of this plugin's replay.
439
+ *
440
+ * A replay dies mid-batch only between two appends, and the bracket events it
441
+ * writes carry no marker - so the orphan shows up as an open turn holding
442
+ * nothing but turn/step brackets, `tool/call` copies, and this rerun's own
443
+ * marked copies. Any real turn in flight carries a plain user or assistant
444
+ * message and fails the test, as does a regenerated turn that never closed.
445
+ *
446
+ * @param events - complete contiguous raw event log.
447
+ * @param rerunId - the rerun whose replay may have died.
448
+ * @returns true when the open turn belongs to this plugin's interrupted write.
449
+ */
450
+ export function replayOrphanOpen(events, rerunId) {
451
+ let openSeq = -1
452
+ for (const event of events) {
453
+ if (event.type === 'turn/start') openSeq = event.seq
454
+ else if (event.type === 'turn/end') openSeq = -1
455
+ }
456
+ if (openSeq === -1) return false
457
+ // Walk the seq the scan means, not the array slot: a missing seq ends the walk
458
+ // (a gap is not a licence to read whatever happens to sit at that index).
459
+ const bySeq = eventIndex(events)
460
+ for (let seq = openSeq; ; seq += 1) {
461
+ const event = bySeq.get(seq)
462
+ if (event === undefined) break
463
+ if (event.type === 'turn/start' || event.type === 'step/start' || event.type === 'step/end' || event.type === 'turn/end' || event.type === 'tool/call') continue
464
+ const marker = replayMarkerOf(event)
465
+ if (marker !== null && marker.rerunId === rerunId) continue
466
+ return false
467
+ }
468
+ return true
469
+ }
470
+
471
+ /** Whether an operation is in flight that will still write the surface. */
472
+ export function isBusy(events) {
473
+ if (openTurn(events) !== null) return true
474
+ let compaction = false
475
+ for (const event of events) {
476
+ if (event.type === 'compaction/start') compaction = true
477
+ else if (event.type === 'compaction/end') compaction = false
478
+ }
479
+ return compaction
480
+ }
481
+
482
+ /**
483
+ * Durable message identity of one surface event.
484
+ * @param event - raw session event.
485
+ * @returns the message id, or undefined for an event without one.
486
+ */
487
+ export function messageIdOf(event) {
488
+ const data = event.data
489
+ if (!data || typeof data !== 'object') return undefined
490
+ if (event.type === 'user/message') return typeof data.id === 'string' ? data.id : undefined
491
+ if (event.type === 'assistant/message' || event.type === 'tool/result' || event.type === 'system/message') {
492
+ const message = data.message
493
+ return message && typeof message.id === 'string' ? message.id : undefined
494
+ }
495
+ return undefined
496
+ }
497
+
498
+ /** Highest turn number recorded in the log, or 0 for an empty log. */
499
+ export function lastTurnOf(events) {
500
+ let last = 0
501
+ for (const event of events) {
502
+ const turn = event.data && event.data.turn
503
+ if (typeof turn === 'number' && turn > last) last = turn
504
+ }
505
+ return last
506
+ }
507
+
508
+ /**
509
+ * Prompt-facing parts of a user message: plain text plus the durable
510
+ * attachment references a rerun would have to re-admit.
511
+ * @param event - raw `user/message` event.
512
+ * @returns `{ text, images, files, attachments }`.
513
+ */
514
+ export function readPromptParts(event) {
515
+ const data = (event && event.data) || {}
516
+ const blocks = Array.isArray(data.content) ? data.content : []
517
+ const text = []
518
+ const images = []
519
+ const files = []
520
+ for (const block of blocks) {
521
+ if (!block || typeof block !== 'object') continue
522
+ if (block.type === 'text' && typeof block.text === 'string') text.push(block.text)
523
+ else if (block.type === 'image' && block.attachment) images.push(block.attachment)
524
+ else if (block.type === 'file' && block.attachment) files.push(block.attachment)
525
+ }
526
+ return { text: text.join('\n'), images, files, attachments: images.length + files.length }
527
+ }
528
+
529
+ /** Whether the message source records a replay by this plugin. */
530
+ export function replayMarkerOf(event) {
531
+ const data = event && event.data
532
+ if (!data || typeof data !== 'object') return null
533
+ const message = data.message && typeof data.message === 'object' ? data.message : data
534
+ const source = message && message.source
535
+ if (!source || typeof source !== 'object' || source.rerunBy !== PLUGIN_ID) return null
536
+ return {
537
+ rerunId: typeof source.rerunId === 'string' ? source.rerunId : null,
538
+ originalSeq: typeof source.originalSeq === 'number' ? source.originalSeq : null,
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Whether one event is a replacement carrier this plugin landed for a rerun.
544
+ *
545
+ * Current shape (0.1.27+): a turn-free `user/message` with NO READABLE TEXT,
546
+ * marked by `source.kind === 'plugin:dsh-rerun-turn'` - the same silent
547
+ * replacement the sibling plugins write. Since 0.1.27 its content is an empty
548
+ * list only where the installed adapter is proven to drop it, and one
549
+ * zero-width space otherwise; the mark is the source, never the content, so
550
+ * both shapes stay recognised. 0.1.26 used the empty list everywhere.
551
+ * 0.1.14-0.1.25 used an empty `system/message` inside a synthetic bookkeeping
552
+ * turn (source `system-prompt` plus our `plugin` marker), which cost a turn
553
+ * number per rerun; 0.1.0-0.1.13 used a developer/user carrier. All four shapes
554
+ * stay recognised so ledgers over historical logs remain correct - a legacy
555
+ * carrier turn still hides its own rows on screen.
556
+ */
557
+ export function isRerunCarrier(event) {
558
+ if (!event) return false
559
+ const type = event.type
560
+ if (type !== 'developer/message' && type !== 'user/message' && type !== 'system/message') return false
561
+ const data = event.data || {}
562
+ const message = data.message && typeof data.message === 'object' ? data.message : data
563
+ const source = message && message.source
564
+ if (!source || typeof source.rerunId !== 'string') return false
565
+ if (source.rerunBy !== PLUGIN_ID) return false
566
+ if (source.kind === `plugin:${PLUGIN_ID}`) return true
567
+ return source.kind === 'system-prompt' && source.plugin === PLUGIN_ID
568
+ }
569
+
570
+ /**
571
+ * Characters a silent carrier may be built from: ordinary whitespace, the
572
+ * zero-width space the fallback carrier carries, and the neighbouring
573
+ * invisible formatting characters (zero-width joiners, word joiner, BOM).
574
+ * Nothing here is information a model could quote back.
575
+ */
576
+ const INVISIBLE_TEXT_RE = /^[\s\u200b-\u200f\u2060\ufeff]*$/
577
+
578
+ /**
579
+ * Whether content blocks carry anything a model could read.
580
+ *
581
+ * An empty list carries nothing. A text block carries something unless its
582
+ * text is made only of invisible characters. Every other block type (image,
583
+ * file, attachment) counts as readable: a carrier never holds one.
584
+ *
585
+ * @param content - the `content` array of a message.
586
+ * @returns true when at least one block holds readable information.
587
+ */
588
+ function hasReadableContent(content) {
589
+ if (!Array.isArray(content)) return false
590
+ for (const block of content) {
591
+ if (!block || typeof block !== 'object') continue
592
+ if (block.type !== 'text') return true
593
+ if (typeof block.text !== 'string' || !INVISIBLE_TEXT_RE.test(block.text)) return true
594
+ }
595
+ return false
596
+ }
597
+
598
+ /**
599
+ * Whether one event is a plugin's SILENT surface-replacement carrier.
600
+ *
601
+ * That shape is a `user/message` written by a plugin (`source.kind` is
602
+ * `plugin:<id>`) that carries NO READABLE CONTENT: the replacement
603
+ * dsh-delete-turn writes for a deletion and this plugin writes for a rerun's
604
+ * shadow. It is not a prompt - there is nothing to re-send - and the platform
605
+ * agrees: a human prompt is a user message whose `source.kind` is `'user'`
606
+ * (`dsh-session-turn-outline` reads no other kind, which is why dsh-edit-turn's
607
+ * rewrite deliberately keeps `kind: 'user'`).
608
+ *
609
+ * "No readable content" covers both carrier shapes: the empty list a host
610
+ * writes where its adapter is proven to drop it, and the single zero-width
611
+ * space the fallback writes (0.1.27). Requiring exact emptiness would make the
612
+ * fallback carrier read as a human prompt and let a chained rerun re-send it -
613
+ * a question nobody asked.
614
+ *
615
+ * The content-carrying half matters the other way: a rewrite that DOES carry
616
+ * wording - current or historical `plugin:dsh-edit-turn` carriers - is a prompt
617
+ * standing in a human's place and stays rerunnable.
618
+ *
619
+ * @param event - raw session event.
620
+ * @returns true when the event is a plugin-written text-free replacement carrier.
621
+ */
622
+ export function isSilentPluginCarrier(event) {
623
+ if (!event) return false
624
+ const type = event.type
625
+ if (type !== 'user/message' && type !== 'developer/message' && type !== 'system/message') return false
626
+ const data = event.data || {}
627
+ const message = data.message && typeof data.message === 'object' ? data.message : data
628
+ const source = message && message.source
629
+ if (!source || typeof source.kind !== 'string' || !source.kind.startsWith('plugin:')) return false
630
+ return !hasReadableContent(message.content)
631
+ }
632
+
633
+ /**
634
+ * Build this plugin's rerun ledger from the log alone.
635
+ *
636
+ * Every rerun is one replacement whose carrier source is
637
+ * `{ kind: 'plugin:dsh-rerun-turn', rerunBy, rerunId, ... }`. A replacement
638
+ * landed by any other producer - compaction, dsh-edit-turn - is ignored.
639
+ *
640
+ * @param events - complete contiguous raw event log.
641
+ * @returns `{ hidden, reruns }`: one hidden entry per retired or carrier seq,
642
+ * and one record per landed rerun with its replay progress.
643
+ */
644
+ export function rerunLedger(events) {
645
+ const folded = foldSurface(events)
646
+ const bySeq = new Map(events.map((event) => [event.seq, event]))
647
+ const turnOf = turnIndex(events)
648
+ // Replacement lineage: shadowed seq -> replacement seq. A retired node may
649
+ // itself be the stand-in for an older original (dsh-edit-turn rewrote a
650
+ // prompt in place), and hiding must reach the original too - the sibling
651
+ // plugin's client will surface that original row itself when its own
652
+ // replacement bubble can no longer render.
653
+ const revisions = new Map()
654
+ for (const replacement of folded.replacements) {
655
+ for (const seq of replacement.shadowed) revisions.set(seq, replacement.seq)
656
+ }
657
+ /** Whether following a node's replacement chain runs into this window. */
658
+ const chainHits = (seq, shadowedSet) => {
659
+ let current = revisions.get(seq)
660
+ const seen = new Set([seq])
661
+ while (current !== undefined && !seen.has(current)) {
662
+ if (shadowedSet.has(current)) return true
663
+ seen.add(current)
664
+ current = revisions.get(current)
665
+ }
666
+ return false
667
+ }
668
+ const hidden = []
669
+ const reruns = []
670
+ for (const replacement of folded.replacements) {
671
+ const carrier = bySeq.get(replacement.seq)
672
+ if (!isRerunCarrier(carrier)) continue
673
+ const carrierData = carrier.data || {}
674
+ const carrierMessage = carrierData.message && typeof carrierData.message === 'object' ? carrierData.message : carrierData
675
+ const source = carrierMessage.source
676
+ const rerunId = source.rerunId
677
+ const shadowedSet = new Set(replacement.shadowed)
678
+ for (const seq of replacement.shadowed) {
679
+ const turn = turnOf.get(seq)
680
+ hidden.push({ seq, turn: typeof turn === 'number' ? turn : null, rerunId })
681
+ }
682
+ // Every original whose live stand-in this rerun retired is retired too:
683
+ // its row would otherwise reappear (the sibling edit plugin's client
684
+ // un-hides an original once its own replacement bubble cannot render).
685
+ const already = new Set(replacement.shadowed)
686
+ for (const seq of revisions.keys()) {
687
+ if (already.has(seq)) continue
688
+ if (!chainHits(seq, shadowedSet)) continue
689
+ already.add(seq)
690
+ const turn = turnOf.get(seq)
691
+ hidden.push({ seq, turn: typeof turn === 'number' ? turn : null, rerunId })
692
+ }
693
+ // The carrier row itself is retired too: the synthetic turn around it has
694
+ // no visible content, and hiding its seq takes any turn-tail strip with it.
695
+ hidden.push({ seq: replacement.seq, turn: null, rerunId })
696
+ // Replay progress: every shadowed surface seq the walk copies needs a
697
+ // later copy citing it, except the prompt itself, which the regeneration
698
+ // re-sends (spotted by its rpcId) or - when admission failed - replays as
699
+ // a copy like the rest. Nodes the walk never copies (system messages) are
700
+ // expected to stay uncited.
701
+ const covered = new Set()
702
+ for (const event of events) {
703
+ if (event.seq <= replacement.seq) continue
704
+ const marker = replayMarkerOf(event)
705
+ if (marker !== null && marker.rerunId === rerunId && marker.originalSeq !== null) covered.add(marker.originalSeq)
706
+ }
707
+ const promptRequestId = typeof source.promptRequestId === 'string' ? source.promptRequestId : null
708
+ let promptLanded = false
709
+ if (promptRequestId !== null) {
710
+ promptLanded = events.some((event) => {
711
+ if (event.seq <= replacement.seq || event.type !== 'user/message') return false
712
+ const promptSource = event.data && event.data.source
713
+ return Boolean(promptSource && promptSource.kind === 'user' && promptSource.rpcId === promptRequestId)
714
+ })
715
+ }
716
+ const walkTo = typeof source.logTo === 'number' ? source.logTo : Number.POSITIVE_INFINITY
717
+ // The walk the replay actually takes: with the prompt landed it starts at
718
+ // the next turn's bracket (`replayFrom`; absent = no tail to replay), and
719
+ // without it - the failed-admission fallback - it reproduces the whole
720
+ // window from the rerun turn's own bracket (`logFrom`).
721
+ const tailFrom = typeof source.replayFrom === 'number' ? source.replayFrom : null
722
+ const fallbackFrom = typeof source.logFrom === 'number' ? source.logFrom : null
723
+ const expectsCopy = (seq) => {
724
+ const event = bySeq.get(seq)
725
+ if (event === undefined || !REPLAYED_SURFACE_TYPES.has(event.type)) return false
726
+ // A carrier is bookkeeping, never conversation: the replay walk retires
727
+ // it without a copy (see buildReplayWrites), so it must never be counted
728
+ // as missing - an eternally missing seq would make every /state poll
729
+ // append the replay batch again, growing the log without bound.
730
+ if (isRerunCarrier(event)) return false
731
+ const from = promptLanded ? tailFrom : fallbackFrom
732
+ return from !== null && seq >= from && seq <= walkTo
733
+ }
734
+ const missing = []
735
+ for (const seq of replacement.shadowed) {
736
+ // The prompt itself: covered by the rpcId event, or by its own copy when
737
+ // the regeneration never happened. Its seq can sit anywhere - an in-place
738
+ // rewrite by a sibling plugin leaves the live prompt as a late carrier -
739
+ // so it is classified first.
740
+ if (seq === source.promptSeq) {
741
+ if (!promptLanded && !covered.has(seq)) missing.push(seq)
742
+ continue
743
+ }
744
+ // Everything else needs a copy exactly when the replay walk covers it
745
+ // (its originalSeq is cited by the copy). Nodes the rerun turn itself
746
+ // produced, and any surface node outside the walked range, are retired
747
+ // without copies.
748
+ if (expectsCopy(seq) && !covered.has(seq)) missing.push(seq)
749
+ }
750
+ reruns.push({
751
+ rerunId,
752
+ carrierSeq: replacement.seq,
753
+ startSeq: replacement.startSeq,
754
+ endSeq: replacement.endSeq,
755
+ shadowed: replacement.shadowed,
756
+ promptSeq: typeof source.promptSeq === 'number' ? source.promptSeq : null,
757
+ promptRequestId,
758
+ replayFrom: typeof source.replayFrom === 'number' ? source.replayFrom : null,
759
+ logFrom: typeof source.logFrom === 'number' ? source.logFrom : null,
760
+ logTo: typeof source.logTo === 'number' ? source.logTo : null,
761
+ rerunTurnEnd: typeof source.rerunTurnEnd === 'number' ? source.rerunTurnEnd : null,
762
+ turn: typeof source.turn === 'number' ? source.turn : null,
763
+ // The synthetic bookkeeping turn a LEGACY carrier lives in
764
+ // (0.1.14-0.1.25); the client hides its rows (an empty turn still draws a
765
+ // process/tail strip). Current carriers open no turn, so this is null and
766
+ // there is nothing to hide by turn number.
767
+ carrierTurn: typeof source.carrierTurn === 'number' ? source.carrierTurn : null,
768
+ complete: missing.length === 0,
769
+ missing,
770
+ })
771
+ }
772
+ return { hidden, reruns }
773
+ }
774
+
775
+ /**
776
+ * Turns whose every surface node has been retired by a landed rerun.
777
+ *
778
+ * The platform renders a process/tail strip for every turn, and the client
779
+ * hides retired rows by seq - but a turn whose content is gone leaves its
780
+ * strip behind ("用时 1 秒" with nothing under it), which reads as debris after
781
+ * a rerun of an earlier turn. Those turns have no visible nodes left, so their
782
+ * whole rows must go. Mirrors the client's hidden-set gating: a rerun's
783
+ * retirements count only once it is complete and is not the one in flight.
784
+ *
785
+ * @param events - complete contiguous raw event log.
786
+ * @param folded - `foldSurface(events)`.
787
+ * @param ledger - `rerunLedger(events)`.
788
+ * @param options - `{ inFlightId? }`: the rerun whose retirements are still
789
+ * awaiting their replacement on screen.
790
+ * @returns turn numbers, ascending.
791
+ */
792
+ export function retiredTurnList(events, folded, ledger, options) {
793
+ const completeIds = new Set(ledger.reruns.filter((entry) => entry.complete).map((entry) => entry.rerunId))
794
+ const inFlightId = options && typeof options.inFlightId === 'string' ? options.inFlightId : null
795
+ const active = ledger.hidden.filter((entry) => {
796
+ if (typeof entry.rerunId !== 'string') return true
797
+ if (!completeIds.has(entry.rerunId)) return false
798
+ if (inFlightId !== null && entry.rerunId === inFlightId) return false
799
+ return true
800
+ })
801
+ const hiddenSeqs = new Set(active.map((entry) => entry.seq))
802
+ const bySeq = new Map(events.map((event) => [event.seq, event]))
803
+ const turnOf = turnIndex(events)
804
+ const visibleTurns = new Set()
805
+ for (const seq of folded.nodes) {
806
+ if (hiddenSeqs.has(seq)) continue
807
+ // System messages render no chat row: a turn whose only visible node is
808
+ // its system prompt is an empty turn to the viewer.
809
+ const event = bySeq.get(seq)
810
+ if (event !== undefined && event.type === 'system/message') continue
811
+ const turn = turnOf.get(seq)
812
+ if (typeof turn === 'number') visibleTurns.add(turn)
813
+ }
814
+ const markerTurns = new Set(ledger.reruns.map((entry) => entry.carrierTurn).filter((turn) => typeof turn === 'number'))
815
+ const out = []
816
+ for (const turn of new Set(active.map((entry) => entry.turn))) {
817
+ if (typeof turn !== 'number') continue
818
+ if (visibleTurns.has(turn)) continue
819
+ if (markerTurns.has(turn)) continue
820
+ out.push(turn)
821
+ }
822
+ // Brackets-only turns own no surface node at all (the log keeps turn/step
823
+ // brackets a replay left behind), yet the platform still draws their process
824
+ // strip. The trailing turn may be a generation in flight, so it is never
825
+ // touched; during an in-flight rerun the retired window is awaiting its
826
+ // replacement and stays untouched too.
827
+ if (inFlightId === null) {
828
+ const surfaceTurns = new Set()
829
+ for (const seq of folded.nodes) {
830
+ const turn = turnOf.get(seq)
831
+ if (typeof turn === 'number') surfaceTurns.add(turn)
832
+ }
833
+ let maxTurn = null
834
+ for (const event of events) {
835
+ if (event.type !== 'turn/start') continue
836
+ const turn = event.data && event.data.turn
837
+ if (typeof turn !== 'number') continue
838
+ if (maxTurn === null || turn > maxTurn) maxTurn = turn
839
+ }
840
+ for (const event of events) {
841
+ if (event.type !== 'turn/start') continue
842
+ const turn = event.data && event.data.turn
843
+ if (typeof turn !== 'number') continue
844
+ if (surfaceTurns.has(turn) || markerTurns.has(turn) || turn === maxTurn) continue
845
+ if (!out.includes(turn)) out.push(turn)
846
+ }
847
+ }
848
+ return out.sort((left, right) => left - right)
849
+ }
850
+
851
+ /** Planner rejection with a machine code the HTTP layer forwards verbatim. */
852
+ export class RerunPlanError extends Error {
853
+ constructor(code, message) {
854
+ super(message)
855
+ this.name = 'RerunPlanError'
856
+ this.code = code
857
+ }
858
+ }
859
+
860
+ /**
861
+ * Resolve one rerun target inside a log: the reply the button was pressed on.
862
+ * @param events - complete contiguous raw event log.
863
+ * @param request - `{ seq?, messageId? }`.
864
+ * @returns the target assistant event.
865
+ * @throws {RerunPlanError} with `not-rerunnable` when no unique target exists.
866
+ */
867
+ function resolveTarget(events, request) {
868
+ let targetSeq = typeof request.seq === 'number' ? request.seq : undefined
869
+ if (targetSeq === undefined && typeof request.messageId === 'string' && request.messageId !== '') {
870
+ for (const event of events) {
871
+ if (messageIdOf(event) === request.messageId) {
872
+ targetSeq = event.seq
873
+ break
874
+ }
875
+ }
876
+ }
877
+ if (targetSeq === undefined) throw new RerunPlanError('not-rerunnable', 'no rerun target was found')
878
+ const target = events.find((event) => event.seq === targetSeq)
879
+ if (!target) throw new RerunPlanError('not-rerunnable', 'the target event does not exist')
880
+ // A reply is the normal target. A turn that never produced a finalized reply has
881
+ // none - the user stopped it, or it failed - so its prompt is the target instead.
882
+ // planRerun then requires that prompt to be the turn's own live prompt before it
883
+ // plans anything, so this widens what can be addressed, not what can be planned.
884
+ if (target.type !== 'assistant/message' && target.type !== 'user/message') {
885
+ throw new RerunPlanError('not-rerunnable', 'rerunning targets a model reply')
886
+ }
887
+ return target
888
+ }
889
+
890
+ /**
891
+ * Plan one rerun: the target turn, the shadow window, the log range the replay
892
+ * walks, and the prompt the regeneration re-sends.
893
+ *
894
+ * The window is `[the turn's own prompt .. the last surface node]` - the
895
+ * complete remainder of the conversation in surface order. The prompt is what
896
+ * the rerun re-sends; everything the turn produced and everything built on it
897
+ * is shadowed now and replayed after the fresh answer lands.
898
+ *
899
+ * @param events - complete contiguous raw event log.
900
+ * @param surfaceNodes - current surface seqs in model order.
901
+ * @param request - `{ seq?, messageId? }` addressing a reply.
902
+ * @returns the plan (without `rerunId`, which the caller mints).
903
+ * @throws {RerunPlanError} with a stable code when the target cannot be planned.
904
+ */
905
+ export function planRerun(events, surfaceNodes, request) {
906
+ const nodeIndex = new Map(surfaceNodes.map((seq, index) => [seq, index]))
907
+ const turnOf = turnIndex(events)
908
+ const target = resolveTarget(events, request)
909
+ if (!nodeIndex.has(target.seq)) {
910
+ throw new RerunPlanError('already-retired', 'this reply is no longer on the current surface')
911
+ }
912
+ if (target.seq === surfaceNodes[0]) {
913
+ throw new RerunPlanError('not-rerunnable', 'the system prompt head cannot be rerun')
914
+ }
915
+ const turn = turnOf.get(target.seq)
916
+ if (typeof turn !== 'number') {
917
+ throw new RerunPlanError('not-rerunnable', 'the reply does not belong to a turn')
918
+ }
919
+ const bySeq = eventIndex(events)
920
+ const brackets = turnSpans(events)
921
+ const revisions = replacementChains(events)
922
+ const head = surfaceNodes[0]
923
+ const resolved = resolveRerunPrompt(bySeq, nodeIndex, brackets, revisions, head, turn, target.seq)
924
+ if (resolved.reason === 'no-prompt') {
925
+ throw new RerunPlanError('not-rerunnable', 'the turn has no prompt to re-send')
926
+ }
927
+ if (resolved.reason === 'retired') {
928
+ throw new RerunPlanError('already-retired', 'the turn prompt is no longer on the current surface')
929
+ }
930
+ if (resolved.reason === 'not-user') {
931
+ throw new RerunPlanError('not-rerunnable', 'the turn prompt is not a user message')
932
+ }
933
+ if (resolved.reason === 'carrier') {
934
+ throw new RerunPlanError('not-rerunnable', 'the turn prompt was replaced by a deletion or an earlier rerun; there is no prompt left to re-send')
935
+ }
936
+ if (resolved.reason === 'head') {
937
+ throw new RerunPlanError('not-rerunnable', 'the system prompt head cannot be rerun')
938
+ }
939
+ const livePromptSeq = resolved.promptSeq
940
+ // A prompt target is an address, never a licence. It is accepted only for a turn
941
+ // that has no rerunnable reply of its own - the shape a user reaches by stopping a
942
+ // turn, or by a turn that failed - and only when it IS the turn's live prompt.
943
+ // Everything else is refused exactly as before: a turn that does have a reply
944
+ // addresses that reply, and a shadowed prompt (or another turn's prompt) would
945
+ // re-ask a question this turn never asked. The predicate is the advertisement's
946
+ // own, so advertised and plannable cannot drift apart.
947
+ if (target.type !== 'assistant/message') {
948
+ const ownReply = rerunnableReplyOf({ bySeq, nodeIndex, turnOf, brackets, revisions, head }, events, turn)
949
+ if (target.seq !== livePromptSeq || ownReply !== null) {
950
+ throw new RerunPlanError('not-rerunnable', 'rerunning targets a model reply')
951
+ }
952
+ }
953
+ const span = resolved.span
954
+ const promptEvent = bySeq.get(livePromptSeq)
955
+ const shadowed = surfaceNodes.slice(nodeIndex.get(livePromptSeq))
956
+ if (shadowed.length === 0 || shadowed[0] !== livePromptSeq) {
957
+ throw new RerunPlanError('not-rerunnable', 'the prompt does not open a rerun window')
958
+ }
959
+ if (promptEvent.data && Array.isArray(promptEvent.data.content)) {
960
+ const files = promptEvent.data.content.filter((block) => block && block.type === 'file')
961
+ if (files.length > 0) {
962
+ throw new RerunPlanError('attachments-unsupported', 'the turn prompt carries file attachments, which a rerun cannot re-admit yet')
963
+ }
964
+ }
965
+ // The replay walks the tail AFTER the rerun turn: the shadowed window is
966
+ // [the prompt .. the last surface node], but the rerun turn's own reply is
967
+ // replaced by the fresh answer, not replayed - only the later turns come
968
+ // back. When the prompt never lands (admission failed), the walk falls back
969
+ // to the rerun turn's own `turn/start`, so the copies reproduce the whole
970
+ // window and the context keeps its content.
971
+ const lastShadowed = shadowed[shadowed.length - 1]
972
+ let logTo = lastShadowed
973
+ for (let seq = lastShadowed + 1; ; seq += 1) {
974
+ const event = bySeq.get(seq)
975
+ if (event === undefined) break
976
+ if (isSurfaceEvent(event)) break
977
+ logTo = seq
978
+ if (event.type === 'turn/end') break
979
+ }
980
+ const spans = turnSpans(events)
981
+ const spanIndex = spans.findIndex((entry) => entry.turn === turn)
982
+ const nextSpan = spanIndex >= 0 ? spans[spanIndex + 1] : undefined
983
+ const replayFrom = nextSpan && nextSpan.startSeq <= logTo ? nextSpan.startSeq : null
984
+ const parts = readPromptParts(promptEvent)
985
+ return {
986
+ turn,
987
+ targetSeq: target.seq,
988
+ promptSeq: livePromptSeq,
989
+ startSeq: shadowed[0],
990
+ endSeq: shadowed[shadowed.length - 1],
991
+ shadowed,
992
+ // The seq where the replay's copies start in the normal path - the next
993
+ // turn's own bracket - and the fallback start (the rerun turn's bracket)
994
+ // for the failed-admission replay. `rerunTurnEnd` closes the rerun turn;
995
+ // its surface nodes are retired without copies.
996
+ replayFrom,
997
+ logFrom: span.startSeq,
998
+ logTo,
999
+ rerunTurnEnd: span.endSeq,
1000
+ prompt: parts,
1001
+ }
1002
+ }
1003
+
1004
+ /**
1005
+ * The silent carrier of the shadow step.
1006
+ *
1007
+ * Two properties are mandatory, and only one shape has both: the carrier must
1008
+ * be a surface event whose `sourceEventSeqs` cover the shadowed window
1009
+ * completely, and it must leave no message the model can read. That shape is a
1010
+ * turn-free `user/message` carrying no READABLE text:
1011
+ *
1012
+ * - the format reads a `user/message` with no open turn and no open step at
1013
+ * all. Every other surface type needs one: `system/message` and
1014
+ * `developer/message` are step events (`requireStep`), `assistant/message`
1015
+ * goes through the same step check, and a replacement `tool/result` needs
1016
+ * an open turn. So a carrier of any other type must open a turn - and a
1017
+ * turn opened just to hold bookkeeping is exactly what shows up on screen
1018
+ * as an empty "completed" strip and as a hole in the trajectory numbering
1019
+ * (0.1.14-0.1.25). The agent loop's process-local turn counter would also
1020
+ * have to be re-pointed at it (the 0.1.0/0.1.1 corruption, see README).
1021
+ *
1022
+ * - "no readable text" is host-dependent, and that is measured rather than
1023
+ * assumed: an EMPTY content list is only safe where the adapter in play
1024
+ * drops a user message whose converted content is nothing.
1025
+ * `dsh-llm-deepseek` always does (`role === "user" && content.length ===
1026
+ * 0`); `@deepseek-ai/dsh-llm-pi-ai` only where the local hand patch named
1027
+ * `dsh-delete-turn:skip-empty-user` is present (upstream has not added the
1028
+ * skip yet). Unpatched, pi-ai maps `content: []` to
1029
+ * `{ role: 'user', content: '' }` and the provider refuses the whole
1030
+ * request: HTTP 400 `user message must have content`, which aborts the
1031
+ * turn (observed 2026-10-07 in the DSH desktop app, whose bundled runtime
1032
+ * carries no patch, while the npx cache copy the web host loads does).
1033
+ * The fallback is ONE ZERO-WIDTH SPACE, the shape dsh-delete-turn ships
1034
+ * for the identical reason: it is invisible to the user, costs a few
1035
+ * heuristic tokens, and every measured provider accepts it. A non-empty
1036
+ * *readable* marker text is still out of the question - the model quoted
1037
+ * it back at 0.1.13 - and nothing at all is not: an empty string is the
1038
+ * one shape the provider rejects.
1039
+ */
1040
+ const CARRIER_SOURCE_KIND = `plugin:${PLUGIN_ID}`
1041
+
1042
+ /**
1043
+ * The one adapter line that makes an empty carrier safe.
1044
+ *
1045
+ * `dsh-llm-pi-ai` drops a user message whose converted content is empty under
1046
+ * this marker (the official DeepSeek adapter already does it natively). Its
1047
+ * absence - a different build, an upstream release - is "not proven", and an
1048
+ * unproven host must never write an empty carrier.
1049
+ */
1050
+ export const ADAPTER_PATCH_MARKER = 'dsh-delete-turn:skip-empty-user'
1051
+
1052
+ /** The one invisible character the fallback carrier carries. */
1053
+ export const CARRIER_ZWSP = '\u200b'
1054
+
1055
+ /**
1056
+ * Pure decision shared by the probe and its tests: does this adapter source
1057
+ * carry the line that drops a user message whose content converts to nothing?
1058
+ * Anything that is not a string - an unreadable file, a missing package - is no
1059
+ * proof.
1060
+ *
1061
+ * @param adapterSource - the text of `@deepseek-ai/dsh-llm-pi-ai`'s entry file.
1062
+ * @returns true only when the skip is provably present.
1063
+ */
1064
+ export function adapterSourceDropsEmptyUserContent(adapterSource) {
1065
+ return typeof adapterSource === 'string' && adapterSource.includes(ADAPTER_PATCH_MARKER)
1066
+ }
1067
+
1068
+ /**
1069
+ * Pure carrier content for a host that does (or does not) prove the drop.
1070
+ *
1071
+ * @param dropsEmptyUserContent - the probe's verdict; anything but `true` fails
1072
+ * closed to the carrier every provider accepts.
1073
+ * @returns the `content` array of the shadow carrier.
1074
+ */
1075
+ export function silentCarrierContent(dropsEmptyUserContent) {
1076
+ return dropsEmptyUserContent === true ? [] : [{ type: 'text', text: CARRIER_ZWSP }]
1077
+ }
1078
+
1079
+ /**
1080
+ * The provider a session's last model request used, from its own log. The
1081
+ * carrier shape follows the ADAPTER behind that provider, so the verdict has to
1082
+ * be per session rather than once at load.
1083
+ *
1084
+ * @param events - the session's committed events.
1085
+ * @returns the provider id, or null when the log does not name one.
1086
+ */
1087
+ export function providerOf(events) {
1088
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1089
+ const event = events[index]
1090
+ if (event === null || typeof event !== 'object') continue
1091
+ const data = event.data
1092
+ if (data === null || typeof data !== 'object') continue
1093
+ if (event.type === 'model/selection' && typeof data.provider === 'string' && data.provider !== '') return data.provider
1094
+ const header = data.header
1095
+ const config = header !== null && typeof header === 'object' ? header.config : null
1096
+ if (event.type === 'request/header' && config !== null && typeof config === 'object' && typeof config.provider === 'string' && config.provider !== '') {
1097
+ return config.provider
1098
+ }
1099
+ }
1100
+ return null
1101
+ }
1102
+
1103
+ /**
1104
+ * Whether the adapter serving `provider` drops an empty user message before the
1105
+ * wire. The DeepSeek adapter does it natively (its converter skips
1106
+ * `role === "user" | "assistant"` with no content) and is the one adapter whose
1107
+ * extension hooks include `prepareExtensions`; pi-ai carries the same
1108
+ * `resolveImageAccess` but no `prepareExtensions`.
1109
+ *
1110
+ * @param ctx - plugin context, for the `llm` registry.
1111
+ * @param provider - provider id from the session log.
1112
+ * @returns true only when the adapter in play is the proven one.
1113
+ */
1114
+ export function adapterDropsEmptyUserContentFor(ctx, provider) {
1115
+ if (typeof provider !== 'string' || provider === '') return false
1116
+ try {
1117
+ const llm = ctx.get('llm')
1118
+ const adapters = llm === null || llm === undefined ? null : llm.adapters
1119
+ if (adapters === null || adapters === undefined || typeof adapters.get !== 'function') return false
1120
+ const entry = adapters.get(provider)
1121
+ const adapter = entry === null || entry === undefined ? null : entry.adapter
1122
+ return adapter !== null && adapter !== undefined && typeof adapter.prepareExtensions === 'function'
1123
+ } catch {
1124
+ return false
1125
+ }
1126
+ }
1127
+
1128
+ /**
1129
+ * The carrier verdict for one session: the adapter in play first, the load-time
1130
+ * pi-ai proof as the fallback.
1131
+ *
1132
+ * @param ctx - plugin context.
1133
+ * @param events - the session's committed events.
1134
+ * @returns true when the empty carrier is safe for this session.
1135
+ */
1136
+ export function dropsEmptyUserContentFor(ctx, events) {
1137
+ if (adapterDropsEmptyUserContentFor(ctx, providerOf(events))) return true
1138
+ return ADAPTER_DROPS_EMPTY_USER_CONTENT
1139
+ }
1140
+
1141
+ /**
1142
+ * Resolve the one adapter this plugin can prove the drop for - the pi-ai build
1143
+ * the running host itself would load - and read the mark. Any failure (package
1144
+ * absent, file unreadable, resolution refused) is "not proven" and yields the
1145
+ * safe carrier; see {@link ADAPTER_DROPS_EMPTY_USER_CONTENT} for why a global
1146
+ * probe may never be optimistic.
1147
+ *
1148
+ * @returns true when the installed adapter text carries the skip.
1149
+ */
1150
+ export function probeAdapterDropsEmptyUserContent() {
1151
+ try {
1152
+ const entry = process.argv[1]
1153
+ const require = createRequire(entry ?? import.meta.url)
1154
+ const resolved = require.resolve('@deepseek-ai/dsh-llm-pi-ai', { paths: entry ? [dirname(entry)] : [] })
1155
+ return adapterSourceDropsEmptyUserContent(readFileSync(resolved, 'utf8'))
1156
+ } catch {
1157
+ return false
1158
+ }
1159
+ }
1160
+
1161
+ /**
1162
+ * The carrier shape this process writes, decided ONCE at load.
1163
+ *
1164
+ * Why one decision and not one per request: the adapter in play depends on the
1165
+ * session's provider, so a profile holding both a DeepSeek-adapter provider and
1166
+ * an unpatched pi-ai one would write an empty carrier for the latter and break
1167
+ * it. The empty carrier is therefore unlocked only where the installed pi-ai
1168
+ * build proves it skips empty user content, and the conservative zero-width
1169
+ * carrier is the default everywhere else.
1170
+ */
1171
+ export const ADAPTER_DROPS_EMPTY_USER_CONTENT = probeAdapterDropsEmptyUserContent()
1172
+
1173
+ /**
1174
+ * Build the write of the shadow step: one silent carrier replacement over the
1175
+ * whole window, appended without any turn bracket.
1176
+ *
1177
+ * @param plan - the planned window.
1178
+ * @param rerunId - the operation identity the recovery path keys on.
1179
+ * @param promptRequestId - the `rpcId` the regenerated prompt will carry.
1180
+ * @param dropsEmptyUserContent - whether the installed adapter is proven to
1181
+ * drop a user message with empty content. Defaults to the load-time probe;
1182
+ * injectable so the shape is testable without this machine's adapter cache.
1183
+ * @returns a one-element `{ type, data }` list for `session.append`.
1184
+ */
1185
+ export function buildShadowWrites(
1186
+ plan,
1187
+ rerunId,
1188
+ promptRequestId,
1189
+ dropsEmptyUserContent = ADAPTER_DROPS_EMPTY_USER_CONTENT,
1190
+ ) {
1191
+ return [
1192
+ {
1193
+ type: 'user/message',
1194
+ surfaceOp: { op: 'replace', startSeq: plan.startSeq, endSeq: plan.endSeq },
1195
+ sourceEventSeqs: plan.shadowed,
1196
+ data: {
1197
+ id: randomUUID(),
1198
+ role: 'user',
1199
+ content: silentCarrierContent(dropsEmptyUserContent),
1200
+ source: {
1201
+ kind: CARRIER_SOURCE_KIND,
1202
+ rerunBy: PLUGIN_ID,
1203
+ rerunId,
1204
+ promptRequestId,
1205
+ promptSeq: plan.promptSeq,
1206
+ turn: plan.turn,
1207
+ replayFrom: plan.replayFrom,
1208
+ logFrom: plan.logFrom,
1209
+ logTo: plan.logTo,
1210
+ rerunTurnEnd: plan.rerunTurnEnd,
1211
+ },
1212
+ },
1213
+ },
1214
+ ]
1215
+ }
1216
+
1217
+ /** Source marker shared by every event a replay appends. */
1218
+ function replaySource(source, rerunId, originalSeq) {
1219
+ return {
1220
+ ...(source && typeof source === 'object' ? source : {}),
1221
+ rerunBy: PLUGIN_ID,
1222
+ rerunId,
1223
+ originalSeq,
1224
+ }
1225
+ }
1226
+
1227
+ /**
1228
+ * The edit-turn record type whose text/reasoning blocks this replay carries.
1229
+ *
1230
+ * edit-turn's patches are projections over the original assistant message: a
1231
+ * patch record names seq + blockIndex, and the model's copy is rewritten when
1232
+ * the session folds. A rerun that copies that later turn would otherwise copy
1233
+ * the recorded (pre-edit) content and silently drop the user's edit. Reading the
1234
+ * record here and applying it to the copy keeps both plugins usable in either
1235
+ * order: rerun an earlier turn and the edits on the turns it preserves travel
1236
+ * with them.
1237
+ *
1238
+ * This is a read-only cross-plugin contract. It never throws: a malformed or
1239
+ * future record is skipped, exactly as a projection would skip it.
1240
+ */
1241
+ export const EDIT_TURN_PATCH_TYPE = 'plugin:dsh-edit-turn/patch'
1242
+
1243
+ const EDIT_BLOCK_TYPES = {
1244
+ text: ['text'],
1245
+ reasoning: ['reasoning', 'thinking'],
1246
+ }
1247
+
1248
+ /**
1249
+ * Latest edit-turn patch per (seq, blockIndex) in the log.
1250
+ * @param events - complete event log.
1251
+ * @returns `Map<seq, Map<blockIndex, { kind, text }>>`.
1252
+ */
1253
+ export function editPatchesOf(events) {
1254
+ const out = new Map()
1255
+ for (const event of events) {
1256
+ if (!event || event.type !== EDIT_TURN_PATCH_TYPE) continue
1257
+ const data = event.data
1258
+ if (!data || data.version !== 1 || !Array.isArray(data.targets)) continue
1259
+ for (const target of data.targets) {
1260
+ if (!target || typeof target !== 'object') continue
1261
+ const seq = target.seq
1262
+ const blockIndex = target.blockIndex
1263
+ if (!Number.isSafeInteger(seq) || seq < 0) continue
1264
+ if (!Number.isSafeInteger(blockIndex) || blockIndex < 0) continue
1265
+ if (target.kind !== 'text' && target.kind !== 'reasoning') continue
1266
+ if (typeof target.text !== 'string') continue
1267
+ let byBlock = out.get(seq)
1268
+ if (byBlock === undefined) {
1269
+ byBlock = new Map()
1270
+ out.set(seq, byBlock)
1271
+ }
1272
+ byBlock.set(blockIndex, { kind: target.kind, text: target.text })
1273
+ }
1274
+ }
1275
+ return out
1276
+ }
1277
+
1278
+ /**
1279
+ * Apply edit-turn patches to one recorded assistant message's content.
1280
+ *
1281
+ * The block indices address the recorded content, so this runs before the
1282
+ * replay filters unhealthy tool calls; a patch aimed at a tool-call block is
1283
+ * skipped, never invented. Reasoning text drops its signature for the same
1284
+ * reason edit-turn's projection does: the signature signs the old text.
1285
+ *
1286
+ * @param content - the recorded block array.
1287
+ * @param patches - the block map for this seq, if any.
1288
+ * @returns a patched copy (the recorded array is never mutated).
1289
+ */
1290
+ export function applyEditPatches(content, patches) {
1291
+ const blocks = Array.isArray(content) ? content.slice() : []
1292
+ if (!(patches instanceof Map) || patches.size === 0) return blocks
1293
+ for (const [index, patch] of patches) {
1294
+ const block = blocks[index]
1295
+ if (!block || typeof block !== 'object') continue
1296
+ const accepted = EDIT_BLOCK_TYPES[patch.kind]
1297
+ if (!accepted || !accepted.includes(block.type)) continue
1298
+ if (typeof block.text !== 'string') continue
1299
+ const next = { ...block, text: patch.text }
1300
+ if (patch.kind === 'reasoning') {
1301
+ delete next.signature
1302
+ delete next.thinkingSignature
1303
+ }
1304
+ blocks[index] = next
1305
+ }
1306
+ return blocks
1307
+ }
1308
+
1309
+ /**
1310
+ * Build the replay writes for one rerun's shadowed log range.
1311
+ *
1312
+ * Every shadowed event after the prompt is copied verbatim except for:
1313
+ * fresh turn numbers (the format requires them contiguous), fresh message
1314
+ * ids, remapped `sourceEventSeqs` on tool results, dropped usage numbers and
1315
+ * embedded streams, and the replay marker in each message source. System
1316
+ * messages are skipped - the system prompt is loop-owned machinery that
1317
+ * reconciles itself on the next request. Log-only records (attempts, retries,
1318
+ * splices, title/request bookkeeping) are skipped too: they describe the
1319
+ * original run, not the conversation.
1320
+ *
1321
+ * Tool calls are copied only as complete pairs. A call whose result never
1322
+ * landed (an interrupted turn) is dropped along with its advertisement in the
1323
+ * copied assistant content, because the format refuses a turn that closes with
1324
+ * an unresolved call. The inverse repair shape - a `TOOL_NOT_STARTED` result
1325
+ * with no call event - is copied as-is and keeps its absent
1326
+ * `sourceEventSeqs`: the validator accepts that repair only without one.
1327
+ *
1328
+ * @param events - complete contiguous raw event log.
1329
+ * @param plan - the planned window (`logFrom`..`logTo`).
1330
+ * @param baseTurn - the first turn number the replay may use.
1331
+ * @param rerunId - the operation identity.
1332
+ * @param startSeq - the seq the first write will land at (all writes are
1333
+ * appended back to back, so each predicted seq is `startSeq` + its offset).
1334
+ * @param promptCopied - whether the prompt itself is part of the replay
1335
+ * (admission failed); when false the walk skips the prompt event.
1336
+ * @returns an ordered `{ type, data, surfaceOp? }` write list.
1337
+ */
1338
+ export function buildReplayWrites(events, plan, baseTurn, rerunId, startSeq, promptCopied) {
1339
+ // Replay EXACTLY the surface nodes the rerun shadowed - never the raw log
1340
+ // range. After earlier reruns the range can contain retired originals (and
1341
+ // retired replacement carriers) that are no longer on the surface; copying
1342
+ // them would resurrect content the conversation no longer has in its context
1343
+ // and grow a duplicate history with every chained rerun. Log-only companions
1344
+ // (turn/step brackets, tool calls) are included only for turns that still
1345
+ // own a shadowed node.
1346
+ const shadowedSet = new Set(plan.shadowed)
1347
+ const editPatches = editPatchesOf(events)
1348
+ const turnOf = turnIndex(events)
1349
+ const shadowedTurns = new Set()
1350
+ for (const seq of plan.shadowed) {
1351
+ const turn = turnOf.get(seq)
1352
+ if (typeof turn === 'number') shadowedTurns.add(turn)
1353
+ }
1354
+ const included = (event) => {
1355
+ if (isSurfaceEvent(event)) return shadowedSet.has(event.seq)
1356
+ if (
1357
+ event.type === 'turn/start' ||
1358
+ event.type === 'turn/end' ||
1359
+ event.type === 'step/start' ||
1360
+ event.type === 'step/end' ||
1361
+ event.type === 'tool/call'
1362
+ ) {
1363
+ return typeof event.data.turn === 'number' && shadowedTurns.has(event.data.turn)
1364
+ }
1365
+ return false
1366
+ }
1367
+ const range = []
1368
+ const bySeq = eventIndex(events)
1369
+ for (let seq = plan.logFrom; seq <= plan.logTo; seq += 1) {
1370
+ const event = bySeq.get(seq)
1371
+ if (event === undefined) continue
1372
+ if (included(event)) range.push(event)
1373
+ }
1374
+ // Tool pairing facts for the whole range, so assistant content can be
1375
+ // corrected before anything is written.
1376
+ const calledIds = new Set()
1377
+ const resultIds = new Set()
1378
+ const repairIds = new Set()
1379
+ for (const event of range) {
1380
+ if (event.type === 'tool/call') calledIds.add(event.data.callId)
1381
+ else if (event.type === 'tool/result') {
1382
+ resultIds.add(event.data.message && event.data.message.source ? event.data.message.source.callId : event.data.callId)
1383
+ const error = event.data.error
1384
+ if (error && error.name === 'ToolNotStartedError' && error.code === 'TOOL_NOT_STARTED' && event.sourceEventSeqs === undefined) {
1385
+ repairIds.add(event.data.message && event.data.message.source ? event.data.message.source.callId : event.data.callId)
1386
+ }
1387
+ }
1388
+ }
1389
+ const healthyIds = new Set()
1390
+ for (const id of calledIds) if (resultIds.has(id)) healthyIds.add(id)
1391
+ for (const id of repairIds) if (!calledIds.has(id)) healthyIds.add(id)
1392
+ const pairedResultIds = new Set()
1393
+ for (const id of calledIds) if (resultIds.has(id)) pairedResultIds.add(id)
1394
+ for (const id of repairIds) if (!calledIds.has(id)) pairedResultIds.add(id)
1395
+
1396
+ const writes = []
1397
+ let predicted = startSeq
1398
+ let nextTurn = baseTurn
1399
+ const turnMap = new Map()
1400
+ const assistantSeqById = new Map()
1401
+ let lastAssistantSeq = null
1402
+ const seqOf = () => {
1403
+ const seq = predicted
1404
+ predicted += 1
1405
+ return seq
1406
+ }
1407
+ for (const event of range) {
1408
+ const data = event.data || {}
1409
+ if (event.type === 'turn/start') {
1410
+ turnMap.set(data.turn, nextTurn)
1411
+ writes.push({ type: 'turn/start', data: { turn: nextTurn } })
1412
+ seqOf()
1413
+ continue
1414
+ }
1415
+ if (event.type === 'turn/end') {
1416
+ writes.push({ type: 'turn/end', data: { turn: turnMap.get(data.turn), reason: data.reason } })
1417
+ seqOf()
1418
+ nextTurn += 1
1419
+ continue
1420
+ }
1421
+ if (event.type === 'step/start' || event.type === 'step/end') {
1422
+ writes.push({ type: event.type, data: { turn: turnMap.get(data.turn), step: data.step } })
1423
+ seqOf()
1424
+ continue
1425
+ }
1426
+ if (event.type === 'user/message') {
1427
+ if (event.seq === plan.promptSeq && promptCopied !== true) continue
1428
+ // This plugin's own carriers are bookkeeping, not conversation: a later
1429
+ // rerun's window can contain one (it stands where a retired prompt was),
1430
+ // and copying it would resurrect an empty user node whose content no
1431
+ // adapter ever sends. Retire it without a copy - the same treatment
1432
+ // legacy system carriers already get by type.
1433
+ if (isRerunCarrier(event)) continue
1434
+ writes.push({
1435
+ type: 'user/message',
1436
+ surfaceOp: 'append',
1437
+ data: {
1438
+ id: randomUUID(),
1439
+ role: 'user',
1440
+ content: data.content,
1441
+ source: replaySource(data.source, rerunId, event.seq),
1442
+ },
1443
+ })
1444
+ seqOf()
1445
+ continue
1446
+ }
1447
+ if (event.type === 'assistant/message') {
1448
+ const message = data.message || {}
1449
+ const source = { ...(message.source || {}) }
1450
+ delete source.replayState
1451
+ const content = applyEditPatches(message.content, editPatches.get(event.seq))
1452
+ .filter((block) => !(block && block.type === 'tool-call' && !healthyIds.has(block.id)))
1453
+ writes.push({
1454
+ type: 'assistant/message',
1455
+ surfaceOp: 'append',
1456
+ data: {
1457
+ turn: turnMap.get(data.turn),
1458
+ step: data.step,
1459
+ message: {
1460
+ id: randomUUID(),
1461
+ role: 'assistant',
1462
+ content,
1463
+ source: replaySource(source, rerunId, event.seq),
1464
+ },
1465
+ stream: [],
1466
+ ...(data.interrupted === true ? { interrupted: true } : {}),
1467
+ },
1468
+ })
1469
+ assistantSeqById.set(event.seq, predicted)
1470
+ lastAssistantSeq = predicted
1471
+ seqOf()
1472
+ continue
1473
+ }
1474
+ if (event.type === 'tool/call') {
1475
+ if (!pairedResultIds.has(data.callId)) continue
1476
+ writes.push({
1477
+ type: 'tool/call',
1478
+ data: { turn: turnMap.get(data.turn), step: data.step, callId: data.callId, name: data.name, arguments: data.arguments },
1479
+ })
1480
+ seqOf()
1481
+ continue
1482
+ }
1483
+ if (event.type === 'tool/result') {
1484
+ const callId = data.message && data.message.source ? data.message.source.callId : data.callId
1485
+ if (!pairedResultIds.has(callId)) continue
1486
+ const message = data.message
1487
+ const source = replaySource(message && message.source, rerunId, event.seq)
1488
+ // The TOOL_NOT_STARTED repair is accepted only without sourceEventSeqs;
1489
+ // ordinary results remap theirs onto the copied assistant message.
1490
+ let sourceEventSeqs
1491
+ if (!repairIds.has(callId)) {
1492
+ const remapped = Array.isArray(event.sourceEventSeqs)
1493
+ ? event.sourceEventSeqs.map((seq) => assistantSeqById.get(seq)).filter((seq) => typeof seq === 'number')
1494
+ : []
1495
+ if (remapped.length > 0) sourceEventSeqs = remapped
1496
+ else if (typeof lastAssistantSeq === 'number') sourceEventSeqs = [lastAssistantSeq]
1497
+ }
1498
+ const originalMessage = message || {}
1499
+ const rest = { ...originalMessage }
1500
+ delete rest.id
1501
+ delete rest.content
1502
+ delete rest.source
1503
+ // The interrupted-repair carrier must keep its contract-shaped id
1504
+ // (`interrupted-tool-result-<callId>-<n>`): the validator refuses a
1505
+ // repair whose id does not match, and a random id breaks it. The suffix
1506
+ // is the copy's own predicted seq, so the identity stays self-describing.
1507
+ const messageId = repairIds.has(callId) ? `interrupted-tool-result-${callId}-${predicted}` : randomUUID()
1508
+ writes.push({
1509
+ type: 'tool/result',
1510
+ surfaceOp: 'append',
1511
+ ...(sourceEventSeqs === undefined ? {} : { sourceEventSeqs }),
1512
+ data: {
1513
+ turn: turnMap.get(data.turn),
1514
+ step: data.step,
1515
+ message: {
1516
+ // The message shape travels verbatim (v4's first-class tool role
1517
+ // keeps its `toolCallId` and bare content blocks); only the id and
1518
+ // the source attribution are ours.
1519
+ ...rest,
1520
+ id: messageId,
1521
+ content: originalMessage.content ?? [],
1522
+ source,
1523
+ },
1524
+ ...(data.error === undefined ? {} : { error: data.error }),
1525
+ ...(data.meta === undefined ? {} : { meta: data.meta }),
1526
+ },
1527
+ })
1528
+ seqOf()
1529
+ continue
1530
+ }
1531
+ // system/message and every log-only record are skipped on purpose.
1532
+ }
1533
+ return writes
1534
+ }
1535
+
1536
+ /**
1537
+ * The first live reply of `turn` that can itself be rerun, or null.
1538
+ *
1539
+ * This is the predicate the advertisement uses for a reply, factored out so
1540
+ * `planRerun` can ask the identical question when it decides whether a prompt may
1541
+ * be addressed. Advertising and planning must not drift apart: an entry offered
1542
+ * for a turn whose reply is rerunnable would otherwise be refused on click.
1543
+ *
1544
+ * @param context - `{ bySeq, nodeIndex, brackets, revisions, head }` as prepared by the caller.
1545
+ * @param events - complete contiguous raw event log.
1546
+ * @param turn - the turn whose reply is asked about.
1547
+ * @returns the assistant event, or null when the turn has none that can be rerun.
1548
+ */
1549
+ function rerunnableReplyOf(context, events, turn) {
1550
+ const { bySeq, nodeIndex, brackets, revisions, head } = context
1551
+ for (const event of events) {
1552
+ if (event.type !== 'assistant/message') continue
1553
+ if (!nodeIndex.has(event.seq)) continue
1554
+ if (event.seq === head) continue
1555
+ if (context.turnOf.get(event.seq) !== turn) continue
1556
+ if (resolveRerunPrompt(bySeq, nodeIndex, brackets, revisions, head, turn, event.seq).reason !== null) continue
1557
+ return event
1558
+ }
1559
+ return null
1560
+ }
1561
+
1562
+ /**
1563
+ * Every model reply that can currently be rerun.
1564
+ * @param events - complete contiguous raw event log.
1565
+ * @param surfaceNodes - current surface seqs in model order.
1566
+ * @returns one entry per live reply, in conversation order.
1567
+ */
1568
+ export function rerunnableReplies(events, surfaceNodes) {
1569
+ const nodeIndex = new Map(surfaceNodes.map((seq, index) => [seq, index]))
1570
+ const turnOf = turnIndex(events)
1571
+ const brackets = turnSpans(events)
1572
+ const revisions = replacementChains(events)
1573
+ const bySeq = eventIndex(events)
1574
+ const head = surfaceNodes[0]
1575
+ const out = []
1576
+ for (const event of events) {
1577
+ if (event.type !== 'assistant/message') continue
1578
+ if (!nodeIndex.has(event.seq)) continue
1579
+ if (event.seq === head) continue
1580
+ const turn = turnOf.get(event.seq)
1581
+ // Advertised here means plannable there: this is the SAME resolution
1582
+ // `planRerun` runs, so a reply whose prompt is gone - or whose prompt's
1583
+ // replacement chain lands on a non-user node such as dsh-delete-turn's
1584
+ // carrier - is left out instead of being offered as a button that can only
1585
+ // answer "this reply cannot be rerun".
1586
+ if (typeof turn !== 'number') continue
1587
+ // Advertised means "this turn has an O": a message whose blocks carry
1588
+ // nothing readable is not model output, so it is not a turn a rerun can be
1589
+ // addressed at (the plugin's own silent carrier is the case that reaches
1590
+ // here; the chain rule below also refuses it as a prompt).
1591
+ if (!hasReadableContent(event.data && event.data.message ? event.data.message.content : null)) continue
1592
+ if (resolveRerunPrompt(bySeq, nodeIndex, brackets, revisions, head, turn, event.seq).reason !== null) continue
1593
+ out.push({
1594
+ seq: event.seq,
1595
+ turn,
1596
+ messageId: messageIdOf(event) ?? null,
1597
+ })
1598
+ }
1599
+ // A turn whose reply never finalized has no answer to replace, but it still has
1600
+ // something worth restarting: its prompt. Addressing the prompt re-sends it, which
1601
+ // is what "run this again" means when there is no reply. It is also the only way
1602
+ // such a turn gets a button at all - the browser half finds a row's target by its
1603
+ // turn number, so a turn missing from this list offers nothing on the prompt row
1604
+ // and nothing on the answer strip. Only turns with no reply of their own are added,
1605
+ // so an existing row's target never moves, and the same resolveRerunPrompt decides
1606
+ // both sides (the 0.1.24 invariant: advertised means plannable).
1607
+ const addressed = new Set(out.map((entry) => entry.turn))
1608
+ for (const event of events) {
1609
+ if (event.type !== 'user/message') continue
1610
+ if (!nodeIndex.has(event.seq)) continue
1611
+ if (event.seq === head) continue
1612
+ const turn = turnOf.get(event.seq)
1613
+ if (typeof turn !== 'number' || addressed.has(turn)) continue
1614
+ const resolved = resolveRerunPrompt(bySeq, nodeIndex, brackets, revisions, head, turn, event.seq)
1615
+ if (resolved.reason !== null) continue
1616
+ // Only the turn's own live prompt addresses its turn; a shadowed copy does not.
1617
+ if (resolved.promptSeq !== event.seq) continue
1618
+ addressed.add(turn)
1619
+ out.push({ seq: event.seq, turn, messageId: null })
1620
+ }
1621
+ return out
1622
+ }
1623
+
1624
+ // ---------------------------------------------------------------------------
1625
+ // host service plumbing
1626
+ // ---------------------------------------------------------------------------
1627
+
1628
+ class HttpError extends Error {
1629
+ constructor(status, code, message) {
1630
+ super(message)
1631
+ this.name = 'HttpError'
1632
+ this.status = status
1633
+ this.code = code
1634
+ }
1635
+ }
1636
+
1637
+ // A session id travels in two spellings: the raw uuid and `session-<uuid>`.
1638
+ function idVariants(sessionId) {
1639
+ const out = new Set([sessionId])
1640
+ if (sessionId.startsWith('session-')) out.add(sessionId.slice('session-'.length))
1641
+ else out.add(`session-${sessionId}`)
1642
+ return [...out]
1643
+ }
1644
+
1645
+ function findLiveSession(ctx, sessionId) {
1646
+ const sessions = ctx.get('sessions')
1647
+ if (!sessions || typeof sessions.get !== 'function') return undefined
1648
+ for (const variant of idVariants(sessionId)) {
1649
+ const found = sessions.get(variant)
1650
+ if (found) return found
1651
+ }
1652
+ return undefined
1653
+ }
1654
+
1655
+ // Resolve the live Agent (and its Session) through the official controller -
1656
+ // the same path the web UI uses, which resumes a cold session on the way.
1657
+ // Always returns `{ agent?, session }`: `agent` is present only when the
1658
+ // controller resolved one (the loop object exposes `whenIdle` and the idle
1659
+ // turn counter the replay syncs); a bare live session is the fallback.
1660
+ async function resolveAgent(ctx, sessionId) {
1661
+ const controller = ctx.get('sessionController')
1662
+ if (controller && typeof controller.resolveAgent === 'function') {
1663
+ try {
1664
+ const result = await controller.resolveAgent(sessionId)
1665
+ if (result && result.agent && result.agent.session) return { agent: result.agent, session: result.agent.session }
1666
+ } catch {
1667
+ // fall through to the live-store lookup
1668
+ }
1669
+ }
1670
+ const live = findLiveSession(ctx, sessionId)
1671
+ if (live) return { session: live }
1672
+ return undefined
1673
+ }
1674
+
1675
+ function eventsFromLive(session) {
1676
+ if (session && typeof session.snapshotEvents === 'function') {
1677
+ try {
1678
+ const events = session.snapshotEvents()
1679
+ if (Array.isArray(events)) return events
1680
+ } catch {
1681
+ // fall through to the query service
1682
+ }
1683
+ }
1684
+ return undefined
1685
+ }
1686
+
1687
+ // Live-preferred read through the public query service; the live session's own
1688
+ // snapshot is the fallback when the service is absent.
1689
+ async function readEvents(ctx, sessionId) {
1690
+ const query = ctx.get('sessionQuery')
1691
+ if (query && typeof query.readSession === 'function') {
1692
+ try {
1693
+ const snapshot = await query.readSession(sessionId)
1694
+ if (snapshot && Array.isArray(snapshot.events)) return snapshot.events
1695
+ } catch {
1696
+ // fall through to the live snapshot
1697
+ }
1698
+ }
1699
+ const live = findLiveSession(ctx, sessionId)
1700
+ return eventsFromLive(live) ?? null
1701
+ }
1702
+
1703
+ function surfaceOf(ctx, sessionId, events) {
1704
+ const live = findLiveSession(ctx, sessionId)
1705
+ const nodes = live && live.surface && Array.isArray(live.surface.nodes) ? live.surface.nodes : undefined
1706
+ return nodes ?? foldSurface(events).nodes
1707
+ }
1708
+
1709
+ // The append is committed in memory the moment `session.append` returns; the
1710
+ // persistence writer buffers asynchronously. Await the official durability
1711
+ // checkpoint so a reload or a DSH restart still sees the write.
1712
+ async function flushSession(ctx, session) {
1713
+ const errors = []
1714
+ const sessions = ctx.get('sessions')
1715
+ if (sessions && typeof sessions.flush === 'function') {
1716
+ try {
1717
+ await Promise.race([sessions.flush(session), new Promise((resolve) => setTimeout(resolve, FLUSH_DEADLINE_MS))])
1718
+ return { flushed: true }
1719
+ } catch (error) {
1720
+ errors.push(String((error && error.message) || error))
1721
+ }
1722
+ } else {
1723
+ errors.push('sessions.flush unavailable')
1724
+ }
1725
+ const persistence = ctx.get('sessionPersistence')
1726
+ if (persistence && typeof persistence.flush === 'function') {
1727
+ try {
1728
+ await Promise.race([persistence.flush(), new Promise((resolve) => setTimeout(resolve, FLUSH_DEADLINE_MS))])
1729
+ return { flushed: true }
1730
+ } catch (error) {
1731
+ errors.push(String((error && error.message) || error))
1732
+ }
1733
+ } else {
1734
+ errors.push('sessionPersistence.flush unavailable')
1735
+ }
1736
+ return { flushed: false, flushError: errors.join(' | ') }
1737
+ }
1738
+
1739
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
1740
+
1741
+ /**
1742
+ * Re-point the agent loop's idle turn counter at the log's true last turn.
1743
+ *
1744
+ * Why this exists: the replay (and any external writer of completed turns,
1745
+ * including the sibling edit plugin's corrections) appends `turn/start`
1746
+ * events the loop did not open. The loop's next turn is `phase.lastTurn + 1`
1747
+ * from its own process-local counter, initialized from the `turnBoundary`
1748
+ * projection only when the agent ATTACHES - an already-attached idle loop
1749
+ * never re-reads it. So without this sync the loop's next real prompt reuses
1750
+ * a turn number the replay already consumed, and the log fails its cold read
1751
+ * ("turn/start does not open the expected turn"). DSH exposes no official
1752
+ * re-sync API; this is the one place the plugin touches loop state, guarded
1753
+ * and best-effort: an unexpected shape changes nothing and is reported.
1754
+ *
1755
+ * @param agent - the live agent from `sessionController.resolveAgent`.
1756
+ * @param maxTurn - the highest turn number the log now contains.
1757
+ * @returns 'synced' | 'already-current' | 'unavailable'.
1758
+ */
1759
+ export function syncLoopTurn(agent, maxTurn) {
1760
+ try {
1761
+ const phase = agent && agent.phase
1762
+ if (!phase || typeof phase !== 'object' || typeof phase.lastTurn !== 'number' || phase.kind !== 'idle') {
1763
+ return 'unavailable'
1764
+ }
1765
+ if (maxTurn > phase.lastTurn) {
1766
+ phase.lastTurn = maxTurn
1767
+ return 'synced'
1768
+ }
1769
+ return 'already-current'
1770
+ } catch {
1771
+ return 'unavailable'
1772
+ }
1773
+ }
1774
+
1775
+ // ---------------------------------------------------------------------------
1776
+ // rerun tasks
1777
+ // ---------------------------------------------------------------------------
1778
+
1779
+ /** One in-flight operation per session; every route checks it first. */
1780
+ const locks = new Map()
1781
+
1782
+ function lock(sessionId) {
1783
+ if (locks.has(sessionId)) return false
1784
+ locks.set(sessionId, { startedAt: Date.now() })
1785
+ return true
1786
+ }
1787
+
1788
+ function unlock(sessionId) {
1789
+ locks.delete(sessionId)
1790
+ }
1791
+
1792
+ function locked(sessionId) {
1793
+ return locks.has(sessionId)
1794
+ }
1795
+
1796
+ /**
1797
+ * The last auto-resume attempt per rerun, for the no-progress gate: a replay
1798
+ * that leaves the same missing set behind must not be re-appended on every
1799
+ * poll.
1800
+ */
1801
+ const resumeAttempts = new Map()
1802
+
1803
+ /** Live rerun progress for /state, keyed by session id. */
1804
+ const progress = new Map()
1805
+
1806
+ /**
1807
+ * The next progress record for one session.
1808
+ *
1809
+ * `progress` describes the CURRENT phase, so a phase change replaces the
1810
+ * record instead of merging into it. Merging let one phase's `error` /
1811
+ * `promptError` survive every later phase - including `done` - so `/state`
1812
+ * kept reporting an interruption the rerun had already recovered from, and
1813
+ * the browser notice built from it could never go away.
1814
+ *
1815
+ * @param current - the stored record (may be empty).
1816
+ * @param patch - the fields being set now; a `phase` starts a new record.
1817
+ * @returns the record to store.
1818
+ */
1819
+ export function progressAfter(current, patch) {
1820
+ const base = patch !== null && typeof patch === 'object' && patch.phase !== undefined ? {} : current || {}
1821
+ const next = { ...base, ...patch }
1822
+ if (next.phase === undefined) delete next.phase
1823
+ return next
1824
+ }
1825
+
1826
+ function setProgress(sessionId, patch) {
1827
+ const next = progressAfter(progress.get(sessionId) || {}, patch)
1828
+ progress.set(sessionId, next)
1829
+ return next
1830
+ }
1831
+
1832
+ /**
1833
+ * Append one write to the live session, expecting a specific seq.
1834
+ * @returns the landed event, or throws when the log moved under us.
1835
+ */
1836
+ function appendWrite(session, write, expectedSeq) {
1837
+ if (typeof expectedSeq === 'number' && session.seq !== expectedSeq) {
1838
+ throw new HttpError(409, 'stale', `the log moved: expected seq ${expectedSeq}, found ${session.seq}`)
1839
+ }
1840
+ const opts = write.surfaceOp === undefined ? [] : [{ surfaceOp: write.surfaceOp, ...(write.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: write.sourceEventSeqs }) }]
1841
+ return session.append(write.type, write.data, ...opts)
1842
+ }
1843
+
1844
+ /**
1845
+ * Whether the regenerated prompt (its rpcId) is still sitting unclaimed in the
1846
+ * agent inbox - replaying before it is claimed would put the copies before the
1847
+ * fresh answer.
1848
+ */
1849
+ function inboxHoldsPrompt(agent, promptRequestId) {
1850
+ const inbox = agent && agent.inbox
1851
+ if (!inbox || !Array.isArray(inbox.nextTurn) || promptRequestId === null) return false
1852
+ return inbox.nextTurn.some((message) => {
1853
+ const source = message && message.source
1854
+ return Boolean(source && source.kind === 'user' && source.rpcId === promptRequestId)
1855
+ })
1856
+ }
1857
+
1858
+ /**
1859
+ * Whether the regenerated prompt landed on the surface: either the loop
1860
+ * claimed it (the rpcId event exists) or an earlier replay copied it.
1861
+ */
1862
+ function promptLandedIn(events, record) {
1863
+ const promptRequestId = record.promptRequestId
1864
+ const markerCopied = events.some((event) => {
1865
+ if (event.seq <= record.carrierSeq) return false
1866
+ const marker = replayMarkerOf(event)
1867
+ return marker !== null && marker.rerunId === record.rerunId && marker.originalSeq === record.promptSeq
1868
+ })
1869
+ if (markerCopied) return true
1870
+ if (promptRequestId === null) return false
1871
+ return events.some((event) => {
1872
+ if (event.seq <= record.carrierSeq || event.type !== 'user/message') return false
1873
+ const source = event.data && event.data.source
1874
+ return Boolean(source && source.kind === 'user' && source.rpcId === promptRequestId)
1875
+ })
1876
+ }
1877
+
1878
+ /**
1879
+ * How many leading bracket writes a crashed replay already landed.
1880
+ *
1881
+ * A replay dies only between two appends, so a partial write is a prefix of
1882
+ * the plan sitting at the tail of the log. The largest tail that structurally
1883
+ * matches a plan prefix is skipped on resume - the format requires turn
1884
+ * numbers contiguous, and a duplicated `turn/start` would make the whole log
1885
+ * unreadable. Marker-bearing surface writes are never absorbed: their presence
1886
+ * is tracked separately through `originalSeq`.
1887
+ *
1888
+ * @param events - complete contiguous raw event log.
1889
+ * @param writes - the replay plan (ordered writes).
1890
+ * @param cap - how many trailing events may be considered.
1891
+ * @returns the number of leading writes already on the log tail.
1892
+ */
1893
+ export function matchReplayPrefix(events, writes, cap) {
1894
+ const limit = Math.min(writes.length, typeof cap === 'number' && cap >= 0 ? cap : 0)
1895
+ for (let k = limit; k >= 1; k -= 1) {
1896
+ let match = true
1897
+ for (let j = 0; j < k; j += 1) {
1898
+ const write = writes[j]
1899
+ const landed = events[events.length - k + j]
1900
+ if (!landed || landed.type !== write.type || isSurfaceEvent(write)) {
1901
+ match = false
1902
+ break
1903
+ }
1904
+ if (write.type === 'turn/start' && landed.data.turn !== write.data.turn) { match = false; break }
1905
+ if ((write.type === 'step/start' || write.type === 'step/end') && (landed.data.turn !== write.data.turn || landed.data.step !== write.data.step)) { match = false; break }
1906
+ if (write.type === 'turn/end' && landed.data.turn !== write.data.turn) { match = false; break }
1907
+ if (write.type === 'tool/call' && landed.data.callId !== write.data.callId) { match = false; break }
1908
+ }
1909
+ if (match) return k
1910
+ }
1911
+ return 0
1912
+ }
1913
+
1914
+ /**
1915
+ * The replay phase, shared by the fresh-rerun task and the resume path.
1916
+ *
1917
+ * Waits for a quiet tail - no open turn, no queued rerun prompt - because the
1918
+ * copies must land directly after the fresh answer for the spliced order to
1919
+ * hold, then appends the missing suffix. When the tail never quiets, the rerun
1920
+ * stays incomplete and `/state`'s resume path picks it up later.
1921
+ * @returns `{ replayed, deferred, error? }`.
1922
+ */
1923
+ async function performReplay(ctx, sessionId, rerunId, config) {
1924
+ const resolution = await resolveAgent(ctx, sessionId)
1925
+ const session = resolution && (resolution.session ?? resolution.agent?.session)
1926
+ if (!session || typeof session.append !== 'function') {
1927
+ return { replayed: 0, deferred: true, error: 'session-not-active' }
1928
+ }
1929
+ let deferLeft = REPLAY_DEFER_MAX
1930
+ while (true) {
1931
+ const events = eventsFromLive(session) ?? (await readEvents(ctx, sessionId))
1932
+ if (!events) return { replayed: 0, deferred: true, error: 'session-not-found' }
1933
+ const ledger = rerunLedger(events)
1934
+ const record = ledger.reruns.find((entry) => entry.rerunId === rerunId)
1935
+ if (!record) return { replayed: 0, deferred: true, error: 'rerun-not-found' }
1936
+ if (record.complete) return { replayed: 0, deferred: false }
1937
+ const open = openTurn(events)
1938
+ if (isBusy(events) && !(open !== null && replayOrphanOpen(events, rerunId))) {
1939
+ // A real turn in flight or a compaction. Our own crash-orphan - an open
1940
+ // turn of pure brackets and marked copies - is continued below instead:
1941
+ // leaving it open would refuse the session's next real turn on read.
1942
+ if (deferLeft-- <= 0) return { replayed: 0, deferred: true, error: 'busy' }
1943
+ await sleep(REPLAY_DEFER_MS)
1944
+ continue
1945
+ }
1946
+ if (inboxHoldsPrompt(resolution && resolution.agent, record.promptRequestId)) {
1947
+ // The regenerated prompt is admitted but not claimed yet; the copies
1948
+ // must not overtake it.
1949
+ if (deferLeft-- <= 0) return { replayed: 0, deferred: true, error: 'prompt-pending' }
1950
+ await sleep(REPLAY_DEFER_MS)
1951
+ continue
1952
+ }
1953
+ const promptLanded = promptLandedIn(events, record)
1954
+ // Resume point: the suffix after the last original event that already has
1955
+ // a copy. Bracket events written just before a crash carry no marker, so
1956
+ // leading writes that already exist verbatim at the tail are skipped.
1957
+ let lastCopied = record.carrierSeq
1958
+ for (const event of events) {
1959
+ if (event.seq <= record.carrierSeq) continue
1960
+ const marker = replayMarkerOf(event)
1961
+ if (marker !== null && marker.rerunId === rerunId && marker.originalSeq !== null && marker.originalSeq > lastCopied) {
1962
+ lastCopied = marker.originalSeq
1963
+ }
1964
+ }
1965
+ // Continue an orphan open turn at its own number; otherwise open the next.
1966
+ const baseTurn = open !== null && replayOrphanOpen(events, rerunId) ? open : lastTurnOf(events) + 1
1967
+ // Normal path: the walk starts at the next turn's bracket (the rerun
1968
+ // turn's own reply is replaced, not replayed). Fallback - the prompt never
1969
+ // landed - the walk starts at the rerun turn's own bracket, so the copies
1970
+ // reproduce the whole window and the context keeps its content.
1971
+ const fallbackFrom = record.logFrom ?? record.promptSeq ?? record.startSeq
1972
+ const walkFrom = promptLanded ? record.replayFrom ?? fallbackFrom : fallbackFrom
1973
+ if (walkFrom === null || walkFrom > (record.logTo ?? record.endSeq)) {
1974
+ return { replayed: 0, deferred: false }
1975
+ }
1976
+ const plan = {
1977
+ logFrom: walkFrom,
1978
+ logTo: record.logTo ?? record.endSeq,
1979
+ promptSeq: record.promptSeq ?? record.startSeq,
1980
+ // The replay copies exactly these surface nodes (and nothing the log
1981
+ // happens to hold between them), so the shadowed list must travel.
1982
+ shadowed: record.shadowed,
1983
+ }
1984
+ const startSeq = session.seq
1985
+ const writes = buildReplayWrites(events, plan, baseTurn, rerunId, startSeq, !promptLanded)
1986
+ // The cap is a COUNT of events that follow the carrier, not an array
1987
+ // distance: the same number when the list is dense, and still right when the
1988
+ // list inherits its head.
1989
+ const skip = matchReplayPrefix(events, writes, events.filter((event) => typeof event.seq === 'number' && event.seq > record.carrierSeq).length)
1990
+ let replayed = 0
1991
+ try {
1992
+ for (let index = skip; index < writes.length; index += 1) {
1993
+ appendWrite(session, writes[index], startSeq + index)
1994
+ replayed += 1
1995
+ }
1996
+ } catch (error) {
1997
+ await flushSession(ctx, session)
1998
+ const message = String((error && error.message) || error)
1999
+ setProgress(sessionId, { phase: 'interrupted', rerunId, error: message })
2000
+ noteRequest({ kind: 'replay', sessionId, ok: false, rerunId, error: message })
2001
+ return { replayed, deferred: true, error: message }
2002
+ }
2003
+ // The log now holds completed turns the loop never opened; re-point its
2004
+ // idle counter SYNCHRONOUSLY (same tick as the appends, before any await)
2005
+ // so its next prompt opens the correct number instead of colliding.
2006
+ const playedMax = writes.reduce((max, write) => {
2007
+ const turn = write.data && typeof write.data.turn === 'number' ? write.data.turn : 0
2008
+ return turn > max ? turn : max
2009
+ }, 0)
2010
+ const sync = syncLoopTurn(resolution && resolution.agent, playedMax)
2011
+ if (sync === 'unavailable' && playedMax > lastTurnOf(events)) {
2012
+ noteRequest({ kind: 'replay', sessionId, ok: false, rerunId, error: `loop turn counter not synced (${playedMax}); a later prompt may reuse a turn number` })
2013
+ }
2014
+ await flushSession(ctx, session)
2015
+ noteRequest({ kind: 'replay', sessionId, ok: true, rerunId, replayed, skipped: skip, sync })
2016
+ return { replayed, deferred: false }
2017
+ }
2018
+ }
2019
+
2020
+ /**
2021
+ * The background task behind one rerun: regenerate, then replay the tail.
2022
+ * Never throws - every outcome lands in `progress` for /state to report.
2023
+ * `afterSeq` is the log seq of the shadow's last write; the fallback poll
2024
+ * waits for a turn/end beyond it.
2025
+ */
2026
+ async function runRerunTask(ctx, sessionId, resolution, plan, rerunId, promptRequestId, afterSeq, config) {
2027
+ const session = resolution.session
2028
+ try {
2029
+ setProgress(sessionId, { phase: 'generating', rerunId })
2030
+ let promptError = null
2031
+ let promptAccepted = false
2032
+ const controller = ctx.get('sessionController')
2033
+ if (!controller || typeof controller.prompt !== 'function') {
2034
+ promptError = 'sessionController.prompt unavailable'
2035
+ } else {
2036
+ const content = []
2037
+ if (plan.prompt.text.trim() !== '') content.push({ type: 'text', text: plan.prompt.text })
2038
+ for (const ref of plan.prompt.images) {
2039
+ try {
2040
+ const attachments = ctx.get('attachments')
2041
+ const stored = await attachments.readImage(ref)
2042
+ content.push({
2043
+ type: 'image',
2044
+ mediaType: ref.mediaType,
2045
+ data: Buffer.from(stored.data).toString('base64'),
2046
+ ...(ref.name === undefined ? {} : { name: ref.name }),
2047
+ })
2048
+ } catch (error) {
2049
+ promptError = `could not re-admit an image attachment: ${String((error && error.message) || error)}`
2050
+ break
2051
+ }
2052
+ }
2053
+ if (promptError === null && content.length > 0) {
2054
+ try {
2055
+ await controller.prompt(
2056
+ { requestId: promptRequestId, sessionId, mode: 'queue', content },
2057
+ AbortSignal.timeout(PROMPT_DEADLINE_MS),
2058
+ )
2059
+ promptAccepted = true
2060
+ } catch (error) {
2061
+ promptError = String((error && error.message) || error)
2062
+ }
2063
+ } else if (content.length === 0 && promptError === null) {
2064
+ promptError = 'the turn prompt has no re-sendable content'
2065
+ }
2066
+ }
2067
+ setProgress(sessionId, { phase: promptAccepted ? 'waiting' : 'replaying', rerunId, ...(promptError === null ? {} : { promptError }) })
2068
+ if (promptAccepted) {
2069
+ // Wait for the regenerated turn to close: `whenIdle` is the precise
2070
+ // signal, and the log poll - which only settles once a turn/end lands
2071
+ // after the shadow - is the fallback for an agent object without one.
2072
+ const deadline = Date.now() + (config.idleTimeoutMs > 0 ? config.idleTimeoutMs : DEFAULT_IDLE_TIMEOUT_MS)
2073
+ const agent = resolution.agent
2074
+ const idle = agent && typeof agent.whenIdle === 'function' ? agent.whenIdle().catch(() => {}) : new Promise(() => {})
2075
+ const timeout = (async () => {
2076
+ while (Date.now() < deadline) {
2077
+ const events = eventsFromLive(session)
2078
+ if (events && afterSeq >= 0 && openTurn(events) === null && events.some((event) => event.type === 'turn/end' && event.seq > afterSeq)) return
2079
+ await sleep(700)
2080
+ }
2081
+ })()
2082
+ await Promise.race([idle, timeout])
2083
+ const events = eventsFromLive(session)
2084
+ const settled =
2085
+ events !== undefined &&
2086
+ afterSeq >= 0 &&
2087
+ openTurn(events) === null &&
2088
+ events.some((event) => event.type === 'turn/end' && event.seq > afterSeq)
2089
+ if (!settled && Date.now() >= deadline) {
2090
+ setProgress(sessionId, { phase: 'interrupted', rerunId, error: 'the regenerated turn did not settle in time; replay deferred' })
2091
+ return
2092
+ }
2093
+ }
2094
+ const result = await performReplay(ctx, sessionId, rerunId, config)
2095
+ if (result.deferred) {
2096
+ setProgress(sessionId, {
2097
+ phase: 'interrupted',
2098
+ rerunId,
2099
+ ...(result.error === undefined ? {} : { error: `replay deferred: ${result.error}; /state will resume it` }),
2100
+ })
2101
+ } else {
2102
+ setProgress(sessionId, { phase: 'done', rerunId, replayed: result.replayed })
2103
+ }
2104
+ } catch (error) {
2105
+ setProgress(sessionId, { phase: 'failed', rerunId, error: String((error && error.message) || error) })
2106
+ noteRequest({ kind: 'rerun', sessionId, ok: false, rerunId, error: String((error && error.message) || error) })
2107
+ } finally {
2108
+ unlock(sessionId)
2109
+ }
2110
+ }
2111
+
2112
+ /**
2113
+ * Resume one interrupted rerun's replay: no regeneration, just the copies.
2114
+ */
2115
+ async function runReplayTask(ctx, sessionId, rerunId, config) {
2116
+ try {
2117
+ setProgress(sessionId, { phase: 'replaying', ...(rerunId === null ? {} : { rerunId }) })
2118
+ const result = await performReplay(ctx, sessionId, rerunId, config)
2119
+ if (result.deferred) {
2120
+ setProgress(sessionId, { phase: 'interrupted', ...(rerunId === null ? {} : { rerunId }), ...(result.error === undefined ? {} : { error: `replay deferred: ${result.error}` }) })
2121
+ } else {
2122
+ setProgress(sessionId, { phase: 'done', ...(rerunId === null ? {} : { rerunId }), replayed: result.replayed })
2123
+ }
2124
+ } catch (error) {
2125
+ setProgress(sessionId, { phase: 'failed', ...(rerunId === null ? {} : { rerunId }), error: String((error && error.message) || error) })
2126
+ } finally {
2127
+ unlock(sessionId)
2128
+ }
2129
+ }
2130
+
2131
+ // ---------------------------------------------------------------------------
2132
+ // operations
2133
+ // ---------------------------------------------------------------------------
2134
+
2135
+ /**
2136
+ * The state of a session that has no log (yet).
2137
+ *
2138
+ * A named session with nothing written to it is a normal, empty session, not an
2139
+ * error: the panel loads, shows "nothing to rerun", and the next refresh picks
2140
+ * the log up as soon as it exists. Answering 404 here is what turned a legal
2141
+ * session into "状态加载失败,稍后重试。".
2142
+ *
2143
+ * @param config - the resolved plugin config.
2144
+ * @returns the same shape {@link stateOf} returns for a real session.
2145
+ */
2146
+ function emptyState(config) {
2147
+ return {
2148
+ hidden: [],
2149
+ markerTurns: [],
2150
+ retiredTurns: [],
2151
+ reruns: [],
2152
+ replies: [],
2153
+ live: false,
2154
+ busy: false,
2155
+ rerunning: false,
2156
+ progress: null,
2157
+ lastSeq: -1,
2158
+ config: { confirm: config.confirm, autoResume: config.autoResume === true },
2159
+ version: PLUGIN_VERSION,
2160
+ }
2161
+ }
2162
+
2163
+ async function stateOf(ctx, sessionId, config) {
2164
+ const events = await readEvents(ctx, sessionId)
2165
+ if (!events) {
2166
+ // Honest in the diagnostics ledger, empty - not failed - to the panel.
2167
+ noteRequest({ kind: 'state', sessionId, ok: true, code: 'session-empty' })
2168
+ return emptyState(config)
2169
+ }
2170
+ const folded = foldSurface(events)
2171
+ const ledger = rerunLedger(events)
2172
+ const live = findLiveSession(ctx, sessionId)
2173
+ const replies = rerunnableReplies(events, folded.nodes)
2174
+ const busy = isBusy(events)
2175
+ const rerunning = locked(sessionId)
2176
+ const current = progress.get(sessionId) || null
2177
+ noteRequest({
2178
+ kind: 'state',
2179
+ sessionId,
2180
+ ok: true,
2181
+ events: events.length,
2182
+ replies: replies.length,
2183
+ hidden: ledger.hidden.length,
2184
+ reruns: ledger.reruns.length,
2185
+ incomplete: ledger.reruns.filter((entry) => !entry.complete).length,
2186
+ live: Boolean(live),
2187
+ rerunning,
2188
+ })
2189
+ // Auto-resume: a rerun whose replay never finished (a crash mid-generation,
2190
+ // a tail that never quieted) is completed from the log alone - no model call.
2191
+ // The gate exempts this plugin's own crash-orphan (an open turn of pure
2192
+ // brackets and marked copies): the resume is what closes it.
2193
+ if (config.autoResume === true && live && !rerunning && ledger.reruns.some((entry) => !entry.complete)) {
2194
+ const incomplete = ledger.reruns.find((entry) => !entry.complete)
2195
+ const orphanOpen = openTurn(events) !== null && replayOrphanOpen(events, incomplete.rerunId)
2196
+ // A replay that leaves the same missing set behind made no progress; the
2197
+ // next poll must not append it again (that is how a log grows hundreds of
2198
+ // duplicate turns in a minute). A changed set - shorter, or longer because
2199
+ // the tail moved - is progress and retries at once.
2200
+ const signature = incomplete.missing.join(',')
2201
+ const attempt = resumeAttempts.get(incomplete.rerunId)
2202
+ const stalled = attempt !== undefined && attempt.signature === signature && Date.now() - attempt.at < RESUME_STALL_MS
2203
+ if ((!isBusy(events) || orphanOpen) && !stalled && lock(sessionId)) {
2204
+ resumeAttempts.set(incomplete.rerunId, { signature, at: Date.now() })
2205
+ runReplayTask(ctx, sessionId, incomplete.rerunId, config)
2206
+ } else if (stalled) {
2207
+ noteRequest({ kind: 'resume-stalled', sessionId, ok: true, rerunId: incomplete.rerunId, missing: incomplete.missing })
2208
+ }
2209
+ }
2210
+ return {
2211
+ hidden: ledger.hidden,
2212
+ // Bookkeeping turns are UI noise, never conversation; the client hides
2213
+ // their rows by turn number.
2214
+ markerTurns: ledger.reruns.map((entry) => entry.carrierTurn).filter((turn) => typeof turn === 'number'),
2215
+ // Turns whose content is fully retired: their process/tail strips would
2216
+ // otherwise linger as empty "用时" debris.
2217
+ retiredTurns: retiredTurnList(events, folded, ledger, {
2218
+ inFlightId: rerunning === true && current !== null && typeof current.rerunId === 'string' ? current.rerunId : null,
2219
+ }),
2220
+ reruns: ledger.reruns,
2221
+ replies,
2222
+ live: Boolean(live),
2223
+ busy,
2224
+ rerunning,
2225
+ progress: current,
2226
+ lastSeq: events.length > 0 ? events[events.length - 1].seq : -1,
2227
+ config: { confirm: config.confirm, autoResume: config.autoResume === true },
2228
+ version: PLUGIN_VERSION,
2229
+ }
2230
+ }
2231
+
2232
+ async function applyRerun(ctx, sessionId, body, config) {
2233
+ if (locked(sessionId)) throw new HttpError(409, 'rerunning', 'a rerun is already in flight')
2234
+ const resolution = await resolveAgent(ctx, sessionId)
2235
+ const session = resolution && (resolution.session ?? (resolution.agent && resolution.agent.session))
2236
+ if (!session || typeof session.append !== 'function') {
2237
+ throw new HttpError(409, 'session-not-active', 'the session is not open in DSH')
2238
+ }
2239
+ const events = await readEvents(ctx, sessionId)
2240
+ if (!events) throw new HttpError(404, 'session-not-found', 'no session log for this id')
2241
+ if (isBusy(events)) throw new HttpError(409, 'busy', 'the session is still working')
2242
+ const surfaceNodes = surfaceOf(ctx, sessionId, events)
2243
+ let plan
2244
+ try {
2245
+ plan = planRerun(events, surfaceNodes, {
2246
+ seq: typeof body.seq === 'number' ? body.seq : undefined,
2247
+ messageId: typeof body.messageId === 'string' ? body.messageId : undefined,
2248
+ })
2249
+ } catch (error) {
2250
+ if (error instanceof RerunPlanError) {
2251
+ const status = error.code === 'already-retired' ? 409 : 400
2252
+ throw new HttpError(status, error.code, error.message)
2253
+ }
2254
+ throw error
2255
+ }
2256
+ // The live surface is the append authority; a node that vanished between the
2257
+ // read and this check means another writer landed first.
2258
+ for (const seq of plan.shadowed) {
2259
+ if (!surfaceNodes.includes(seq)) throw new HttpError(409, 'stale', 'the session changed, retry')
2260
+ }
2261
+ if (!lock(sessionId)) throw new HttpError(409, 'rerunning', 'a rerun is already in flight')
2262
+ const rerunId = randomUUID()
2263
+ const promptRequestId = randomUUID()
2264
+ let afterSeq = -1
2265
+ try {
2266
+ // One write, no turn bracket: the carrier is a turn-free text-free
2267
+ // user/message replacement, so the log's turn numbering is untouched and the
2268
+ // loop's own counter stays authoritative for the regenerated turn. A carrier
2269
+ // that opened a turn would add a turn number with no content (the empty
2270
+ // "completed" strip and the trajectory numbering hole) and would have to be
2271
+ // synced into the loop's process-local counter by hand. Its content shape
2272
+ // follows the adapter that serves THIS session (empty where it drops an
2273
+ // empty user message, one zero-width space otherwise) - see
2274
+ // buildShadowWrites; a session whose provider is not the proven adapter
2275
+ // still gets the safe carrier.
2276
+ const shadowWrites = buildShadowWrites(plan, rerunId, promptRequestId, dropsEmptyUserContentFor(ctx, events))
2277
+ for (const write of shadowWrites) {
2278
+ appendWrite(session, write, session.seq)
2279
+ afterSeq = session.seq - 1
2280
+ }
2281
+ } catch (error) {
2282
+ unlock(sessionId)
2283
+ throw new HttpError(409, 'stale', `the surface refused the shadow: ${String((error && error.message) || error)}`)
2284
+ }
2285
+ const flush = await flushSession(ctx, session)
2286
+ setProgress(sessionId, { phase: 'generating', rerunId })
2287
+ // The regeneration and the replay run in the background; /apply returns as
2288
+ // soon as the shadow is durable so the client can retire the old rows.
2289
+ runRerunTask(ctx, sessionId, resolution, plan, rerunId, promptRequestId, afterSeq, config)
2290
+ return {
2291
+ started: true,
2292
+ rerunId,
2293
+ carrierSeq: plan.startSeq,
2294
+ shadowed: plan.shadowed,
2295
+ turn: plan.turn,
2296
+ promptSeq: plan.promptSeq,
2297
+ ...flush,
2298
+ }
2299
+ }
2300
+
2301
+ async function replayRoute(ctx, sessionId, body, config) {
2302
+ if (locked(sessionId)) throw new HttpError(409, 'rerunning', 'a rerun is already in flight')
2303
+ const live = findLiveSession(ctx, sessionId)
2304
+ if (!live) throw new HttpError(409, 'session-not-active', 'the session is not open in DSH')
2305
+ const events = await readEvents(ctx, sessionId)
2306
+ if (!events) throw new HttpError(404, 'session-not-found', 'no session log for this id')
2307
+ const ledger = rerunLedger(events)
2308
+ const rerunId = typeof body.rerunId === 'string' && body.rerunId !== '' ? body.rerunId : null
2309
+ const incomplete = rerunId === null ? ledger.reruns.find((entry) => !entry.complete) : ledger.reruns.find((entry) => entry.rerunId === rerunId && !entry.complete)
2310
+ // The busy gate exempts this plugin's own crash-orphan: the replay is what
2311
+ // closes it.
2312
+ const orphanOpen = incomplete !== undefined && openTurn(events) !== null && replayOrphanOpen(events, incomplete.rerunId)
2313
+ if (isBusy(events) && !orphanOpen) throw new HttpError(409, 'busy', 'the session is still working')
2314
+ if (!incomplete) {
2315
+ if (rerunId !== null && ledger.reruns.some((entry) => entry.rerunId === rerunId)) {
2316
+ return { started: false, complete: true }
2317
+ }
2318
+ throw new HttpError(404, 'rerun-not-found', 'no incomplete rerun for this id')
2319
+ }
2320
+ if (!lock(sessionId)) throw new HttpError(409, 'rerunning', 'a rerun is already in flight')
2321
+ setProgress(sessionId, { phase: 'replaying', rerunId: incomplete.rerunId })
2322
+ runReplayTask(ctx, sessionId, incomplete.rerunId, config)
2323
+ return { started: true, rerunId: incomplete.rerunId }
2324
+ }
2325
+
2326
+ // ---------------------------------------------------------------------------
2327
+ // http
2328
+ // ---------------------------------------------------------------------------
2329
+
2330
+ function isLoopbackAddress(address) {
2331
+ if (typeof address !== 'string' || address.length === 0) return false
2332
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
2333
+ }
2334
+
2335
+ function isLocalHostHeader(host) {
2336
+ if (typeof host !== 'string' || host.length === 0) return false
2337
+ const trimmed = host.trim().toLowerCase()
2338
+ if (trimmed.startsWith('[')) {
2339
+ const end = trimmed.indexOf(']')
2340
+ if (end === -1) return false
2341
+ const rest = trimmed.slice(end + 1)
2342
+ if (rest !== '' && !/^:[0-9]+$/.test(rest)) return false
2343
+ return trimmed.slice(1, end) === '::1'
2344
+ }
2345
+ const match = /^([^:]*)(?::([0-9]+))?$/.exec(trimmed)
2346
+ if (match === null) return false
2347
+ return match[1] === 'localhost' || match[1] === '127.0.0.1' || match[1] === '::1'
2348
+ }
2349
+
2350
+ function sendJson(res, status, body) {
2351
+ const payload = JSON.stringify(body)
2352
+ res.writeHead(status, {
2353
+ 'content-type': 'application/json; charset=utf-8',
2354
+ 'content-length': Buffer.byteLength(payload),
2355
+ })
2356
+ res.end(payload)
2357
+ }
2358
+
2359
+ function readBody(req) {
2360
+ return new Promise((resolve, reject) => {
2361
+ let data = ''
2362
+ req.on('data', (chunk) => {
2363
+ data += chunk
2364
+ if (data.length > 1e6) req.destroy()
2365
+ })
2366
+ req.on('end', () => resolve(data))
2367
+ req.on('error', reject)
2368
+ req.on('aborted', () => reject(new Error('aborted')))
2369
+ })
2370
+ }
2371
+
2372
+ // Rewriting the derived context is destructive for the model, so every route
2373
+ // demands a loopback socket, a loopback Host header, and a same-origin check
2374
+ // when the browser sends Origin.
2375
+ function guard(req, res) {
2376
+ if (!isLoopbackAddress(req.socket && req.socket.remoteAddress)) {
2377
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'loopback only' })
2378
+ return false
2379
+ }
2380
+ const host = req.headers.host
2381
+ if (!isLocalHostHeader(host)) {
2382
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'unexpected host' })
2383
+ return false
2384
+ }
2385
+ const origin = req.headers.origin
2386
+ if (typeof origin === 'string' && origin.length > 0) {
2387
+ let originHost = null
2388
+ try {
2389
+ originHost = new URL(origin).host
2390
+ } catch {
2391
+ originHost = null
2392
+ }
2393
+ if (originHost !== host) {
2394
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'cross-origin request' })
2395
+ return false
2396
+ }
2397
+ }
2398
+ return true
2399
+ }
2400
+
2401
+ function sessionIdFromQuery(url) {
2402
+ try {
2403
+ return (new URL(url, 'http://localhost').searchParams.get('sessionId') || '').trim()
2404
+ } catch {
2405
+ return ''
2406
+ }
2407
+ }
2408
+
2409
+ function requireSessionId(value) {
2410
+ if (!value) throw new HttpError(400, 'invalid', 'sessionId required')
2411
+ if (!SESSION_ID_RE.test(value)) throw new HttpError(400, 'invalid', 'invalid session id')
2412
+ return value
2413
+ }
2414
+
2415
+ function failure(res, error) {
2416
+ const status = error instanceof HttpError ? error.status : 500
2417
+ const code = error instanceof HttpError ? error.code : 'internal'
2418
+ if (!(error instanceof HttpError)) console.error('[dsh-rerun-turn] internal error', error)
2419
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2420
+ }
2421
+
2422
+ // ---------------------------------------------------------------------------
2423
+ // dev tools (config.devTools; used by end-to-end verification)
2424
+ // ---------------------------------------------------------------------------
2425
+
2426
+ /** Compact text of one derived message, for the dev transcript route. */
2427
+ function messageTextOf(message) {
2428
+ if (!message || !Array.isArray(message.content)) return ''
2429
+ const parts = []
2430
+ for (const block of message.content) {
2431
+ if (block && block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
2432
+ else if (block && block.type === 'tool-call') parts.push(`<tool-call ${block.name}>`)
2433
+ }
2434
+ return parts.join('\n')
2435
+ }
2436
+
2437
+ /**
2438
+ * Wait until a fresh session has closed `count` turns.
2439
+ * @returns the events, or null on timeout.
2440
+ */
2441
+ async function waitForTurns(ctx, sessionId, count, timeoutMs) {
2442
+ const deadline = Date.now() + timeoutMs
2443
+ while (Date.now() < deadline) {
2444
+ const live = findLiveSession(ctx, sessionId)
2445
+ const events = live ? eventsFromLive(live) : await readEvents(ctx, sessionId)
2446
+ if (events) {
2447
+ let closed = 0
2448
+ for (const event of events) if (event.type === 'turn/end') closed += 1
2449
+ if (closed >= count && openTurn(events) === null) return events
2450
+ }
2451
+ await sleep(500)
2452
+ }
2453
+ return null
2454
+ }
2455
+
2456
+ /**
2457
+ * Create a throwaway session and drive `turns` short model turns in it.
2458
+ * Every turn asks for a unique token, so a replayed copy can be told apart
2459
+ * from a regenerated answer in the derived context.
2460
+ */
2461
+ async function devScratch(ctx, turns, cwd) {
2462
+ const controller = ctx.get('sessionController')
2463
+ if (!controller || typeof controller.create !== 'function' || typeof controller.prompt !== 'function') {
2464
+ throw new HttpError(503, 'dev-unavailable', 'sessionController is not available')
2465
+ }
2466
+ const count = Math.max(1, Math.min(6, typeof turns === 'number' ? Math.floor(turns) : 3))
2467
+ const sessionId = `session-${randomUUID()}`
2468
+ const created = await controller.create({ sessionId, cwd })
2469
+ const tokens = []
2470
+ for (let turn = 1; turn <= count; turn += 1) {
2471
+ const token = `TOKEN-${turn}-${randomUUID().slice(0, 8)}`
2472
+ tokens.push(token)
2473
+ await controller.prompt(
2474
+ {
2475
+ requestId: randomUUID(),
2476
+ sessionId,
2477
+ mode: 'queue',
2478
+ content: [{ type: 'text', text: `Reply with exactly this text and nothing else: ${token}` }],
2479
+ },
2480
+ AbortSignal.timeout(PROMPT_DEADLINE_MS),
2481
+ )
2482
+ const settled = await waitForTurns(ctx, sessionId, turn, 5 * 60_000)
2483
+ if (!settled) throw new HttpError(504, 'dev-timeout', `turn ${turn} did not settle`)
2484
+ }
2485
+ return { sessionId: created && created.sessionId ? created.sessionId : sessionId, turns: count, tokens }
2486
+ }
2487
+
2488
+ /** Send one prompt into a live session and wait for its turn to close. */
2489
+ async function devPrompt(ctx, sessionId, text) {
2490
+ const controller = ctx.get('sessionController')
2491
+ if (!controller || typeof controller.prompt !== 'function') {
2492
+ throw new HttpError(503, 'dev-unavailable', 'sessionController is not available')
2493
+ }
2494
+ await controller.prompt(
2495
+ {
2496
+ requestId: randomUUID(),
2497
+ sessionId,
2498
+ mode: 'queue',
2499
+ content: [{ type: 'text', text: typeof text === 'string' && text !== '' ? text : 'ping' }],
2500
+ },
2501
+ AbortSignal.timeout(PROMPT_DEADLINE_MS),
2502
+ )
2503
+ const live = findLiveSession(ctx, sessionId)
2504
+ const before = live ? eventsFromLive(live) : await readEvents(ctx, sessionId)
2505
+ const closed = before ? before.filter((event) => event.type === 'turn/end').length : 0
2506
+ const settled = await waitForTurns(ctx, sessionId, closed + 1, 5 * 60_000)
2507
+ if (!settled) throw new HttpError(504, 'dev-timeout', 'the prompt did not settle')
2508
+ return { sessionId, turns: closed + 1 }
2509
+ }
2510
+
2511
+ /** The live derived context of one session - exactly what the next request sends. */
2512
+ async function devDerived(ctx, sessionId) {
2513
+ const resolution = await resolveAgent(ctx, sessionId)
2514
+ const session = resolution && (resolution.session ?? resolution.agent?.session)
2515
+ if (!session) throw new HttpError(404, 'session-not-found', 'no live session for this id')
2516
+ let messages
2517
+ if (typeof session.deriveMessages === 'function') {
2518
+ messages = session.deriveMessages()
2519
+ } else {
2520
+ const events = await readEvents(ctx, sessionId)
2521
+ if (!events) throw new HttpError(404, 'session-not-found', 'no session log for this id')
2522
+ const folded = foldSurface(events)
2523
+ const bySeq = new Map(events.map((event) => [event.seq, event]))
2524
+ messages = []
2525
+ for (const seq of folded.nodes) {
2526
+ const event = bySeq.get(seq)
2527
+ if (!event) continue
2528
+ const message = event.type === 'user/message' ? event.data : event.data && event.data.message
2529
+ if (!message) continue
2530
+ if (Array.isArray(message.content) && message.content.length === 0) continue
2531
+ messages.push(message)
2532
+ }
2533
+ }
2534
+ const derived = messages
2535
+ // What the next request really sends. `deriveMessages()` still carries an
2536
+ // empty user message (this plugin's silent replacement carrier) and an empty
2537
+ // developer message. An empty USER message only leaves the wire where the
2538
+ // installed adapter is proven to drop it (dsh-llm-deepseek natively, pi-ai
2539
+ // under `dsh-delete-turn:skip-empty-user`); on a host without that proof the
2540
+ // carrier is one zero-width space instead - that message IS what the adapter
2541
+ // sends, so it stays in this report rather than being explained away.
2542
+ .filter(
2543
+ (message) =>
2544
+ !(
2545
+ Array.isArray(message.content) &&
2546
+ message.content.length === 0 &&
2547
+ (message.role === 'developer' || (message.role === 'user' && ADAPTER_DROPS_EMPTY_USER_CONTENT))
2548
+ ),
2549
+ )
2550
+ .map((message) => ({
2551
+ role: message.role,
2552
+ text: messageTextOf(message),
2553
+ id: message.id,
2554
+ }))
2555
+ .filter((entry) => entry.text !== '' || entry.role !== 'developer')
2556
+ // The replay markers, so a verification can tell copies from fresh output.
2557
+ const events = (session && eventsFromLive(session)) ?? (await readEvents(ctx, sessionId)) ?? []
2558
+ const copies = events
2559
+ .map((event) => {
2560
+ const marker = replayMarkerOf(event)
2561
+ return marker === null ? null : { seq: event.seq, ...marker }
2562
+ })
2563
+ .filter(Boolean)
2564
+ return {
2565
+ sessionId,
2566
+ derived,
2567
+ copies,
2568
+ // Which carrier shape this host writes, so a live check can tell "no blank
2569
+ // message reaches the model" from "the fallback carrier is the one blank
2570
+ // message on the wire".
2571
+ carrier: {
2572
+ shape: ADAPTER_DROPS_EMPTY_USER_CONTENT ? 'empty' : 'zero-width-space',
2573
+ adapterDropsEmptyUserContent: ADAPTER_DROPS_EMPTY_USER_CONTENT,
2574
+ },
2575
+ }
2576
+ }
2577
+
2578
+ // ---------------------------------------------------------------------------
2579
+ // plugin
2580
+ // ---------------------------------------------------------------------------
2581
+
2582
+ export function apply(ctx, config) {
2583
+ const resolved = {
2584
+ confirm: config && config.confirm === true,
2585
+ autoResume: !(config && config.autoResume === false),
2586
+ idleTimeoutMs:
2587
+ config && typeof config.idleTimeoutMs === 'number' && config.idleTimeoutMs > 0 ? config.idleTimeoutMs : DEFAULT_IDLE_TIMEOUT_MS,
2588
+ devTools: config && config.devTools === true,
2589
+ }
2590
+
2591
+ const registerRoutes = (webServer, fiber) => {
2592
+ fiber.effect(() =>
2593
+ webServer.register({
2594
+ kind: 'exact',
2595
+ path: `${ROUTE_PREFIX}/state`,
2596
+ handler: async (req, res) => {
2597
+ if (!guard(req, res)) return
2598
+ if (req.method !== 'GET') {
2599
+ sendJson(res, 405, { ok: false, code: 'method', error: 'GET only' })
2600
+ return
2601
+ }
2602
+ try {
2603
+ const sessionId = requireSessionId(sessionIdFromQuery(req.url))
2604
+ sendJson(res, 200, { ok: true, ...(await stateOf(ctx, sessionId, resolved)) })
2605
+ } catch (error) {
2606
+ failure(res, error)
2607
+ }
2608
+ },
2609
+ }),
2610
+ )
2611
+
2612
+ // Read-only diagnostics. The browser half's own state cannot be observed
2613
+ // from here, so the next best thing is an honest record of what its
2614
+ // requests asked for and what they got back.
2615
+ fiber.effect(() =>
2616
+ webServer.register({
2617
+ kind: 'exact',
2618
+ path: `${ROUTE_PREFIX}/debug`,
2619
+ handler: (req, res) => {
2620
+ if (!guard(req, res)) return
2621
+ if (req.method !== 'GET') {
2622
+ sendJson(res, 405, { ok: false, code: 'method', error: 'GET only' })
2623
+ return
2624
+ }
2625
+ sendJson(res, 200, { ok: true, version: PLUGIN_VERSION, requests: recentRequests() })
2626
+ },
2627
+ }),
2628
+ )
2629
+
2630
+ fiber.effect(() =>
2631
+ webServer.register({
2632
+ kind: 'exact',
2633
+ path: `${ROUTE_PREFIX}/apply`,
2634
+ handler: async (req, res) => {
2635
+ if (!guard(req, res)) return
2636
+ if (req.method !== 'POST') {
2637
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2638
+ return
2639
+ }
2640
+ let body = {}
2641
+ try {
2642
+ const raw = await readBody(req)
2643
+ if (raw) body = JSON.parse(raw)
2644
+ } catch {
2645
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2646
+ return
2647
+ }
2648
+ try {
2649
+ const sessionId = requireSessionId(typeof body.sessionId === 'string' ? body.sessionId.trim() : '')
2650
+ const result = await applyRerun(ctx, sessionId, body, resolved)
2651
+ noteRequest({
2652
+ kind: 'apply',
2653
+ sessionId,
2654
+ ok: true,
2655
+ rerunId: result.rerunId,
2656
+ seq: typeof body.seq === 'number' ? body.seq : null,
2657
+ shadowed: Array.isArray(result.shadowed) ? result.shadowed.length : null,
2658
+ })
2659
+ sendJson(res, 200, { ok: true, ...result })
2660
+ } catch (error) {
2661
+ noteRequest({
2662
+ kind: 'apply',
2663
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId.trim() : null,
2664
+ ok: false,
2665
+ code: error && error.code ? String(error.code) : 'internal',
2666
+ })
2667
+ failure(res, error)
2668
+ }
2669
+ },
2670
+ }),
2671
+ )
2672
+
2673
+ fiber.effect(() =>
2674
+ webServer.register({
2675
+ kind: 'exact',
2676
+ path: `${ROUTE_PREFIX}/replay`,
2677
+ handler: async (req, res) => {
2678
+ if (!guard(req, res)) return
2679
+ if (req.method !== 'POST') {
2680
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2681
+ return
2682
+ }
2683
+ let body = {}
2684
+ try {
2685
+ const raw = await readBody(req)
2686
+ if (raw) body = JSON.parse(raw)
2687
+ } catch {
2688
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2689
+ return
2690
+ }
2691
+ try {
2692
+ const sessionId = requireSessionId(typeof body.sessionId === 'string' ? body.sessionId.trim() : '')
2693
+ sendJson(res, 200, { ok: true, ...(await replayRoute(ctx, sessionId, body, resolved)) })
2694
+ } catch (error) {
2695
+ failure(res, error)
2696
+ }
2697
+ },
2698
+ }),
2699
+ )
2700
+
2701
+ if (resolved.devTools === true) {
2702
+ fiber.effect(() =>
2703
+ webServer.register({
2704
+ kind: 'exact',
2705
+ path: `${ROUTE_PREFIX}/dev/scratch`,
2706
+ handler: async (req, res) => {
2707
+ if (!guard(req, res)) return
2708
+ if (req.method !== 'POST') {
2709
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2710
+ return
2711
+ }
2712
+ let body = {}
2713
+ try {
2714
+ const raw = await readBody(req)
2715
+ if (raw) body = JSON.parse(raw)
2716
+ } catch {
2717
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2718
+ return
2719
+ }
2720
+ try {
2721
+ const cwd = typeof body.cwd === 'string' && body.cwd !== '' ? body.cwd : process.cwd()
2722
+ sendJson(res, 200, { ok: true, ...(await devScratch(ctx, body.turns, cwd)) })
2723
+ } catch (error) {
2724
+ failure(res, error)
2725
+ }
2726
+ },
2727
+ }),
2728
+ )
2729
+ fiber.effect(() =>
2730
+ webServer.register({
2731
+ kind: 'exact',
2732
+ path: `${ROUTE_PREFIX}/dev/prompt`,
2733
+ handler: async (req, res) => {
2734
+ if (!guard(req, res)) return
2735
+ if (req.method !== 'POST') {
2736
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2737
+ return
2738
+ }
2739
+ let body = {}
2740
+ try {
2741
+ const raw = await readBody(req)
2742
+ if (raw) body = JSON.parse(raw)
2743
+ } catch {
2744
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2745
+ return
2746
+ }
2747
+ try {
2748
+ const sessionId = requireSessionId(typeof body.sessionId === 'string' ? body.sessionId.trim() : '')
2749
+ sendJson(res, 200, { ok: true, ...(await devPrompt(ctx, sessionId, body.text)) })
2750
+ } catch (error) {
2751
+ failure(res, error)
2752
+ }
2753
+ },
2754
+ }),
2755
+ )
2756
+ fiber.effect(() =>
2757
+ webServer.register({
2758
+ kind: 'exact',
2759
+ path: `${ROUTE_PREFIX}/dev/derived`,
2760
+ handler: async (req, res) => {
2761
+ if (!guard(req, res)) return
2762
+ if (req.method !== 'GET') {
2763
+ sendJson(res, 405, { ok: false, code: 'method', error: 'GET only' })
2764
+ return
2765
+ }
2766
+ try {
2767
+ const sessionId = requireSessionId(sessionIdFromQuery(req.url))
2768
+ sendJson(res, 200, { ok: true, ...(await devDerived(ctx, sessionId)) })
2769
+ } catch (error) {
2770
+ failure(res, error)
2771
+ }
2772
+ },
2773
+ }),
2774
+ )
2775
+ }
2776
+ }
2777
+
2778
+ const webServer = ctx.get('webServer')
2779
+ if (webServer) {
2780
+ registerRoutes(webServer, ctx)
2781
+ } else {
2782
+ ctx.inject(['webServer'], (sub) => registerRoutes(sub.webServer, sub))
2783
+ }
2784
+ }