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,2813 @@
1
+ // dsh-edit-turn host half (dsh-edit-turn.js), VENDORED by tools/vendor.mjs - DO NOT EDIT.
2
+ //
3
+ // Source: ../dsh-edit-turn/lib/index.js (v0.5.4, sha256 9efbde9d50f56073)
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-edit-turn - host half.
9
+ //
10
+ // Two loopback-only JSON routes:
11
+ //
12
+ // GET /dsh-edit-turn/state?sessionId=<id>
13
+ // POST /dsh-edit-turn/apply { sessionId, seq|messageId|turn, text }
14
+ //
15
+ // An edit is two official operations, in order:
16
+ //
17
+ // 1. ROLLBACK - append ONE surface event whose `surfaceOp` is
18
+ // `{ op: 'replace', startSeq, endSeq }` over the inclusive surface window
19
+ // "the addressed user message .. the last surface node". The official fold
20
+ // swaps that whole window for the replacing event, so every event recorded
21
+ // after the edit point leaves the derived model context while the
22
+ // append-only log keeps every original byte ("Committed events are never
23
+ // rewritten"). The window always ends at the last surface node, so an
24
+ // assistant message (which carries its own tool_use blocks) and the
25
+ // tool/result it produced are always shadowed together: no call/result
26
+ // pair can be left dangling.
27
+ //
28
+ //
29
+ // A revised PROMPT carries the message itself: the carrier's content is the
30
+ // user's block list after the edit, rebuilt block by block. A block the user
31
+ // did not touch is copied out of the original message verbatim - same object,
32
+ // same fields, same attachment reference - a block the user added is admitted
33
+ // through the platform's attachment store (`ctx.get('attachments')`, the seam
34
+ // dsh-acp uses) and a block the user removed is simply not written. The revised
35
+ // text lands where the original's first text block was, so the layout survives
36
+ // the edit. Nothing in that path names a block shape: the only test in the
37
+ // module is "does this block carry text", which is the editor's own field, so a
38
+ // block type the platform adds later needs no change here.
39
+ //
40
+ // The silent replacement carrier is an EMPTY `developer/message` (0.2.12;
41
+ // before that an empty `system/message`, which no reader accepts - see the
42
+ // README). Empty content projects to no model message, so the rollback adds
43
+ // nothing the model can see and the derived context after an edit is exactly
44
+ // what it would be had the conversation really stopped at the edit point.
45
+ // `sourceEventSeqs` must list the complete shadowed node set, which
46
+ // is why an `assistant/message` carrier is impossible (it forbids
47
+ // `sourceEventSeqs` outright).
48
+ //
49
+ // The module resolves `@deepseek-ai/schemastery` defensively. `dsh-tools` is a
50
+ // host-provided peer (the loader resolves it for every plugin), but the schema
51
+ // package is a regular dependency: when it cannot be resolved - a pruned
52
+ // package cache, an installation that skipped dependencies - a static import
53
+ // takes the whole plugin down and the feature simply disappears from the UI
54
+ // with nothing but a line on the host's stdout to explain it. A guarded require
55
+ // degrades to "no config form, defaults apply" instead, which costs a settings
56
+ // surface rather than the feature. Every field is optional in `apply` anyway.
57
+ import { randomUUID } from 'node:crypto'
58
+ import { readFile } from 'node:fs/promises'
59
+ import { createRequire } from 'node:module'
60
+ import { dshTools } from './_platform.js'
61
+ import { dshSession as sessionApi } from './_platform.js'
62
+ import {
63
+ PATCH_TYPE,
64
+ buildPatchData,
65
+ editableBlocks,
66
+ kindOfBlock,
67
+ patchList,
68
+ patchProjection,
69
+ patchesOf,
70
+ projectedBlocks,
71
+ } from './dsh-edit-turn.patch.js'
72
+
73
+ const { defineTool } = dshTools
74
+
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-edit-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.5.4'
94
+
95
+ // A ring of the last few requests, answering "did the browser half even ask, and
96
+ // what did it get?" without needing its console. Read-only diagnostics: the
97
+ // browser half's own state is otherwise invisible from the host side.
98
+ const REQUEST_LOG_LIMIT = 40
99
+ const requestLog = []
100
+
101
+ /** Record one request for the diagnostic route. */
102
+ export function noteRequest(entry) {
103
+ requestLog.push({ at: Date.now(), ...entry })
104
+ if (requestLog.length > REQUEST_LOG_LIMIT) requestLog.shift()
105
+ }
106
+
107
+ /** The recorded requests, oldest first. */
108
+ export function recentRequests() {
109
+ return requestLog.slice()
110
+ }
111
+
112
+ const ROUTE_PREFIX = '/dsh-edit-turn'
113
+ // A session id is an OPAQUE string to DSH: the host's own schema is
114
+ // `z.string().min(1)`, and a named session created in the GUI (`bili-whale`,
115
+ // stored as ~/.dsh/storages/<profile>/sessions/bili-whale.json) is exactly as
116
+ // real as a UUID one. A UUID-only test rejected those with a 400, so the panel
117
+ // answered "状态加载失败" for a session that plainly exists. The character class
118
+ // still refuses everything that could leave a path or a URL: `/`, `\`, `..`
119
+ // (the first character must be alphanumeric, so a leading dot is already out),
120
+ // whitespace and control characters.
121
+ const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
122
+ const MAX_TEXT = 200_000
123
+ const FLUSH_DEADLINE_MS = 5_000
124
+
125
+ // A revised block list travels as base64 inside the JSON body, so the body limit
126
+ // IS the upload limit. The platform's own per-image ceiling defaults to 20 MiB
127
+ // (dsh-attachment-local), which base64 carries in ~27 MiB of text; the store
128
+ // enforces its own limit independently, this one only bounds the socket read.
129
+ const MAX_BODY_BYTES = 64 * 1024 * 1024
130
+ const MAX_UPLOAD_BYTES = 20 * 1024 * 1024
131
+ // A preview is a courtesy: above this the chip keeps its label and asks for
132
+ // nothing. Never worth streaming a whole file to draw a thumbnail.
133
+ const MAX_PREVIEW_BYTES = 32 * 1024 * 1024
134
+ // One message cannot carry more blocks than this. The cap exists so a malformed
135
+ // or hostile body cannot make the host loop over an unbounded list.
136
+ const MAX_PARTS = 64
137
+
138
+ /**
139
+ * Service names the durable attachment store is reachable under.
140
+ *
141
+ * `attachments` is the platform's own registration (the `AttachmentStore`
142
+ * base class in @deepseek-ai/dsh-attachment, and every `ctx.get('attachments')`
143
+ * consumer such as dsh-acp); the other two are the package names, accepted so a
144
+ * rename cannot silently cost the feature. Absence is a supported state, never
145
+ * an error: the edit degrades to the text-only rewrite it was before blocks.
146
+ */
147
+ const ATTACHMENT_SERVICES = ['attachments', 'attachment', 'attachment-local']
148
+
149
+ /**
150
+ * Model-visible text of the replacement carrier.
151
+ *
152
+ * A `user/message` carrier always projects into the model context, so the
153
+ * default states the one fact the revised context cannot express on its own:
154
+ * earlier turns were deliberately dropped. Keep it short and factual.
155
+ */
156
+ const DEFAULT_MARKER = '[dsh-edit-turn] The user revised an earlier message. Every turn after that message was rolled back; the revised message follows. Send your reply to the revised message.'
157
+
158
+ /**
159
+ * Deployment policy for the rollback.
160
+ *
161
+ * `undefined` when the schema package could not be resolved - DSH then hands
162
+ * `apply` no config at all, and every field below is read with the same default
163
+ * there, so the plugin behaves identically minus the settings form.
164
+ */
165
+ export const Config =
166
+ z === null
167
+ ? undefined
168
+ : z.object({
169
+ markerText: z.string().default(DEFAULT_MARKER),
170
+ /**
171
+ * Whether the client asks for a second confirmation before applying. Off
172
+ * by default: the editor is already an explicit action the user opened, and
173
+ * the panel states what saving does. Set it to `true` to require the extra
174
+ * step.
175
+ */
176
+ confirm: z.boolean().default(false),
177
+ /**
178
+ * How a reply edit lands. `auto` uses the in-place plugin-record
179
+ * projection when the host exposes it and falls back to the historical
180
+ * replay splice otherwise; `patch` refuses to run without the
181
+ * projection; `replay` always uses the old path. Prompt edits always use
182
+ * the official surface replacement.
183
+ *
184
+ * There is deliberately no `replace` value: appending a fresh
185
+ * `assistant/message` with a replace op is refused by the session's own
186
+ * surface validation (see the note in the README).
187
+ */
188
+ replyMode: z.string().default('auto'),
189
+ /**
190
+ * Which editor presentation the browser half draws. `frame` outlines the
191
+ * whole message row (reference-UI style); `bubble` is exactly the
192
+ * message bubble; `center` is a large centred panel. The setting exists
193
+ * because the best shape is a matter of taste and was hard to pick
194
+ * without trying them side by side.
195
+ */
196
+ editorStyle: z.union([z.const('frame'), z.const('bubble'), z.const('center')]).default('frame'),
197
+ })
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // pure session-log logic (no DSH SDK imports; unit-testable under node --test)
201
+ // ---------------------------------------------------------------------------
202
+
203
+ /** The four event types that may carry `surfaceOp` (official surface contract). */
204
+ const SURFACE_TYPES = new Set([
205
+ 'system/message',
206
+ 'user/message',
207
+ 'assistant/message',
208
+ 'tool/result',
209
+ ])
210
+
211
+ /**
212
+ * Whether one event participates in the model-visible surface.
213
+ * @param event - raw session event.
214
+ * @returns true for a message-producing event type.
215
+ */
216
+ export function isSurfaceEvent(event) {
217
+ const type = event && event.type
218
+ return typeof type === 'string' && SURFACE_TYPES.has(type)
219
+ }
220
+
221
+ /**
222
+ * Replay the surface operations of a complete log.
223
+ *
224
+ * Mirrors the official fold: `append` pushes the event onto the tail; a
225
+ * `replace` swaps the inclusive window between its two surface nodes for the
226
+ * replacing event. Replacements whose anchors are no longer present are skipped
227
+ * defensively - a corrupt log must not throw inside an HTTP handler.
228
+ *
229
+ * @param events - complete contiguous raw event log in seq order.
230
+ * @returns current surface seqs in model order plus every landed replacement.
231
+ */
232
+ export function foldSurface(events) {
233
+ const nodes = []
234
+ const replacements = []
235
+ for (const event of events) {
236
+ const op = event.surfaceOp
237
+ if (op === undefined) continue
238
+ if (op === 'append') {
239
+ nodes.push(event.seq)
240
+ continue
241
+ }
242
+ if (op === null || typeof op !== 'object' || op.op !== 'replace') continue
243
+ const startIdx = nodes.indexOf(op.startSeq)
244
+ const endIdx = nodes.indexOf(op.endSeq)
245
+ if (startIdx === -1 || endIdx === -1 || startIdx > endIdx) continue
246
+ const shadowed = nodes.slice(startIdx, endIdx + 1)
247
+ nodes.splice(startIdx, endIdx - startIdx + 1, event.seq)
248
+ replacements.push({ seq: event.seq, startSeq: op.startSeq, endSeq: op.endSeq, shadowed })
249
+ }
250
+ return { nodes, replacements }
251
+ }
252
+
253
+ /**
254
+ * Map every event seq to the turn that encloses it.
255
+ *
256
+ * Turn brackets are the durable source for user messages (their payload has no
257
+ * turn field); assistant and tool events carry their own turn and override the
258
+ * bracket reading.
259
+ *
260
+ * @param events - complete contiguous raw event log.
261
+ * @returns seq -> turn number (undefined outside any turn).
262
+ */
263
+ export function turnIndex(events) {
264
+ const turnOf = new Map()
265
+ let current
266
+ for (const event of events) {
267
+ if (event.type === 'turn/start') {
268
+ current = event.data && event.data.turn
269
+ turnOf.set(event.seq, current)
270
+ continue
271
+ }
272
+ if (event.type === 'turn/end') {
273
+ turnOf.set(event.seq, current)
274
+ current = undefined
275
+ continue
276
+ }
277
+ const data = event.data
278
+ const explicit =
279
+ (event.type === 'assistant/message' || event.type === 'tool/result' || event.type === 'tool/call') &&
280
+ data &&
281
+ typeof data.turn === 'number'
282
+ ? data.turn
283
+ : undefined
284
+ turnOf.set(event.seq, explicit !== undefined ? explicit : current)
285
+ }
286
+ return turnOf
287
+ }
288
+
289
+ /**
290
+ * One turn bracket: its number, log range, first prompt and reply count.
291
+ *
292
+ * A turn NUMBER is not unique in a log - a replay reuses numbers on fresh
293
+ * brackets - so planning must locate the bracket that CONTAINS an event rather
294
+ * than the first bracket carrying its number (the same rule dsh-rerun-turn
295
+ * learned in 0.1.23; this is the same walk).
296
+ *
297
+ * @param events - complete contiguous raw event log.
298
+ * @returns one entry per `turn/start`, in log order.
299
+ */
300
+ export function turnSpans(events) {
301
+ const spans = []
302
+ let open = null
303
+ for (const event of events) {
304
+ if (event.type === 'turn/start') {
305
+ open = {
306
+ turn: event.data && event.data.turn,
307
+ startSeq: event.seq,
308
+ endSeq: null,
309
+ promptSeq: null,
310
+ replies: 0,
311
+ }
312
+ spans.push(open)
313
+ continue
314
+ }
315
+ if (open === null) continue
316
+ if (event.type === 'turn/end') {
317
+ open.endSeq = event.seq
318
+ open = null
319
+ continue
320
+ }
321
+ if (event.type === 'user/message' && open.promptSeq === null) open.promptSeq = event.seq
322
+ if (event.type === 'assistant/message') open.replies += 1
323
+ }
324
+ return spans
325
+ }
326
+
327
+ /** The turn still awaiting its `turn/end`, or null when every turn closed. */
328
+ export function openTurn(events) {
329
+ let open = null
330
+ for (const event of events) {
331
+ if (event.type === 'turn/start') open = event.data && event.data.turn
332
+ else if (event.type === 'turn/end' && (open === null || event.data.turn === open)) open = null
333
+ }
334
+ return open
335
+ }
336
+
337
+ /** Whether an operation is in flight that will still write the surface. */
338
+ export function isBusy(events) {
339
+ if (openTurn(events) !== null) return true
340
+ let compaction = false
341
+ for (const event of events) {
342
+ if (event.type === 'compaction/start') compaction = true
343
+ else if (event.type === 'compaction/end') compaction = false
344
+ }
345
+ return compaction
346
+ }
347
+
348
+ /**
349
+ * Durable message identity of one surface event.
350
+ * @param event - raw session event.
351
+ * @returns the message id, or undefined for an event without one.
352
+ */
353
+ export function messageIdOf(event) {
354
+ const data = event.data
355
+ if (!data || typeof data !== 'object') return undefined
356
+ if (event.type === 'user/message') return typeof data.id === 'string' ? data.id : undefined
357
+ if (event.type === 'assistant/message' || event.type === 'tool/result' || event.type === 'system/message') {
358
+ const message = data.message
359
+ return message && typeof message.id === 'string' ? message.id : undefined
360
+ }
361
+ return undefined
362
+ }
363
+
364
+ /**
365
+ * Whether one event is a human-authored prompt.
366
+ *
367
+ * Injected context, this plugin's own placeholder and compaction checkpoints
368
+ * are all `user/message` events too; only `source.kind === 'user'` is a prompt
369
+ * the user actually typed, so only those are editable.
370
+ *
371
+ * @param event - raw session event.
372
+ * @returns true for a human prompt.
373
+ */
374
+ export function isEditCarrier(source) {
375
+ if (!source || typeof source !== 'object') return false
376
+ // Current shape. `editedBy` is what identifies a carrier now; the prompt carrier
377
+ // deliberately keeps `kind: 'user'` (see buildCarrier) so the platform still reads
378
+ // it as the human prompt, and the silent reply carrier keeps a producer-owned kind.
379
+ if (source.editedBy === PLUGIN_ID) return true
380
+ // Historical shapes, kept so ledgers and editability stay correct over logs
381
+ // written by earlier releases: the producer-owned kind without `editedBy`, and
382
+ // the session-format v3 `{ kind: 'plugin', plugin }`.
383
+ if (source.kind === `plugin:${PLUGIN_ID}`) return true
384
+ return source.kind === 'plugin' && source.plugin === PLUGIN_ID
385
+ }
386
+
387
+ export function isHumanPrompt(event) {
388
+ if (!event || event.type !== 'user/message') return false
389
+ const data = event.data
390
+ if (!data || !data.source) return false
391
+ // The platform's own test, and the one every consumer applies (`turn-outline`,
392
+ // the Trajectory view, `ui-chat`, the inbox steering filter, `lastPromptAt`): a
393
+ // human prompt is a `user/message` whose source kind is `'user'`. A message this
394
+ // plugin rewrote stands in a human's place and keeps that kind, so it stays
395
+ // editable (edit it again). Matching a plugin-owned kind instead is what made
396
+ // the rewrite invisible to the turn outline - the round lost its prompt.
397
+ if (data.source.kind === 'user') return true
398
+ // Carriers written before that fix carry a producer-owned kind. Same message -
399
+ // a `user/message` this plugin rewrote - so it must stay editable, or upgrading
400
+ // would silently make every earlier edit un-editable.
401
+ return isEditCarrier(data.source)
402
+ }
403
+
404
+ /**
405
+ * Whether an event is a reply the model produced.
406
+ *
407
+ * Editing one of these is a different operation from editing a prompt: the
408
+ * official append contract refuses to let an `assistant/message` carry
409
+ * `sourceEventSeqs` ("assistant/message embeds its source stream"), so a reply
410
+ * can never be the replacement carrier of a rollback. The rollback is therefore
411
+ * followed by appending the corrected text as a new assistant message, and the
412
+ * model goes on seeing it as its own answer.
413
+ *
414
+ * @param event - raw session event.
415
+ * @returns true for an assistant reply.
416
+ */
417
+ export function isAssistantReply(event) {
418
+ return Boolean(event) && event.type === 'assistant/message'
419
+ }
420
+
421
+ /**
422
+ * Whether one content block carries the editable text.
423
+ *
424
+ * This is the module's ONLY block-shape test, and it is deliberately about the
425
+ * field the editor owns rather than about a block class. Every other block - a
426
+ * picture, a file, and whatever type a later platform adds - is carried through
427
+ * an edit untouched unless the user removed it, so no code below ever has to
428
+ * learn a new name.
429
+ *
430
+ * @param block - one content block.
431
+ * @returns true when the block holds text the editor prefills.
432
+ */
433
+ export function isTextBlock(block) {
434
+ return Boolean(block) && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string'
435
+ }
436
+
437
+ /**
438
+ * The content blocks of a message payload, in message order.
439
+ *
440
+ * `user/message` carries its message fields on `data`; the other three surface
441
+ * types nest them under `data.message`, so both shapes read the same way now
442
+ * that the model's replies are editable too.
443
+ *
444
+ * @param event - raw session event.
445
+ * @returns the block array, or an empty one when the message carries none.
446
+ */
447
+ export function readMessageBlocks(event) {
448
+ const data = (event && event.data) || {}
449
+ const message = data.message && typeof data.message === 'object' ? data.message : data
450
+ return Array.isArray(message.content) ? message.content : []
451
+ }
452
+
453
+ /**
454
+ * Read the plain text of a message payload, plus how many non-text parts it
455
+ * carries. The count is what tells a reader that a text-only carrier would drop
456
+ * something, and it stays exactly what it always was.
457
+ * @param event - raw session event.
458
+ * @returns `{ text, attachments }`.
459
+ */
460
+ export function readMessageText(event) {
461
+ let text = ''
462
+ let attachments = 0
463
+ for (const block of readMessageBlocks(event)) {
464
+ if (!block || typeof block !== 'object') continue
465
+ if (isTextBlock(block)) text += (text === '' ? '' : '\n') + block.text
466
+ else attachments += 1
467
+ }
468
+ return { text, attachments }
469
+ }
470
+
471
+ /**
472
+ * The non-text blocks of a message, described for the editor's chips.
473
+ *
474
+ * Read by FIELD PRESENCE, never by type. A block that carries a durable
475
+ * `attachment` reference is described from that reference (name, media type,
476
+ * byte length, pixel size) whatever the platform calls the block; a block
477
+ * without one is described by its own type name alone, which is what a chip can
478
+ * honestly show. This list is for DRAWING and for offering a delete - it never
479
+ * decides what an edit writes, and a block the user keeps is copied verbatim
480
+ * whether or not this function could describe it.
481
+ *
482
+ * @param blocks - the message content, in message order.
483
+ * @param preview - whether the deployment can hand these bytes back for a thumbnail.
484
+ * @returns one entry per non-text block, in message order.
485
+ */
486
+ export function blockSummaries(blocks, preview = false) {
487
+ const out = []
488
+ for (let index = 0; index < blocks.length; index += 1) {
489
+ const block = blocks[index]
490
+ if (!block || typeof block !== 'object' || isTextBlock(block)) continue
491
+ const raw = block.attachment
492
+ const attachment = raw && typeof raw === 'object' ? raw : null
493
+ const summary = {
494
+ index,
495
+ type: typeof block.type === 'string' && block.type !== '' ? block.type : 'block',
496
+ preview: false,
497
+ }
498
+ if (attachment !== null) {
499
+ if (typeof attachment.name === 'string' && attachment.name !== '') summary.name = attachment.name
500
+ if (typeof attachment.mediaType === 'string' && attachment.mediaType !== '') summary.mediaType = attachment.mediaType
501
+ if (typeof attachment.bytes === 'number') summary.bytes = attachment.bytes
502
+ if (typeof attachment.width === 'number') summary.width = attachment.width
503
+ if (typeof attachment.height === 'number') summary.height = attachment.height
504
+ summary.preview = preview && typeof attachment.attachmentId === 'string' && attachment.attachmentId !== ''
505
+ }
506
+ out.push(summary)
507
+ }
508
+ return out
509
+ }
510
+
511
+ /**
512
+ * Whether two JSON values are the same value.
513
+ *
514
+ * Used to answer "did this edit change anything at all": the rebuilt block list
515
+ * is compared against the original one, field by field. Key ORDER is not part
516
+ * of a JSON value - a session reader is free to hand the same object back with
517
+ * its keys in another order - so this walks the keys instead of comparing
518
+ * stringified text.
519
+ *
520
+ * @param a - first JSON value.
521
+ * @param b - second JSON value.
522
+ * @returns true when the two are indistinguishable JSON.
523
+ */
524
+ export function sameJson(a, b) {
525
+ if (a === b) return true
526
+ if (Array.isArray(a) || Array.isArray(b)) {
527
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
528
+ for (let index = 0; index < a.length; index += 1) {
529
+ if (!sameJson(a[index], b[index])) return false
530
+ }
531
+ return true
532
+ }
533
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false
534
+ const keys = Object.keys(a)
535
+ if (keys.length !== Object.keys(b).length) return false
536
+ for (const key of keys) {
537
+ if (!Object.prototype.hasOwnProperty.call(b, key)) return false
538
+ if (!sameJson(a[key], b[key])) return false
539
+ }
540
+ return true
541
+ }
542
+
543
+ /**
544
+ * Normalise one submitted block list.
545
+ *
546
+ * The wire vocabulary is exactly two entries:
547
+ *
548
+ * `{ keep: <index> }` - the original block at that index, untouched;
549
+ * `{ add: { data, mediaType?, name? } }` - bytes the user just picked.
550
+ *
551
+ * Text is never listed: the revised text rides in its own field and the host
552
+ * puts it back where the original's first text block was. A `keep` that names
553
+ * a text block is therefore not an error - it is the text, and the text is
554
+ * already accounted for.
555
+ *
556
+ * @param raw - the submitted `parts` array.
557
+ * @param blockCount - how many blocks the original message carries.
558
+ * @returns `[{ keep } | { add }]` in submitted order.
559
+ * @throws {HttpError} 400 `invalid` for anything this vocabulary does not name.
560
+ */
561
+ export function normalizeParts(raw, blockCount) {
562
+ if (!Array.isArray(raw)) throw new HttpError(400, 'invalid', 'parts must be an array')
563
+ if (raw.length > MAX_PARTS) throw new HttpError(400, 'invalid', `a message cannot carry more than ${MAX_PARTS} blocks`)
564
+ const parts = []
565
+ for (const entry of raw) {
566
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
567
+ throw new HttpError(400, 'invalid', 'every part must be an object')
568
+ }
569
+ if (entry.keep !== undefined) {
570
+ const index = entry.keep
571
+ if (!Number.isInteger(index) || index < 0 || index >= blockCount) {
572
+ throw new HttpError(400, 'invalid', 'a kept block index is out of range')
573
+ }
574
+ if (parts.some((part) => part.keep === index)) throw new HttpError(400, 'invalid', 'a block was kept twice')
575
+ parts.push({ keep: index })
576
+ continue
577
+ }
578
+ const upload = entry.add
579
+ if (upload && typeof upload === 'object' && typeof upload.data === 'string') {
580
+ parts.push({
581
+ add: {
582
+ data: upload.data,
583
+ ...(typeof upload.mediaType === 'string' && upload.mediaType !== '' ? { mediaType: upload.mediaType } : {}),
584
+ ...(typeof upload.name === 'string' && upload.name !== '' ? { name: upload.name } : {}),
585
+ },
586
+ })
587
+ continue
588
+ }
589
+ throw new HttpError(400, 'invalid', 'every part is either a kept block or an upload')
590
+ }
591
+ return parts
592
+ }
593
+
594
+ /**
595
+ * The ordered slots a submitted block list describes, plus where the text goes.
596
+ *
597
+ * Layout is the original message's, never a re-invention: the revised text is
598
+ * placed where the original's FIRST text block stood (the editor holds every
599
+ * text block at once, so the others merge into it), and the kept blocks keep
600
+ * their relative order around it. A message with no text block at all - a
601
+ * picture-only prompt - gets its text appended, which is the only position that
602
+ * does not move something the user did not touch.
603
+ *
604
+ * @param originalBlocks - the message content before the edit.
605
+ * @param parts - normalised parts (see {@link normalizeParts}).
606
+ * @returns `{ slots, textAt, added }`; `textAt` indexes `slots`.
607
+ */
608
+ export function planBlockLayout(originalBlocks, parts) {
609
+ const slots = []
610
+ let added = 0
611
+ for (const part of parts) {
612
+ if (part.keep !== undefined) {
613
+ // The text blocks are the editor's own content, carried by `text`.
614
+ if (isTextBlock(originalBlocks[part.keep])) continue
615
+ slots.push({ kind: 'original', index: part.keep })
616
+ continue
617
+ }
618
+ slots.push({ kind: 'add', upload: part.add })
619
+ added += 1
620
+ }
621
+ let firstText = -1
622
+ for (let index = 0; index < originalBlocks.length; index += 1) {
623
+ if (isTextBlock(originalBlocks[index])) {
624
+ firstText = index
625
+ break
626
+ }
627
+ }
628
+ let textAt = slots.length
629
+ if (firstText >= 0) {
630
+ // The text stands before the first kept block that came after it in the
631
+ // original message. When no kept block did - everything after it was
632
+ // removed, or it was the last block of all - it keeps its own place at the
633
+ // head of what is left, ahead of the blocks that used to stand before it.
634
+ let anchored = false
635
+ for (let index = 0; index < slots.length; index += 1) {
636
+ const slot = slots[index]
637
+ if (slot.kind === 'original' && slot.index > firstText) {
638
+ textAt = index
639
+ anchored = true
640
+ break
641
+ }
642
+ }
643
+ if (!anchored) {
644
+ let before = 0
645
+ for (const slot of slots) {
646
+ if (slot.kind === 'original' && slot.index < firstText) before += 1
647
+ }
648
+ textAt = before
649
+ }
650
+ }
651
+ return { slots, textAt, added }
652
+ }
653
+
654
+ /**
655
+ * Build the carrier content from a layout.
656
+ *
657
+ * A kept block is copied out of the original VERBATIM - a structured clone of
658
+ * the very object the message carries, so an attachment reference, a name, a
659
+ * dimension and every field a later platform adds cross the edit untouched and
660
+ * byte-identical. Nothing here inspects what the block is.
661
+ *
662
+ * @param originalBlocks - the message content before the edit.
663
+ * @param layout - the layout from {@link planBlockLayout}.
664
+ * @param admitted - blocks for the layout's `add` slots, in slot order.
665
+ * @param text - the revised text.
666
+ * @returns the block array the carrier is written with.
667
+ */
668
+ export function assembleBlocks(originalBlocks, layout, admitted, text) {
669
+ const content = []
670
+ let next = 0
671
+ for (let index = 0; index <= layout.slots.length; index += 1) {
672
+ if (index === layout.textAt) content.push({ type: 'text', text })
673
+ const slot = layout.slots[index]
674
+ if (slot === undefined) continue
675
+ if (slot.kind === 'original') content.push(copyBlock(originalBlocks[slot.index]))
676
+ else content.push(admitted[next++])
677
+ }
678
+ return content
679
+ }
680
+
681
+ /**
682
+ * A verbatim copy of one block.
683
+ *
684
+ * `structuredClone` is what makes "untouched" literally true rather than
685
+ * nearly true: the carrier is serialized into the session log, so an identical
686
+ * copy and the same reference produce identical bytes - the clone only removes
687
+ * the chance that a later writer mutates the original through it.
688
+ *
689
+ * @param block - one content block.
690
+ * @returns an independent copy of the same JSON value.
691
+ */
692
+ function copyBlock(block) {
693
+ try {
694
+ return structuredClone(block)
695
+ } catch {
696
+ // Not clonable (an exotic in-memory block): the block itself is still the
697
+ // verbatim value, which is what this function promises.
698
+ return block
699
+ }
700
+ }
701
+
702
+ /**
703
+ * Rebuild this plugin's rollback ledger from the log alone.
704
+ *
705
+ * Every rollback is one replacement event whose message source carries this
706
+ * plugin's marker (`{ editedBy: 'dsh-edit-turn' }`; see {@link isEditCarrier}).
707
+ * A replacement landed by any other producer - compaction, for instance - is
708
+ * ignored.
709
+ *
710
+ * @param events - complete contiguous raw event log.
711
+ * @returns `{ hidden, edits }`: one hidden entry per shadowed seq, and one
712
+ * record per landed rollback.
713
+ */
714
+ export function rollbackLedger(events) {
715
+ const folded = foldSurface(events)
716
+ const bySeq = new Map(events.map((event) => [event.seq, event]))
717
+ const turnOf = turnIndex(events)
718
+ const hidden = []
719
+ const edits = []
720
+ for (const replacement of folded.replacements) {
721
+ const event = bySeq.get(replacement.seq)
722
+ const data = event && event.data
723
+ const source = data && (data.source || (data.message && data.message.source))
724
+ if (!isEditCarrier(source)) continue
725
+ for (const seq of replacement.shadowed) {
726
+ const turn = turnOf.get(seq)
727
+ hidden.push({ seq, turn: typeof turn === 'number' ? turn : null, replacement: replacement.seq })
728
+ }
729
+ edits.push({
730
+ replacementSeq: replacement.seq,
731
+ startSeq: replacement.startSeq,
732
+ endSeq: replacement.endSeq,
733
+ shadowed: replacement.shadowed,
734
+ })
735
+ }
736
+ return { hidden, edits }
737
+ }
738
+
739
+ /** The turn number the format expects next: the last one opened, plus one. */
740
+ export function nextTurnOf(events) {
741
+ let last = 0
742
+ for (const event of events) {
743
+ const turn = event.data && event.data.turn
744
+ if (typeof turn === 'number' && turn > last) last = turn
745
+ }
746
+ return last + 1
747
+ }
748
+
749
+ /** Highest turn number recorded in the log, or undefined for an empty log. */
750
+ export function lastTurnOf(events) {
751
+ let last
752
+ for (const event of events) {
753
+ const turn = event.data && event.data.turn
754
+ if (typeof turn === 'number' && (last === undefined || turn > last)) last = turn
755
+ }
756
+ return last
757
+ }
758
+
759
+ /** Planner rejection with a machine code the HTTP layer forwards verbatim. */
760
+ export class EditPlanError extends Error {
761
+ constructor(code, message) {
762
+ super(message)
763
+ this.name = 'EditPlanError'
764
+ this.code = code
765
+ }
766
+ }
767
+
768
+ /**
769
+ * Resolve one editing target inside a log.
770
+ * @param events - complete contiguous raw event log.
771
+ * @param request - `{ seq?, messageId?, turn? }`.
772
+ * @returns the target event.
773
+ * @throws {EditPlanError} with `not-editable` when no unique target exists.
774
+ */
775
+ function resolveTarget(events, request) {
776
+ let targetSeq = typeof request.seq === 'number' ? request.seq : undefined
777
+ if (targetSeq === undefined && typeof request.messageId === 'string' && request.messageId !== '') {
778
+ for (const event of events) {
779
+ if (messageIdOf(event) === request.messageId) {
780
+ targetSeq = event.seq
781
+ break
782
+ }
783
+ }
784
+ }
785
+ if (targetSeq === undefined && typeof request.turn === 'number') {
786
+ for (const event of events) {
787
+ if (!isHumanPrompt(event)) continue
788
+ if (turnIndex(events).get(event.seq) !== request.turn) continue
789
+ targetSeq = event.seq
790
+ break
791
+ }
792
+ }
793
+ if (targetSeq === undefined) throw new EditPlanError('not-editable', 'no editing target was found')
794
+ const target = events.find((event) => event.seq === targetSeq)
795
+ if (!target) throw new EditPlanError('not-editable', 'the target event does not exist')
796
+ return target
797
+ }
798
+
799
+ /**
800
+ * Turn one UI target into the canonical rollback window plus, for a reply, the
801
+ * replay range that puts the later turns back after the correction.
802
+ *
803
+ * A revised PROMPT is replaced in place: its window is the message alone, so
804
+ * the reply under it and everything after stay exactly where they were.
805
+ *
806
+ * A revised REPLY cannot be swapped in place - the format refuses
807
+ * `sourceEventSeqs` on an `assistant/message`, so a new reply can only be
808
+ * APPENDED. The window therefore runs from the addressed reply to the last
809
+ * surface node, and the correction is appended in a fresh turn. Everything the
810
+ * window took is replayed back behind the correction by
811
+ * {@link buildReplayWrites}: the same infix splice dsh-rerun-turn performs, with
812
+ * the user's text instead of a regenerated answer.
813
+ *
814
+ * @param events - complete contiguous raw event log.
815
+ * @param surfaceNodes - current surface seqs in model order.
816
+ * @param request - `{ seq?, messageId?, turn? }` (`turn` addresses a prompt only).
817
+ * @returns `{ targetSeq, messageId, startSeq, endSeq, shadowed, mode, turn, step, provider, model, original, attachments, replayFrom, logTo, turnStart, turnEnd }`.
818
+ * @throws {EditPlanError} with a stable code when the target cannot be planned.
819
+ */
820
+ export function planRollback(events, surfaceNodes, request, options = {}) {
821
+ const nodeIndex = new Map(surfaceNodes.map((seq, index) => [seq, index]))
822
+ const turnOf = turnIndex(events)
823
+ const target = resolveTarget(events, request, turnOf)
824
+ if (!nodeIndex.has(target.seq)) {
825
+ throw new EditPlanError('already-rolled-back', 'this message is no longer on the current surface')
826
+ }
827
+ // Surface node 0 is the system prompt head: the official append contract only
828
+ // lets a system/message rewrite exactly that node, and no UI row targets it.
829
+ if (target.seq === surfaceNodes[0]) {
830
+ throw new EditPlanError('not-editable', 'the system prompt head cannot be edited')
831
+ }
832
+ // Two editable kinds. A prompt is rewritten in place and the conversation
833
+ // continues; a reply is either patched in place through the message projection
834
+ // or, on a host without it, replaced by an appended correction and a replay.
835
+ const mode = isHumanPrompt(target) ? 'prompt' : isAssistantReply(target) ? 'reply' : null
836
+ if (mode === null) {
837
+ throw new EditPlanError('not-editable', 'only your own messages and the model replies can be edited')
838
+ }
839
+ const turn = turnOf.get(target.seq)
840
+ const data = target.data && typeof target.data === 'object' ? target.data : {}
841
+ const message = data.message && typeof data.message === 'object' ? data.message : data
842
+ const source = message.source && typeof message.source === 'object' ? message.source : null
843
+ const step = typeof data.step === 'number' ? data.step : 1
844
+ const contentBlocks = readMessageBlocks(target)
845
+
846
+ // The in-place path: one block of the reply, rewritten by a plugin record and
847
+ // its projection. Nothing leaves the surface, so there is no window and no
848
+ // replay; the tool calls and the other blocks stay exactly as recorded.
849
+ if (mode === 'reply' && options.patch === true) {
850
+ const patches = options.patches instanceof Map ? options.patches : new Map()
851
+ const blocks = projectedBlocks(message, target.seq, patches)
852
+ if (blocks.length === 0) {
853
+ throw new EditPlanError('not-editable', 'this reply has no editable block')
854
+ }
855
+ const wanted = typeof request.blockIndex === 'number'
856
+ ? blocks.find((block) => block.index === request.blockIndex)
857
+ : blocks.find((block) => block.kind === 'text') ?? blocks[0]
858
+ if (wanted === undefined) throw new EditPlanError('not-editable', 'the requested block does not exist')
859
+ if (typeof request.kind === 'string' && request.kind !== wanted.kind) {
860
+ throw new EditPlanError('not-editable', 'the requested block changed kind')
861
+ }
862
+ return {
863
+ targetSeq: target.seq,
864
+ messageId: messageIdOf(target),
865
+ mode: 'reply',
866
+ patch: true,
867
+ startSeq: null,
868
+ endSeq: null,
869
+ shadowed: [],
870
+ blockIndex: wanted.index,
871
+ kind: wanted.kind,
872
+ original: wanted.text,
873
+ // `blocks` here are the EDITOR's blocks (index/kind/text/original), not
874
+ // the raw content array; patch mode never rebuilds a message carrier.
875
+ blocks,
876
+ turn: typeof turn === 'number' ? turn : null,
877
+ step,
878
+ provider: source && typeof source.provider === 'string' ? source.provider : null,
879
+ model: source && typeof source.model === 'string' ? source.model : null,
880
+ attachments: contentBlocks.filter((block) => kindOfBlock(block) === null).length,
881
+ }
882
+ }
883
+ const startIdx = nodeIndex.get(target.seq)
884
+ // Two different windows, because the two edits mean different things.
885
+ //
886
+ // A revised PROMPT is replaced in place: only the message itself leaves the
887
+ // surface, so the reply under it and everything after stay exactly where they
888
+ // were - edit the wording, keep the conversation.
889
+ //
890
+ // A revised REPLY cannot be a replacement carrier (the format refuses
891
+ // `sourceEventSeqs` on an assistant message), so the correction is appended
892
+ // at the tail and everything from the addressed reply to the end must leave
893
+ // the surface first. `buildReplayWrites` then puts every later turn back,
894
+ // event by event, with fresh turn numbers and message ids - the model reads
895
+ // prefix + corrected reply + the same later turns, in order.
896
+ const shadowed = mode === 'prompt' ? [target.seq] : surfaceNodes.slice(startIdx)
897
+ if (shadowed.length === 0 || shadowed[0] !== target.seq) {
898
+ throw new EditPlanError('not-editable', 'the target does not open a rollback window')
899
+ }
900
+ // The replay range: the log range the shadow covers, and the bracket where
901
+ // the later turns start. A reply in the last turn has neither, and the edit
902
+ // degenerates to the old tail-less rollback (there is nothing to replay).
903
+ let replayFrom = null
904
+ let logTo = null
905
+ let turnStart = null
906
+ let turnEnd = null
907
+ if (mode === 'reply') {
908
+ const spans = turnSpans(events)
909
+ // A closed bracket that CONTAINS the reply. The fallback (the last bracket
910
+ // that starts before it) only matters for a malformed log with a bracket
911
+ // that never closed; a valid log always takes the containment branch.
912
+ const owning = spans.find(
913
+ (entry) => entry.endSeq !== null && entry.startSeq <= target.seq && target.seq <= entry.endSeq,
914
+ ) ?? spans.filter((entry) => entry.startSeq <= target.seq).at(-1)
915
+ if (owning !== undefined) {
916
+ turnStart = owning.startSeq
917
+ turnEnd = owning.endSeq
918
+ }
919
+ const lastShadowed = shadowed[shadowed.length - 1]
920
+ const bySeq = new Map(events.map((event) => [event.seq, event]))
921
+ logTo = lastShadowed
922
+ for (let seq = lastShadowed + 1; ; seq += 1) {
923
+ const event = bySeq.get(seq)
924
+ if (event === undefined) break
925
+ // The window already ends on the last surface node: only log-only events
926
+ // (step/turn closing records) can follow it.
927
+ if (isSurfaceEvent(event)) break
928
+ logTo = seq
929
+ if (event.type === 'turn/end') break
930
+ }
931
+ const owningIndex = owning === undefined ? -1 : spans.indexOf(owning)
932
+ const nextSpan = owningIndex >= 0 ? spans[owningIndex + 1] : undefined
933
+ if (nextSpan !== undefined && nextSpan.startSeq <= logTo) replayFrom = nextSpan.startSeq
934
+ }
935
+ const { text, attachments } = readMessageText(target)
936
+ // The blocks themselves travel with the plan: the carrier is rebuilt from
937
+ // them, so no caller has to re-read the message to know what it carries.
938
+ const blocks = contentBlocks
939
+ return {
940
+ targetSeq: target.seq,
941
+ messageId: messageIdOf(target),
942
+ startSeq: shadowed[0],
943
+ endSeq: shadowed[shadowed.length - 1],
944
+ shadowed,
945
+ mode,
946
+ patch: false,
947
+ turn: typeof turn === 'number' ? turn : null,
948
+ // The appended correction is keyed by turn:step in the client's reducer, so a
949
+ // missing step would make two corrections collide on "undefined:undefined".
950
+ step,
951
+ provider: source && typeof source.provider === 'string' ? source.provider : null,
952
+ model: source && typeof source.model === 'string' ? source.model : null,
953
+ original: text,
954
+ attachments,
955
+ blocks,
956
+ // Reply-only replay range. `replayFrom` is the next turn's bracket (null when
957
+ // the edited reply is in the last turn); `logTo` is the end of the last turn
958
+ // the window shadowed. Both are computed from the ORIGINAL log and stay valid
959
+ // while the correction is appended after it.
960
+ replayFrom,
961
+ logTo,
962
+ turnStart,
963
+ turnEnd,
964
+ }
965
+ }
966
+
967
+ // --- reply replay -----------------------------------------------------------
968
+ //
969
+ // A reply edit lands exactly like a rerun's infix splice: the shadow takes the
970
+ // old answer and every later turn off the surface, the correction is appended in
971
+ // a fresh turn, and this walk puts the later turns back as fresh copies. The
972
+ // algorithm is the one dsh-rerun-turn ships (`buildReplayWrites` there); keep the
973
+ // two in step - `test/replay-parity.test.js` compares their output on one log
974
+ // when the sibling repository is checked out.
975
+
976
+ /** Marker written into every replayed event's source. */
977
+ export const REPLAY_MARKER = PLUGIN_ID
978
+
979
+ /** Text that carries nothing a model could read (spaces, zero-width glue). */
980
+ const INVISIBLE_TEXT_RE = /^[\s\u200b-\u200f\u2060\ufeff]*$/
981
+
982
+ /**
983
+ * Whether content blocks carry anything readable.
984
+ * @param content - the `content` array of a message.
985
+ * @returns true when at least one block is not invisible text.
986
+ */
987
+ export function hasReadableContent(content) {
988
+ if (!Array.isArray(content)) return false
989
+ for (const block of content) {
990
+ if (!block || typeof block !== 'object') continue
991
+ if (block.type !== 'text') return true
992
+ if (typeof block.text !== 'string' || !INVISIBLE_TEXT_RE.test(block.text)) return true
993
+ }
994
+ return false
995
+ }
996
+
997
+ /**
998
+ * Whether an event is a plugin's silent surface carrier rather than conversation.
999
+ *
1000
+ * `dsh-delete-turn` writes one for a deletion and `dsh-rerun-turn` for a rerun's
1001
+ * shadow - a `user/message` whose source kind is `plugin:<id>` and whose content
1002
+ * is empty or invisible. A replay must retire it without a copy: it projects to
1003
+ * no model message, so copying it would resurrect an empty user node.
1004
+ *
1005
+ * A rewritten prompt is NOT this shape: `dsh-edit-turn` keeps `kind: 'user'` and
1006
+ * carries the user's wording, so it stays a real prompt and is copied.
1007
+ *
1008
+ * @param event - raw session event.
1009
+ * @returns true for a text-free plugin replacement.
1010
+ */
1011
+ export function isSilentPluginCarrier(event) {
1012
+ if (!event || event.type !== 'user/message') return false
1013
+ const data = event.data || {}
1014
+ const source = data.source
1015
+ if (!source || typeof source.kind !== 'string' || !source.kind.startsWith('plugin:')) return false
1016
+ return !hasReadableContent(data.content)
1017
+ }
1018
+
1019
+ /** Stamp one copied event's source with this plugin's replay markers. */
1020
+ function replaySource(source, replayId, originalSeq) {
1021
+ return {
1022
+ ...(source && typeof source === 'object' ? source : {}),
1023
+ replayBy: REPLAY_MARKER,
1024
+ replayId,
1025
+ originalSeq,
1026
+ }
1027
+ }
1028
+
1029
+ /**
1030
+ * Build the replay writes for a reply edit's shadowed tail.
1031
+ *
1032
+ * Every shadowed event after the edited reply is copied verbatim except for:
1033
+ * fresh turn numbers (the log requires them contiguous), fresh message ids,
1034
+ * remapped `sourceEventSeqs` on tool results, dropped usage numbers and embedded
1035
+ * streams, and the replay marker in each message source. System, developer and
1036
+ * every log-only record are skipped: they describe the original run, not the
1037
+ * conversation.
1038
+ *
1039
+ * Tool calls are copied only as complete pairs. A call whose result never landed
1040
+ * (an interrupted turn) is dropped along with its advertisement in the copied
1041
+ * assistant content, because the format refuses a turn that closes with an
1042
+ * unresolved call. The inverse repair shape - a `TOOL_NOT_STARTED` result with no
1043
+ * call event - is copied as-is and keeps its absent `sourceEventSeqs`: the
1044
+ * validator accepts that repair only without one.
1045
+ *
1046
+ * @param events - complete contiguous raw event log (the pre-edit snapshot).
1047
+ * @param plan - the planned window (`shadowed`, `replayFrom`, `logTo`).
1048
+ * @param baseTurn - the first fresh turn number the replay may use.
1049
+ * @param replayId - the operation identity recorded on every copy.
1050
+ * @param startSeq - the seq the first write will land at (writes are appended
1051
+ * back to back, so each predicted seq is `startSeq` + its offset).
1052
+ * @param promptCopied - parity with dsh-rerun-turn's builder: when true, the
1053
+ * plan's `promptSeq` is replayed too. A reply edit never shadows the prompt,
1054
+ * so its own plans leave this false.
1055
+ * @returns an ordered `{ type, data, surfaceOp?, sourceEventSeqs? }` write list.
1056
+ */
1057
+ export function buildReplayWrites(events, plan, baseTurn, replayId, startSeq, promptCopied = false) {
1058
+ const shadowedSet = new Set(plan.shadowed)
1059
+ const bySeq = new Map(events.map((event) => [event.seq, event]))
1060
+ const turnOf = turnIndex(events)
1061
+ const shadowedTurns = new Set()
1062
+ for (const seq of plan.shadowed) {
1063
+ const turn = turnOf.get(seq)
1064
+ if (typeof turn === 'number') shadowedTurns.add(turn)
1065
+ }
1066
+ const included = (event) => {
1067
+ if (isSurfaceEvent(event)) return shadowedSet.has(event.seq)
1068
+ if (
1069
+ event.type === 'turn/start' ||
1070
+ event.type === 'turn/end' ||
1071
+ event.type === 'step/start' ||
1072
+ event.type === 'step/end' ||
1073
+ event.type === 'tool/call'
1074
+ ) {
1075
+ return typeof event.data.turn === 'number' && shadowedTurns.has(event.data.turn)
1076
+ }
1077
+ return false
1078
+ }
1079
+ const range = []
1080
+ // `replayFrom` is this plugin's plan field; `logFrom` is the name the sibling
1081
+ // builder uses, accepted here so the parity test can feed one plan object.
1082
+ const walkFrom = typeof plan.replayFrom === 'number' ? plan.replayFrom : plan.logFrom
1083
+ for (let seq = walkFrom; seq <= plan.logTo; seq += 1) {
1084
+ const event = bySeq.get(seq)
1085
+ if (event === undefined) continue
1086
+ if (included(event)) range.push(event)
1087
+ }
1088
+ // Tool pairing facts for the whole range, so assistant content can be
1089
+ // corrected before anything is written.
1090
+ const calledIds = new Set()
1091
+ const resultIds = new Set()
1092
+ const repairIds = new Set()
1093
+ for (const event of range) {
1094
+ if (event.type === 'tool/call') calledIds.add(event.data.callId)
1095
+ else if (event.type === 'tool/result') {
1096
+ resultIds.add(event.data.message && event.data.message.source ? event.data.message.source.callId : event.data.callId)
1097
+ const error = event.data.error
1098
+ if (error && error.name === 'ToolNotStartedError' && error.code === 'TOOL_NOT_STARTED' && event.sourceEventSeqs === undefined) {
1099
+ repairIds.add(event.data.message && event.data.message.source ? event.data.message.source.callId : event.data.callId)
1100
+ }
1101
+ }
1102
+ }
1103
+ const healthyIds = new Set()
1104
+ for (const id of calledIds) if (resultIds.has(id)) healthyIds.add(id)
1105
+ for (const id of repairIds) if (!calledIds.has(id)) healthyIds.add(id)
1106
+ const pairedResultIds = new Set()
1107
+ for (const id of calledIds) if (resultIds.has(id)) pairedResultIds.add(id)
1108
+ for (const id of repairIds) if (!calledIds.has(id)) pairedResultIds.add(id)
1109
+
1110
+ const writes = []
1111
+ let predicted = startSeq
1112
+ let nextTurn = baseTurn
1113
+ const turnMap = new Map()
1114
+ const assistantSeqById = new Map()
1115
+ let lastAssistantSeq = null
1116
+ const seqOf = () => {
1117
+ const seq = predicted
1118
+ predicted += 1
1119
+ return seq
1120
+ }
1121
+ for (const event of range) {
1122
+ const data = event.data || {}
1123
+ if (event.type === 'turn/start') {
1124
+ turnMap.set(data.turn, nextTurn)
1125
+ writes.push({ type: 'turn/start', data: { turn: nextTurn } })
1126
+ seqOf()
1127
+ continue
1128
+ }
1129
+ if (event.type === 'turn/end') {
1130
+ writes.push({ type: 'turn/end', data: { turn: turnMap.get(data.turn), reason: data.reason } })
1131
+ seqOf()
1132
+ nextTurn += 1
1133
+ continue
1134
+ }
1135
+ if (event.type === 'step/start' || event.type === 'step/end') {
1136
+ writes.push({ type: event.type, data: { turn: turnMap.get(data.turn), step: data.step } })
1137
+ seqOf()
1138
+ continue
1139
+ }
1140
+ if (event.type === 'user/message') {
1141
+ if (event.seq === plan.promptSeq && promptCopied !== true) continue
1142
+ // A silent carrier standing where a prompt was is bookkeeping, not
1143
+ // conversation: retire it without a copy, exactly as rerun does.
1144
+ if (isSilentPluginCarrier(event)) continue
1145
+ writes.push({
1146
+ type: 'user/message',
1147
+ surfaceOp: 'append',
1148
+ data: {
1149
+ id: randomUUID(),
1150
+ role: 'user',
1151
+ content: data.content,
1152
+ source: replaySource(data.source, replayId, event.seq),
1153
+ },
1154
+ })
1155
+ seqOf()
1156
+ continue
1157
+ }
1158
+ if (event.type === 'assistant/message') {
1159
+ const message = data.message || {}
1160
+ const source = { ...(message.source || {}) }
1161
+ delete source.replayState
1162
+ const content = Array.isArray(message.content)
1163
+ ? message.content.filter((block) => !(block && block.type === 'tool-call' && !healthyIds.has(block.id)))
1164
+ : []
1165
+ writes.push({
1166
+ type: 'assistant/message',
1167
+ surfaceOp: 'append',
1168
+ data: {
1169
+ turn: turnMap.get(data.turn),
1170
+ step: data.step,
1171
+ message: {
1172
+ id: randomUUID(),
1173
+ role: 'assistant',
1174
+ content,
1175
+ source: replaySource(source, replayId, event.seq),
1176
+ },
1177
+ stream: [],
1178
+ ...(data.interrupted === true ? { interrupted: true } : {}),
1179
+ },
1180
+ })
1181
+ assistantSeqById.set(event.seq, predicted)
1182
+ lastAssistantSeq = predicted
1183
+ seqOf()
1184
+ continue
1185
+ }
1186
+ if (event.type === 'tool/call') {
1187
+ if (!pairedResultIds.has(data.callId)) continue
1188
+ writes.push({
1189
+ type: 'tool/call',
1190
+ data: { turn: turnMap.get(data.turn), step: data.step, callId: data.callId, name: data.name, arguments: data.arguments },
1191
+ })
1192
+ seqOf()
1193
+ continue
1194
+ }
1195
+ if (event.type === 'tool/result') {
1196
+ const callId = data.message && data.message.source ? data.message.source.callId : data.callId
1197
+ if (!pairedResultIds.has(callId)) continue
1198
+ const message = data.message
1199
+ const source = replaySource(message && message.source, replayId, event.seq)
1200
+ // The TOOL_NOT_STARTED repair is accepted only without sourceEventSeqs;
1201
+ // ordinary results remap theirs onto the copied assistant message.
1202
+ let sourceEventSeqs
1203
+ if (!repairIds.has(callId)) {
1204
+ const remapped = Array.isArray(event.sourceEventSeqs)
1205
+ ? event.sourceEventSeqs.map((seq) => assistantSeqById.get(seq)).filter((seq) => typeof seq === 'number')
1206
+ : []
1207
+ if (remapped.length > 0) sourceEventSeqs = remapped
1208
+ else if (typeof lastAssistantSeq === 'number') sourceEventSeqs = [lastAssistantSeq]
1209
+ }
1210
+ const originalMessage = message || {}
1211
+ const rest = { ...originalMessage }
1212
+ delete rest.id
1213
+ delete rest.content
1214
+ delete rest.source
1215
+ // The interrupted-repair carrier must keep its contract-shaped id
1216
+ // (`interrupted-tool-result-<callId>-<n>`): the validator refuses a repair
1217
+ // whose id does not match, and a random id breaks it. The suffix is the
1218
+ // copy's own predicted seq, so the identity stays self-describing.
1219
+ const messageId = repairIds.has(callId) ? `interrupted-tool-result-${callId}-${predicted}` : randomUUID()
1220
+ writes.push({
1221
+ type: 'tool/result',
1222
+ surfaceOp: 'append',
1223
+ ...(sourceEventSeqs === undefined ? {} : { sourceEventSeqs }),
1224
+ data: {
1225
+ turn: turnMap.get(data.turn),
1226
+ step: data.step,
1227
+ message: {
1228
+ ...rest,
1229
+ id: messageId,
1230
+ content: originalMessage.content ?? [],
1231
+ source,
1232
+ },
1233
+ ...(data.error === undefined ? {} : { error: data.error }),
1234
+ ...(data.meta === undefined ? {} : { meta: data.meta }),
1235
+ },
1236
+ })
1237
+ seqOf()
1238
+ continue
1239
+ }
1240
+ // system/message, developer/message and every log-only record are skipped.
1241
+ }
1242
+ return writes
1243
+ }
1244
+
1245
+ /**
1246
+ * Every human prompt that can currently be edited.
1247
+ *
1248
+ * A prompt that already left the surface (an earlier rollback shadowed it, or a
1249
+ * compaction consumed it) keeps its transcript row on purpose, so it must not
1250
+ * be offered again.
1251
+ *
1252
+ * @param events - complete contiguous raw event log.
1253
+ * @param surfaceNodes - current surface seqs in model order.
1254
+ * @param options - `{ preview }`: whether the deployment can hand attachment
1255
+ * bytes back, which decides if a chip may offer a thumbnail.
1256
+ * @returns one entry per editable prompt, in conversation order.
1257
+ */
1258
+ export function editableTurns(events, surfaceNodes, options = {}) {
1259
+ const eventBySeq = new Map(events.map((event) => [event.seq, event]))
1260
+ const turnOf = turnIndex(events)
1261
+ const head = surfaceNodes[0]
1262
+ const out = []
1263
+ // Surface order, not log order: a prompt rewritten in place travels as a
1264
+ // replace-carrier, which is APPENDED at the end of the log while standing at
1265
+ // the surface position of the wording it replaced. Walking `events` would
1266
+ // report the revision as the newest message in the conversation.
1267
+ for (const seq of surfaceNodes) {
1268
+ const event = eventBySeq.get(seq)
1269
+ if (!event || !isHumanPrompt(event)) continue
1270
+ if (seq === head) continue
1271
+ const { text, attachments } = readMessageText(event)
1272
+ // A replacement carrier is appended after its original turn's bracket has
1273
+ // closed, so turnIndex cannot name its turn. It still stands at that
1274
+ // prompt's position in the conversation: inherit the turn from the event
1275
+ // it replaced, or the editor's turn list loses the row (turn: null).
1276
+ let turn = turnOf.get(seq)
1277
+ if (typeof turn !== 'number' && Array.isArray(event.sourceEventSeqs)) {
1278
+ for (const source of event.sourceEventSeqs) {
1279
+ const inherited = turnOf.get(source)
1280
+ if (typeof inherited === 'number') {
1281
+ turn = inherited
1282
+ break
1283
+ }
1284
+ }
1285
+ }
1286
+ out.push({
1287
+ seq,
1288
+ turn: typeof turn === 'number' ? turn : null,
1289
+ messageId: messageIdOf(event) ?? null,
1290
+ text,
1291
+ attachments,
1292
+ // What the editor draws beside the text: one chip per non-text block,
1293
+ // described by field presence only (see blockSummaries).
1294
+ blocks: blockSummaries(readMessageBlocks(event), options.preview === true),
1295
+ })
1296
+ }
1297
+ return out
1298
+ }
1299
+
1300
+ /**
1301
+ * Every model reply that can currently be rewritten.
1302
+ *
1303
+ * In patch mode (the in-place projection path) a reply is offered when it has
1304
+ * any editable block - output text or a reasoning/thinking block - and the
1305
+ * blocks travel with the entry so the editor can pick one. In the legacy replay
1306
+ * mode only text is editable, and a reply without text is skipped.
1307
+ *
1308
+ * @param events - complete contiguous raw event log.
1309
+ * @param surfaceNodes - current surface seqs in model order.
1310
+ * @param options - `{ patches, patch }`: landed patch overlays and whether the
1311
+ * deployment can write a patch record.
1312
+ * @returns one entry per editable reply, in conversation order.
1313
+ */
1314
+ export function editableReplies(events, surfaceNodes, options = {}) {
1315
+ const nodeIndex = new Map(surfaceNodes.map((seq, index) => [seq, index]))
1316
+ const turnOf = turnIndex(events)
1317
+ const head = surfaceNodes[0]
1318
+ const patches = options.patches instanceof Map ? options.patches : new Map()
1319
+ const patch = options.patch === true
1320
+ const out = []
1321
+ for (const event of events) {
1322
+ if (!isAssistantReply(event)) continue
1323
+ if (!nodeIndex.has(event.seq)) continue
1324
+ if (event.seq === head) continue
1325
+ const data = event.data && typeof event.data === 'object' ? event.data : {}
1326
+ const message = data.message && typeof data.message === 'object' ? data.message : data
1327
+ const blocks = projectedBlocks(message, event.seq, patches)
1328
+ if (blocks.length === 0) continue
1329
+ const text = blocks.filter((block) => block.kind === 'text').map((block) => block.text).join('\n')
1330
+ if (!patch && text.trim() === '') continue
1331
+ if (patch && blocks.every((block) => block.text.trim() === '')) continue
1332
+ const turn = turnOf.get(event.seq)
1333
+ // One turn runs many steps, and every step's assistant message carries its
1334
+ // own reasoning. The answer's row is the one with the action strip, so its
1335
+ // block list is widened to the whole turn: every reasoning and every answer
1336
+ // text of that turn is offered, each annotated with the seq it lives in.
1337
+ let listed = blocks.map((block) => ({ ...block, seq: event.seq }))
1338
+ const carriesAnswer = blocks.some((block) => block.kind === 'text' && block.text.trim() !== '')
1339
+ if (patch && carriesAnswer && typeof turn === 'number') {
1340
+ const acrossTurn = []
1341
+ for (const other of events) {
1342
+ if (!isAssistantReply(other) || turnOf.get(other.seq) !== turn) continue
1343
+ if (!nodeIndex.has(other.seq)) continue
1344
+ const otherData = other.data && typeof other.data === 'object' ? other.data : {}
1345
+ const otherMessage = otherData.message && typeof otherData.message === 'object' ? otherData.message : otherData
1346
+ for (const block of projectedBlocks(otherMessage, other.seq, patches)) {
1347
+ acrossTurn.push({ ...block, seq: other.seq })
1348
+ }
1349
+ }
1350
+ if (acrossTurn.length > listed.length) listed = acrossTurn
1351
+ }
1352
+ out.push({
1353
+ seq: event.seq,
1354
+ turn: typeof turn === 'number' ? turn : null,
1355
+ messageId: messageIdOf(event) ?? null,
1356
+ text,
1357
+ // For a reply these are the blocks a text-only rewrite would drop:
1358
+ // tool calls and any other non-editable content.
1359
+ attachments: readMessageBlocks(event).filter((block) => patch ? kindOfBlock(block) === null : !isTextBlock(block)).length,
1360
+ patched: blocks.some((block) => block.patched),
1361
+ // Present only where the editor can target one: the replay path can only
1362
+ // replace the whole reply, so it has no block picker.
1363
+ ...(patch ? { blocks: listed } : {}),
1364
+ })
1365
+ }
1366
+ return out
1367
+ }
1368
+
1369
+ // ---------------------------------------------------------------------------
1370
+ // host service plumbing
1371
+ // ---------------------------------------------------------------------------
1372
+
1373
+ class HttpError extends Error {
1374
+ constructor(status, code, message) {
1375
+ super(message)
1376
+ this.name = 'HttpError'
1377
+ this.status = status
1378
+ this.code = code
1379
+ }
1380
+ }
1381
+
1382
+ // A session id travels in two spellings: the raw uuid and `session-<uuid>`.
1383
+ // The store, the persistence directories and the workspace rows disagree about
1384
+ // which one they hold, so every lookup tries both.
1385
+ function idVariants(sessionId) {
1386
+ const out = new Set([sessionId])
1387
+ if (sessionId.startsWith('session-')) out.add(sessionId.slice('session-'.length))
1388
+ else out.add(`session-${sessionId}`)
1389
+ return [...out]
1390
+ }
1391
+
1392
+ function findLiveSession(ctx, sessionId) {
1393
+ const sessions = ctx.get('sessions')
1394
+ if (!sessions || typeof sessions.get !== 'function') return undefined
1395
+ for (const variant of idVariants(sessionId)) {
1396
+ const found = sessions.get(variant)
1397
+ if (found) return found
1398
+ }
1399
+ return undefined
1400
+ }
1401
+
1402
+ // Resolve the live Session that owns the append. An already-open session is
1403
+ // used directly; a cold one is resumed through the official controller, which
1404
+ // is exactly what the web UI does when the user opens it.
1405
+ /**
1406
+ * The live agent whose loop owns this session's turn counter, when one exists.
1407
+ * @param ctx - plugin context.
1408
+ * @param sessionId - session to resolve.
1409
+ * @returns the agent, or undefined (cold session, or no controller mounted).
1410
+ */
1411
+ async function resolveLoopAgent(ctx, sessionId) {
1412
+ const controller = ctx.get('sessionController')
1413
+ if (!controller || typeof controller.resolveAgent !== 'function') return undefined
1414
+ try {
1415
+ const result = await controller.resolveAgent(sessionId)
1416
+ return result && result.agent ? result.agent : undefined
1417
+ } catch {
1418
+ return undefined
1419
+ }
1420
+ }
1421
+
1422
+ async function resolveSession(ctx, sessionId) {
1423
+ const live = findLiveSession(ctx, sessionId)
1424
+ if (live) return live
1425
+ const controller = ctx.get('sessionController')
1426
+ if (controller && typeof controller.resolveAgent === 'function') {
1427
+ try {
1428
+ const result = await controller.resolveAgent(sessionId)
1429
+ if (result && result.agent && result.agent.session) return result.agent.session
1430
+ } catch {
1431
+ // fall through to the explicit failure below
1432
+ }
1433
+ }
1434
+ return undefined
1435
+ }
1436
+
1437
+ /**
1438
+ * Make the live agent loop agree with a turn this plugin opened in the log.
1439
+ *
1440
+ * The loop keeps its own counter in an idle-phase field (`phase.lastTurn`): it
1441
+ * is seeded when the loop is constructed from the projection and advanced only
1442
+ * by turns the loop itself opens. A reply edit has to open a turn - the read
1443
+ * path admits an `assistant/message` only inside an open turn and step - so
1444
+ * afterwards that field still names the turn this plugin consumed, and the
1445
+ * loop's next run would open the same number. That collides: both turn/start
1446
+ * events claim one number and the log fails its next load
1447
+ * (`turn/start does not open the expected turn`), which is the corruption this
1448
+ * plugin already shipped once and repaired.
1449
+ *
1450
+ * The shape guard is deliberate and the failure is soft: if the loop is not
1451
+ * idle, or its shape is not what this expects, nothing is touched and the
1452
+ * caller records why. The sibling plugin dsh-rerun-turn solves the same
1453
+ * problem the same way (`syncLoopTurn`); there is no official seam for it.
1454
+ *
1455
+ * @param agent - the live loop agent, when one exists.
1456
+ * @param maxTurn - the highest turn now in the log.
1457
+ * @returns `'synced' | 'already-current' | 'unavailable'`.
1458
+ */
1459
+ export function syncLoopTurn(agent, maxTurn) {
1460
+ try {
1461
+ const phase = agent && agent.phase
1462
+ if (!phase || typeof phase !== 'object' || phase.kind !== 'idle' || typeof phase.lastTurn !== 'number') {
1463
+ return 'unavailable'
1464
+ }
1465
+ if (maxTurn > phase.lastTurn) {
1466
+ phase.lastTurn = maxTurn
1467
+ return 'synced'
1468
+ }
1469
+ return 'already-current'
1470
+ } catch {
1471
+ return 'unavailable'
1472
+ }
1473
+ }
1474
+
1475
+ function eventsFromLive(session) {
1476
+ if (session && typeof session.snapshotEvents === 'function') {
1477
+ try {
1478
+ const events = session.snapshotEvents()
1479
+ if (Array.isArray(events)) return events
1480
+ } catch {
1481
+ // fall through to the query service
1482
+ }
1483
+ }
1484
+ return undefined
1485
+ }
1486
+
1487
+ // Live-preferred read through the public query service; the live session's own
1488
+ // snapshot is the fallback when the service is absent.
1489
+ async function readEvents(ctx, sessionId) {
1490
+ const query = ctx.get('sessionQuery')
1491
+ if (query && typeof query.readSession === 'function') {
1492
+ try {
1493
+ const snapshot = await query.readSession(sessionId)
1494
+ if (snapshot && Array.isArray(snapshot.events)) return snapshot.events
1495
+ } catch {
1496
+ // fall through to the live snapshot
1497
+ }
1498
+ }
1499
+ const events = eventsFromLive(findLiveSession(ctx, sessionId))
1500
+ return events ?? null
1501
+ }
1502
+
1503
+ function surfaceOf(ctx, sessionId, events) {
1504
+ const live = findLiveSession(ctx, sessionId)
1505
+ const nodes = live && live.surface && Array.isArray(live.surface.nodes) ? live.surface.nodes : undefined
1506
+ return nodes ?? foldSurface(events).nodes
1507
+ }
1508
+
1509
+ // The append is committed in memory the moment `session.append` returns; the
1510
+ // persistence writer buffers asynchronously. Await the official durability
1511
+ // checkpoint so a reload or a DSH restart still sees the rollback.
1512
+ async function flushSession(ctx, session) {
1513
+ const errors = []
1514
+ const sessions = ctx.get('sessions')
1515
+ if (sessions && typeof sessions.flush === 'function') {
1516
+ try {
1517
+ await Promise.race([sessions.flush(session), new Promise((resolve) => setTimeout(resolve, FLUSH_DEADLINE_MS))])
1518
+ return { flushed: true }
1519
+ } catch (error) {
1520
+ errors.push(String((error && error.message) || error))
1521
+ }
1522
+ } else {
1523
+ errors.push('sessions.flush unavailable')
1524
+ }
1525
+ const persistence = ctx.get('sessionPersistence')
1526
+ if (persistence && typeof persistence.flush === 'function') {
1527
+ try {
1528
+ await Promise.race([persistence.flush(), new Promise((resolve) => setTimeout(resolve, FLUSH_DEADLINE_MS))])
1529
+ return { flushed: true }
1530
+ } catch (error) {
1531
+ errors.push(String((error && error.message) || error))
1532
+ }
1533
+ } else {
1534
+ errors.push('sessionPersistence.flush unavailable')
1535
+ }
1536
+ return { flushed: false, flushError: errors.join(' | ') }
1537
+ }
1538
+
1539
+ // --- attachment admission ----------------------------------------------------
1540
+ //
1541
+ // The platform's durable store is the only path by which bytes become a
1542
+ // reference a session may cite (@deepseek-ai/dsh-attachment's `AttachmentStore`;
1543
+ // the local backend is @deepseek-ai/dsh-attachment-local). It is resolved at
1544
+ // REQUEST time, never assumed: a deployment that mounts none must keep working
1545
+ // exactly as this plugin did before blocks travelled at all - text only, with
1546
+ // the editor saying so - and one that mounts a store later starts working with
1547
+ // no restart.
1548
+
1549
+ /**
1550
+ * The durable attachment store this deployment mounts, when it has one.
1551
+ *
1552
+ * Candidate names are probed the way the platform's own consumers reach it
1553
+ * (`ctx.get('attachments')`, e.g. dsh-acp). An object is only accepted when it
1554
+ * can actually admit something: a service that merely shares the name must not
1555
+ * make the editor promise to keep a block the host cannot store.
1556
+ *
1557
+ * @param ctx - plugin context.
1558
+ * @returns the store, or null when the deployment mounts none.
1559
+ */
1560
+ export function resolveAttachmentStore(ctx) {
1561
+ if (!ctx || typeof ctx.get !== 'function') return null
1562
+ for (const name of ATTACHMENT_SERVICES) {
1563
+ let store
1564
+ try {
1565
+ store = ctx.get(name)
1566
+ } catch {
1567
+ store = null
1568
+ }
1569
+ if (!store || typeof store !== 'object') continue
1570
+ if (typeof store.saveImage === 'function' || typeof store.saveFile === 'function') return store
1571
+ }
1572
+ return null
1573
+ }
1574
+
1575
+ /**
1576
+ * Whether this deployment can hand attachment bytes back for a chip thumbnail.
1577
+ * @param store - the resolved store, or null.
1578
+ * @returns true when a read path exists.
1579
+ */
1580
+ export function canPreviewAttachments(store) {
1581
+ return Boolean(store) && (typeof store.readImage === 'function' || typeof store.fileHostPath === 'function')
1582
+ }
1583
+
1584
+ /**
1585
+ * Decode one upload exactly the way the platform's wire admission does.
1586
+ *
1587
+ * Canonical base64 only (the platform's `admission.js` test): a payload whose
1588
+ * re-encoding differs is refused rather than silently decoded into different
1589
+ * bytes than the browser meant to send.
1590
+ *
1591
+ * @param data - base64 text.
1592
+ * @returns the decoded bytes.
1593
+ * @throws {HttpError} 400 `invalid` for anything but bounded canonical base64.
1594
+ */
1595
+ function decodeUpload(data) {
1596
+ if (typeof data !== 'string' || data === '') throw new HttpError(400, 'invalid', 'an upload carried no data')
1597
+ if (data.length > MAX_UPLOAD_BYTES * 2) throw new HttpError(400, 'invalid', 'an upload is too large')
1598
+ const decoded = Buffer.from(data, 'base64')
1599
+ if (decoded.toString('base64') !== data) throw new HttpError(400, 'invalid', 'an upload is not canonical base64')
1600
+ if (decoded.byteLength > MAX_UPLOAD_BYTES) throw new HttpError(400, 'invalid', 'an upload is too large')
1601
+ return new Uint8Array(decoded)
1602
+ }
1603
+
1604
+ /**
1605
+ * Admit one uploaded payload and hand back the block that cites it.
1606
+ *
1607
+ * The STORE decides the shape, not this plugin: bytes it accepts as an image
1608
+ * become the platform's image block, anything else is stored verbatim as a file
1609
+ * block. That is the platform's own vocabulary (`AttachmentStore.saveImage` /
1610
+ * `saveFile`, and `admitPromptContent` builds the same two shapes), and it is
1611
+ * the only place a block type is named in the whole edit path - a block the
1612
+ * user did not touch never passes through here at all.
1613
+ *
1614
+ * @param store - the resolved attachment store.
1615
+ * @param upload - `{ data, mediaType?, name? }`.
1616
+ * @returns the content block citing the durable reference.
1617
+ * @throws {HttpError} 400 `attachment-refused` when the store refuses it.
1618
+ */
1619
+ export async function admitUpload(store, upload) {
1620
+ const data = decodeUpload(upload.data)
1621
+ const name = typeof upload.name === 'string' && upload.name !== '' ? upload.name : undefined
1622
+ const mediaType = typeof upload.mediaType === 'string' && upload.mediaType !== '' ? upload.mediaType : undefined
1623
+ // The store's own advertised media types decide whether it can take this as
1624
+ // an image; without that list, the declared type family is the only signal.
1625
+ const imageTypes = store.imageLimits && Array.isArray(store.imageLimits.mediaTypes) ? store.imageLimits.mediaTypes : null
1626
+ const asImage = mediaType !== undefined && typeof store.saveImage === 'function' &&
1627
+ (imageTypes === null ? mediaType.startsWith('image/') : imageTypes.includes(mediaType))
1628
+ try {
1629
+ if (asImage) {
1630
+ const ref = await store.saveImage(name === undefined ? { data, mediaType } : { data, mediaType, name })
1631
+ return { type: 'image', attachment: ref }
1632
+ }
1633
+ if (typeof store.saveFile !== 'function') {
1634
+ throw new HttpError(400, 'attachment-refused', 'this deployment can only store images')
1635
+ }
1636
+ const ref = await store.saveFile(name === undefined ? { data } : { data, name })
1637
+ return { type: 'file', attachment: ref }
1638
+ } catch (error) {
1639
+ if (error instanceof HttpError) throw error
1640
+ // The store's own refusal (too many images, wrong bytes, an unwritable
1641
+ // root) is reported as-is and NOTHING is written: admission runs before the
1642
+ // first append, so a refused upload can never leave a half-built carrier.
1643
+ const detail = String((error && error.message) || error)
1644
+ throw new HttpError(400, 'attachment-refused', detail)
1645
+ }
1646
+ }
1647
+
1648
+ /**
1649
+ * The bytes of one block's attachment, for a chip's thumbnail.
1650
+ *
1651
+ * A display-only read, deliberately kept out of the edit path. It answers from
1652
+ * whatever read seam the mounted store offers - an image reader, or the host
1653
+ * path of a verbatim file - and gives up quietly when neither exists, because a
1654
+ * chip without a picture is still a usable chip. The block is located by the
1655
+ * seq of the message and its index inside that message's content, and the only
1656
+ * authorization is that the session's own log really does cite it: the same bar
1657
+ * the platform's attachment RPC applies before handing bytes over.
1658
+ *
1659
+ * @param ctx - plugin context.
1660
+ * @param sessionId - the session whose log owns the block.
1661
+ * @param seq - seq of the message event.
1662
+ * @param index - the block's index in that message's content.
1663
+ * @returns `{ data, mediaType }`, or null when there is nothing to serve.
1664
+ */
1665
+ export async function attachmentBytes(ctx, sessionId, seq, index) {
1666
+ const events = await readEvents(ctx, sessionId)
1667
+ if (!events) return null
1668
+ const event = events.find((item) => item && item.seq === seq)
1669
+ if (!event) return null
1670
+ const block = readMessageBlocks(event)[index]
1671
+ if (!block || typeof block !== 'object') return null
1672
+ const ref = block.attachment
1673
+ if (!ref || typeof ref !== 'object' || typeof ref.attachmentId !== 'string' || ref.attachmentId === '') return null
1674
+ if (typeof ref.bytes === 'number' && ref.bytes > MAX_PREVIEW_BYTES) return null
1675
+ const store = resolveAttachmentStore(ctx)
1676
+ if (store === null) return null
1677
+ if (typeof store.readImage === 'function') {
1678
+ try {
1679
+ const stored = await store.readImage(ref)
1680
+ if (stored && stored.data) {
1681
+ const mediaType = stored.ref && typeof stored.ref.mediaType === 'string' ? stored.ref.mediaType : ref.mediaType
1682
+ return { data: Buffer.from(stored.data), mediaType: typeof mediaType === 'string' ? mediaType : undefined }
1683
+ }
1684
+ } catch {
1685
+ // Not an image reference; a stored file is read below.
1686
+ }
1687
+ }
1688
+ if (typeof store.fileHostPath === 'function') {
1689
+ try {
1690
+ const path = store.fileHostPath(ref)
1691
+ if (typeof path === 'string' && path !== '') return { data: await readFile(path), mediaType: undefined }
1692
+ } catch {
1693
+ // The reference resolves to nothing this deployment can serve.
1694
+ }
1695
+ }
1696
+ return null
1697
+ }
1698
+
1699
+ // --- operations --------------------------------------------------------------
1700
+
1701
+ async function stateOf(ctx, sessionId, config) {
1702
+ const events = await readEvents(ctx, sessionId)
1703
+ if (!events) {
1704
+ // A named session with nothing in it yet is an EMPTY session, not a failed
1705
+ // one: the editor opens with nothing to edit, and the next refresh picks the
1706
+ // log up once it exists. Answering 404 here is what the panel printed as
1707
+ // "状态加载失败,稍后重试。". The capability probe still runs, because "what
1708
+ // can this deployment do" does not depend on the log.
1709
+ noteRequest({ kind: 'state', sessionId, ok: true, code: 'session-empty' })
1710
+ const store = resolveAttachmentStore(ctx)
1711
+ return {
1712
+ hidden: [],
1713
+ edits: 0,
1714
+ revisions: [],
1715
+ surface: [],
1716
+ turns: [],
1717
+ replies: [],
1718
+ patches: [],
1719
+ mode: config.patch === true ? 'patch' : 'replay',
1720
+ live: false,
1721
+ busy: false,
1722
+ lastSeq: -1,
1723
+ capabilities: { attachments: store !== null, preview: canPreviewAttachments(store) },
1724
+ config: {
1725
+ confirm: config.confirm,
1726
+ replyMode: config.replyMode,
1727
+ patch: config.patch === true,
1728
+ editorStyle: config.editorStyle,
1729
+ },
1730
+ version: PLUGIN_VERSION,
1731
+ }
1732
+ }
1733
+ const folded = foldSurface(events)
1734
+ const ledger = rollbackLedger(events)
1735
+ const patches = patchesOf(events)
1736
+ // A patch whose target has been retired (a later rerun shadowed it) is inert:
1737
+ // the projection skips it and no row can show it. Reporting it in /state made
1738
+ // the browser draw a patch that could never land, and made "which patches are
1739
+ // live" ambiguous. Keep the internal map for the replies; publish the active
1740
+ // subset only.
1741
+ const surfaceSet = new Set(folded.nodes)
1742
+ const activePatches = new Map([...patches].filter(([seq]) => surfaceSet.has(seq)))
1743
+ const live = findLiveSession(ctx, sessionId)
1744
+ // Probed per request: the editor offers what THIS deployment can do right
1745
+ // now, so a store that is unmounted (or not yet mounted) cannot leave the
1746
+ // editor promising to keep blocks the host would have to drop.
1747
+ const store = resolveAttachmentStore(ctx)
1748
+ const turns = editableTurns(events, folded.nodes, { preview: canPreviewAttachments(store) })
1749
+ const replies = editableReplies(events, folded.nodes, { patches, patch: config.patch === true })
1750
+ noteRequest({
1751
+ kind: 'state',
1752
+ sessionId,
1753
+ ok: true,
1754
+ events: events.length,
1755
+ turns: turns.length,
1756
+ replies: replies.length,
1757
+ hidden: ledger.hidden.length,
1758
+ live: Boolean(live),
1759
+ })
1760
+ return {
1761
+ hidden: ledger.hidden,
1762
+ edits: ledger.edits.length,
1763
+ // The window record behind every hidden entry, with the same field names the
1764
+ // apply response uses (`replacementSeq`, `shadowed`, plus the window bounds).
1765
+ // Published so a sibling plugin can follow a rewritten message to its live
1766
+ // node without re-deriving the ledger from the log itself.
1767
+ revisions: ledger.edits,
1768
+ surface: folded.nodes,
1769
+ turns,
1770
+ replies,
1771
+ // The landed in-place patches, latest per block. The browser half uses them
1772
+ // to draw the projected text in place of the recorded one; the model already
1773
+ // sees them through the host projection.
1774
+ patches: patchList(activePatches),
1775
+ mode: config.patch === true ? 'patch' : 'replay',
1776
+ live: Boolean(live),
1777
+ busy: isBusy(events),
1778
+ lastSeq: events.length > 0 ? events[events.length - 1].seq : -1,
1779
+ // What this deployment can do with a block list. `attachments` is the
1780
+ // admission path (a chip the editor may keep) and `preview` is the read
1781
+ // path (a chip that may draw its own thumbnail); both are answered from a
1782
+ // live service probe, so the editor never promises what the host cannot do.
1783
+ capabilities: { attachments: store !== null, preview: canPreviewAttachments(store) },
1784
+ config: {
1785
+ confirm: config.confirm,
1786
+ replyMode: config.replyMode,
1787
+ patch: config.patch === true,
1788
+ editorStyle: config.editorStyle,
1789
+ },
1790
+ version: PLUGIN_VERSION,
1791
+ }
1792
+ }
1793
+
1794
+ /**
1795
+ * Build the event that carries one rollback replacement.
1796
+ *
1797
+ * @param plan - the planned window.
1798
+ * @param lastTurn - highest turn number in the log, for a coherent bracket.
1799
+ * @param config - resolved deployment policy.
1800
+ * @param content - the block list the revised prompt carries. Omitted, the
1801
+ * carrier falls back to the marker text alone, which is what every caller
1802
+ * that predates block-preserving edits (and the silent developer carrier)
1803
+ * still asks for.
1804
+ * @returns `{ type, data }` for `session.append`.
1805
+ */
1806
+ export function buildCarrier(plan, lastTurn, config, content) {
1807
+ const silent = config.carrier !== 'user/message'
1808
+ if (silent) {
1809
+ // The silent carrier is an empty message that projects to no model message.
1810
+ // It has to be a `developer/message`: the format admits only system-prompt
1811
+ // sources on `system/message`, so an empty plugin-owned system node (what
1812
+ // this used to append) made every session that contained one unreadable -
1813
+ // `SessionFormatError` on load, after a perfectly accepted append. An empty
1814
+ // developer message is legal, dormant, and a replacement never gets a row
1815
+ // of its own (rows are built for append events only), so it is invisible in
1816
+ // the transcript too.
1817
+ return {
1818
+ type: 'developer/message',
1819
+ data: {
1820
+ turn: typeof lastTurn === 'number' ? lastTurn : 0,
1821
+ step: 1,
1822
+ message: {
1823
+ id: randomUUID(),
1824
+ role: 'developer',
1825
+ content: [],
1826
+ source: { kind: `plugin:${PLUGIN_ID}`, editedBy: PLUGIN_ID },
1827
+ },
1828
+ },
1829
+ }
1830
+ }
1831
+ return {
1832
+ type: 'user/message',
1833
+ data: {
1834
+ id: randomUUID(),
1835
+ role: 'user',
1836
+ content: Array.isArray(content) && content.length > 0 ? content : [{ type: 'text', text: config.markerText }],
1837
+ // `kind: 'user'`, NOT a plugin-owned kind. This carrier stands in a human's
1838
+ // place - it IS the wording the user is asking with now - and the platform
1839
+ // owns that judgement: a human prompt is exactly a `user/message` whose
1840
+ // `source.kind` is `'user'`. Writing anything else here made the turn's
1841
+ // prompt unrecognisable to every consumer that tests it -
1842
+ // `dsh-session-turn-outline` (the turn rail and the Trajectory view),
1843
+ // `dsh-client-ui-trajectory`, `dsh-client-ui-chat`, the inbox steering
1844
+ // filter, and `lastPromptAt` on the session list - so an edited turn
1845
+ // showed no prompt at all and `turnOutline` reported `prompt: ""`. The
1846
+ // format's producer-owned kind (`plugin:<id>`) is for messages a plugin
1847
+ // authors in its own voice; a prompt it merely rewrote is not one.
1848
+ // `editedBy` below carries the provenance that `kind` used to.
1849
+ source: { kind: 'user', editedBy: PLUGIN_ID },
1850
+ },
1851
+ }
1852
+ }
1853
+
1854
+ /**
1855
+ * The new assistant message that carries an edited reply.
1856
+ *
1857
+ * A reply cannot be swapped in place - the validator refuses `sourceEventSeqs`
1858
+ * on an `assistant/message` - so the correction is appended as a fresh reply.
1859
+ * `turn`/`step` are always set because the client keys a reply node by
1860
+ * `turn:step`; leaving them out would make two corrections collide.
1861
+ *
1862
+ * `source.kind` stays `model` so the entry renders and projects exactly like an
1863
+ * ordinary reply, while `editedBy` records honestly that the text was written by
1864
+ * the plugin and not produced by the model.
1865
+ *
1866
+ * @param plan - the planned window, for the original's provider/model.
1867
+ * @param text - the replacement text.
1868
+ * @param turn - the turn the correction lands in (the freshly opened one).
1869
+ * @param step - the step the correction lands in.
1870
+ * @returns `{ type, data }` for `session.append`, to be marked `surfaceOp: 'append'`.
1871
+ */
1872
+ export function buildCorrection(plan, text, turn, step) {
1873
+ const source = { kind: 'model', editedBy: PLUGIN_ID }
1874
+ if (typeof plan.provider === 'string' && plan.provider !== '') source.provider = plan.provider
1875
+ if (typeof plan.model === 'string' && plan.model !== '') source.model = plan.model
1876
+ return {
1877
+ type: 'assistant/message',
1878
+ data: {
1879
+ turn: typeof turn === 'number' ? turn : 0,
1880
+ step: typeof step === 'number' ? step : 1,
1881
+ message: {
1882
+ id: randomUUID(),
1883
+ role: 'assistant',
1884
+ content: [{ type: 'text', text }],
1885
+ source,
1886
+ },
1887
+ stream: [],
1888
+ },
1889
+ }
1890
+ }
1891
+
1892
+ /**
1893
+ * The all-blocks save: one plugin record carrying a target per edited block,
1894
+ * possibly across several messages of the same turn. Each target is planned
1895
+ * exactly like a single-block save, and unchanged blocks are simply left out.
1896
+ *
1897
+ * @param ctx - cordis context.
1898
+ * @param sessionId - the addressed session.
1899
+ * @param body - `{ targets: [{ seq, blockIndex, kind, text }] }`.
1900
+ * @param config - plugin config.
1901
+ * @returns the same shape `/apply` returns for a reply patch.
1902
+ */
1903
+ async function applyTargetsEdit(ctx, sessionId, body, config) {
1904
+ const targets = Array.isArray(body.targets) ? body.targets : []
1905
+ if (targets.length === 0 || targets.length > MAX_PARTS) {
1906
+ throw new HttpError(400, 'invalid', 'targets must be a nonempty, bounded array')
1907
+ }
1908
+ for (const target of targets) {
1909
+ if (target === null || typeof target !== 'object') throw new HttpError(400, 'invalid', 'each target must be an object')
1910
+ if (typeof target.text !== 'string' || target.text.trim() === '') throw new HttpError(400, 'invalid', 'an edited block cannot be empty')
1911
+ if (target.text.length > MAX_TEXT) throw new HttpError(400, 'invalid', 'the revised block is too long')
1912
+ }
1913
+ const session = await resolveSession(ctx, sessionId)
1914
+ if (!session || typeof session.append !== 'function') {
1915
+ throw new HttpError(409, 'session-not-active', 'the session is not open in DSH')
1916
+ }
1917
+ const events = await readEvents(ctx, sessionId)
1918
+ if (!events) throw new HttpError(404, 'session-not-found', 'no session log for this id')
1919
+ // No busy gate here: this path only appends the in-place patch record, which
1920
+ // leaves every surface node where it is. A running turn keeps writing its own
1921
+ // events; the record lands between them and the fold ignores it.
1922
+ const surfaceNodes = surfaceOf(ctx, sessionId, events)
1923
+ const patches = patchesOf(events)
1924
+ const plans = []
1925
+ for (const target of targets) {
1926
+ let plan
1927
+ try {
1928
+ plan = planRollback(events, surfaceNodes, { seq: target.seq, blockIndex: target.blockIndex, kind: target.kind }, { patches, patch: config.patch === true })
1929
+ } catch (error) {
1930
+ if (error instanceof EditPlanError) {
1931
+ const status = error.code === 'not-editable' ? 400 : 409
1932
+ throw new HttpError(status, error.code, error.message)
1933
+ }
1934
+ throw error
1935
+ }
1936
+ if (plan.patch !== true) throw new HttpError(400, 'not-editable', 'all-blocks editing needs the in-place reply path')
1937
+ if (target.text !== plan.original) plans.push({ plan, text: target.text })
1938
+ }
1939
+ if (plans.length === 0) {
1940
+ return { kind: 'reply', applied: false, unchanged: true, patch: true, shadowed: [], targets: [] }
1941
+ }
1942
+ if (typeof sessionApi.appendPluginRecord !== 'function') {
1943
+ throw new HttpError(409, 'unsupported', 'this harness does not expose plugin records; reply edits need the replay path')
1944
+ }
1945
+ let recordSeq
1946
+ try {
1947
+ recordSeq = sessionApi.appendPluginRecord(
1948
+ session,
1949
+ PATCH_TYPE,
1950
+ buildPatchData(plans.map(({ plan, text }) => ({ seq: plan.targetSeq, blockIndex: plan.blockIndex, kind: plan.kind, text }))),
1951
+ )
1952
+ } catch (error) {
1953
+ const message = String((error && error.message) || error)
1954
+ if (isProjectionUnavailable(message)) {
1955
+ throw new HttpError(409, 'projection-missing', 'the edit-turn projection is not registered for this session; restart DSH so the owning plugin registers it, then retry')
1956
+ }
1957
+ throw new HttpError(409, 'stale', `the session refused the patch record: ${message}`)
1958
+ }
1959
+ const flush = await flushSession(ctx, session)
1960
+ return {
1961
+ kind: 'reply',
1962
+ applied: true,
1963
+ mode: 'patch',
1964
+ patch: true,
1965
+ recordSeq,
1966
+ targets: plans.map(({ plan, text }) => ({ seq: plan.targetSeq, blockIndex: plan.blockIndex, kind: plan.kind, text, original: plan.original })),
1967
+ shadowed: [],
1968
+ ...flush,
1969
+ }
1970
+ }
1971
+
1972
+ async function applyEdit(ctx, sessionId, body, config) {
1973
+ if (Array.isArray(body.targets) && body.targets.length > 0) return applyTargetsEdit(ctx, sessionId, body, config)
1974
+ const text = typeof body.text === 'string' ? body.text : ''
1975
+ if (text.trim() === '') throw new HttpError(400, 'invalid', 'the revised message cannot be empty')
1976
+ if (text.length > MAX_TEXT) throw new HttpError(400, 'invalid', 'the revised message is too long')
1977
+
1978
+ const session = await resolveSession(ctx, sessionId)
1979
+ if (!session || typeof session.append !== 'function') {
1980
+ throw new HttpError(409, 'session-not-active', 'the session is not open in DSH')
1981
+ }
1982
+ const events = await readEvents(ctx, sessionId)
1983
+ if (!events) throw new HttpError(404, 'session-not-found', 'no session log for this id')
1984
+ const busy = isBusy(events)
1985
+
1986
+ const surfaceNodes = surfaceOf(ctx, sessionId, events)
1987
+ const patches = patchesOf(events)
1988
+ const patchMode = config.patch === true
1989
+ const request = {
1990
+ // A block from another step of the same turn names its own seq; that is
1991
+ // the message the projection has to patch.
1992
+ seq: typeof body.targetSeq === 'number' ? body.targetSeq : typeof body.seq === 'number' ? body.seq : undefined,
1993
+ messageId: typeof body.messageId === 'string' ? body.messageId : undefined,
1994
+ turn: typeof body.turn === 'number' ? body.turn : undefined,
1995
+ blockIndex: typeof body.blockIndex === 'number' ? body.blockIndex : undefined,
1996
+ kind: typeof body.kind === 'string' ? body.kind : undefined,
1997
+ }
1998
+ let plan
1999
+ try {
2000
+ plan = planRollback(events, surfaceNodes, request, { patches, patch: patchMode })
2001
+ } catch (error) {
2002
+ if (error instanceof EditPlanError) {
2003
+ const status = error.code === 'not-editable' ? 400 : 409
2004
+ throw new HttpError(status, error.code, error.message)
2005
+ }
2006
+ throw error
2007
+ }
2008
+
2009
+ // A running turn is a hard stop for every path that moves the surface: the
2010
+ // prompt rewrite shadows a message the turn may still be reading, and the
2011
+ // replay splice shadows a window and regenerates the tail. The in-place record
2012
+ // below moves nothing, so it is allowed to land while the agent is still
2013
+ // writing - the model reads it on its next fold.
2014
+ if (busy && plan.patch !== true) throw new HttpError(409, 'busy', 'the session is still working')
2015
+
2016
+ // The in-place reply path: one small plugin record, interpreted by this
2017
+ // plugin's projection. Nothing leaves the surface, so there is no window to
2018
+ // check, no turn to open and no tail to replay. The record is append-only and
2019
+ // the original event keeps its bytes; the model sees the patched block on the
2020
+ // next fold.
2021
+ if (plan.patch === true) {
2022
+ if (typeof sessionApi.appendPluginRecord !== 'function') {
2023
+ throw new HttpError(409, 'unsupported', 'this harness does not expose plugin records; reply edits need the replay path')
2024
+ }
2025
+ if (text === plan.original) {
2026
+ return {
2027
+ kind: 'reply',
2028
+ applied: false,
2029
+ unchanged: true,
2030
+ patch: true,
2031
+ shadowed: [],
2032
+ blockIndex: plan.blockIndex,
2033
+ kindOfBlock: plan.kind,
2034
+ original: plan.original,
2035
+ }
2036
+ }
2037
+ let recordSeq
2038
+ try {
2039
+ recordSeq = sessionApi.appendPluginRecord(
2040
+ session,
2041
+ PATCH_TYPE,
2042
+ buildPatchData([{ seq: plan.targetSeq, blockIndex: plan.blockIndex, kind: plan.kind, text }]),
2043
+ )
2044
+ } catch (error) {
2045
+ const message = String((error && error.message) || error)
2046
+ // The projection is not registered for this session (a live reload that
2047
+ // dropped it). The same edit can land through the replay path, which
2048
+ // needs no projection - so fall through instead of failing the save.
2049
+ if (isProjectionUnavailable(message)) {
2050
+ // The fallback replays the tail, which a running turn forbids.
2051
+ if (busy) throw new HttpError(409, 'busy', 'the session is still working')
2052
+ plan = planRollback(events, surfaceNodes, request, { patches, patch: false })
2053
+ } else {
2054
+ throw new HttpError(409, 'stale', `the session refused the patch record: ${message}`)
2055
+ }
2056
+ }
2057
+ if (plan.patch === true) {
2058
+ const flush = await flushSession(ctx, session)
2059
+ return {
2060
+ kind: 'reply',
2061
+ applied: true,
2062
+ mode: 'patch',
2063
+ patch: true,
2064
+ recordSeq,
2065
+ target: {
2066
+ seq: plan.targetSeq,
2067
+ blockIndex: plan.blockIndex,
2068
+ kind: plan.kind,
2069
+ text,
2070
+ original: plan.original,
2071
+ },
2072
+ shadowed: [],
2073
+ ...flush,
2074
+ }
2075
+ }
2076
+ }
2077
+
2078
+ // The live surface is the append authority; a node that vanished between the
2079
+ // read and this check means another writer landed first.
2080
+ for (const seq of plan.shadowed) {
2081
+ if (!surfaceNodes.includes(seq)) throw new HttpError(409, 'stale', 'the session changed, retry')
2082
+ }
2083
+
2084
+ // The submitted block list, when the browser half sent one: which of the
2085
+ // message's blocks the user kept, in order, plus anything they just picked.
2086
+ // A caller that sends `text` only is a client from before blocks travelled -
2087
+ // a supported caller, not a broken one: it gets exactly the text-only carrier
2088
+ // this plugin has always written, and the answer says what that cost.
2089
+ let parts = plan.mode === 'prompt' && Array.isArray(body.parts) ? normalizeParts(body.parts, plan.blocks.length) : null
2090
+ let layout = parts === null ? null : planBlockLayout(plan.blocks, parts)
2091
+ // What this deployment can admit, probed NOW rather than remembered: with no
2092
+ // store mounted, nothing can be uploaded and no block may be promised, so the
2093
+ // edit degrades to the text-only carrier - the exact behaviour every release
2094
+ // before this one had - and the answer reports the blocks it had to leave
2095
+ // behind instead of writing a reference nothing can resolve.
2096
+ const store = plan.mode === 'prompt' ? resolveAttachmentStore(ctx) : null
2097
+ if (layout !== null && store === null) {
2098
+ parts = null
2099
+ layout = null
2100
+ }
2101
+
2102
+ // Nothing to write when the revision changes nothing.
2103
+ //
2104
+ // The editor opens prefilled with exactly this text - it comes from
2105
+ // `readMessageText`, the same parse behind `/state`'s `turns[].text` and
2106
+ // `replies[].text` - so "open the editor and save without typing" arrives here
2107
+ // as an exact string match. It must not write: every write is a replacement
2108
+ // event (and, for a reply, a synthetic turn plus a fresh answer), so an
2109
+ // unchanged save used to add a revision with no revision behind it and a whole
2110
+ // turn to the rail while the conversation had not moved at all.
2111
+ //
2112
+ // Since blocks travel, the same question is asked of the whole message: the
2113
+ // carrier is rebuilt from the submitted list and compared against the original
2114
+ // block for block (see sameJson), so a save that keeps every block where it was
2115
+ // writes nothing either. A caller that sends text only keeps the original,
2116
+ // narrower test - its carrier IS text-only by construction, and comparing that
2117
+ // against a message with a picture in it would turn "I changed nothing" into a
2118
+ // write that drops the picture.
2119
+ //
2120
+ // Compared verbatim, deliberately, which is the same caliber the editor was
2121
+ // filled with: a trailing space is a real difference and keeps the old
2122
+ // behaviour, and nothing here trims (the only trim in this function is the
2123
+ // emptiness check above, which is about validity, not equality).
2124
+ //
2125
+ // The answer is a FLAG, not a refusal: the editor's "re-run" button saves
2126
+ // first and re-runs regardless, and its whole point is that the user wants the
2127
+ // turn regenerated even when the wording is what it already was. So the caller
2128
+ // decides what happens next, and this returns before anything is appended.
2129
+ const keepsEveryBlock = parts !== null && layout !== null && layout.added === 0 &&
2130
+ sameJson(assembleBlocks(plan.blocks, layout, [], text), plan.blocks)
2131
+ if (text === plan.original && (parts === null || keepsEveryBlock)) {
2132
+ return {
2133
+ kind: plan.mode,
2134
+ applied: false,
2135
+ unchanged: true,
2136
+ // Nothing left the surface, so nothing is shadowed: the caller must not
2137
+ // hide a row on account of this answer.
2138
+ shadowed: [],
2139
+ original: plan.original,
2140
+ // Nothing was written, so nothing was left behind either - and the
2141
+ // message's blocks are the ones it already had.
2142
+ dropped: false,
2143
+ blocks: blockSummaries(plan.blocks, canPreviewAttachments(store)),
2144
+ }
2145
+ }
2146
+
2147
+ // Admission happens here, BEFORE the first append and outside the try blocks
2148
+ // below: a refused upload must not be able to leave a rollback (or a synthetic
2149
+ // turn) behind in the log. The blocks come back in slot order, which is the
2150
+ // order the layout put them in.
2151
+ const admitted = []
2152
+ if (layout !== null) {
2153
+ for (const slot of layout.slots) {
2154
+ if (slot.kind === 'add') admitted.push(await admitUpload(store, slot.upload))
2155
+ }
2156
+ }
2157
+ const content = layout === null ? [{ type: 'text', text }] : assembleBlocks(plan.blocks, layout, admitted, text)
2158
+ // Whether this save left non-text blocks behind, told to the caller instead of
2159
+ // being discovered later: true for a reply (its tool calls and reasoning
2160
+ // cannot survive a replacement) and true for a message rewritten without its
2161
+ // blocks. False whenever the carrier really did carry them.
2162
+ const dropped = layout === null && plan.blocks.some((block) => !isTextBlock(block))
2163
+
2164
+ // A revised prompt has to (a) replace the old wording in the model context and
2165
+ // (b) NOT be answered. The platform answers any user message it finds on the
2166
+ // surface, so the revision cannot be *appended* - appending one made the loop
2167
+ // answer it, and the next save added another copy (three "你好" bubbles). It
2168
+ // travels as the rollback's replacement instead: a replace-type carrier, which
2169
+ // removes the old prompt and stands in its place, in one event.
2170
+ // A reply edit needs somewhere to land: `assistant/message` (and any message
2171
+ // with a step coordinate) is only readable inside an OPEN turn and step, and
2172
+ // opening one in the log is what advances the runtime's own turn counter too
2173
+ // (it projects `lastTurn` from every turn/start it observes). A prompt edit
2174
+ // does not: `user/message` carries the revision and needs no turn.
2175
+ const editTurn = plan.mode === 'reply' ? nextTurnOf(events) : lastTurnOf(events)
2176
+ // One identity for the whole reply splice: every copy the replay appends
2177
+ // carries it, so a later reader (or a sibling plugin) can tell a replayed turn
2178
+ // from the one it retired without re-deriving anything.
2179
+ const replayId = plan.mode === 'reply' ? randomUUID() : null
2180
+ // Resolved BEFORE the appends so the loop counter can be re-pointed in the
2181
+ // same tick as the writes, not after an await that lets the loop start.
2182
+ const loopAgent = plan.mode === 'reply' ? await resolveLoopAgent(ctx, sessionId) : undefined
2183
+ const carrier = buildCarrier(plan, editTurn, plan.mode === 'prompt' ? { ...config, carrier: 'user/message', markerText: text } : config, content)
2184
+ if (plan.mode === 'reply') {
2185
+ try {
2186
+ session.append('turn/start', { turn: editTurn })
2187
+ session.append('step/start', { turn: editTurn, step: 1 })
2188
+ } catch (error) {
2189
+ return {
2190
+ kind: 'reply',
2191
+ applied: false,
2192
+ applyError: `could not open a turn for the correction: ${String((error && error.message) || error)}`,
2193
+ shadowed: plan.shadowed,
2194
+ dropped,
2195
+ }
2196
+ }
2197
+ }
2198
+ let replacement
2199
+ try {
2200
+ // A replacement carrier has to be a surface event with non-empty
2201
+ // `sourceEventSeqs` coverage of the whole shadowed window. An assistant
2202
+ // message forbids `sourceEventSeqs` outright, so the carrier is either an
2203
+ // empty `developer/message` (default: dormant, invisible to the model, and
2204
+ // never given a row of its own because rows are built for appends) or a
2205
+ // short `user/message` marker.
2206
+ replacement = session.append(carrier.type, carrier.data, {
2207
+ surfaceOp: { op: 'replace', startSeq: plan.startSeq, endSeq: plan.endSeq },
2208
+ sourceEventSeqs: plan.shadowed,
2209
+ })
2210
+ } catch (error) {
2211
+ throw new HttpError(409, 'stale', `the surface refused the rollback: ${String((error && error.message) || error)}`)
2212
+ }
2213
+
2214
+ // A prompt edit saved here: the carrier that replaced the window IS the
2215
+ // revised prompt, so the model reads it as the user's wording from here on.
2216
+ // Nothing is prompted and nothing else needs writing.
2217
+ if (plan.mode === 'prompt') {
2218
+ const flush = await flushSession(ctx, session)
2219
+ return {
2220
+ kind: 'prompt',
2221
+ replacementSeq: replacement.seq,
2222
+ applied: true,
2223
+ shadowed: plan.shadowed,
2224
+ dropped,
2225
+ // What the carrier now carries, described exactly the way /state describes
2226
+ // it. The browser half adopts this for the row it re-draws before its own
2227
+ // refresh lands - without it a second save could not know which blocks are
2228
+ // still there and would rewrite the message text-only.
2229
+ blocks: blockSummaries(content, canPreviewAttachments(store)),
2230
+ ...flush,
2231
+ }
2232
+ }
2233
+
2234
+ // Step two of a reply edit: the correction itself, inside the turn just
2235
+ // opened. An `assistant/message` may never carry `sourceEventSeqs`, so it can
2236
+ // never be a replacement carrier (checked against the real validator, not
2237
+ // assumed); it is appended in the same shape the agent loop records a reply,
2238
+ // and the model goes on seeing the edited text as its own answer.
2239
+ const correction = buildCorrection(plan, text, editTurn, 1)
2240
+ let appended
2241
+ try {
2242
+ appended = session.append(correction.type, correction.data, { surfaceOp: 'append' })
2243
+ // Close the step and the turn behind the corrected reply: the host anchors
2244
+ // a turn's tail (duration, action strip) at its last `turn/end`, and the
2245
+ // format only reads a step message inside an open turn and step.
2246
+ session.append('step/end', { turn: editTurn, step: 1 })
2247
+ session.append('turn/end', { turn: editTurn, reason: { kind: 'completed' } })
2248
+ } catch (error) {
2249
+ const failedFlush = await flushSession(ctx, session)
2250
+ return {
2251
+ kind: 'reply',
2252
+ replacementSeq: replacement.seq,
2253
+ applied: false,
2254
+ applyError: `the corrected reply was refused: ${String((error && error.message) || error)}`,
2255
+ shadowed: plan.shadowed,
2256
+ dropped,
2257
+ ...failedFlush,
2258
+ }
2259
+ }
2260
+
2261
+ // Step three: put every later turn back behind the correction, as fresh
2262
+ // copies. This is the same infix splice dsh-rerun-turn performs after a
2263
+ // regenerated answer - shadow the tail, write the new reply, replay what
2264
+ // followed - with the user's text taking the place of the model call.
2265
+ let replay = null
2266
+ if (typeof plan.replayFrom === 'number' && typeof plan.logTo === 'number') {
2267
+ const writes = buildReplayWrites(events, plan, editTurn + 1, replayId, session.seq)
2268
+ let replayed = 0
2269
+ let replayError = null
2270
+ try {
2271
+ for (const write of writes) {
2272
+ const options = {}
2273
+ if (write.surfaceOp !== undefined) options.surfaceOp = write.surfaceOp
2274
+ if (write.sourceEventSeqs !== undefined) options.sourceEventSeqs = write.sourceEventSeqs
2275
+ session.append(write.type, write.data, options)
2276
+ replayed += 1
2277
+ }
2278
+ } catch (error) {
2279
+ replayError = String((error && error.message) || error)
2280
+ }
2281
+ const playedMax = writes.reduce((max, write) => {
2282
+ const turn = write.data && typeof write.data.turn === 'number' ? write.data.turn : 0
2283
+ return turn > max ? turn : max
2284
+ }, 0)
2285
+ replay = {
2286
+ id: replayId,
2287
+ replayed,
2288
+ total: writes.length,
2289
+ turns: writes.reduce((count, write) => count + (write.type === 'turn/start' ? 1 : 0), 0),
2290
+ ...(replayError === null ? {} : { error: replayError }),
2291
+ }
2292
+ // The replayed turns are closed in the log but were never opened by the
2293
+ // live loop: re-point its idle counter at the highest one, synchronously.
2294
+ const loopTurn = syncLoopTurn(loopAgent, playedMax > editTurn ? playedMax : editTurn)
2295
+ if (loopTurn === 'unavailable') {
2296
+ noteRequest({ kind: 'reply', sessionId, ok: replayError === null, loopTurn, turn: editTurn, replayId, replayed })
2297
+ }
2298
+ const corrected = await flushSession(ctx, session)
2299
+ return {
2300
+ kind: 'reply',
2301
+ replacementSeq: replacement.seq,
2302
+ appendedSeq: appended.seq,
2303
+ applied: true,
2304
+ loopTurn,
2305
+ replay,
2306
+ shadowed: plan.shadowed,
2307
+ dropped,
2308
+ ...corrected,
2309
+ }
2310
+ }
2311
+
2312
+ // No later turn to replay: the correction is the last answer in the log.
2313
+ // The synthetic turn still moved the loop's counter; sync it the same way.
2314
+ const loopTurn = syncLoopTurn(loopAgent, editTurn)
2315
+ if (loopTurn === 'unavailable') {
2316
+ noteRequest({ kind: 'reply', sessionId, ok: true, loopTurn, turn: editTurn, replayId })
2317
+ }
2318
+ const corrected = await flushSession(ctx, session)
2319
+ return {
2320
+ kind: 'reply',
2321
+ replacementSeq: replacement.seq,
2322
+ appendedSeq: appended.seq,
2323
+ applied: true,
2324
+ loopTurn,
2325
+ replay: null,
2326
+ shadowed: plan.shadowed,
2327
+ dropped,
2328
+ ...corrected,
2329
+ }
2330
+ }
2331
+
2332
+ // --- tool --------------------------------------------------------------------
2333
+
2334
+ /**
2335
+ * Session id the calling agent runs in, when the tool context exposes one.
2336
+ * @param exec - tool execution context.
2337
+ * @returns the session id, or undefined when the caller has no agent.
2338
+ */
2339
+ function sessionIdFromExec(exec) {
2340
+ const agent = exec && exec.agent
2341
+ const session = agent && agent.session
2342
+ if (session && typeof session.id === 'string' && session.id !== '') return session.id
2343
+ if (agent && typeof agent.sessionId === 'string' && agent.sessionId !== '') return agent.sessionId
2344
+ if (exec && typeof exec.sessionId === 'string' && exec.sessionId !== '') return exec.sessionId
2345
+ return undefined
2346
+ }
2347
+
2348
+ function registerTool(ctx, config) {
2349
+ const tools = ctx.get('tools')
2350
+ if (!tools || typeof tools.register !== 'function') return
2351
+ tools.register(
2352
+ defineTool({
2353
+ name: 'edit_turn_targets',
2354
+ description:
2355
+ 'List the user turns and model replies of a DeepSeek Harness session that the edit-turn plugin can rewrite, with each message\'s current text and, for a reply, every editable block (output text and reasoning). A prompt is replaced where it stands; a reply block is patched in place when the host supports projections, otherwise the reply correction is appended and the later turns are replayed behind it. Read-only: it changes nothing.',
2356
+ parameters: {
2357
+ sessionId: {
2358
+ type: 'string',
2359
+ description: 'Session id to inspect. Defaults to the session this agent is running in.',
2360
+ },
2361
+ limit: { type: 'number', description: 'Maximum number of turns to return (default 20).' },
2362
+ },
2363
+ output: {
2364
+ schema: { type: 'string' },
2365
+ render: (_args, value) => [{ type: 'text', text: value }],
2366
+ },
2367
+ async execute(args, exec) {
2368
+ const sessionId = typeof args.sessionId === 'string' && args.sessionId !== '' ? args.sessionId : sessionIdFromExec(exec)
2369
+ if (sessionId === undefined) {
2370
+ throw new Error('no sessionId was supplied and the calling agent has no session')
2371
+ }
2372
+ const events = await readEvents(ctx, sessionId)
2373
+ if (!events) throw new Error(`no session log for ${sessionId}`)
2374
+ const nodes = surfaceOf(ctx, sessionId, events)
2375
+ const patches = patchesOf(events)
2376
+ const turns = editableTurns(events, nodes)
2377
+ const replies = editableReplies(events, nodes, { patches, patch: config && config.patch === true })
2378
+ const limit = typeof args.limit === 'number' && args.limit > 0 ? Math.floor(args.limit) : 20
2379
+ const shown = turns.slice(-limit)
2380
+ const shownReplies = replies.slice(-limit)
2381
+ const lines = [
2382
+ `session ${sessionId}: ${turns.length} editable turn(s), ${replies.length} editable reply/replies, ${isBusy(events) ? 'BUSY' : 'idle'}`,
2383
+ ]
2384
+ for (const turn of shown) {
2385
+ const preview = turn.text.length > 160 ? `${turn.text.slice(0, 160)}...` : turn.text
2386
+ lines.push(`- turn ${turn.turn} (seq ${turn.seq}, ${turn.attachments} attachment(s)): ${preview}`)
2387
+ }
2388
+ if (turns.length > shown.length) lines.push(`(${turns.length - shown.length} earlier turn(s) omitted)`)
2389
+ for (const reply of shownReplies) {
2390
+ const preview = reply.text.length > 160 ? `${reply.text.slice(0, 160)}...` : reply.text
2391
+ const blocks = Array.isArray(reply.blocks)
2392
+ ? ` [${reply.blocks.map((block) => `${block.index}:${block.kind}${block.patched ? '*' : ''}`).join(', ')}]`
2393
+ : ''
2394
+ lines.push(`- reply (seq ${reply.seq}, ${reply.attachments} non-text part(s))${blocks}: ${preview}`)
2395
+ }
2396
+ if (replies.length > shownReplies.length) lines.push(`(${replies.length - shownReplies.length} earlier reply/replies omitted)`)
2397
+ lines.push('editing a turn replaces its wording in place (no model call); editing a reply block patches it in place when the host supports plugin-record projections, otherwise it replaces the reply and replays the tail. Re-running a turn is dsh-rerun-turn\'s button.')
2398
+ return lines.join('\n')
2399
+ },
2400
+ }),
2401
+ )
2402
+ }
2403
+
2404
+ // --- http --------------------------------------------------------------------
2405
+
2406
+ function isLoopbackAddress(address) {
2407
+ if (typeof address !== 'string' || address.length === 0) return false
2408
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
2409
+ }
2410
+
2411
+ function isLocalHostHeader(host) {
2412
+ if (typeof host !== 'string' || host.length === 0) return false
2413
+ const trimmed = host.trim().toLowerCase()
2414
+ // A bracketed IPv6 literal keeps its colons, so the port can only be split
2415
+ // off after the closing bracket, and nothing but an optional port may follow.
2416
+ if (trimmed.startsWith('[')) {
2417
+ const end = trimmed.indexOf(']')
2418
+ if (end === -1) return false
2419
+ const rest = trimmed.slice(end + 1)
2420
+ if (rest !== '' && !/^:[0-9]+$/.test(rest)) return false
2421
+ return trimmed.slice(1, end) === '::1'
2422
+ }
2423
+ const match = /^([^:]*)(?::([0-9]+))?$/.exec(trimmed)
2424
+ if (match === null) return false
2425
+ // Exact matches only: a name like `127.0.0.1.evil.test` must not pass.
2426
+ return match[1] === 'localhost' || match[1] === '127.0.0.1' || match[1] === '::1'
2427
+ }
2428
+
2429
+ function sendJson(res, status, body) {
2430
+ const payload = JSON.stringify(body)
2431
+ res.writeHead(status, {
2432
+ 'content-type': 'application/json; charset=utf-8',
2433
+ 'content-length': Buffer.byteLength(payload),
2434
+ })
2435
+ res.end(payload)
2436
+ }
2437
+
2438
+ // The body limit is the upload limit: a revised message with blocks arrives as
2439
+ // base64 inside this JSON, so /apply asks for a larger ceiling than the tiny
2440
+ // default. The read is refused rather than truncated, and the socket keeps
2441
+ // draining so the refusal can still be answered.
2442
+ function readBody(req, limit = 1e6) {
2443
+ return new Promise((resolve, reject) => {
2444
+ let data = ''
2445
+ let refused = false
2446
+ req.on('data', (chunk) => {
2447
+ if (refused) return
2448
+ data += chunk
2449
+ if (data.length > limit) {
2450
+ refused = true
2451
+ data = ''
2452
+ reject(new HttpError(413, 'invalid', 'the request body is too large'))
2453
+ }
2454
+ })
2455
+ req.on('end', () => {
2456
+ if (!refused) resolve(data)
2457
+ })
2458
+ req.on('error', (error) => {
2459
+ if (!refused) reject(error)
2460
+ })
2461
+ req.on('aborted', () => {
2462
+ if (!refused) reject(new Error('aborted'))
2463
+ })
2464
+ })
2465
+ }
2466
+
2467
+ // Rewriting the derived context is destructive for the model, so every route
2468
+ // demands a loopback socket, a loopback Host header, and a same-origin check
2469
+ // when the browser sends Origin.
2470
+ function guard(req, res) {
2471
+ if (!isLoopbackAddress(req.socket && req.socket.remoteAddress)) {
2472
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'loopback only' })
2473
+ return false
2474
+ }
2475
+ const host = req.headers.host
2476
+ if (!isLocalHostHeader(host)) {
2477
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'unexpected host' })
2478
+ return false
2479
+ }
2480
+ const origin = req.headers.origin
2481
+ if (typeof origin === 'string' && origin.length > 0) {
2482
+ let originHost = null
2483
+ try {
2484
+ originHost = new URL(origin).host
2485
+ } catch {
2486
+ originHost = null
2487
+ }
2488
+ if (originHost !== host) {
2489
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'cross-origin request' })
2490
+ return false
2491
+ }
2492
+ }
2493
+ return true
2494
+ }
2495
+
2496
+ function sessionIdFromQuery(url) {
2497
+ try {
2498
+ return (new URL(url, 'http://localhost').searchParams.get('sessionId') || '').trim()
2499
+ } catch {
2500
+ return ''
2501
+ }
2502
+ }
2503
+
2504
+ function requireSessionId(value) {
2505
+ if (!value) throw new HttpError(400, 'invalid', 'sessionId required')
2506
+ if (!SESSION_ID_RE.test(value)) throw new HttpError(400, 'invalid', 'invalid session id')
2507
+ return value
2508
+ }
2509
+
2510
+ /**
2511
+ * Whether the host refused a plugin record because its projection is no longer
2512
+ * registered for this session (a live reload that dropped it, or a session
2513
+ * loaded before the owning plugin). Such a save can still go through the replay
2514
+ * path, so it is not fatal.
2515
+ *
2516
+ * @param message - the host's error text.
2517
+ * @returns true when the record's projection is gone.
2518
+ */
2519
+ export function isProjectionUnavailable(message) {
2520
+ return typeof message === 'string' && /projection .*was removed or replaced/i.test(message)
2521
+ }
2522
+
2523
+ function failure(res, error) {
2524
+ const message = String((error && error.message) || error)
2525
+ // The host refuses to derive a session whose projection left the registry
2526
+ // (`SurfaceManager._assertProjections`). It is a known, self-explaining state
2527
+ // - the plugin was reloaded while that session was open - not an internal
2528
+ // fault, so it answers 409 with the host's own words and does not dump a stack
2529
+ // into the log on every request.
2530
+ if (isProjectionUnavailable(message)) {
2531
+ sendJson(res, 409, { ok: false, code: 'projection-missing', error: message })
2532
+ return
2533
+ }
2534
+ const status = error instanceof HttpError ? error.status : 500
2535
+ const code = error instanceof HttpError ? error.code : 'internal'
2536
+ // An unexpected throw is the only case the client cannot explain; leave the
2537
+ // stack in the host log so a report can name the cause.
2538
+ if (!(error instanceof HttpError)) console.error('[dsh-edit-turn] internal error', error)
2539
+ sendJson(res, status, { ok: false, code, error: message })
2540
+ }
2541
+
2542
+ /**
2543
+ * The one projection object this PROCESS uses, kept across plugin reloads.
2544
+ *
2545
+ * The host registry compares projection IDENTITY, not type:
2546
+ * `SurfaceManager._assertProjections()` (dsh-session/lib/index.js) throws
2547
+ * `session message projection "<type>" was removed or replaced` when a
2548
+ * projection a LIVE session already folded with is no longer in the registry
2549
+ * array, and `registerMessageProjection`'s own docstring states the rule:
2550
+ * "Disposing the contribution makes sessions that used it refuse further
2551
+ * derivation."
2552
+ *
2553
+ * A reload disposes the previous fiber, which splices the old object out of the
2554
+ * registry. Building a fresh object then leaves every open session that carries
2555
+ * a patch event unable to derive anything: the surface read throws, so this
2556
+ * plugin's own save/state paths answer 500, and so does any sibling that reads
2557
+ * `session.surface.nodes` (verified live - dsh-delete-turn's /state answered 500
2558
+ * for such a session after a reload). Reusing one object from a process-global
2559
+ * hands the registry the SAME definition back, so a reloaded plugin keeps the
2560
+ * open sessions foldable.
2561
+ *
2562
+ * The object is a pure, stateless interpreter, which is what makes the reuse
2563
+ * safe. One consequence is deliberate: after a code change the projection keeps
2564
+ * running the PREVIOUS definition for sessions that are already open, until the
2565
+ * session is reopened or DSH restarts. That is the better half of the trade -
2566
+ * the alternative is a session that cannot be read at all.
2567
+ *
2568
+ * @returns the process-wide projection definition.
2569
+ */
2570
+ function sharedPatchProjection() {
2571
+ const KEY = '__DSH_EDIT_TURN_PATCH_PROJECTION__'
2572
+ try {
2573
+ const stashed = globalThis[KEY]
2574
+ if (
2575
+ stashed !== undefined &&
2576
+ stashed !== null &&
2577
+ typeof stashed.project === 'function' &&
2578
+ stashed.type === PATCH_TYPE
2579
+ ) {
2580
+ return stashed
2581
+ }
2582
+ const fresh = patchProjection()
2583
+ globalThis[KEY] = fresh
2584
+ return fresh
2585
+ } catch {
2586
+ // A frozen or absent globalThis is not worth failing the load over.
2587
+ return patchProjection()
2588
+ }
2589
+ }
2590
+
2591
+ // --- plugin ------------------------------------------------------------------
2592
+
2593
+ export function apply(ctx, config) {
2594
+ const resolved = {
2595
+ markerText:
2596
+ config && typeof config.markerText === 'string' && config.markerText.trim() !== ''
2597
+ ? config.markerText
2598
+ : DEFAULT_MARKER,
2599
+ carrier: config && config.carrier === 'user/message' ? 'user/message' : 'system/message',
2600
+ confirm: config && typeof config.confirm === 'boolean' ? config.confirm : false,
2601
+ replyMode: config && (config.replyMode === 'replay' || config.replyMode === 'patch') ? config.replyMode : 'auto',
2602
+ editorStyle: config && (config.editorStyle === 'bubble' || config.editorStyle === 'center')
2603
+ ? config.editorStyle
2604
+ : 'frame',
2605
+ }
2606
+
2607
+ // The in-place reply path needs two host seams: a plugin record with the
2608
+ // `ignorable` envelope, and a message projection registry. Both are probed at
2609
+ // load; when either is missing the reply path keeps the official replay
2610
+ // splice, and `replyMode: 'patch'` turns that silence into a load error.
2611
+ const sessionsService = ctx.get('sessions')
2612
+ let patch = false
2613
+ if (
2614
+ resolved.replyMode !== 'replay' &&
2615
+ typeof sessionApi.appendPluginRecord === 'function' &&
2616
+ sessionsService &&
2617
+ typeof sessionsService.registerMessageProjection === 'function'
2618
+ ) {
2619
+ try {
2620
+ // A live reload (HMR, a re-applied bundle) leaves the previous
2621
+ // registration in place: the registry rejects a second definition of the
2622
+ // same type. Reuse ours instead of failing back to replay - the
2623
+ // projection is a stateless pure function, so the old instance is exactly
2624
+ // as good as a fresh one.
2625
+ const registry = sessionsService.messageProjections
2626
+ const existing = Array.isArray(registry)
2627
+ ? registry.find((entry) => entry && entry.type === PATCH_TYPE)
2628
+ : undefined
2629
+ if (existing === undefined) sessionsService.registerMessageProjection(sharedPatchProjection())
2630
+ patch = true
2631
+ } catch (error) {
2632
+ if (resolved.replyMode === 'patch') throw error
2633
+ }
2634
+ }
2635
+ resolved.patch = patch
2636
+
2637
+ const registerRoutes = (webServer, fiber) => {
2638
+ fiber.effect(() =>
2639
+ webServer.register({
2640
+ kind: 'exact',
2641
+ path: `${ROUTE_PREFIX}/state`,
2642
+ handler: async (req, res) => {
2643
+ if (!guard(req, res)) return
2644
+ if (req.method !== 'GET') {
2645
+ sendJson(res, 405, { ok: false, code: 'method', error: 'GET only' })
2646
+ return
2647
+ }
2648
+ try {
2649
+ const sessionId = requireSessionId(sessionIdFromQuery(req.url))
2650
+ sendJson(res, 200, { ok: true, ...(await stateOf(ctx, sessionId, resolved)) })
2651
+ } catch (error) {
2652
+ failure(res, error)
2653
+ }
2654
+ },
2655
+ }),
2656
+ )
2657
+
2658
+ // The bytes behind one block, for the editor's chips. Read-only, loopback
2659
+ // and same-origin like everything else here, and answered only for a block
2660
+ // the session's own log cites.
2661
+ fiber.effect(() =>
2662
+ webServer.register({
2663
+ kind: 'exact',
2664
+ path: `${ROUTE_PREFIX}/attachment`,
2665
+ handler: async (req, res) => {
2666
+ if (!guard(req, res)) return
2667
+ if (req.method !== 'GET') {
2668
+ sendJson(res, 405, { ok: false, code: 'method', error: 'GET only' })
2669
+ return
2670
+ }
2671
+ try {
2672
+ const url = new URL(req.url, 'http://localhost')
2673
+ const sessionId = requireSessionId((url.searchParams.get('sessionId') || '').trim())
2674
+ const seq = Number(url.searchParams.get('seq'))
2675
+ const index = Number(url.searchParams.get('index'))
2676
+ if (!Number.isInteger(seq) || seq < 0 || !Number.isInteger(index) || index < 0) {
2677
+ throw new HttpError(400, 'invalid', 'seq and index must be whole numbers')
2678
+ }
2679
+ const found = await attachmentBytes(ctx, sessionId, seq, index)
2680
+ if (found === null) {
2681
+ // Deliberately without a code: the editor translates codes into
2682
+ // sentences, and "this chip has no picture" is not one the user
2683
+ // needs to read - the chip simply draws its label.
2684
+ sendJson(res, 404, { ok: false, error: 'no attachment bytes for this block' })
2685
+ return
2686
+ }
2687
+ res.writeHead(200, {
2688
+ 'content-type': typeof found.mediaType === 'string' && found.mediaType !== '' ? found.mediaType : 'application/octet-stream',
2689
+ 'content-length': found.data.byteLength,
2690
+ // The stored object is immutable and content-addressed.
2691
+ 'cache-control': 'private, max-age=600',
2692
+ })
2693
+ res.end(found.data)
2694
+ } catch (error) {
2695
+ failure(res, error)
2696
+ }
2697
+ },
2698
+ }),
2699
+ )
2700
+
2701
+ // Read-only diagnostics. The browser half's own state cannot be observed
2702
+ // from here, so the next best thing is an honest record of what its requests
2703
+ // asked for and what they got back.
2704
+ fiber.effect(() =>
2705
+ webServer.register({
2706
+ kind: 'exact',
2707
+ path: `${ROUTE_PREFIX}/debug`,
2708
+ handler: (req, res) => {
2709
+ if (!guard(req, res)) return
2710
+ if (req.method !== 'GET') {
2711
+ sendJson(res, 405, { ok: false, code: 'method', error: 'GET only' })
2712
+ return
2713
+ }
2714
+ sendJson(res, 200, {
2715
+ ok: true,
2716
+ version: PLUGIN_VERSION,
2717
+ // How this deployment resolves a reply edit. `patch` means both
2718
+ // host seams were found and the projection registered; `replay`
2719
+ // means the historical splice is what a save will use.
2720
+ mode: resolved.patch === true ? 'patch' : 'replay',
2721
+ capabilities: {
2722
+ pluginRecords: typeof sessionApi.appendPluginRecord === 'function',
2723
+ projection: resolved.patch === true,
2724
+ },
2725
+ requests: recentRequests(),
2726
+ })
2727
+ },
2728
+ }),
2729
+ )
2730
+
2731
+ fiber.effect(() =>
2732
+ webServer.register({
2733
+ kind: 'exact',
2734
+ path: `${ROUTE_PREFIX}/apply`,
2735
+ handler: async (req, res) => {
2736
+ if (!guard(req, res)) return
2737
+ if (req.method !== 'POST') {
2738
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2739
+ return
2740
+ }
2741
+ let raw
2742
+ try {
2743
+ // A block list travels as base64 inside this body, so the ceiling is
2744
+ // the upload ceiling (see MAX_BODY_BYTES) - and an oversized body is
2745
+ // reported as such instead of being read as far as it goes.
2746
+ raw = await readBody(req, MAX_BODY_BYTES)
2747
+ } catch (error) {
2748
+ const status = error instanceof HttpError ? error.status : 400
2749
+ const detail = error instanceof HttpError ? error.message : 'malformed JSON body'
2750
+ sendJson(res, status, { ok: false, code: 'invalid', error: detail })
2751
+ return
2752
+ }
2753
+ let body = {}
2754
+ try {
2755
+ if (raw) body = JSON.parse(raw)
2756
+ } catch {
2757
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2758
+ return
2759
+ }
2760
+ try {
2761
+ const sessionId = requireSessionId(typeof body.sessionId === 'string' ? body.sessionId.trim() : '')
2762
+ const result = await applyEdit(ctx, sessionId, body, resolved)
2763
+ // Recorded so the next "the button does nothing" can be answered
2764
+ // from here: an apply that never appears was never sent - the click
2765
+ // was lost in the browser half, not refused by this one.
2766
+ noteRequest({
2767
+ kind: 'apply',
2768
+ sessionId,
2769
+ ok: true,
2770
+ edit: result.kind,
2771
+ seq: typeof body.seq === 'number' ? body.seq : null,
2772
+ replacement: typeof result.replacementSeq === 'number' ? result.replacementSeq : null,
2773
+ // A save the host did not write because the text was already the
2774
+ // live text. Worth distinguishing from a landed edit here: the log
2775
+ // shows nothing for it, so this ring is the only place that records
2776
+ // "the user pressed save and nothing needed saving".
2777
+ unchanged: result.unchanged === true,
2778
+ // Whether non-text blocks were left behind by this save (see
2779
+ // applyEdit). The log cannot show this: the carrier is one event
2780
+ // either way.
2781
+ dropped: result.dropped === true,
2782
+ })
2783
+ sendJson(res, 200, { ok: true, ...result })
2784
+ } catch (error) {
2785
+ noteRequest({
2786
+ kind: 'apply',
2787
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId.trim() : null,
2788
+ ok: false,
2789
+ code: error && error.code ? String(error.code) : 'internal',
2790
+ })
2791
+ failure(res, error)
2792
+ }
2793
+ },
2794
+ }),
2795
+ )
2796
+ }
2797
+
2798
+ const webServer = ctx.get('webServer')
2799
+ if (webServer) {
2800
+ registerRoutes(webServer, ctx)
2801
+ } else {
2802
+ ctx.inject(['webServer'], (sub) => registerRoutes(sub.webServer, sub))
2803
+ }
2804
+
2805
+ const tools = ctx.get('tools')
2806
+ if (tools) {
2807
+ registerTool(ctx, resolved)
2808
+ } else {
2809
+ ctx.inject(['tools'], (sub) => registerTool(sub, resolved))
2810
+ }
2811
+ }
2812
+
2813
+ export default apply