@parallelworks/code 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1277 @@
1
+ import { INTERRUPTED_NOTICE, applyPartDelta, askQuestionsFromArgs, classifyPseudoUserMessage, finalizeParts, firstNonEmptyLine, hiddenTranscriptTool, interruptionNotice, parseSubagentNotice, planFromArgs, resultFailed, subagentDeliveryLine, taskCallFromArgs } from "@parallelworks/ui/ai/headless";
2
+ import { DateTime } from "luxon";
3
+ // src/transcript.ts
4
+ var MAIN_SESSION_AUTHOR = {
5
+ id: "main",
6
+ username: "main session"
7
+ };
8
+ var synthCounter = 0;
9
+ function synthId(prefix) {
10
+ synthCounter += 1;
11
+ return `${prefix}-${synthCounter}`;
12
+ }
13
+ function userMessage(text, fromMain, id, pastes, images, imageUrl) {
14
+ const pseudo = classifyPseudoUserMessage("user", text);
15
+ const attachments = imageAttachments(images, imageUrl);
16
+ return {
17
+ id: id ?? synthId("u"),
18
+ role: "user",
19
+ content: text,
20
+ ...pseudo ? { pseudo } : {},
21
+ ...fromMain ? { author: MAIN_SESSION_AUTHOR } : {},
22
+ ...pastes?.length ? { pastes } : {},
23
+ ...attachments.length ? { attachments } : {}
24
+ };
25
+ }
26
+ /** The daemon sends a preview of each image inline; one whose original it
27
+ * names opens at full size from the host, any other from its preview. */
28
+ function imageAttachments(images, imageUrl) {
29
+ return (images ?? []).filter((image) => image.mime.startsWith("image/")).map((image) => {
30
+ const preview = `data:${image.mime};base64,${image.data}`;
31
+ const previewSize = Math.floor(image.data.length * 3 / 4) - (image.data.match(/=*$/)?.[0].length ?? 0);
32
+ const original = image.ref && imageUrl ? imageUrl(image.ref) : void 0;
33
+ return {
34
+ id: original ?? preview,
35
+ previewUrl: preview,
36
+ filename: "",
37
+ contentType: original && image.originalMime || image.mime,
38
+ size: original ? image.originalSize ?? 0 : previewSize,
39
+ uploadedAt: ""
40
+ };
41
+ });
42
+ }
43
+ function assistantMessage(parts = [], id) {
44
+ return {
45
+ id: id ?? synthId("a"),
46
+ role: "assistant",
47
+ parts
48
+ };
49
+ }
50
+ var SHELL_RECORD = /^<shell-input>([\s\S]*?)<\/shell-input>\s*<shell-stdout>([\s\S]*)<\/shell-stdout>\s*$/;
51
+ /** A `!` command and what it printed, from the user message the daemon records them as. */
52
+ function parseShellRecord(text) {
53
+ const match = SHELL_RECORD.exec(text.trim());
54
+ if (!match) return null;
55
+ return {
56
+ command: (match[1] ?? "").trim(),
57
+ output: match[2] ?? ""
58
+ };
59
+ }
60
+ function fenced(text) {
61
+ const longest = (text.match(/`+/g) ?? []).reduce((max, run) => Math.max(max, run.length), 0);
62
+ const fence = "`".repeat(Math.max(3, longest + 1));
63
+ return `${fence}\n${text}\n${fence}`;
64
+ }
65
+ /** A `!` run as the terminal shows it: the command, then its output. */
66
+ function shellRunPart(command, output) {
67
+ const shown = output.replace(/^\s*\n/, "").trimEnd();
68
+ return {
69
+ kind: "notice",
70
+ text: `! ${command}`,
71
+ ...shown ? {
72
+ detail: fenced(shown),
73
+ open: true
74
+ } : {}
75
+ };
76
+ }
77
+ /** The daemon emits nothing for a `!` run, so the page that ran it shows it. */
78
+ function appendShellRun(state, command, output) {
79
+ return {
80
+ ...state,
81
+ messages: [...state.messages, assistantMessage([shellRunPart(command, output)])]
82
+ };
83
+ }
84
+ /** The daemon pairs results to calls positionally; the wire carries no ids. */
85
+ function completeOldestRunning(parts, result) {
86
+ const idx = parts.findIndex((p) => p.kind === "tool_call" && p.status === "running");
87
+ if (idx === -1) return parts;
88
+ return parts.map((p, i) => i === idx && p.kind === "tool_call" ? {
89
+ ...p,
90
+ status: resultFailed(p.name, result) ? "error" : "ok",
91
+ result
92
+ } : p);
93
+ }
94
+ function approvalSubject(req) {
95
+ if (req.reason === "file is outside the workspace") return "path";
96
+ if (req.tool === "NotebookRun" || req.reason === "code in the notebook kernel") return "code";
97
+ if (req.tool !== void 0 && req.tool !== "Bash") return "call";
98
+ return "command";
99
+ }
100
+ function approvalToPart(req, words) {
101
+ const subject = req.kind === "confirm" ? approvalSubject(req) : void 0;
102
+ const canAllowDirectory = subject === "path";
103
+ return {
104
+ kind: "approval",
105
+ id: req.id,
106
+ approvalKind: req.kind,
107
+ ...subject !== void 0 ? { subject } : {},
108
+ ...req.tool !== void 0 ? { toolName: req.tool } : {},
109
+ ...req.command !== void 0 ? { command: req.command } : {},
110
+ ...req.reason !== void 0 ? { reason: req.reason } : {},
111
+ ...req.agent !== void 0 ? { agent: req.agent } : {},
112
+ ...req.mode !== void 0 ? { mode: req.mode } : {},
113
+ ...req.kind === "ask" ? { questions: askQuestions(req.questions) } : {},
114
+ ...req.callId !== void 0 ? { toolCallId: req.callId } : {},
115
+ ...req.plan !== void 0 ? { plan: req.plan } : {},
116
+ canAllowDirectory,
117
+ ...canAllowDirectory && req.allowDir && words ? { allowDirectoryLabel: words.allowDirectory(req.allowDir) } : {}
118
+ };
119
+ }
120
+ function askQuestions(questions) {
121
+ return (questions ?? []).map((q) => ({
122
+ question: q.question,
123
+ ...q.header ? { header: q.header } : {},
124
+ ...q.multiSelect ? { multiSelect: true } : {},
125
+ ...q.options?.length ? { options: q.options.map((o) => ({
126
+ label: o.label,
127
+ ...o.description !== void 0 ? { description: o.description } : {},
128
+ ...o.preview !== void 0 ? { preview: o.preview } : {}
129
+ })) } : {}
130
+ }));
131
+ }
132
+ function approvalAnswerBody(answer) {
133
+ if (answer.kind === "confirm") return {
134
+ allowed: answer.allowed,
135
+ ...answer.allowed && answer.allowDir ? { allowDir: true } : {},
136
+ ...answer.denyMessage !== void 0 ? { denyMessage: answer.denyMessage } : {}
137
+ };
138
+ return {
139
+ answers: answer.answers,
140
+ ...answer.chat !== void 0 ? { chat: answer.chat } : {}
141
+ };
142
+ }
143
+ /** What a recorded ask gave each question; denied is the reader choosing to chat about them instead. */
144
+ function askOutcome(d) {
145
+ const answers = (d.answers ?? []).map((a) => ({
146
+ ...a.picked?.length ? { picked: a.picked } : {},
147
+ ...a.text ? { text: a.text } : {},
148
+ ...a.notes ? { notes: a.notes } : {}
149
+ }));
150
+ return d.status === "denied" ? {
151
+ answers,
152
+ chat: true
153
+ } : { answers };
154
+ }
155
+ /** A review still under way, or one the turn cut short, settled nothing. */
156
+ function toolDecision(d) {
157
+ if (d.status === "reviewing" || d.status === "aborted") return null;
158
+ return {
159
+ status: d.status,
160
+ by: d.by,
161
+ at: d.at,
162
+ ...d.username ? { name: d.username } : {},
163
+ ...d.note ? { note: d.note } : {},
164
+ ...d.rationale ? { reason: d.rationale } : {},
165
+ ...d.action ? { action: d.action } : {}
166
+ };
167
+ }
168
+ /** Ids come from the item's position, so a refetch keeps message identity and
169
+ * React does not remount (and collapse) the whole transcript. */
170
+ function historyToMessages(history, options = {}) {
171
+ const finalizeOpen = options.finalizeOpen ?? true;
172
+ const { words } = options;
173
+ const lastSettledTurnEnd = history.findLastIndex((item) => item.kind === "turn_end" && !item.turnEnd?.pendingAgents);
174
+ const messages = [];
175
+ let current = null;
176
+ const flush = (finalize) => {
177
+ if (current) {
178
+ if (finalize) current = {
179
+ ...current,
180
+ parts: finalizeParts(current.parts ?? [])
181
+ };
182
+ messages.push(current);
183
+ current = null;
184
+ }
185
+ };
186
+ const open = (index) => {
187
+ if (!current) current = assistantMessage([], `h-a-${index}`);
188
+ return current;
189
+ };
190
+ const append = (part, index) => {
191
+ const message = open(index);
192
+ current = {
193
+ ...message,
194
+ parts: [...message.parts ?? [], part]
195
+ };
196
+ };
197
+ const ranCommand = (command, index, answer) => {
198
+ if (!command) {
199
+ append(answer.document ? {
200
+ kind: "text",
201
+ text: answer.document
202
+ } : {
203
+ kind: "notice",
204
+ text: answer.text,
205
+ ...answer.detail ? { detail: answer.detail } : {}
206
+ }, index);
207
+ return;
208
+ }
209
+ flush(true);
210
+ messages.push({
211
+ ...userMessage(command, false, `h-u-${index}`),
212
+ commandAnswer: answer
213
+ });
214
+ };
215
+ const pending = [];
216
+ const settle = (call, result) => {
217
+ const message = open(-1);
218
+ current = {
219
+ ...message,
220
+ parts: settleCall(message.parts ?? [], call, result)
221
+ };
222
+ };
223
+ const dropWaitingAsks = () => {
224
+ const waiting = new Set(pending.flatMap((call) => call.kind === "ask" ? [call.id] : []));
225
+ if (current && waiting.size > 0) current = {
226
+ ...current,
227
+ parts: (current.parts ?? []).filter((p) => !(p.kind === "approval" && waiting.has(p.id)))
228
+ };
229
+ };
230
+ history.forEach((item, index) => {
231
+ switch (item.kind) {
232
+ case "user": {
233
+ flush(true);
234
+ const shell = parseShellRecord(item.text ?? "");
235
+ if (shell) {
236
+ append(shellRunPart(shell.command, shell.output), index);
237
+ return;
238
+ }
239
+ messages.push(userMessage(item.text ?? "", item.fromMain ?? false, `h-u-${index}`, item.pastes, item.images, options.imageUrl));
240
+ return;
241
+ }
242
+ case "assistant": {
243
+ const interrupted = interruptionNotice(item.text ?? "");
244
+ append(interrupted ? {
245
+ kind: "notice",
246
+ text: interrupted
247
+ } : {
248
+ kind: "text",
249
+ text: item.text ?? ""
250
+ }, index);
251
+ return;
252
+ }
253
+ case "thinking":
254
+ append({
255
+ kind: "reasoning",
256
+ text: item.text ?? ""
257
+ }, index);
258
+ return;
259
+ case "tool_call": {
260
+ const name = item.toolName ?? "";
261
+ const args = item.toolArgs ?? "";
262
+ const id = `h-${index}`;
263
+ if (name === "Task") {
264
+ const { description, agentType } = taskCallFromArgs(args);
265
+ append({
266
+ kind: "subagent",
267
+ id,
268
+ status: "running",
269
+ description,
270
+ ...agentType ? { agentType } : {}
271
+ }, index);
272
+ pending.push({
273
+ kind: "subagent",
274
+ id
275
+ });
276
+ return;
277
+ }
278
+ if (name === "AskUserQuestion") {
279
+ const [card, call] = askCard(id, args, item.decision);
280
+ append(card, index);
281
+ pending.push(call);
282
+ return;
283
+ }
284
+ if (name === "ExitPlanMode") {
285
+ append({
286
+ kind: "text",
287
+ text: planFromArgs(args)
288
+ }, index);
289
+ pending.push({ kind: "hidden" });
290
+ return;
291
+ }
292
+ const todos = name === "TodoWrite" ? todosFromArgs(args) : null;
293
+ if (todos?.length) {
294
+ const message = open(index);
295
+ current = {
296
+ ...message,
297
+ parts: applyPartDelta(message.parts ?? [], {
298
+ type: "todo_snapshot",
299
+ todos
300
+ })
301
+ };
302
+ pending.push({ kind: "hidden" });
303
+ return;
304
+ }
305
+ if (hiddenTranscriptTool(name)) {
306
+ pending.push({ kind: "hidden" });
307
+ return;
308
+ }
309
+ const decision = item.decision && toolDecision(item.decision);
310
+ append({
311
+ kind: "tool_call",
312
+ id: item.callId || id,
313
+ name,
314
+ args,
315
+ status: "running",
316
+ ...item.startLine ? { startLine: item.startLine } : {},
317
+ ...planFileEdit(name, args) ? { foldDiff: true } : {},
318
+ ...decision ? { decision } : {}
319
+ }, index);
320
+ pending.push({ kind: "tool" });
321
+ return;
322
+ }
323
+ case "tool_result": {
324
+ const call = pending.shift();
325
+ if (call) settle(call, item.text ?? "");
326
+ const images = imageAttachments(item.images, options.imageUrl);
327
+ if (images.length) append({
328
+ kind: "image",
329
+ images
330
+ }, index);
331
+ return;
332
+ }
333
+ case "plan_view": {
334
+ const path = item.text ?? "";
335
+ ranCommand(item.toolName, index, {
336
+ text: words ? words.planAnswer(path, item.toolName === "/plan open") : path,
337
+ ...item.planBody ? { document: item.planBody } : {}
338
+ });
339
+ return;
340
+ }
341
+ case "notice": {
342
+ const text = item.text ?? "";
343
+ const delivery = parseSubagentNotice(text);
344
+ if (delivery?.silent) return;
345
+ append(delivery ? {
346
+ kind: "notice",
347
+ text: deliveryLine(delivery, words),
348
+ ...delivery.body ? { detail: delivery.body } : {}
349
+ } : {
350
+ kind: "notice",
351
+ text: text.trim()
352
+ }, index);
353
+ return;
354
+ }
355
+ case "warning":
356
+ append({
357
+ kind: "warning",
358
+ text: item.text ?? ""
359
+ }, index);
360
+ return;
361
+ case "error":
362
+ append({
363
+ kind: "error",
364
+ text: item.text ?? ""
365
+ }, index);
366
+ return;
367
+ case "goal_view":
368
+ ranCommand(item.toolName, index, { text: item.text ?? "" });
369
+ return;
370
+ case "compaction": {
371
+ const notice = options.compactionNotice;
372
+ if (notice) ranCommand(item.toolName, index, {
373
+ text: item.toolName ? notice.command : notice.automatic,
374
+ ...item.text ? { detail: item.text } : {}
375
+ });
376
+ return;
377
+ }
378
+ case "goal_progress": {
379
+ const progress = parseGoalProgress(item.text);
380
+ const text = goalText(progress, options.goalNotice);
381
+ const detail = goalDetail(progress, words);
382
+ if (text) append({
383
+ kind: "notice",
384
+ text,
385
+ ...detail ? { detail } : {}
386
+ }, index);
387
+ return;
388
+ }
389
+ case "turn_end": {
390
+ const te = item.turnEnd;
391
+ if (te && words) {
392
+ const waiting = index > lastSettledTurnEnd && (te.pendingAgents ?? 0) > 0;
393
+ append({
394
+ kind: "notice",
395
+ text: words.turnEnd(te, turnVerb(te.endedAt), waiting)
396
+ }, index);
397
+ }
398
+ return;
399
+ }
400
+ case "recap": {
401
+ const text = recapText(item.text, options.recapNotice);
402
+ if (text) append({
403
+ kind: "notice",
404
+ text
405
+ }, index);
406
+ return;
407
+ }
408
+ default: return;
409
+ }
410
+ });
411
+ dropWaitingAsks();
412
+ flush(finalizeOpen);
413
+ return messages;
414
+ }
415
+ /** An ask's card, settled from its record when it has one, or else by the result that follows. */
416
+ function askCard(id, args, d) {
417
+ const card = {
418
+ kind: "approval",
419
+ id,
420
+ approvalKind: "ask",
421
+ questions: askQuestionsFromArgs(args),
422
+ canAllowDirectory: false
423
+ };
424
+ if (!d?.answers?.length) return [card, {
425
+ kind: "ask",
426
+ id
427
+ }];
428
+ return [{
429
+ ...card,
430
+ resolved: true,
431
+ ...askOutcome(d)
432
+ }, { kind: "hidden" }];
433
+ }
434
+ var BACKGROUND_STARTED_PREFIX = "Started background subagent";
435
+ function settleCall(parts, call, result) {
436
+ switch (call.kind) {
437
+ case "tool": return completeOldestRunning(parts, result);
438
+ case "subagent": return parts.map((p) => {
439
+ if (p.kind !== "subagent" || p.id !== call.id) return p;
440
+ if (result.startsWith(BACKGROUND_STARTED_PREFIX)) return {
441
+ ...p,
442
+ background: true
443
+ };
444
+ return {
445
+ ...p,
446
+ status: resultFailed("Task", result) ? "failed" : "done",
447
+ summary: firstNonEmptyLine(result, 60)
448
+ };
449
+ });
450
+ case "ask": return parts.map((p) => p.kind === "approval" && p.id === call.id ? {
451
+ ...p,
452
+ resolved: true,
453
+ answer: result.trim()
454
+ } : p);
455
+ default: return parts;
456
+ }
457
+ }
458
+ /** A session with no history resumes from the start: the daemon stamps a seq
459
+ * before the agent records it, so a prompt sent with `create` falls in that
460
+ * window, and replaying a session that seeded nothing can duplicate nothing. */
461
+ function resumeCursor(detail) {
462
+ return detail.history?.length ? detail.lastSeq ?? 0 : 0;
463
+ }
464
+ function initialTranscript(detail, options = {}) {
465
+ const running = detail.status === "awaiting_approval" || !!detail.turnId;
466
+ const messages = historyToMessages(detail.history ?? [], {
467
+ ...options,
468
+ finalizeOpen: !running
469
+ });
470
+ let streaming = null;
471
+ const last = messages[messages.length - 1];
472
+ if (running && last && last.role === "assistant") {
473
+ streaming = last;
474
+ messages.pop();
475
+ }
476
+ if (detail.approvals && detail.approvals.length > 0) {
477
+ const approvals = detail.approvals.map((req) => approvalToPart(req, options.words));
478
+ streaming = streaming ? {
479
+ ...streaming,
480
+ parts: [...streaming.parts ?? [], ...approvals]
481
+ } : assistantMessage(approvals);
482
+ }
483
+ const terminal = (streaming ?? messages.at(-1))?.parts?.at(-1);
484
+ const seededTerminalTurnId = detail.history?.findLast((item) => item.kind !== "turn_end")?.turnId;
485
+ return {
486
+ messages,
487
+ streaming,
488
+ seededTerminal: seededTerminalTurnId && (terminal?.kind === "error" || terminal?.kind === "notice") ? {
489
+ part: terminal,
490
+ turnId: seededTerminalTurnId
491
+ } : null,
492
+ cursor: resumeCursor(detail),
493
+ turnEnded: !running,
494
+ queued: [],
495
+ steered: [],
496
+ notes: [],
497
+ turnStartedAt: running ? detail.turnStartedAt ?? null : null,
498
+ waitingForUsageLimit: running && !!detail.waitingForUsageLimit,
499
+ usageLimitResumeAt: running && detail.waitingForUsageLimit ? detail.usageLimitResumeAt ?? null : null,
500
+ seededSeq: detail.lastSeq ?? 0
501
+ };
502
+ }
503
+ /** The approvals the live feed is still waiting on. */
504
+ function pendingApprovals(transcript) {
505
+ return (transcript.streaming?.parts ?? []).filter((p) => p.kind === "approval" && !p.resolved);
506
+ }
507
+ /** Status as the live feed shows it; `detail.status` is only the fetch moment. */
508
+ function liveSessionStatus(status, transcript, goal) {
509
+ if (status === "live_elsewhere" || !transcript) return status;
510
+ if (pendingApprovals(transcript).length > 0) return "awaiting_approval";
511
+ if (turnRunning(transcript) || goal?.checking) return "running";
512
+ return transcript.turnEnded ? "idle" : status;
513
+ }
514
+ /** A recorded ask settles its card with each question's answer, whether they were given here or in the terminal. */
515
+ function answeredAsk(parts, d) {
516
+ const card = parts.find((p) => p.kind === "approval" && p.toolCallId === d.callId);
517
+ return card ? applyPartDelta(parts, {
518
+ type: "approval_resolved",
519
+ id: card.id,
520
+ ...askOutcome(d)
521
+ }) : parts;
522
+ }
523
+ /** The running call an event names; a daemon older than tool_end's callId names none, so the newest call of its name stands in. */
524
+ function runningToolId(parts, callId, name) {
525
+ for (let i = parts.length - 1; i >= 0; i -= 1) {
526
+ const p = parts[i];
527
+ if (p !== void 0 && p.kind === "tool_call" && p.status === "running" && (callId ? p.id === callId : name === void 0 || p.name === name)) return p.id;
528
+ }
529
+ return null;
530
+ }
531
+ function resolveApprovalEverywhere(state, id) {
532
+ const resolve = (m) => m.parts?.some((p) => p.kind === "approval" && p.id === id) ? {
533
+ ...m,
534
+ parts: applyPartDelta(m.parts ?? [], {
535
+ type: "approval_resolved",
536
+ id
537
+ })
538
+ } : m;
539
+ return {
540
+ ...state,
541
+ messages: state.messages.map(resolve),
542
+ streaming: state.streaming ? resolve(state.streaming) : null
543
+ };
544
+ }
545
+ /** The daemon queues a message sent mid-turn rather than cutting the turn
546
+ * short, so the page must not close the turn either: its open tool calls
547
+ * would read as interrupted while they are still running. */
548
+ function appendOwnMessage(state, text, id, pastes, previews) {
549
+ const message = userMessage(text, false, id, pastes, previews);
550
+ if (turnRunning(state)) return {
551
+ ...state,
552
+ queued: [...state.queued, message]
553
+ };
554
+ return {
555
+ ...state,
556
+ messages: [...state.messages, message],
557
+ seededTerminal: null,
558
+ turnEnded: false,
559
+ turnStartedAt: nowIso(),
560
+ opening: message.id
561
+ };
562
+ }
563
+ /** An own message takes the pastes and images its echo says the model received. */
564
+ function withSentPastesAndImages(messages, ev, id, imageUrl) {
565
+ const pastes = ev.pastes?.length ? ev.pastes : null;
566
+ const attachments = imageAttachments(ev.images, imageUrl);
567
+ const idx = messages.findLastIndex((m) => id ? m.id === id : m.role === "user" && m.content === ev.content);
568
+ const message = messages[idx];
569
+ if (!message || !pastes && !message.pastes?.length && !attachments.length) return messages;
570
+ const sent = {
571
+ ...message,
572
+ pastes,
573
+ ...attachments.length ? { attachments } : {}
574
+ };
575
+ return messages.map((m, i) => i === idx ? sent : m);
576
+ }
577
+ /** Held apart until the daemon reports the model was handed it. */
578
+ function appendSteeredMessage(state, text, id, pastes, previews) {
579
+ return {
580
+ ...state,
581
+ steered: [...state.steered, userMessage(text, false, id, pastes, previews)]
582
+ };
583
+ }
584
+ /** The daemon queued a message this page had shown as sent, because the turn
585
+ * ahead of it had not reached the page yet. */
586
+ function markQueued(state, id) {
587
+ const message = state.messages.find((m) => m.id === id);
588
+ if (!message) return state;
589
+ return {
590
+ ...state,
591
+ messages: state.messages.filter((m) => m.id !== id),
592
+ queued: [...state.queued, message],
593
+ ...state.opening === id ? { opening: null } : {}
594
+ };
595
+ }
596
+ /** Left in place, a message the machine refused reads as one the session received. */
597
+ function dropMessage(state, id) {
598
+ const dropped = {
599
+ ...state,
600
+ messages: state.messages.filter((m) => m.id !== id),
601
+ queued: state.queued.filter((m) => m.id !== id),
602
+ steered: state.steered.filter((m) => m.id !== id)
603
+ };
604
+ return state.opening === id ? {
605
+ ...dropped,
606
+ opening: null,
607
+ turnEnded: true,
608
+ turnStartedAt: null
609
+ } : dropped;
610
+ }
611
+ /** Everything sent that the transcript has not placed yet, in the order it
612
+ * will be read: handed to the model, then steered, then turns of their own. */
613
+ function pendingMessages(state) {
614
+ return [
615
+ ...state.notes,
616
+ ...state.steered,
617
+ ...state.queued
618
+ ];
619
+ }
620
+ /** A turn runs before it streams anything, and after it is handed a note. */
621
+ function turnRunning(state) {
622
+ return !!state && (!!state.streaming || !state.turnEnded && (state.turnStartedAt !== null || state.notes.length > 0));
623
+ }
624
+ /** Whether the turn waits on a Bash call, which the machine can move to the background. */
625
+ function bashRunning(state) {
626
+ return (state?.streaming?.parts ?? []).some((p) => p.kind === "tool_call" && p.name === "Bash" && p.status === "running");
627
+ }
628
+ /** Daemons before the interrupted flag close a stopped turn with the
629
+ * cancelled context's error. */
630
+ function stoppedTurn(ev) {
631
+ return !!ev.interrupted || /context canceled$/.test(ev.content ?? "");
632
+ }
633
+ /** What the agent records for a call a stop cut off (serverapi.UserInterruptedTool), so a stopped call reads live as it replays. */
634
+ function userInterruptedTool(name) {
635
+ return `The user interrupted ${name} before it finished.`;
636
+ }
637
+ function interruptRunningCalls(parts) {
638
+ return parts.reduce((settled, p) => p.kind === "tool_call" && p.status === "running" ? applyPartDelta(settled, {
639
+ type: "tool_end",
640
+ id: p.id,
641
+ result: userInterruptedTool(p.name),
642
+ isError: false
643
+ }) : settled, parts);
644
+ }
645
+ var TODO_STATUSES = /* @__PURE__ */ new Set([
646
+ "pending",
647
+ "in_progress",
648
+ "completed"
649
+ ]);
650
+ /** TodoWrite's whole list, which its arguments carry; null when they hold none. */
651
+ function todosFromArgs(argsJSON) {
652
+ let args;
653
+ try {
654
+ args = JSON.parse(argsJSON);
655
+ } catch {
656
+ return null;
657
+ }
658
+ const raw = args && typeof args === "object" ? args["todos"] : void 0;
659
+ if (!Array.isArray(raw)) return null;
660
+ return raw.flatMap((t) => {
661
+ const { content, status, activeForm } = t && typeof t === "object" ? t : {};
662
+ if (typeof content !== "string" || typeof status !== "string" || !TODO_STATUSES.has(status)) return [];
663
+ return [{
664
+ content,
665
+ status,
666
+ ...typeof activeForm === "string" ? { activeForm } : {}
667
+ }];
668
+ });
669
+ }
670
+ function applyPartEvent(parts, ev, imageUrl, words) {
671
+ switch (ev.type) {
672
+ case "chunk": return applyPartDelta(parts, {
673
+ type: "text",
674
+ text: ev.content ?? ""
675
+ });
676
+ case "reasoning": return applyPartDelta(parts, {
677
+ type: "reasoning",
678
+ text: ev.content ?? ""
679
+ });
680
+ case "retract": return applyPartDelta(parts, { type: "retract" });
681
+ case "tool_start": {
682
+ const todos = ev.name === "TodoWrite" ? todosFromArgs(ev.args ?? "") : null;
683
+ if (todos?.length) return applyPartDelta(parts, {
684
+ type: "todo_snapshot",
685
+ todos
686
+ });
687
+ if (hiddenTranscriptTool(ev.name ?? "")) return parts;
688
+ const id = ev.callId || String(ev.seq);
689
+ const started = applyPartDelta(parts, {
690
+ type: "tool_start",
691
+ id,
692
+ name: ev.name ?? "",
693
+ args: ev.args ?? "",
694
+ ...ev.startLine !== void 0 ? { startLine: ev.startLine } : {}
695
+ });
696
+ return planFileEdit(ev.name ?? "", ev.args ?? "") ? started.map((p) => p.kind === "tool_call" && p.id === id ? {
697
+ ...p,
698
+ foldDiff: true
699
+ } : p) : started;
700
+ }
701
+ case "tool_update": {
702
+ const id = runningToolId(parts, ev.callId, ev.name);
703
+ return id === null ? parts : parts.map((p) => p.kind === "tool_call" && p.id === id ? {
704
+ ...p,
705
+ args: ev.args ?? p.args,
706
+ argsRewritten: true
707
+ } : p);
708
+ }
709
+ case "tool_end": {
710
+ const id = runningToolId(parts, ev.callId, ev.name);
711
+ const call = parts.find((p) => p.kind === "tool_call" && p.id === id);
712
+ if (id === null || call?.kind !== "tool_call") return parts;
713
+ const result = ev.result ?? "";
714
+ return applyPartDelta(parts, {
715
+ type: "tool_end",
716
+ id,
717
+ result,
718
+ isError: !!ev.isError || resultFailed(call.name, result)
719
+ });
720
+ }
721
+ case "images": {
722
+ const images = imageAttachments(ev.images, imageUrl);
723
+ return images.length ? [...parts, {
724
+ kind: "image",
725
+ images
726
+ }] : parts;
727
+ }
728
+ case "subagent_start": return applyPartDelta(parts, {
729
+ type: "subagent_start",
730
+ id: ev.id ?? String(ev.seq),
731
+ ...ev.agentType !== void 0 ? { agentType: ev.agentType } : {},
732
+ ...ev.color !== void 0 ? { color: ev.color } : {},
733
+ ...ev.background !== void 0 ? { background: ev.background } : {},
734
+ ...ev.name !== void 0 ? { description: ev.name } : {}
735
+ });
736
+ case "subagent_action": return applyPartDelta(parts, {
737
+ type: "subagent_action",
738
+ id: ev.id ?? "",
739
+ action: ev.content ?? ""
740
+ });
741
+ case "subagent_end": return applyPartDelta(parts, {
742
+ type: "subagent_end",
743
+ id: ev.id ?? "",
744
+ ok: !ev.isError,
745
+ ...ev.result !== void 0 ? { summary: ev.result } : {},
746
+ ...ev.interrupted ? { interrupted: true } : {}
747
+ });
748
+ case "notice":
749
+ case "warning": return ev.recorded && !ev.turnId ? null : applyPartDelta(parts, {
750
+ type: ev.type,
751
+ text: (ev.content ?? "").trim()
752
+ });
753
+ case "error": return stoppedTurn(ev) ? [...interruptRunningCalls(parts), {
754
+ kind: "notice",
755
+ text: INTERRUPTED_NOTICE
756
+ }] : [...parts, {
757
+ kind: "error",
758
+ text: ev.content ?? ""
759
+ }];
760
+ case "decision": {
761
+ if (ev.decision?.answers?.length) return answeredAsk(parts, ev.decision);
762
+ const decision = ev.decision && toolDecision(ev.decision);
763
+ return decision && ev.decision ? applyPartDelta(parts, {
764
+ type: "tool_decision",
765
+ id: ev.decision.callId,
766
+ decision
767
+ }) : parts;
768
+ }
769
+ case "approval_request": return ev.approval ? applyPartDelta(parts, {
770
+ type: "approval_request",
771
+ approval: approvalToPart(ev.approval, words)
772
+ }) : parts;
773
+ default: return null;
774
+ }
775
+ }
776
+ function controlEffects(ev) {
777
+ switch (ev.type) {
778
+ case "state": return ev.state ? [{
779
+ type: "state",
780
+ state: ev.state
781
+ }] : [];
782
+ case "cleared": return ev.newId ? [{
783
+ type: "cleared",
784
+ newId: ev.newId
785
+ }] : [];
786
+ case "history_changed": return [{ type: "refetch" }];
787
+ default: return [];
788
+ }
789
+ }
790
+ function parseGoalProgress(text) {
791
+ try {
792
+ return JSON.parse(text ?? "");
793
+ } catch {
794
+ return null;
795
+ }
796
+ }
797
+ var TURN_VERBS = [
798
+ "baked",
799
+ "brewed",
800
+ "churned",
801
+ "cogitated",
802
+ "cooked",
803
+ "crunched",
804
+ "sauteed",
805
+ "worked"
806
+ ];
807
+ function deliveryLine(n, words) {
808
+ return words ? words.deliveryLine(n) : subagentDeliveryLine(n);
809
+ }
810
+ function isPlanFile(path) {
811
+ const slashed = path.replaceAll("\\", "/");
812
+ const base = slashed.slice(slashed.lastIndexOf("/") + 1).toLowerCase();
813
+ if (base === "plan.md") return true;
814
+ return base.endsWith(".md") && (slashed.startsWith("plans/") || slashed.includes("/plans/"));
815
+ }
816
+ /** An edit to the plan file, whose diff the plan shows anyway, so it stays behind its row as in the terminal. */
817
+ function planFileEdit(name, argsJSON) {
818
+ if (name !== "EditFile" && name !== "WriteFile") return false;
819
+ try {
820
+ const args = JSON.parse(argsJSON);
821
+ const path = args && typeof args === "object" ? args["path"] : void 0;
822
+ return typeof path === "string" && isPlanFile(path);
823
+ } catch {
824
+ return false;
825
+ }
826
+ }
827
+ /** The verb the terminal picks for a turn, so the same turn reads the same in both. */
828
+ function turnVerb(endedAt) {
829
+ return TURN_VERBS[fnv32a(goUtcTime(endedAt)) % TURN_VERBS.length] ?? "worked";
830
+ }
831
+ function goUtcTime(wire) {
832
+ const m = /^(.*?:\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.exec(wire);
833
+ if (!m) return wire;
834
+ const utc = DateTime.fromISO(`${m[1]}${m[3]}`, { setZone: true }).toUTC();
835
+ const fraction = (m[2] ?? "").replace(/0+$/, "").replace(/\.$/, "");
836
+ return `${utc.toFormat("yyyy-MM-dd'T'HH:mm:ss")}${fraction}Z`;
837
+ }
838
+ function fnv32a(text) {
839
+ let hash = 2166136261;
840
+ for (const byte of new TextEncoder().encode(text)) {
841
+ hash ^= byte;
842
+ hash = Math.imul(hash, 16777619) >>> 0;
843
+ }
844
+ return hash;
845
+ }
846
+ /** A loop stopped with nothing to report files nothing in the terminal, and
847
+ * nothing here. */
848
+ function goalText(p, goalNotice) {
849
+ if (!p || !goalNotice || !p.err && p.outcome === "stopped") return null;
850
+ return goalNotice(p);
851
+ }
852
+ function recapText(recap, recapNotice) {
853
+ return recap && recapNotice ? recapNotice(recap) : null;
854
+ }
855
+ /** Between turns a notice stands alone rather than opening a turn. */
856
+ function appendNotice(state, text, detail, kind = "notice") {
857
+ const notice = {
858
+ kind,
859
+ text,
860
+ ...detail ? { detail } : {}
861
+ };
862
+ return state.streaming ? {
863
+ ...state,
864
+ streaming: {
865
+ ...state.streaming,
866
+ parts: [...state.streaming.parts ?? [], notice]
867
+ }
868
+ } : {
869
+ ...state,
870
+ messages: [...state.messages, assistantMessage([notice])]
871
+ };
872
+ }
873
+ /** The session files its notice above the reply still streaming, which reaches the history when it ends. */
874
+ function placeSessionNotice(state, text, kind) {
875
+ if (!state.streaming) return appendNotice(state, text, void 0, kind);
876
+ const parts = state.streaming.parts ?? [];
877
+ let at = parts.length;
878
+ while (at > 0 && ["text", "reasoning"].includes(parts[at - 1]?.kind ?? "")) at--;
879
+ return {
880
+ ...state,
881
+ streaming: {
882
+ ...state.streaming,
883
+ parts: [
884
+ ...parts.slice(0, at),
885
+ {
886
+ kind,
887
+ text
888
+ },
889
+ ...parts.slice(at)
890
+ ]
891
+ }
892
+ };
893
+ }
894
+ /** A continuing step opens to its goal and why it isn't met, as the terminal's does; other steps say all there is. */
895
+ function goalDetail(p, words) {
896
+ if (!p || !words || p.outcome === "achieved" || p.err || p.resumeAt || !p.reason?.trim()) return null;
897
+ return words.goalDetail(p);
898
+ }
899
+ var SUBAGENT_EVENTS = /* @__PURE__ */ new Set([
900
+ "subagent_start",
901
+ "subagent_action",
902
+ "subagent_end"
903
+ ]);
904
+ /** Keeps the auto-reviewer's reviews under way for whoever asked: a review
905
+ * start adds its call, and a verdict, or a review the turn cut short, takes
906
+ * it away. */
907
+ function trackReview(state, ev) {
908
+ const d = ev.decision;
909
+ if (!d?.callId || ev.type !== "decision" && ev.type !== "subagent_decision") return state;
910
+ const scope = ev.type === "subagent_decision" ? ev.id ?? "" : "";
911
+ const reviews = state.reviews ?? {};
912
+ const under = reviews[scope] ?? [];
913
+ const decided = state.decided ?? [];
914
+ if (d.status === "reviewing") {
915
+ if (decided.includes(d.callId) || under.includes(d.callId)) return state;
916
+ return {
917
+ ...state,
918
+ reviews: {
919
+ ...reviews,
920
+ [scope]: [...under, d.callId]
921
+ }
922
+ };
923
+ }
924
+ return {
925
+ ...state,
926
+ reviews: {
927
+ ...reviews,
928
+ [scope]: under.filter((id) => id !== d.callId)
929
+ },
930
+ decided: [...decided, d.callId].slice(-200)
931
+ };
932
+ }
933
+ /** How many of the main conversation's calls the auto-reviewer is deciding on. */
934
+ function reviewingCount(state) {
935
+ return state?.reviews?.[""]?.length ?? 0;
936
+ }
937
+ /** Shows a subagent's reviews on its card, wherever its turn left it. */
938
+ function showReviews(state, id) {
939
+ const count = state.reviews?.[id]?.length ?? 0;
940
+ const update = (m) => m.parts?.some((p) => p.kind === "subagent" && p.id === id) ? {
941
+ ...m,
942
+ parts: applyPartDelta(m.parts ?? [], {
943
+ type: "subagent_reviewing",
944
+ id,
945
+ count
946
+ })
947
+ } : m;
948
+ return {
949
+ ...state,
950
+ messages: state.messages.map(update),
951
+ streaming: state.streaming ? update(state.streaming) : null
952
+ };
953
+ }
954
+ /** A subagent can outlive the turn that started it, and its later frames
955
+ * update its card where that turn left it rather than open a new turn. */
956
+ function applyToSettledSubagent(state, ev) {
957
+ if (!SUBAGENT_EVENTS.has(ev.type) || !ev.id) return null;
958
+ const holds = (m) => !!m.parts?.some((p) => p.kind === "subagent" && p.id === ev.id);
959
+ if (state.streaming && holds(state.streaming)) return ev.type === "subagent_start" ? state : null;
960
+ const idx = state.messages.findLastIndex(holds);
961
+ const message = state.messages[idx];
962
+ if (!message) return null;
963
+ if (ev.type === "subagent_start") return state;
964
+ const parts = applyPartEvent(message.parts ?? [], ev);
965
+ return parts ? {
966
+ ...state,
967
+ messages: state.messages.map((m, i) => i === idx ? {
968
+ ...m,
969
+ parts
970
+ } : m)
971
+ } : null;
972
+ }
973
+ var ENDS_THOUGHT = /* @__PURE__ */ new Set([
974
+ "chunk",
975
+ "tool_start",
976
+ "subagent_start",
977
+ "approval_request",
978
+ "notice",
979
+ "warning",
980
+ "error",
981
+ "done",
982
+ "user_message",
983
+ "turn_start"
984
+ ]);
985
+ /** Times a thought from when its model step began until something else arrives, as the terminal does. */
986
+ function timeThought(state, ev, now) {
987
+ const last = state.streaming?.parts?.at(-1);
988
+ if (ev.type === "reasoning") return last?.kind === "reasoning" ? state : {
989
+ ...state,
990
+ thoughtStartedAt: state.stepStartedAt ?? now()
991
+ };
992
+ if (ev.type === "tool_end") return {
993
+ ...state,
994
+ stepStartedAt: now()
995
+ };
996
+ if (!ENDS_THOUGHT.has(ev.type)) return state;
997
+ const at = now();
998
+ const opensStep = ev.type === "user_message" || ev.type === "turn_start";
999
+ if (!state.streaming || last?.kind !== "reasoning" || last.durationMs !== void 0 || !state.thoughtStartedAt) return opensStep ? {
1000
+ ...state,
1001
+ stepStartedAt: at,
1002
+ thoughtStartedAt: null
1003
+ } : state;
1004
+ const durationMs = Math.max(0, DateTime.fromISO(at).diff(DateTime.fromISO(state.thoughtStartedAt)).as("milliseconds"));
1005
+ return {
1006
+ ...state,
1007
+ streaming: {
1008
+ ...state.streaming,
1009
+ parts: [...(state.streaming.parts ?? []).slice(0, -1), {
1010
+ ...last,
1011
+ durationMs
1012
+ }]
1013
+ },
1014
+ thoughtStartedAt: null,
1015
+ stepStartedAt: at
1016
+ };
1017
+ }
1018
+ function finishTurn(state) {
1019
+ const done = state.streaming ? {
1020
+ ...state,
1021
+ streaming: {
1022
+ ...state.streaming,
1023
+ parts: finalizeParts(state.streaming.parts ?? [])
1024
+ }
1025
+ } : state;
1026
+ const { "": _ended, ...children } = state.reviews ?? {};
1027
+ return {
1028
+ ...placeNotes(done),
1029
+ turnEnded: true,
1030
+ turnStartedAt: null,
1031
+ opening: null,
1032
+ waitingForUsageLimit: false,
1033
+ usageLimitResumeAt: null,
1034
+ reviews: children
1035
+ };
1036
+ }
1037
+ /** Where the model speaks after being handed a note, the note joins the
1038
+ * transcript ahead of what it says. */
1039
+ function placeNotes(state) {
1040
+ return {
1041
+ ...state,
1042
+ messages: [
1043
+ ...state.messages,
1044
+ ...state.streaming ? [state.streaming] : [],
1045
+ ...state.notes
1046
+ ],
1047
+ notes: [],
1048
+ streaming: null
1049
+ };
1050
+ }
1051
+ var OUTPUT_EVENTS = /* @__PURE__ */ new Set([
1052
+ "chunk",
1053
+ "reasoning",
1054
+ "approval_request"
1055
+ ]);
1056
+ /** A hidden tool draws nothing, so a note placed there leaves the turn idle. */
1057
+ function speaks(ev) {
1058
+ if (ev.type === "tool_start") return !hiddenTranscriptTool(ev.name ?? "");
1059
+ return OUTPUT_EVENTS.has(ev.type);
1060
+ }
1061
+ var DISCARDED_QUEUE = /^interrupted: discarded \d+ queued message/;
1062
+ /** By id when the send is known: the daemon echoes an MCP prompt expanded. */
1063
+ function takeOwn(list, id, text) {
1064
+ const idx = list.findIndex((m) => id ? m.id === id : m.content === text);
1065
+ return idx === -1 ? [void 0, list] : [list[idx], list.filter((_, i) => i !== idx)];
1066
+ }
1067
+ /** An own message's echo stands in for the copy held until its turn began. */
1068
+ function takeQueued(state, id, text) {
1069
+ const [message, queued] = takeOwn(state.queued, id, text);
1070
+ return message ? {
1071
+ ...state,
1072
+ messages: [...state.messages, message],
1073
+ queued
1074
+ } : state;
1075
+ }
1076
+ /** The echo also says how each of the message's pastes was sent. */
1077
+ function takeEcho(state, id, ev, imageUrl) {
1078
+ const placed = takeQueued(state, id, ev.content ?? "");
1079
+ return {
1080
+ ...placed,
1081
+ messages: withSentPastesAndImages(placed.messages, ev, id, imageUrl)
1082
+ };
1083
+ }
1084
+ /** A handed-over note leaves the steered list, or arrives from another window. */
1085
+ function noteHandedOver(state, id, ev, imageUrl) {
1086
+ const text = ev.content ?? "";
1087
+ const [note, steered] = takeOwn(state.steered, id, text);
1088
+ return {
1089
+ ...state,
1090
+ steered,
1091
+ notes: note ? withSentPastesAndImages([...state.notes, note], ev, note.id, imageUrl) : [...state.notes, userMessage(text, false, void 0, ev.pastes, ev.images, imageUrl)]
1092
+ };
1093
+ }
1094
+ function nowIso() {
1095
+ return DateTime.now().toISO();
1096
+ }
1097
+ /** Out-of-band frames are classified before seq dedupe, as the TUI does. */
1098
+ function applyStreamEvent(state, ev, options = {}) {
1099
+ const now = options.now ?? nowIso;
1100
+ if (ev.type === "cleared" && options.sessionId && ev.newId === options.sessionId && ev.seq > state.cursor) return {
1101
+ state: {
1102
+ ...state,
1103
+ messages: [],
1104
+ streaming: null,
1105
+ seededTerminal: null,
1106
+ turnEnded: true,
1107
+ turnStartedAt: null,
1108
+ waitingForUsageLimit: false,
1109
+ usageLimitResumeAt: null,
1110
+ cursor: ev.seq
1111
+ },
1112
+ effects: []
1113
+ };
1114
+ if (ev.type === "replay_truncated") return {
1115
+ state: {
1116
+ ...state,
1117
+ cursor: Math.max(state.cursor, ev.seq)
1118
+ },
1119
+ effects: [{ type: "refetch" }]
1120
+ };
1121
+ if (ev.type === "cleared" && ev.seq <= (state.seededSeq ?? 0) && ev.newId !== options.sessionId) return {
1122
+ state: {
1123
+ ...state,
1124
+ cursor: Math.max(state.cursor, ev.seq)
1125
+ },
1126
+ effects: []
1127
+ };
1128
+ if (ev.seq === 0) return {
1129
+ state,
1130
+ effects: ev.type === "notice" || ev.type === "warning" ? [{
1131
+ type: "notice",
1132
+ text: ev.content ?? "",
1133
+ warn: ev.type === "warning"
1134
+ }] : []
1135
+ };
1136
+ if (ev.seq <= state.cursor) return {
1137
+ state,
1138
+ effects: []
1139
+ };
1140
+ if (ev.id && !ev.type.startsWith("subagent_")) return {
1141
+ state: {
1142
+ ...state,
1143
+ cursor: ev.seq
1144
+ },
1145
+ effects: []
1146
+ };
1147
+ let next = {
1148
+ ...state,
1149
+ cursor: ev.seq,
1150
+ ...ev.turnEnd ? { turnEndSeq: ev.seq } : {}
1151
+ };
1152
+ if (next.notes.length > 0 && speaks(ev)) next = placeNotes(next);
1153
+ if (ev.type === "notice" && DISCARDED_QUEUE.test(ev.content ?? "")) next = {
1154
+ ...next,
1155
+ queued: []
1156
+ };
1157
+ const lastMessage = next.streaming ?? next.messages.at(-1);
1158
+ const lastPart = lastMessage?.parts?.at(-1);
1159
+ if (ev.type === "error" && next.seededTerminal && ev.turnId === next.seededTerminal.turnId && lastPart === next.seededTerminal.part && next.notes.length === 0 && lastMessage?.role === "assistant" && (stoppedTurn(ev) ? lastPart?.kind === "notice" && lastPart.text === INTERRUPTED_NOTICE : lastPart?.kind === "error" && lastPart.text === (ev.content ?? ""))) return {
1160
+ state: {
1161
+ ...finishTurn(next),
1162
+ seededTerminal: null,
1163
+ turnEnded: true,
1164
+ turnStartedAt: null
1165
+ },
1166
+ effects: []
1167
+ };
1168
+ if (ev.type === "error" || ev.type === "done" || ev.type === "user_message" || ev.type === "user_note" || ev.type === "tool_start" || ev.type === "subagent_start" || speaks(ev)) next = {
1169
+ ...next,
1170
+ seededTerminal: null
1171
+ };
1172
+ next = trackReview(next, ev);
1173
+ if (ev.type === "subagent_end" && ev.id && next.reviews?.[ev.id]) {
1174
+ const { [ev.id]: _ended, ...rest } = next.reviews;
1175
+ next = {
1176
+ ...next,
1177
+ reviews: rest
1178
+ };
1179
+ }
1180
+ if (ev.type === "subagent_decision") return {
1181
+ state: showReviews(next, ev.id ?? ""),
1182
+ effects: []
1183
+ };
1184
+ const settled = applyToSettledSubagent(next, ev);
1185
+ if (settled) return {
1186
+ state: settled,
1187
+ effects: []
1188
+ };
1189
+ next = timeThought(next, ev, now);
1190
+ const parts = applyPartEvent(next.streaming?.parts ?? [], ev, options.imageUrl, options.words);
1191
+ if (parts !== null && (next.streaming !== null || parts.length > 0)) {
1192
+ const streaming = next.streaming ?? assistantMessage();
1193
+ const opened = next.streaming === null && next.turnEnded;
1194
+ next = {
1195
+ ...next,
1196
+ streaming: {
1197
+ ...streaming,
1198
+ parts
1199
+ },
1200
+ turnStartedAt: next.turnStartedAt ?? (opened ? now() : null)
1201
+ };
1202
+ if (ev.type === "error") next = finishTurn(next);
1203
+ return {
1204
+ state: next,
1205
+ effects: []
1206
+ };
1207
+ }
1208
+ switch (ev.type) {
1209
+ case "user_message": {
1210
+ const ownEcho = !!options.echoOf || !!ev.turnId && !!options.ownTurnIds?.has(ev.turnId) || !!ev.content && !!options.ownTexts?.has(ev.content);
1211
+ next = finishTurn(next);
1212
+ next = ownEcho ? takeEcho(next, options.echoOf, ev, options.imageUrl) : {
1213
+ ...next,
1214
+ messages: [...next.messages, userMessage(ev.content ?? "", false, void 0, ev.pastes, ev.images, options.imageUrl)]
1215
+ };
1216
+ next = {
1217
+ ...next,
1218
+ turnEnded: false,
1219
+ turnStartedAt: now()
1220
+ };
1221
+ break;
1222
+ }
1223
+ case "turn_start":
1224
+ next = {
1225
+ ...finishTurn(next),
1226
+ turnEnded: false,
1227
+ turnStartedAt: now()
1228
+ };
1229
+ break;
1230
+ case "user_note":
1231
+ next = noteHandedOver(next, options.echoOf, ev, options.imageUrl);
1232
+ break;
1233
+ case "approval_resolved":
1234
+ if (ev.approvalId) next = resolveApprovalEverywhere(next, ev.approvalId);
1235
+ break;
1236
+ case "usage_limit_wait":
1237
+ next = {
1238
+ ...next,
1239
+ waitingForUsageLimit: !!ev.content,
1240
+ usageLimitResumeAt: ev.content && ev.resumeAt || null
1241
+ };
1242
+ break;
1243
+ case "subagent_delivered": {
1244
+ const delivery = parseSubagentNotice(ev.notice ?? "");
1245
+ if (delivery && !delivery.silent) next = appendNotice(next, deliveryLine(delivery, options.words), delivery.body || void 0);
1246
+ break;
1247
+ }
1248
+ case "done": {
1249
+ const turnEnd = ev.turnEnd && options.words ? options.words.turnEnd(ev.turnEnd, turnVerb(ev.turnEnd.endedAt), (ev.turnEnd.pendingAgents ?? 0) > 0) : null;
1250
+ if (turnEnd) next = appendNotice(next, turnEnd);
1251
+ next = finishTurn(next);
1252
+ if (next.steered.length > 0) next = {
1253
+ ...next,
1254
+ messages: [...next.messages, ...next.steered],
1255
+ steered: []
1256
+ };
1257
+ break;
1258
+ }
1259
+ case "goal": {
1260
+ const text = goalText(ev.goalProgress, options.goalNotice);
1261
+ if (text) next = appendNotice(next, text, goalDetail(ev.goalProgress, options.words) ?? void 0);
1262
+ break;
1263
+ }
1264
+ case "recap": {
1265
+ const text = recapText(ev.content, options.recapNotice);
1266
+ if (text) next = appendNotice(next, text);
1267
+ break;
1268
+ }
1269
+ case "notice":
1270
+ case "warning": if (ev.recorded) next = placeSessionNotice(next, ev.content ?? "", ev.type);
1271
+ }
1272
+ return {
1273
+ state: next,
1274
+ effects: controlEffects(ev)
1275
+ };
1276
+ }
1277
+ export { TURN_VERBS, appendOwnMessage, appendShellRun, appendSteeredMessage, applyStreamEvent, approvalAnswerBody, approvalToPart, bashRunning, dropMessage, historyToMessages, initialTranscript, liveSessionStatus, markQueued, pendingApprovals, pendingMessages, resolveApprovalEverywhere, resumeCursor, reviewingCount, todosFromArgs, toolDecision, turnRunning, turnVerb, userInterruptedTool };