@firstpick/pi-package-webui 0.9.5 → 0.9.7

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.
Files changed (82) hide show
  1. package/README.md +11 -5
  2. package/bin/pi-webui.mjs +457 -77
  3. package/lib/git-workflow-preferences.mjs +21 -1
  4. package/lib/optional-feature-catalog.mjs +1 -1
  5. package/lib/session-actions.mjs +20 -2
  6. package/lib/session-tree-event-targets.mjs +70 -0
  7. package/lib/subagent-launch-policy.mjs +375 -0
  8. package/lib/subagent-launch-slots.mjs +2 -1
  9. package/package.json +1 -1
  10. package/public/app.js +2539 -292
  11. package/public/index.html +87 -31
  12. package/public/service-worker.js +4 -1
  13. package/public/stream-derived-output.mjs +799 -0
  14. package/public/stream-markdown-tail.mjs +204 -0
  15. package/public/stream-output-controller.mjs +193 -51
  16. package/public/stream-render-scheduler.mjs +85 -0
  17. package/public/styles.css +501 -19
  18. package/public/transcript-renderer.mjs +73 -24
  19. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  20. package/tests/browser/composer-action-grid-reorder.spec.mjs +114 -31
  21. package/tests/browser/control-visibility.spec.mjs +141 -2
  22. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  23. package/tests/browser/guided-git-fallback.spec.mjs +153 -0
  24. package/tests/browser/mobile-foundation.spec.mjs +28 -0
  25. package/tests/browser/stream-output-isolation.spec.mjs +308 -3
  26. package/tests/browser/user-noticeable-fixes.spec.mjs +204 -0
  27. package/tests/codex-fast-mode-static.test.mjs +2 -2
  28. package/tests/compact-sections-static.test.mjs +4 -0
  29. package/tests/composer-action-grid-reorder-static.test.mjs +8 -7
  30. package/tests/control-visibility-static.test.mjs +66 -3
  31. package/tests/controls-layout-static.test.mjs +3 -3
  32. package/tests/cwd-footer-reliability-static.test.mjs +1 -1
  33. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  34. package/tests/fast-mode-client-static.test.mjs +5 -2
  35. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  36. package/tests/file-viewer-image-static.test.mjs +3 -3
  37. package/tests/fixtures/fake-pi.mjs +57 -10
  38. package/tests/fixtures/streaming-workloads.mjs +36 -0
  39. package/tests/footer-provider-usage-visual-static.test.mjs +15 -0
  40. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -1
  41. package/tests/git-workflow-preferences.test.mjs +30 -1
  42. package/tests/guided-git-fallback-runtime.test.mjs +418 -0
  43. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  44. package/tests/guided-git-message-reliability-static.test.mjs +8 -7
  45. package/tests/interaction-state-stability-static.test.mjs +3 -1
  46. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  47. package/tests/intercom-conversations-http.test.mjs +16 -0
  48. package/tests/main-output-loading-static.test.mjs +3 -3
  49. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  50. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  51. package/tests/mobile-foundation-static.test.mjs +3 -3
  52. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  53. package/tests/mobile-static.test.mjs +80 -67
  54. package/tests/open-issue-wizard-static.test.mjs +1 -1
  55. package/tests/persistent-ui-layout-static.test.mjs +4 -4
  56. package/tests/prompt-input-vertical-scroll-static.test.mjs +26 -0
  57. package/tests/questionnaire-dialog.test.mjs +3 -3
  58. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  59. package/tests/resource-defaults-helper.test.mjs +12 -0
  60. package/tests/runtime-error-visibility.test.mjs +3 -3
  61. package/tests/session-auth-harness.test.mjs +26 -1
  62. package/tests/session-sampling-helper.test.mjs +1 -0
  63. package/tests/session-sampling-ui-static.test.mjs +3 -3
  64. package/tests/session-tree-event-targets.test.mjs +106 -0
  65. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  66. package/tests/stream-derived-output.test.mjs +121 -0
  67. package/tests/stream-markdown-tail.test.mjs +218 -0
  68. package/tests/stream-output-controller.test.mjs +119 -4
  69. package/tests/stream-output-isolation-static.test.mjs +27 -6
  70. package/tests/stream-output-workloads.test.mjs +40 -3
  71. package/tests/stream-render-scheduler.test.mjs +115 -0
  72. package/tests/streaming-ui-coupling.test.mjs +1 -1
  73. package/tests/subagent-launch-policy.test.mjs +532 -0
  74. package/tests/subagent-observability-static.test.mjs +2 -2
  75. package/tests/subagents-helper.test.mjs +211 -1
  76. package/tests/syntax-highlighting-static.test.mjs +3 -3
  77. package/tests/tab-close-continuity-static.test.mjs +23 -0
  78. package/tests/theme-customizer-static.test.mjs +1 -1
  79. package/tests/thinking-format-parser.test.mjs +15 -0
  80. package/tests/todo-filter-static.test.mjs +148 -0
  81. package/tests/transcript-markdown-tail.test.mjs +137 -0
  82. package/webui-rpc-helper.mjs +220 -3
@@ -0,0 +1,799 @@
1
+ const THINKING_FORMAT_OPEN_TAG_REGEX = /^<think\b[^>]*>/i;
2
+ const THINKING_FORMAT_CLOSE_TAG_REGEX = /<\/think\s*>/i;
3
+ const CHANNEL_THINKING_FORMAT_OPEN_TAG_REGEX = /^<\|([a-z][\w-]*)>/i;
4
+ const TODO_PROGRESS_LINE_REGEX = /^\s*(?:(?:[-*]|\d+[.)])\s*)?\[(?: |x|X|-)\]\s+.+$/;
5
+ const TODO_PROGRESS_PARTIAL_LINE_REGEX = /^\s*(?:(?:[-*]|\d+[.)])\s*)?\[(?: |x|X|-)?\]?\s*.*$/;
6
+
7
+ function escapeRegExp(value) {
8
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9
+ }
10
+
11
+ function textLines(raw) {
12
+ const value = String(raw || "");
13
+ const lines = [];
14
+ let start = 0;
15
+ for (let index = 0; index < value.length; index += 1) {
16
+ if (value[index] !== "\n") continue;
17
+ const end = index > start && value[index - 1] === "\r" ? index - 1 : index;
18
+ lines.push(value.slice(start, end));
19
+ start = index + 1;
20
+ }
21
+ if (start <= value.length) lines.push(value.slice(start));
22
+ return lines;
23
+ }
24
+
25
+ export function stripTodoProgressLinesAuthoritative(text, { streaming = false, todoProgressDetected = true } = {}) {
26
+ if (!todoProgressDetected) return String(text || "");
27
+ let inFence = false;
28
+ const kept = [];
29
+ const raw = String(text || "");
30
+ const hasTrailingNewline = /\r?\n$/.test(raw);
31
+ const lines = textLines(raw);
32
+
33
+ lines.forEach((line, index) => {
34
+ const isUnfinishedTail = streaming && !hasTrailingNewline && index === lines.length - 1;
35
+ if (/^\s*```/.test(line)) {
36
+ inFence = !inFence;
37
+ kept.push(line);
38
+ return;
39
+ }
40
+ if (!inFence && TODO_PROGRESS_LINE_REGEX.test(line)) return;
41
+ if (!inFence && isUnfinishedTail && TODO_PROGRESS_PARTIAL_LINE_REGEX.test(line)) return;
42
+ kept.push(line);
43
+ });
44
+
45
+ return kept.join("\n").replace(/\n{3,}/g, "\n\n").trim();
46
+ }
47
+
48
+ function isPartialThinkingFormatOpenTag(text) {
49
+ const value = String(text || "").trimStart().toLowerCase();
50
+ if (!value) return false;
51
+ if ("<think>".startsWith(value)) return true;
52
+ if (value === "<|" || /^<\|[a-z][\w-]*$/i.test(value)) return true;
53
+ return /^<think\b[^>]*$/i.test(value);
54
+ }
55
+
56
+ function stripPartialThinkingFormatClose(text, closeTag = "</think>") {
57
+ const value = String(text || "");
58
+ const lower = value.toLowerCase();
59
+ const expected = String(closeTag || "").toLowerCase();
60
+ const start = lower.lastIndexOf("<");
61
+ if (start < 0) return value;
62
+ const partial = lower.slice(start).trimEnd();
63
+ return expected.startsWith(partial) ? value.slice(0, start) : value;
64
+ }
65
+
66
+ function stripThinkingFormatOutputSeparator(text) {
67
+ return String(text || "").replace(/^(?:[ \t]*\r?\n)+/, "").replace(/^[ \t]+/, "");
68
+ }
69
+
70
+ function joinedThinkingFormatParts(parts) {
71
+ return parts.map((part) => String(part || "")).filter((part) => part.length > 0).join("\n\n");
72
+ }
73
+
74
+ function thinkingFormatOpenMatch(text) {
75
+ const value = String(text || "");
76
+ const think = THINKING_FORMAT_OPEN_TAG_REGEX.exec(value);
77
+ if (think) return { kind: "think", raw: think[0], closeRegex: THINKING_FORMAT_CLOSE_TAG_REGEX, closeTag: "</think>" };
78
+ const channel = CHANNEL_THINKING_FORMAT_OPEN_TAG_REGEX.exec(value);
79
+ if (!channel) return null;
80
+ const name = channel[1];
81
+ return { kind: "channel", raw: channel[0], closeRegex: new RegExp(`<${escapeRegExp(name)}\\|>`, "i"), closeTag: `<${name}|>` };
82
+ }
83
+
84
+ function thinkingFormatCloseMatch(text, open) {
85
+ const value = String(text || "");
86
+ if (open?.kind !== "think") return open?.closeRegex?.exec(value) || null;
87
+ const tokens = /<think\b[^>]*>|<\/think\s*>/gi;
88
+ let depth = 1;
89
+ let match = null;
90
+ while ((match = tokens.exec(value))) {
91
+ if (/^<\s*\/think/i.test(match[0])) {
92
+ depth -= 1;
93
+ if (depth === 0) return match;
94
+ } else {
95
+ depth += 1;
96
+ }
97
+ }
98
+ return null;
99
+ }
100
+
101
+ export function splitThinkingFormatTextAuthoritative(text, { streaming = false } = {}) {
102
+ let rest = String(text ?? "").trimStart();
103
+ if (!rest) return null;
104
+ if (!thinkingFormatOpenMatch(rest)) {
105
+ return streaming && isPartialThinkingFormatOpenTag(rest)
106
+ ? { hasThinkingFormat: true, thinkingText: "", finalText: "", complete: false }
107
+ : null;
108
+ }
109
+
110
+ const thinkingParts = [];
111
+ let open = thinkingFormatOpenMatch(rest);
112
+ while (open) {
113
+ const afterOpen = rest.slice(open.raw.length);
114
+ const close = thinkingFormatCloseMatch(afterOpen, open);
115
+ if (!close) {
116
+ thinkingParts.push(streaming ? stripPartialThinkingFormatClose(afterOpen, open.closeTag) : afterOpen);
117
+ return { hasThinkingFormat: true, thinkingText: joinedThinkingFormatParts(thinkingParts), finalText: "", complete: false };
118
+ }
119
+
120
+ thinkingParts.push(afterOpen.slice(0, close.index));
121
+ rest = afterOpen.slice(close.index + close[0].length);
122
+ const next = rest.trimStart();
123
+ open = thinkingFormatOpenMatch(next);
124
+ if (open) {
125
+ rest = next;
126
+ continue;
127
+ }
128
+ break;
129
+ }
130
+
131
+ return {
132
+ hasThinkingFormat: true,
133
+ thinkingText: joinedThinkingFormatParts(thinkingParts),
134
+ finalText: stripThinkingFormatOutputSeparator(rest),
135
+ complete: true,
136
+ };
137
+ }
138
+
139
+ export function deriveStreamOutputAuthoritative(rawText, { todoProgressDetected = true } = {}) {
140
+ const raw = String(rawText || "");
141
+ const assistantText = stripTodoProgressLinesAuthoritative(raw, { streaming: true, todoProgressDetected });
142
+ const thinkingFormat = splitThinkingFormatTextAuthoritative(assistantText, { streaming: true });
143
+ const finalText = thinkingFormat?.hasThinkingFormat
144
+ ? stripTodoProgressLinesAuthoritative(thinkingFormat.finalText, { streaming: true, todoProgressDetected })
145
+ : assistantText;
146
+ return { rawText: raw, assistantText, thinkingFormat, finalText };
147
+ }
148
+
149
+ function isWhitespace(char) {
150
+ return /\s/u.test(char);
151
+ }
152
+
153
+ function isDotCharacter(char) {
154
+ return /./u.test(char);
155
+ }
156
+
157
+ function createLineMeta() {
158
+ return {
159
+ prefixPhase: "leading",
160
+ partialCandidate: true,
161
+ partialMask: 0,
162
+ bracketReached: false,
163
+ fullPhase: "prefix",
164
+ fullValid: false,
165
+ fullInvalid: false,
166
+ separatorCount: 0,
167
+ fencePhase: "leading",
168
+ fence: false,
169
+ };
170
+ }
171
+
172
+ function feedLineMeta(meta, char) {
173
+ if (!meta.fence && meta.fencePhase !== "invalid") {
174
+ if (meta.fencePhase === "leading") {
175
+ if (isWhitespace(char)) {
176
+ // Keep looking for the first backtick.
177
+ } else if (char === "`") meta.fencePhase = "tick1";
178
+ else meta.fencePhase = "invalid";
179
+ } else if (meta.fencePhase === "tick1") {
180
+ meta.fencePhase = char === "`" ? "tick2" : "invalid";
181
+ } else if (meta.fencePhase === "tick2") {
182
+ if (char === "`") meta.fence = true;
183
+ else meta.fencePhase = "invalid";
184
+ }
185
+ }
186
+
187
+ if (!meta.bracketReached && meta.partialCandidate) {
188
+ if (meta.prefixPhase === "leading") {
189
+ if (isWhitespace(char)) {
190
+ // Leading whitespace is accepted.
191
+ } else if (char === "[") {
192
+ meta.bracketReached = true;
193
+ meta.partialMask = 0b1111;
194
+ meta.fullPhase = "status";
195
+ } else if (char === "-" || char === "*") meta.prefixPhase = "marker-space";
196
+ else if (/[0-9]/.test(char)) meta.prefixPhase = "digits";
197
+ else meta.partialCandidate = false;
198
+ } else if (meta.prefixPhase === "digits") {
199
+ if (/[0-9]/.test(char)) {
200
+ // Continue the ordered-list marker.
201
+ } else if (char === "." || char === ")") meta.prefixPhase = "marker-space";
202
+ else meta.partialCandidate = false;
203
+ } else if (meta.prefixPhase === "marker-space") {
204
+ if (isWhitespace(char)) {
205
+ // Whitespace between marker and bracket is accepted.
206
+ } else if (char === "[") {
207
+ meta.bracketReached = true;
208
+ meta.partialMask = 0b1111;
209
+ meta.fullPhase = "status";
210
+ } else meta.partialCandidate = false;
211
+ }
212
+ if (!meta.partialCandidate) meta.fullInvalid = true;
213
+ return;
214
+ }
215
+
216
+ let nextPartialMask = 0;
217
+ if ((meta.partialMask & 0b0001) && (char === " " || char === "x" || char === "X" || char === "-")) nextPartialMask |= 0b1110;
218
+ if ((meta.partialMask & 0b0011) && char === "]") nextPartialMask |= 0b1100;
219
+ if ((meta.partialMask & 0b0111) && isWhitespace(char)) nextPartialMask |= 0b1100;
220
+ if (meta.partialMask && isDotCharacter(char)) nextPartialMask |= 0b1000;
221
+ meta.partialMask = nextPartialMask;
222
+ meta.partialCandidate = nextPartialMask !== 0;
223
+
224
+ if (meta.fullInvalid) return;
225
+ if (meta.fullPhase === "status") {
226
+ if (char === " " || char === "x" || char === "X" || char === "-") meta.fullPhase = "close";
227
+ else meta.fullInvalid = true;
228
+ } else if (meta.fullPhase === "close") {
229
+ if (char === "]") meta.fullPhase = "separator";
230
+ else meta.fullInvalid = true;
231
+ } else if (meta.fullPhase === "separator") {
232
+ if (isWhitespace(char)) {
233
+ meta.separatorCount += 1;
234
+ meta.fullValid = meta.separatorCount >= 2 && isDotCharacter(char);
235
+ } else if (meta.separatorCount >= 1 && isDotCharacter(char)) {
236
+ meta.fullValid = true;
237
+ meta.fullPhase = "content";
238
+ } else meta.fullInvalid = true;
239
+ } else if (meta.fullPhase === "content") {
240
+ if (!isDotCharacter(char)) meta.fullInvalid = true;
241
+ }
242
+ if (meta.fullValid && !meta.fullInvalid && meta.fullPhase !== "separator") meta.fullPhase = "content";
243
+ }
244
+
245
+ function appendCollapsedNewlines(base, addition) {
246
+ if (!addition) return base;
247
+ let leading = 0;
248
+ while (addition[leading] === "\n") leading += 1;
249
+ if (leading === 0) return base + addition;
250
+ let trailing = 0;
251
+ while (base.length > trailing && base[base.length - trailing - 1] === "\n") trailing += 1;
252
+ const allowed = Math.max(0, 2 - trailing);
253
+ return base + "\n".repeat(Math.min(allowed, leading)) + addition.slice(leading);
254
+ }
255
+
256
+ function createTodoFilter(todoProgressDetected) {
257
+ return {
258
+ detected: !!todoProgressDetected,
259
+ inFence: false,
260
+ committed: "",
261
+ keptCount: 0,
262
+ line: "",
263
+ meta: createLineMeta(),
264
+ pendingCR: false,
265
+ rawText: "",
266
+ };
267
+ }
268
+
269
+ function commitTodoLine(state) {
270
+ const line = state.pendingCR ? state.line.slice(0, -1) : state.line;
271
+ const keep = !state.detected || state.meta.fence || state.inFence || !state.meta.fullValid || state.meta.fullInvalid;
272
+ if (keep) {
273
+ const addition = `${state.keptCount ? "\n" : ""}${line}`;
274
+ state.committed = appendCollapsedNewlines(state.committed, addition);
275
+ state.keptCount += 1;
276
+ }
277
+ if (state.detected && state.meta.fence) state.inFence = !state.inFence;
278
+ state.line = "";
279
+ state.meta = createLineMeta();
280
+ state.pendingCR = false;
281
+ }
282
+
283
+ function feedTodoFilter(state, suffix) {
284
+ const text = String(suffix || "");
285
+ state.rawText += text;
286
+ if (!state.detected) return;
287
+ for (const char of text) {
288
+ if (char === "\n") {
289
+ commitTodoLine(state);
290
+ continue;
291
+ }
292
+ if (state.pendingCR) {
293
+ feedLineMeta(state.meta, "\r");
294
+ state.pendingCR = false;
295
+ }
296
+ state.line += char;
297
+ if (char === "\r") state.pendingCR = true;
298
+ else feedLineMeta(state.meta, char);
299
+ }
300
+ }
301
+
302
+ function todoFilterValue(state) {
303
+ if (!state.detected) return state.rawText;
304
+ let meta = state.meta;
305
+ if (state.pendingCR) {
306
+ meta = structuredClone(meta);
307
+ feedLineMeta(meta, "\r");
308
+ }
309
+ const keepTail = meta.fence || state.inFence || !meta.partialCandidate || !meta.bracketReached;
310
+ const addition = keepTail ? `${state.keptCount ? "\n" : ""}${state.line}` : "";
311
+ return appendCollapsedNewlines(state.committed, addition).trim();
312
+ }
313
+
314
+ function createOpenDetector() {
315
+ return { buffer: "", phase: "start", index: 0, invalid: false, complete: null };
316
+ }
317
+
318
+ function feedOpenDetector(detector, char) {
319
+ if (detector.invalid || detector.complete) return;
320
+ detector.buffer += char;
321
+ if (detector.phase === "start") {
322
+ if (char === "<") detector.phase = "after-lt";
323
+ else detector.invalid = true;
324
+ } else if (detector.phase === "after-lt") {
325
+ if (char === "|") detector.phase = "channel-first";
326
+ else if (char.toLowerCase() === "t") {
327
+ detector.phase = "think-name";
328
+ detector.index = 1;
329
+ } else detector.invalid = true;
330
+ } else if (detector.phase === "think-name") {
331
+ const expected = "think";
332
+ if (char.toLowerCase() !== expected[detector.index]) detector.invalid = true;
333
+ else if (++detector.index === expected.length) detector.phase = "think-boundary";
334
+ } else if (detector.phase === "think-boundary") {
335
+ if (char === ">") detector.complete = { kind: "think", raw: detector.buffer, closeTag: "</think>" };
336
+ else if (/\w/.test(char)) detector.invalid = true;
337
+ else detector.phase = "think-attrs";
338
+ } else if (detector.phase === "think-attrs") {
339
+ if (char === ">") detector.complete = { kind: "think", raw: detector.buffer, closeTag: "</think>" };
340
+ } else if (detector.phase === "channel-first") {
341
+ if (/[a-z]/i.test(char)) detector.phase = "channel-name";
342
+ else detector.invalid = true;
343
+ } else if (detector.phase === "channel-name") {
344
+ if (char === ">") {
345
+ const name = detector.buffer.slice(2, -1);
346
+ detector.complete = { kind: "channel", raw: detector.buffer, closeTag: `<${name}|>` };
347
+ } else if (!/[\w-]/.test(char)) detector.invalid = true;
348
+ }
349
+ }
350
+
351
+ function openDetectorIsPartial(detector) {
352
+ return !detector.invalid && !detector.complete && detector.buffer.length > 0;
353
+ }
354
+
355
+ function createInsideState(open) {
356
+ return {
357
+ open,
358
+ depth: 1,
359
+ stable: "",
360
+ token: null,
361
+ };
362
+ }
363
+
364
+ function createThinkToken() {
365
+ return { buffer: "<", phase: "after-lt", index: 0, kind: "", hidden: true };
366
+ }
367
+
368
+ function restartThinkToken(inside, buffer) {
369
+ const lastIsOpen = buffer.endsWith("<");
370
+ inside.stable += lastIsOpen ? buffer.slice(0, -1) : buffer;
371
+ inside.token = lastIsOpen ? createThinkToken() : null;
372
+ }
373
+
374
+ function feedThinkToken(inside, char) {
375
+ const token = inside.token;
376
+ if (token.phase === "inner-close-complete") {
377
+ inside.stable += token.buffer;
378
+ inside.token = null;
379
+ return feedThinkInside(inside, char);
380
+ }
381
+ token.buffer += char;
382
+ if (token.phase === "after-lt") {
383
+ if (char === "/") {
384
+ token.kind = "close";
385
+ token.phase = "close-name";
386
+ token.index = 0;
387
+ token.hidden = true;
388
+ } else if (char.toLowerCase() === "t") {
389
+ token.kind = "open";
390
+ token.phase = "open-name";
391
+ token.index = 1;
392
+ token.hidden = false;
393
+ } else restartThinkToken(inside, token.buffer);
394
+ return null;
395
+ }
396
+
397
+ if (token.phase === "open-name") {
398
+ const expected = "think";
399
+ if (char.toLowerCase() !== expected[token.index]) restartThinkToken(inside, token.buffer);
400
+ else if (++token.index === expected.length) token.phase = "open-boundary";
401
+ return null;
402
+ }
403
+ if (token.phase === "open-boundary") {
404
+ if (char === ">") {
405
+ inside.stable += token.buffer;
406
+ inside.depth += 1;
407
+ inside.token = null;
408
+ } else if (/\w/.test(char)) restartThinkToken(inside, token.buffer);
409
+ else token.phase = "open-attrs";
410
+ return null;
411
+ }
412
+ if (token.phase === "open-attrs") {
413
+ if (char === ">") {
414
+ inside.stable += token.buffer;
415
+ inside.depth += 1;
416
+ inside.token = null;
417
+ }
418
+ return null;
419
+ }
420
+ if (token.phase === "close-name") {
421
+ const expected = "think";
422
+ if (char.toLowerCase() === expected[token.index]) {
423
+ token.index += 1;
424
+ if (token.index === expected.length) token.phase = "close-end";
425
+ } else if (isWhitespace(char)) token.phase = "close-hide-only";
426
+ else restartThinkToken(inside, token.buffer);
427
+ return null;
428
+ }
429
+ if (token.phase === "close-hide-only") {
430
+ if (!isWhitespace(char)) restartThinkToken(inside, token.buffer);
431
+ return null;
432
+ }
433
+ if (token.phase === "close-end") {
434
+ if (char === ">") return finishThinkClose(inside);
435
+ if (isWhitespace(char)) token.phase = "close-space";
436
+ else restartThinkToken(inside, token.buffer);
437
+ return null;
438
+ }
439
+ if (token.phase === "close-space") {
440
+ if (char === ">") return finishThinkClose(inside);
441
+ if (!isWhitespace(char)) restartThinkToken(inside, token.buffer);
442
+ }
443
+ return null;
444
+ }
445
+
446
+ function finishThinkClose(inside) {
447
+ const raw = inside.token.buffer;
448
+ inside.depth -= 1;
449
+ if (inside.depth === 0) {
450
+ inside.token = null;
451
+ return { closed: true, raw };
452
+ }
453
+ inside.token.phase = "inner-close-complete";
454
+ inside.token.hidden = true;
455
+ return null;
456
+ }
457
+
458
+ function feedThinkInside(inside, char) {
459
+ if (inside.token) return feedThinkToken(inside, char);
460
+ if (char === "<") inside.token = createThinkToken();
461
+ else inside.stable += char;
462
+ return null;
463
+ }
464
+
465
+ function createChannelToken(expected) {
466
+ return { expected: expected.toLowerCase(), buffer: "<", matchIndex: 1, trailingWhitespace: false, hidden: true };
467
+ }
468
+
469
+ function restartChannelToken(inside, buffer) {
470
+ const lastIsOpen = buffer.endsWith("<");
471
+ inside.stable += lastIsOpen ? buffer.slice(0, -1) : buffer;
472
+ inside.token = lastIsOpen ? createChannelToken(inside.open.closeTag) : null;
473
+ }
474
+
475
+ function feedChannelInside(inside, char) {
476
+ if (!inside.token) {
477
+ if (char === "<") inside.token = createChannelToken(inside.open.closeTag);
478
+ else inside.stable += char;
479
+ return null;
480
+ }
481
+ const token = inside.token;
482
+ token.buffer += char;
483
+ if (token.trailingWhitespace) {
484
+ if (!isWhitespace(char)) restartChannelToken(inside, token.buffer);
485
+ return null;
486
+ }
487
+ if (char.toLowerCase() === token.expected[token.matchIndex]) {
488
+ token.matchIndex += 1;
489
+ if (token.matchIndex === token.expected.length) {
490
+ inside.token = null;
491
+ return { closed: true, raw: token.buffer };
492
+ }
493
+ } else if (isWhitespace(char) && token.matchIndex < token.expected.length) {
494
+ token.trailingWhitespace = true;
495
+ } else restartChannelToken(inside, token.buffer);
496
+ return null;
497
+ }
498
+
499
+ function insideValue(inside) {
500
+ return inside.stable + (inside.token?.hidden ? "" : inside.token?.buffer || "");
501
+ }
502
+
503
+ function createSeparatorState() {
504
+ return { phase: "leading", pendingSpaces: "", pendingCR: false, output: "" };
505
+ }
506
+
507
+ function feedSeparator(state, char) {
508
+ if (state.phase === "output") {
509
+ state.output += char;
510
+ return;
511
+ }
512
+ if (state.pendingCR) {
513
+ if (char === "\n") {
514
+ state.pendingSpaces = "";
515
+ state.pendingCR = false;
516
+ return;
517
+ }
518
+ state.output += `\r${char}`;
519
+ state.pendingSpaces = "";
520
+ state.pendingCR = false;
521
+ state.phase = "output";
522
+ return;
523
+ }
524
+ if (char === " " || char === "\t") state.pendingSpaces += char;
525
+ else if (char === "\n") state.pendingSpaces = "";
526
+ else if (char === "\r") {
527
+ state.pendingSpaces = "";
528
+ state.pendingCR = true;
529
+ } else {
530
+ state.output += char;
531
+ state.pendingSpaces = "";
532
+ state.phase = "output";
533
+ }
534
+ }
535
+
536
+ function separatorValue(state) {
537
+ return state.output + (state.pendingCR ? "\r" : "");
538
+ }
539
+
540
+ function createThinkingState() {
541
+ return {
542
+ input: "",
543
+ mode: "leading",
544
+ leading: "",
545
+ opener: null,
546
+ hasThinkingFormat: false,
547
+ joined: "",
548
+ inside: null,
549
+ betweenRaw: "",
550
+ betweenTrimmedStarted: false,
551
+ betweenOpener: null,
552
+ separator: null,
553
+ finalText: "",
554
+ };
555
+ }
556
+
557
+ function appendThinkingPart(state, part) {
558
+ if (!part) return;
559
+ state.joined += `${state.joined ? "\n\n" : ""}${part}`;
560
+ }
561
+
562
+ function thinkingTextValue(state) {
563
+ if (!state.hasThinkingFormat) return "";
564
+ const current = state.mode === "inside" ? insideValue(state.inside) : "";
565
+ if (!current) return state.joined;
566
+ return state.joined ? `${state.joined}\n\n${current}` : current;
567
+ }
568
+
569
+ function thinkingResult(state) {
570
+ if (!state.hasThinkingFormat) return null;
571
+ return {
572
+ hasThinkingFormat: true,
573
+ thinkingText: thinkingTextValue(state),
574
+ finalText: state.mode === "final"
575
+ ? state.finalText
576
+ : state.mode === "between"
577
+ ? separatorValue(state.separator)
578
+ : "",
579
+ complete: state.mode === "between" || state.mode === "final",
580
+ };
581
+ }
582
+
583
+ function beginInside(state, open) {
584
+ state.hasThinkingFormat = true;
585
+ state.mode = "inside";
586
+ state.inside = createInsideState(open);
587
+ state.betweenRaw = "";
588
+ state.betweenTrimmedStarted = false;
589
+ state.betweenOpener = null;
590
+ state.separator = null;
591
+ }
592
+
593
+ function beginBetween(state) {
594
+ appendThinkingPart(state, insideValue(state.inside));
595
+ state.inside = null;
596
+ state.mode = "between";
597
+ state.betweenRaw = "";
598
+ state.betweenTrimmedStarted = false;
599
+ state.betweenOpener = createOpenDetector();
600
+ state.separator = createSeparatorState();
601
+ }
602
+
603
+ function feedBetween(state, char) {
604
+ state.betweenRaw += char;
605
+ feedSeparator(state.separator, char);
606
+ if (!state.betweenTrimmedStarted) {
607
+ if (isWhitespace(char)) return;
608
+ state.betweenTrimmedStarted = true;
609
+ }
610
+ feedOpenDetector(state.betweenOpener, char);
611
+ if (state.betweenOpener.complete) {
612
+ beginInside(state, state.betweenOpener.complete);
613
+ } else if (state.betweenOpener.invalid) {
614
+ state.mode = "final";
615
+ state.finalText = separatorValue(state.separator);
616
+ state.betweenOpener = null;
617
+ state.separator = null;
618
+ }
619
+ }
620
+
621
+ function feedThinkingState(state, suffix) {
622
+ const text = String(suffix || "");
623
+ state.input += text;
624
+ for (const char of text) {
625
+ if (state.mode === "none") continue;
626
+ if (state.mode === "final") {
627
+ state.finalText += char;
628
+ continue;
629
+ }
630
+ if (state.mode === "leading") {
631
+ if (isWhitespace(char)) {
632
+ state.leading += char;
633
+ continue;
634
+ }
635
+ state.mode = "opening";
636
+ state.opener = createOpenDetector();
637
+ }
638
+ if (state.mode === "opening") {
639
+ feedOpenDetector(state.opener, char);
640
+ if (state.opener.complete) beginInside(state, state.opener.complete);
641
+ else if (state.opener.invalid) {
642
+ state.mode = "none";
643
+ state.hasThinkingFormat = false;
644
+ } else state.hasThinkingFormat = openDetectorIsPartial(state.opener);
645
+ continue;
646
+ }
647
+ if (state.mode === "inside") {
648
+ const closed = state.inside.open.kind === "think"
649
+ ? feedThinkInside(state.inside, char)
650
+ : feedChannelInside(state.inside, char);
651
+ if (closed) beginBetween(state);
652
+ continue;
653
+ }
654
+ if (state.mode === "between") feedBetween(state, char);
655
+ }
656
+ }
657
+
658
+ function thinkingFinalSource(state, assistantText) {
659
+ const parsed = thinkingResult(state);
660
+ return parsed?.hasThinkingFormat ? parsed.finalText : assistantText;
661
+ }
662
+
663
+ function sameThinkingFormat(left, right) {
664
+ return JSON.stringify(left) === JSON.stringify(right);
665
+ }
666
+
667
+ function sameDerived(left, right) {
668
+ return left.rawText === right.rawText
669
+ && left.assistantText === right.assistantText
670
+ && left.finalText === right.finalText
671
+ && sameThinkingFormat(left.thinkingFormat, right.thinkingFormat);
672
+ }
673
+
674
+ function buildIncremental(rawText, todoProgressDetected) {
675
+ const raw = String(rawText || "");
676
+ const todo = createTodoFilter(todoProgressDetected);
677
+ feedTodoFilter(todo, raw);
678
+ const assistantText = todoFilterValue(todo);
679
+ const thinking = createThinkingState();
680
+ feedThinkingState(thinking, assistantText);
681
+ const finalSource = thinkingFinalSource(thinking, assistantText);
682
+ const finalTodo = createTodoFilter(todoProgressDetected);
683
+ feedTodoFilter(finalTodo, finalSource);
684
+ return { todo, thinking, thinkingInput: assistantText, finalTodo, finalInput: finalSource };
685
+ }
686
+
687
+ export function createStreamDerivedOutputState({ todoProgressDetected = true, shadow = false } = {}) {
688
+ let detected = !!todoProgressDetected;
689
+ let rawText = "";
690
+ let incremental = buildIncremental("", detected);
691
+ let value = deriveStreamOutputAuthoritative("", { todoProgressDetected: detected });
692
+ let degraded = false;
693
+ let diagnostics = { scannedCodeUnits: 0, fallbackReason: "", shadowMismatch: false };
694
+
695
+ function currentIncrementalValue() {
696
+ const assistantText = todoFilterValue(incremental.todo);
697
+ const thinkingFormat = thinkingResult(incremental.thinking);
698
+ return {
699
+ rawText,
700
+ assistantText,
701
+ thinkingFormat,
702
+ finalText: thinkingFormat?.hasThinkingFormat ? todoFilterValue(incremental.finalTodo) : assistantText,
703
+ };
704
+ }
705
+
706
+ function rebuild(reason, scannedCodeUnits = rawText.length) {
707
+ incremental = buildIncremental(rawText, detected);
708
+ const candidate = currentIncrementalValue();
709
+ const authoritative = deriveStreamOutputAuthoritative(rawText, { todoProgressDetected: detected });
710
+ const mismatch = !sameDerived(candidate, authoritative);
711
+ degraded = degraded || mismatch;
712
+ value = mismatch ? authoritative : candidate;
713
+ diagnostics = { scannedCodeUnits, fallbackReason: reason, shadowMismatch: mismatch };
714
+ return value;
715
+ }
716
+
717
+ function append(delta) {
718
+ const suffix = String(delta || "");
719
+ if (!suffix) {
720
+ diagnostics = { scannedCodeUnits: 0, fallbackReason: "", shadowMismatch: false };
721
+ return value;
722
+ }
723
+ rawText += suffix;
724
+ if (degraded) return rebuild("shadow-mismatch", rawText.length);
725
+
726
+ feedTodoFilter(incremental.todo, suffix);
727
+ const assistantText = todoFilterValue(incremental.todo);
728
+ if (!assistantText.startsWith(incremental.thinkingInput)) {
729
+ incremental.thinking = createThinkingState();
730
+ feedThinkingState(incremental.thinking, assistantText);
731
+ diagnostics = { scannedCodeUnits: suffix.length + assistantText.length, fallbackReason: "assistant-divergence", shadowMismatch: false };
732
+ } else {
733
+ feedThinkingState(incremental.thinking, assistantText.slice(incremental.thinkingInput.length));
734
+ diagnostics = { scannedCodeUnits: suffix.length, fallbackReason: "", shadowMismatch: false };
735
+ }
736
+ incremental.thinkingInput = assistantText;
737
+
738
+ const finalSource = thinkingFinalSource(incremental.thinking, assistantText);
739
+ if (!finalSource.startsWith(incremental.finalInput)) {
740
+ incremental.finalTodo = createTodoFilter(detected);
741
+ feedTodoFilter(incremental.finalTodo, finalSource);
742
+ diagnostics.scannedCodeUnits += finalSource.length;
743
+ diagnostics.fallbackReason ||= "final-divergence";
744
+ } else {
745
+ feedTodoFilter(incremental.finalTodo, finalSource.slice(incremental.finalInput.length));
746
+ }
747
+ incremental.finalInput = finalSource;
748
+ value = currentIncrementalValue();
749
+
750
+ if (shadow) {
751
+ const authoritative = deriveStreamOutputAuthoritative(rawText, { todoProgressDetected: detected });
752
+ if (!sameDerived(value, authoritative)) {
753
+ degraded = true;
754
+ diagnostics.shadowMismatch = true;
755
+ diagnostics.fallbackReason ||= "shadow-mismatch";
756
+ value = authoritative;
757
+ }
758
+ }
759
+ return value;
760
+ }
761
+
762
+ return {
763
+ append,
764
+ replace(text, { reason = "snapshot", force = false } = {}) {
765
+ const next = String(text || "");
766
+ if (!force && next === rawText) {
767
+ diagnostics = { scannedCodeUnits: 0, fallbackReason: "", shadowMismatch: false };
768
+ return value;
769
+ }
770
+ rawText = next;
771
+ degraded = false;
772
+ return rebuild(reason, rawText.length);
773
+ },
774
+ reset({ todoProgressDetected: nextDetected = detected, reason = "reset" } = {}) {
775
+ detected = !!nextDetected;
776
+ rawText = "";
777
+ degraded = false;
778
+ incremental = buildIncremental("", detected);
779
+ value = deriveStreamOutputAuthoritative("", { todoProgressDetected: detected });
780
+ diagnostics = { scannedCodeUnits: 0, fallbackReason: reason, shadowMismatch: false };
781
+ return value;
782
+ },
783
+ setTodoProgressDetected(nextDetected) {
784
+ const next = !!nextDetected;
785
+ if (next === detected) return value;
786
+ detected = next;
787
+ degraded = false;
788
+ return rebuild("todo-mode-change", rawText.length);
789
+ },
790
+ value() {
791
+ return value;
792
+ },
793
+ takeDiagnostics() {
794
+ const result = diagnostics;
795
+ diagnostics = { scannedCodeUnits: 0, fallbackReason: "", shadowMismatch: false };
796
+ return result;
797
+ },
798
+ };
799
+ }