@leitwerk-dev/protocol 0.1.9 → 0.2.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.
Files changed (100) hide show
  1. package/dist/api-token-contracts.d.ts +25 -0
  2. package/dist/api-token-contracts.d.ts.map +1 -0
  3. package/dist/{chunk-SKQG5SE3.js → chunk-J4VMD5ST.js} +17 -26
  4. package/dist/chunk-J4VMD5ST.js.map +1 -0
  5. package/dist/{chunk-J7LXDQAN.js → chunk-Z4IU6KEN.js} +40 -6
  6. package/dist/chunk-Z4IU6KEN.js.map +1 -0
  7. package/dist/compact-turn-summary.d.ts +31 -0
  8. package/dist/compact-turn-summary.d.ts.map +1 -0
  9. package/dist/config-snapshot.d.ts +2 -0
  10. package/dist/config-snapshot.d.ts.map +1 -1
  11. package/dist/config-snapshot.js +1 -1
  12. package/dist/config-snapshot.js.map +1 -1
  13. package/dist/extension-ui-contracts.d.ts +27 -0
  14. package/dist/extension-ui-contracts.d.ts.map +1 -0
  15. package/dist/form-contract.js +1 -1
  16. package/dist/form-contract.js.map +1 -1
  17. package/dist/{http-contracts-DP9P_2YM.d.ts → http-contracts-ht8DDU4J.d.ts} +163 -37
  18. package/dist/http-contracts.d.ts +109 -38
  19. package/dist/http-contracts.d.ts.map +1 -1
  20. package/dist/http-contracts.js +32 -432
  21. package/dist/http-contracts.js.map +1 -1
  22. package/dist/index.d.ts +5 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1196 -20
  25. package/dist/index.js.map +1 -1
  26. package/dist/initial-prompt.d.ts.map +1 -1
  27. package/dist/launcher-contract.js +1 -1
  28. package/dist/launcher-contract.js.map +1 -1
  29. package/dist/live-turn-projection.d.ts +1 -1
  30. package/dist/live-turn-projection.d.ts.map +1 -1
  31. package/dist/protocol.d.ts +63 -16
  32. package/dist/protocol.d.ts.map +1 -1
  33. package/dist/protocol.js +37 -259
  34. package/dist/protocol.js.map +1 -1
  35. package/dist/streamable-events.d.ts +1 -1
  36. package/dist/streamable-events.d.ts.map +1 -1
  37. package/dist/ticket-creation-contracts.d.ts +33 -0
  38. package/dist/ticket-creation-contracts.d.ts.map +1 -0
  39. package/dist/timeline-projection.d.ts +1 -1
  40. package/dist/timeline-projection.d.ts.map +1 -1
  41. package/dist/tool-renderer-contract.js +10 -21
  42. package/dist/tool-renderer-contract.js.map +1 -1
  43. package/dist/tool-result-truncation.d.ts +6 -0
  44. package/dist/tool-result-truncation.d.ts.map +1 -0
  45. package/dist/turn-continuation.d.ts +1 -1
  46. package/dist/turn-continuation.d.ts.map +1 -1
  47. package/dist/turn-trace-projection.d.ts +5 -0
  48. package/dist/turn-trace-projection.d.ts.map +1 -0
  49. package/dist/usage-snapshot.d.ts +3 -1
  50. package/dist/usage-snapshot.d.ts.map +1 -1
  51. package/dist/ws-event-payloads.d.ts +2 -1
  52. package/dist/ws-event-payloads.d.ts.map +1 -1
  53. package/package.json +3 -3
  54. package/src/api-token-contracts.ts +24 -0
  55. package/src/compact-turn-summary.ts +119 -0
  56. package/src/config-snapshot.ts +2 -0
  57. package/src/extension-ui-contracts.ts +45 -0
  58. package/src/http-contracts.ts +139 -68
  59. package/src/index.ts +5 -0
  60. package/src/initial-prompt.ts +3 -6
  61. package/src/live-turn-projection.ts +41 -113
  62. package/src/protocol.ts +52 -12
  63. package/src/streamable-events.ts +2 -0
  64. package/src/ticket-creation-contracts.ts +34 -0
  65. package/src/timeline-projection.ts +5 -4
  66. package/src/tool-result-truncation.ts +94 -0
  67. package/src/turn-continuation.ts +22 -46
  68. package/src/turn-trace-projection.ts +42 -0
  69. package/src/usage-snapshot.ts +25 -59
  70. package/src/ws-event-payloads.ts +5 -14
  71. package/dist/chunk-J7LXDQAN.js.map +0 -1
  72. package/dist/chunk-SKQG5SE3.js.map +0 -1
  73. package/dist/external-review.js +0 -2
  74. package/dist/external-review.js.map +0 -1
  75. package/dist/initial-prompt.js +0 -103
  76. package/dist/initial-prompt.js.map +0 -1
  77. package/dist/live-turn-projection.js +0 -395
  78. package/dist/live-turn-projection.js.map +0 -1
  79. package/dist/pi-session-message.js +0 -27
  80. package/dist/pi-session-message.js.map +0 -1
  81. package/dist/primary-path-snapshot.js +0 -2
  82. package/dist/primary-path-snapshot.js.map +0 -1
  83. package/dist/session-entry-tree.js +0 -42
  84. package/dist/session-entry-tree.js.map +0 -1
  85. package/dist/streamable-events.js +0 -17
  86. package/dist/streamable-events.js.map +0 -1
  87. package/dist/text-preview.js +0 -23
  88. package/dist/text-preview.js.map +0 -1
  89. package/dist/timeline-projection.js +0 -33
  90. package/dist/timeline-projection.js.map +0 -1
  91. package/dist/timestamp-ordering.js +0 -15
  92. package/dist/timestamp-ordering.js.map +0 -1
  93. package/dist/turn-continuation.js +0 -179
  94. package/dist/turn-continuation.js.map +0 -1
  95. package/dist/usage-by-turn-record.js +0 -25
  96. package/dist/usage-by-turn-record.js.map +0 -1
  97. package/dist/usage-snapshot.js +0 -120
  98. package/dist/usage-snapshot.js.map +0 -1
  99. package/dist/ws-event-payloads.js +0 -47
  100. package/dist/ws-event-payloads.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,21 +1,1197 @@
1
- export * from "./config-snapshot.js";
2
- export * from "./external-review.js";
3
- export * from "./form-contract.js";
4
- export * from "./http-contracts.js";
5
- export * from "./initial-prompt.js";
6
- export * from "./launcher-contract.js";
7
- export * from "./live-turn-projection.js";
8
- export * from "./pi-session-message.js";
9
- export * from "./primary-path-snapshot.js";
10
- export * from "./protocol.js";
11
- export * from "./session-entry-tree.js";
12
- export * from "./streamable-events.js";
13
- export * from "./text-preview.js";
14
- export * from "./timeline-projection.js";
15
- export * from "./timestamp-ordering.js";
16
- export * from "./tool-renderer-contract.js";
17
- export * from "./turn-continuation.js";
18
- export * from "./usage-by-turn-record.js";
19
- export * from "./usage-snapshot.js";
20
- export * from "./ws-event-payloads.js";
1
+ import "./chunk-6L4W7WPV.js";
2
+ import "./chunk-AAV3AAOF.js";
3
+ import {
4
+ parseActionRequestBody,
5
+ parseFutureActionPayloadJson,
6
+ parseFutureActionPayloadObject,
7
+ parseFutureLaunchPayloadJson,
8
+ parseFutureLaunchPayloadObject,
9
+ parseLauncherInputJson,
10
+ parseLauncherModelConfigInput,
11
+ parseLauncherRequestBody,
12
+ parseLauncherTurnConfigsJson,
13
+ parseScheduleRequestInput,
14
+ resolvePromptCacheSwitch,
15
+ serializeFutureActionPayload,
16
+ serializeFutureLaunchPayload,
17
+ validateScheduleRequestInput
18
+ } from "./chunk-J4VMD5ST.js";
19
+ import "./chunk-IEMT3JG4.js";
20
+ import {
21
+ WS_FRAME_DURABILITY,
22
+ WS_PI_STREAM_TYPES,
23
+ WS_PRIMARY_PATH_TYPES,
24
+ WS_PROCESS_TYPES,
25
+ WS_PROTOCOL_VERSION,
26
+ createDurableWsFrame,
27
+ createEphemeralWsFrame,
28
+ err,
29
+ mapWorkerEventToWsType,
30
+ nullableStringSchema,
31
+ ok,
32
+ optionalNullableStringSchema,
33
+ parseLiteral,
34
+ parsePrimaryPathWsFrameInput,
35
+ parseSchema,
36
+ parseWsFrame,
37
+ unknownRecordSchema
38
+ } from "./chunk-Z4IU6KEN.js";
39
+ import {
40
+ TOOL_CALL_RENDERER_VALUE_KINDS,
41
+ TOOL_CALL_RENDERER_VALUE_SOURCES,
42
+ readValueAtPath
43
+ } from "./chunk-IWVU76M5.js";
44
+
45
+ // src/usage-snapshot.ts
46
+ import { copiedUnknownRecordSchema as unknownRecordSchema2 } from "@leitwerk-dev/domain";
47
+ import * as v from "valibot";
48
+ function readFiniteNumber(value) {
49
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
50
+ }
51
+ function normalizeUsageCostSnapshot(value) {
52
+ const parsedValue = v.safeParse(unknownRecordSchema2, value);
53
+ if (!parsedValue.success) {
54
+ return null;
55
+ }
56
+ const record = parsedValue.output;
57
+ const input = readFiniteNumber(record.input) ?? 0;
58
+ const output = readFiniteNumber(record.output) ?? 0;
59
+ const cacheRead = readFiniteNumber(record.cacheRead) ?? 0;
60
+ const cacheWrite = readFiniteNumber(record.cacheWrite) ?? 0;
61
+ return {
62
+ input,
63
+ output,
64
+ cacheRead,
65
+ cacheWrite,
66
+ total: readFiniteNumber(record.total) ?? input + output + cacheRead + cacheWrite
67
+ };
68
+ }
69
+ function cloneUsageSnapshot(usage) {
70
+ if (!usage) {
71
+ return null;
72
+ }
73
+ return {
74
+ ...usage,
75
+ cost: usage.cost ? { ...usage.cost } : null
76
+ };
77
+ }
78
+ function normalizeUsageSnapshot(value) {
79
+ const parsedValue = v.safeParse(unknownRecordSchema2, value);
80
+ if (!parsedValue.success) {
81
+ return null;
82
+ }
83
+ const record = parsedValue.output;
84
+ const input = readFiniteNumber(record.input) ?? 0;
85
+ const output = readFiniteNumber(record.output) ?? 0;
86
+ const reasoning = readFiniteNumber(record.reasoning);
87
+ const cacheRead = readFiniteNumber(record.cacheRead) ?? 0;
88
+ const cacheWrite = readFiniteNumber(record.cacheWrite) ?? 0;
89
+ const cost = normalizeUsageCostSnapshot(record.cost);
90
+ const maxInputTokens = readFiniteNumber(record.maxInputTokens);
91
+ const hasExplicitUsageTelemetry = ["input", "output", "reasoning", "cacheRead", "cacheWrite", "totalTokens"].some(
92
+ (key) => readFiniteNumber(record[key]) !== void 0
93
+ ) || cost !== null;
94
+ if (!hasExplicitUsageTelemetry) {
95
+ return null;
96
+ }
97
+ return {
98
+ input,
99
+ output,
100
+ ...reasoning !== void 0 ? { reasoning } : {},
101
+ cacheRead,
102
+ cacheWrite,
103
+ totalTokens: readFiniteNumber(record.totalTokens) ?? input + output + cacheRead + cacheWrite,
104
+ cost,
105
+ requestCount: Math.max(0, Math.floor(readFiniteNumber(record.requestCount) ?? 1)),
106
+ maxInputTokens: maxInputTokens !== void 0 ? Math.max(0, maxInputTokens) : input
107
+ };
108
+ }
109
+ function mergeUsageSnapshots(total, usage) {
110
+ if (!usage) {
111
+ return cloneUsageSnapshot(total);
112
+ }
113
+ if (!total) {
114
+ return cloneUsageSnapshot(usage);
115
+ }
116
+ const hasRequestMetrics = total.requestCount !== void 0 || usage.requestCount !== void 0 || total.maxInputTokens !== void 0 || usage.maxInputTokens !== void 0;
117
+ return {
118
+ input: total.input + usage.input,
119
+ output: total.output + usage.output,
120
+ ...total.reasoning !== void 0 || usage.reasoning !== void 0 ? { reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0) } : {},
121
+ cacheRead: total.cacheRead + usage.cacheRead,
122
+ cacheWrite: total.cacheWrite + usage.cacheWrite,
123
+ totalTokens: total.totalTokens + usage.totalTokens,
124
+ cost: total.cost && usage.cost ? {
125
+ input: total.cost.input + usage.cost.input,
126
+ output: total.cost.output + usage.cost.output,
127
+ cacheRead: total.cost.cacheRead + usage.cost.cacheRead,
128
+ cacheWrite: total.cost.cacheWrite + usage.cost.cacheWrite,
129
+ total: total.cost.total + usage.cost.total
130
+ } : null,
131
+ ...hasRequestMetrics ? {
132
+ requestCount: (total.requestCount ?? 1) + (usage.requestCount ?? 1),
133
+ maxInputTokens: Math.max(
134
+ total.maxInputTokens ?? total.input,
135
+ usage.maxInputTokens ?? usage.input
136
+ )
137
+ } : {}
138
+ };
139
+ }
140
+
141
+ // src/ws-event-payloads.ts
142
+ import { asUnknownRecord, trimToNull as readWsEventNonEmptyString } from "@leitwerk-dev/domain";
143
+ function asWsEventPayloadRecord(value) {
144
+ return asUnknownRecord(value) ?? {};
145
+ }
146
+ function readWsEventTimestamp(data, fallbackTimestamp) {
147
+ return readWsEventNonEmptyString(data.timestamp) ?? fallbackTimestamp;
148
+ }
149
+ function readWsEventTurnRecordId(data) {
150
+ return readWsEventNonEmptyString(data.turnRecordId);
151
+ }
152
+ function readWsEventPiTurnId(data) {
153
+ return readWsEventNonEmptyString(data.turnId);
154
+ }
155
+ function readWsEventStreamText(data) {
156
+ return typeof data.text === "string" ? data.text : typeof data.delta === "string" ? data.delta : typeof data.chunk === "string" ? data.chunk : null;
157
+ }
158
+ function readWsEventToolName(data) {
159
+ return readWsEventNonEmptyString(data.name) ?? readWsEventNonEmptyString(data.toolName) ?? "tool";
160
+ }
161
+ function readWsEventToolArguments(data) {
162
+ return asUnknownRecord(data.arguments ?? data.args);
163
+ }
164
+ function readWsEventToolCallId(data) {
165
+ return readWsEventNonEmptyString(data.toolCallId);
166
+ }
167
+ function resolveWsEventToolCallId(data, options) {
168
+ return readWsEventToolCallId(data) ?? `${options.toolName ?? readWsEventToolName(data)}:${options.timestamp}${options.ordinal ? `:${options.ordinal}` : ""}`;
169
+ }
170
+
171
+ // src/compact-turn-summary.ts
172
+ var REASONING_PREVIEW_MAX_CHARS = 1024;
173
+ function emptyCompactTurnSummary() {
174
+ return {
175
+ assistant: { text: "", thinking: "", lastUpdatedAt: null },
176
+ currentTool: null,
177
+ usage: null,
178
+ toolCallCount: 0,
179
+ traceItemCount: 0,
180
+ throughEventSequence: 0,
181
+ lastTraceKind: null
182
+ };
183
+ }
184
+ function reasoningPreviewTail(text) {
185
+ const normalized = text.replace(/\r\n?/g, "\n");
186
+ const lines = normalized.split("\n").filter((line) => line.trim() !== "");
187
+ const separator = /\n[^\S\n]*$/.test(normalized) ? "\n" : "";
188
+ return (lines.join("\n") + separator).slice(-REASONING_PREVIEW_MAX_CHARS);
189
+ }
190
+ function applyEventToCompactTurnSummary(previous, event) {
191
+ if (event.eventSequence <= previous.throughEventSequence) return previous;
192
+ const next = {
193
+ ...previous,
194
+ assistant: { ...previous.assistant },
195
+ throughEventSequence: event.eventSequence
196
+ };
197
+ const { eventType, data } = event;
198
+ if (eventType === "pi.stream.delta") {
199
+ const text = readWsEventStreamText(data);
200
+ const key = data.streamType === "thinking" ? "thinking" : "text";
201
+ next.assistant[key] = reasoningPreviewTail(next.assistant[key] + text);
202
+ if (text) next.assistant.lastUpdatedAt = readWsEventTimestamp(data, event.createdAt);
203
+ if (key === "thinking" && text) {
204
+ if (next.lastTraceKind !== "thinking") next.traceItemCount++;
205
+ next.lastTraceKind = "thinking";
206
+ }
207
+ } else if (eventType === "pi.tool.call" || eventType === "pi.tool.result") {
208
+ const isResult = eventType === "pi.tool.result";
209
+ const toolCallId = (readWsEventToolCallId(data) ?? `tool-${event.eventSequence}`).slice(0, 256);
210
+ if (!isResult) {
211
+ next.toolCallCount++;
212
+ next.traceItemCount++;
213
+ next.lastTraceKind = "tool_call";
214
+ }
215
+ if (!isResult || !next.currentTool || next.currentTool.toolCallId === toolCallId) {
216
+ next.currentTool = {
217
+ toolCallId: toolCallId.slice(0, 256),
218
+ toolName: readWsEventToolName(data).slice(0, 256),
219
+ status: isResult ? "completed" : "running",
220
+ isError: data.isError === true
221
+ };
222
+ }
223
+ } else if (eventType === "pi.usage") {
224
+ next.usage = mergeUsageSnapshots(next.usage, normalizeUsageSnapshot(data));
225
+ } else if ([
226
+ "pi.error",
227
+ "pi.retry.start",
228
+ "pi.retry.end",
229
+ "pi.compaction.start",
230
+ "pi.compaction.end"
231
+ ].includes(eventType)) {
232
+ next.traceItemCount++;
233
+ next.lastTraceKind = "operational_event";
234
+ }
235
+ return next;
236
+ }
237
+
238
+ // src/extension-ui-contracts.ts
239
+ import { isUnknownRecord } from "@leitwerk-dev/domain";
240
+ import * as v2 from "valibot";
241
+ var recordSchema = v2.custom(isUnknownRecord);
242
+ var versionSchema = v2.custom((value) => typeof value === "number");
243
+ var leafOutcomeRendererDescriptorSchema = v2.pipe(
244
+ recordSchema,
245
+ v2.object({
246
+ ok: v2.literal(true),
247
+ rendererId: v2.string(),
248
+ kind: v2.literal("custom_element"),
249
+ tagName: v2.string(),
250
+ modulePath: v2.string(),
251
+ rendererApiVersion: versionSchema,
252
+ extensionManifestId: v2.string(),
253
+ moduleUrl: v2.string()
254
+ })
255
+ );
256
+ var leafOutcomeRendererFailureSchema = v2.pipe(
257
+ recordSchema,
258
+ v2.object({
259
+ ok: v2.literal(false),
260
+ rendererId: v2.string(),
261
+ code: v2.string(),
262
+ message: v2.string()
263
+ })
264
+ );
265
+ var browserUiExtensionDescriptorSchema = v2.pipe(
266
+ recordSchema,
267
+ v2.object({
268
+ extensionManifestId: v2.string(),
269
+ modulePath: v2.string(),
270
+ moduleUrl: v2.string(),
271
+ browserApiVersion: versionSchema
272
+ })
273
+ );
274
+
275
+ // src/initial-prompt.ts
276
+ import { isUnknownRecord as isRecord } from "@leitwerk-dev/domain";
277
+ var INITIAL_PROMPT_FIELD_PRIORITY = [
278
+ "initialPrompt",
279
+ "prompt",
280
+ "taskPrompt",
281
+ "userPrompt",
282
+ "instructions",
283
+ "instruction",
284
+ "initialCommand",
285
+ "command",
286
+ "query",
287
+ "message",
288
+ "requestedChange",
289
+ "request",
290
+ "description"
291
+ ];
292
+ function normalizePromptValue(value) {
293
+ const normalized = value.replace(/\s+/g, " ").trim();
294
+ return normalized.length > 0 ? normalized : null;
295
+ }
296
+ function truncatePromptPreview(value, maxLength = 180) {
297
+ const normalized = typeof value === "string" ? normalizePromptValue(value) : null;
298
+ return normalized && normalized.length > maxLength ? `${normalized.slice(0, maxLength).trimEnd()}\u2026` : normalized;
299
+ }
300
+ function readStringField(record, fieldName) {
301
+ const exact = record[fieldName];
302
+ if (typeof exact === "string") {
303
+ return exact.trim() ? exact : null;
304
+ }
305
+ const normalizedFieldName = fieldName.toLowerCase();
306
+ for (const [key, value] of Object.entries(record)) {
307
+ if (key.toLowerCase() !== normalizedFieldName || typeof value !== "string") {
308
+ continue;
309
+ }
310
+ return value.trim() ? value : null;
311
+ }
312
+ return null;
313
+ }
314
+ function extractInitialPromptFromValue(value) {
315
+ if (!isRecord(value)) {
316
+ return null;
317
+ }
318
+ for (const fieldName of INITIAL_PROMPT_FIELD_PRIORITY) {
319
+ const prompt = readStringField(value, fieldName);
320
+ if (prompt) {
321
+ return prompt;
322
+ }
323
+ }
324
+ return null;
325
+ }
326
+ function extractInitialPromptFromParamsJson(paramsJson) {
327
+ if (!paramsJson) {
328
+ return null;
329
+ }
330
+ try {
331
+ return extractInitialPromptFromValue(JSON.parse(paramsJson));
332
+ } catch {
333
+ return null;
334
+ }
335
+ }
336
+ function extractInitialPromptPreviewFromParamsJson(paramsJson, maxLength = 180) {
337
+ return truncatePromptPreview(extractInitialPromptFromParamsJson(paramsJson), maxLength);
338
+ }
339
+ function projectFutureExecutionOverview(summary) {
340
+ const common = {
341
+ id: summary.id,
342
+ scheduleKind: summary.scheduleKind,
343
+ processId: summary.processId,
344
+ nextRunAt: summary.nextRunAt,
345
+ cronExpression: summary.cronExpression,
346
+ title: summary.title,
347
+ status: summary.status ?? "scheduled",
348
+ blockedReason: summary.blockedReason ?? null,
349
+ initialPromptPreview: summary.kind === "launch" ? truncatePromptPreview(extractInitialPromptFromValue(summary.launcherInput)) : null
350
+ };
351
+ return summary.kind === "action" ? {
352
+ ...common,
353
+ kind: "action",
354
+ instanceId: summary.instanceId,
355
+ actionId: summary.actionId,
356
+ actionLabel: summary.actionLabel
357
+ } : {
358
+ ...common,
359
+ kind: "launch",
360
+ instanceId: null,
361
+ launcherId: summary.launcherId,
362
+ launcherLabel: summary.launcherLabel
363
+ };
364
+ }
365
+
366
+ // src/live-turn-projection.ts
367
+ import {
368
+ readFiniteNumber as readNumber,
369
+ readNonBlankString as readString
370
+ } from "@leitwerk-dev/domain";
371
+
372
+ // src/timestamp-ordering.ts
373
+ function compareTimestampStrings(left, right) {
374
+ const leftMs = Date.parse(left);
375
+ const rightMs = Date.parse(right);
376
+ if (Number.isFinite(leftMs) && Number.isFinite(rightMs)) {
377
+ return leftMs - rightMs;
378
+ }
379
+ return left.localeCompare(right);
380
+ }
381
+ function happenedOnOrAfterStart(entryTimestamp, startedAt) {
382
+ if (!startedAt) {
383
+ return true;
384
+ }
385
+ return compareTimestampStrings(entryTimestamp, startedAt) >= 0;
386
+ }
387
+
388
+ // src/live-turn-projection.ts
389
+ var PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES = [
390
+ "pi.error",
391
+ "pi.retry.start",
392
+ "pi.retry.end",
393
+ "pi.compaction.start",
394
+ "pi.compaction.end"
395
+ ];
396
+ var PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPE_SET = new Set(
397
+ PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES
398
+ );
399
+ function cloneToolCall(toolCall) {
400
+ return {
401
+ ...toolCall,
402
+ ...toolCall.arguments ? { arguments: { ...toolCall.arguments } } : {}
403
+ };
404
+ }
405
+ function formatReason(value) {
406
+ const reason = readString(value);
407
+ return reason ? reason.replace(/[_-]+/g, " ") : null;
408
+ }
409
+ function firstMessage(data, keys) {
410
+ for (const key of keys) {
411
+ const value = readString(data[key]);
412
+ if (value) {
413
+ return value;
414
+ }
415
+ }
416
+ return null;
417
+ }
418
+ function retryStartFallbackMessage(data) {
419
+ const attempt = readNumber(data.attempt);
420
+ const maxAttempts = readNumber(data.maxAttempts);
421
+ const delayMs = readNumber(data.delayMs);
422
+ const attemptLabel = attempt !== null && maxAttempts !== null ? ` ${attempt}/${maxAttempts}` : "";
423
+ const delayLabel = delayMs !== null && delayMs > 0 ? ` in ${delayMs}ms` : "";
424
+ return `Retry${attemptLabel} scheduled${delayLabel}.`;
425
+ }
426
+ function retryEndFallbackMessage(data) {
427
+ const attempt = readNumber(data.attempt);
428
+ if (data.success === true) {
429
+ return attempt !== null ? `Retry sequence succeeded after ${attempt} ${attempt === 1 ? "retry" : "retries"}.` : "Retry sequence succeeded.";
430
+ }
431
+ return attempt !== null ? `Retry sequence ended after ${attempt} ${attempt === 1 ? "retry" : "retries"}.` : "Retry sequence ended.";
432
+ }
433
+ function buildPrimaryPathOperationalTraceItem(input) {
434
+ if (!PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPE_SET.has(input.eventType)) {
435
+ return null;
436
+ }
437
+ const timestamp = readWsEventTimestamp(input.data, input.fallbackTimestamp);
438
+ if (input.eventType === "pi.error") {
439
+ return {
440
+ kind: "operational_event",
441
+ eventType: input.eventType,
442
+ severity: "error",
443
+ title: "Pi request failed",
444
+ message: firstMessage(input.data, ["message", "errorMessage", "finalError"]) ?? "Pi reported an error.",
445
+ timestamp
446
+ };
447
+ }
448
+ if (input.eventType === "pi.retry.start") {
449
+ return {
450
+ kind: "operational_event",
451
+ eventType: input.eventType,
452
+ severity: "warning",
453
+ title: "Retry scheduled",
454
+ message: firstMessage(input.data, ["message", "errorMessage"]) ?? retryStartFallbackMessage(input.data),
455
+ timestamp
456
+ };
457
+ }
458
+ if (input.eventType === "pi.retry.end") {
459
+ const success = input.data.success === true;
460
+ return {
461
+ kind: "operational_event",
462
+ eventType: input.eventType,
463
+ severity: success ? "success" : "error",
464
+ title: success ? "Retry succeeded" : "Retry exhausted",
465
+ message: firstMessage(input.data, ["message", "finalError", "errorMessage"]) ?? retryEndFallbackMessage(input.data),
466
+ timestamp
467
+ };
468
+ }
469
+ if (input.eventType === "pi.compaction.start") {
470
+ const reason = formatReason(input.data.reason);
471
+ return {
472
+ kind: "operational_event",
473
+ eventType: input.eventType,
474
+ severity: "info",
475
+ title: "Context compaction started",
476
+ message: reason ? `Pi started compacting context (${reason}).` : "Pi started compacting context.",
477
+ timestamp
478
+ };
479
+ }
480
+ if (input.eventType === "pi.compaction.end") {
481
+ const reason = formatReason(input.data.reason);
482
+ const errorMessage = firstMessage(input.data, ["errorMessage", "message"]);
483
+ const aborted = input.data.aborted === true;
484
+ const willRetry = input.data.willRetry === true;
485
+ const statusMessage = errorMessage ? errorMessage : aborted ? "Context compaction was cancelled." : `Pi compacted context${reason ? ` (${reason})` : ""}.${willRetry ? " Pi will continue automatically." : ""}`;
486
+ return {
487
+ kind: "operational_event",
488
+ eventType: input.eventType,
489
+ severity: errorMessage ? "error" : aborted ? "warning" : "success",
490
+ title: errorMessage ? "Context compaction failed" : aborted ? "Context compaction cancelled" : "Context compacted",
491
+ message: statusMessage,
492
+ timestamp
493
+ };
494
+ }
495
+ return null;
496
+ }
497
+ function addOpenToolCallId(projection, toolName, toolCallId) {
498
+ const ids = projection.openToolCallIdsByName.get(toolName) ?? [];
499
+ ids.push(toolCallId);
500
+ projection.openToolCallIdsByName.set(toolName, ids);
501
+ }
502
+ function consumeLatestOpenToolCallId(projection, toolName) {
503
+ const ids = projection.openToolCallIdsByName.get(toolName);
504
+ if (!ids || ids.length === 0) {
505
+ return null;
506
+ }
507
+ const toolCallId = ids.pop() ?? null;
508
+ if (ids.length === 0) {
509
+ projection.openToolCallIdsByName.delete(toolName);
510
+ } else {
511
+ projection.openToolCallIdsByName.set(toolName, ids);
512
+ }
513
+ return toolCallId;
514
+ }
515
+ function removeOpenToolCallId(projection, toolCallId) {
516
+ for (const [toolName, ids] of projection.openToolCallIdsByName.entries()) {
517
+ const nextIds = ids.filter((candidate) => candidate !== toolCallId);
518
+ if (nextIds.length === ids.length) {
519
+ continue;
520
+ }
521
+ if (nextIds.length === 0) {
522
+ projection.openToolCallIdsByName.delete(toolName);
523
+ } else {
524
+ projection.openToolCallIdsByName.set(toolName, nextIds);
525
+ }
526
+ return;
527
+ }
528
+ }
529
+ function canonicalizeToolCallId(input) {
530
+ const explicitToolCallId = readWsEventToolCallId(input.data);
531
+ if (explicitToolCallId) {
532
+ if (input.preferOpenCall) {
533
+ removeOpenToolCallId(input.projection, explicitToolCallId);
534
+ }
535
+ return explicitToolCallId;
536
+ }
537
+ if (input.preferOpenCall) {
538
+ const openToolCallId = consumeLatestOpenToolCallId(input.projection, input.toolName);
539
+ if (openToolCallId) {
540
+ return openToolCallId;
541
+ }
542
+ }
543
+ return resolveWsEventToolCallId(input.data, {
544
+ timestamp: input.timestamp,
545
+ toolName: input.toolName,
546
+ ordinal: input.projection.nextFallbackOrdinal++
547
+ });
548
+ }
549
+ function appendThinkingTraceText(projection, text) {
550
+ if (text.length === 0) {
551
+ return;
552
+ }
553
+ const lastTraceItem = projection.traceItems.at(-1);
554
+ if (lastTraceItem?.kind === "thinking") {
555
+ lastTraceItem.text += text;
556
+ return;
557
+ }
558
+ projection.traceItems.push({
559
+ kind: "thinking",
560
+ text
561
+ });
562
+ }
563
+ function ensureToolTraceItem(projection, toolCallId) {
564
+ if (projection.traceItems.some(
565
+ (traceItem) => traceItem.kind === "tool_call" && traceItem.toolCallId === toolCallId
566
+ )) {
567
+ return;
568
+ }
569
+ projection.traceItems.push({
570
+ kind: "tool_call",
571
+ toolCallId
572
+ });
573
+ }
574
+ function createMutableLiveTurnProjection() {
575
+ return {
576
+ assistant: {
577
+ text: "",
578
+ thinking: "",
579
+ lastUpdatedAt: null
580
+ },
581
+ toolCalls: [],
582
+ traceItems: [],
583
+ usage: null,
584
+ toolCallsById: /* @__PURE__ */ new Map(),
585
+ openToolCallIdsByName: /* @__PURE__ */ new Map(),
586
+ nextFallbackOrdinal: 1
587
+ };
588
+ }
589
+ function snapshotLiveTurnProjection(projection) {
590
+ return {
591
+ assistant: { ...projection.assistant },
592
+ toolCalls: projection.toolCalls.map(cloneToolCall),
593
+ traceItems: projection.traceItems.map((item) => ({ ...item })),
594
+ usage: cloneUsageSnapshot(projection.usage)
595
+ };
596
+ }
597
+ function applyPiEventToLiveTurnProjection(projection, input) {
598
+ let timestamp = readWsEventTimestamp(input.data, input.fallbackTimestamp);
599
+ if (input.eventType === "pi.stream.delta") {
600
+ const text = readWsEventStreamText(input.data);
601
+ if (text) {
602
+ if (readWsEventNonEmptyString(input.data.streamType) === "thinking") {
603
+ projection.assistant.thinking += text;
604
+ appendThinkingTraceText(projection, text);
605
+ } else {
606
+ projection.assistant.text += text;
607
+ }
608
+ projection.assistant.lastUpdatedAt = timestamp;
609
+ }
610
+ } else if (input.eventType === "pi.tool.call" || input.eventType === "pi.tool.result") {
611
+ const isResult = input.eventType === "pi.tool.result";
612
+ const toolName = readWsEventToolName(input.data);
613
+ const toolCallId = canonicalizeToolCallId({
614
+ projection,
615
+ data: input.data,
616
+ timestamp,
617
+ toolName,
618
+ preferOpenCall: isResult
619
+ });
620
+ const canonicalData = readWsEventToolCallId(input.data) === toolCallId ? input.data : { ...input.data, toolCallId };
621
+ const existingToolCall = projection.toolCallsById.get(toolCallId);
622
+ const toolCall = existingToolCall ?? {
623
+ toolCallId,
624
+ toolName,
625
+ status: "running",
626
+ startedAt: timestamp,
627
+ completedAt: null,
628
+ arguments: isResult ? null : readWsEventToolArguments(canonicalData),
629
+ result: null,
630
+ isError: false
631
+ };
632
+ if (!existingToolCall) {
633
+ projection.toolCalls.push(toolCall);
634
+ projection.toolCallsById.set(toolCallId, toolCall);
635
+ }
636
+ if (isResult) {
637
+ toolCall.status = "completed";
638
+ toolCall.completedAt = timestamp;
639
+ toolCall.result = canonicalData.result ?? null;
640
+ toolCall.isError = canonicalData.isError === true;
641
+ if (existingToolCall) removeOpenToolCallId(projection, toolCallId);
642
+ }
643
+ ensureToolTraceItem(projection, toolCallId);
644
+ if (!isResult) addOpenToolCallId(projection, toolName, toolCallId);
645
+ return {
646
+ canonicalData,
647
+ timestamp,
648
+ toolCallId,
649
+ toolName
650
+ };
651
+ } else if (input.eventType === "pi.usage") {
652
+ projection.usage = mergeUsageSnapshots(projection.usage, normalizeUsageSnapshot(input.data));
653
+ } else {
654
+ const operationalTraceItem = buildPrimaryPathOperationalTraceItem({
655
+ eventType: input.eventType,
656
+ data: input.data,
657
+ fallbackTimestamp: input.fallbackTimestamp
658
+ });
659
+ if (operationalTraceItem) {
660
+ projection.traceItems.push(operationalTraceItem);
661
+ timestamp = operationalTraceItem.timestamp;
662
+ }
663
+ }
664
+ return {
665
+ canonicalData: input.data,
666
+ timestamp,
667
+ toolCallId: null,
668
+ toolName: null
669
+ };
670
+ }
671
+ function compareProcessEventsChronologically(left, right) {
672
+ if (left.eventSequence !== void 0 && right.eventSequence !== void 0) {
673
+ return left.eventSequence - right.eventSequence;
674
+ }
675
+ const leftTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(left.data), left.createdAt);
676
+ const rightTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(right.data), right.createdAt);
677
+ const timestampComparison = compareTimestampStrings(leftTimestamp, rightTimestamp);
678
+ if (timestampComparison !== 0) {
679
+ return timestampComparison;
680
+ }
681
+ const createdAtComparison = compareTimestampStrings(left.createdAt, right.createdAt);
682
+ if (createdAtComparison !== 0) {
683
+ return createdAtComparison;
684
+ }
685
+ return left.id.localeCompare(right.id);
686
+ }
687
+ function buildLiveTurnProjectionFromEvents(events) {
688
+ const projection = createMutableLiveTurnProjection();
689
+ for (const event of [...events].sort(compareProcessEventsChronologically)) {
690
+ applyPiEventToLiveTurnProjection(projection, {
691
+ eventType: event.eventType,
692
+ data: asWsEventPayloadRecord(event.data),
693
+ fallbackTimestamp: event.createdAt
694
+ });
695
+ }
696
+ return projection;
697
+ }
698
+
699
+ // src/pi-session-message.ts
700
+ function isPiSessionMessageEntryType(entry) {
701
+ return entry?.type === "message";
702
+ }
703
+ function isPiSessionMessageRecord(value) {
704
+ return typeof value === "object" && value !== null && !Array.isArray(value);
705
+ }
706
+ function isPiSessionMessageEntryWithRecord(entry) {
707
+ return isPiSessionMessageEntryType(entry) && isPiSessionMessageRecord(entry.message);
708
+ }
709
+ function extractPiSessionMessageText(content) {
710
+ if (typeof content === "string") {
711
+ return content;
712
+ }
713
+ if (!Array.isArray(content)) {
714
+ return "";
715
+ }
716
+ return content.map((block) => {
717
+ if (typeof block !== "object" || block === null || Array.isArray(block)) {
718
+ return "";
719
+ }
720
+ const record = block;
721
+ return record.type === "text" && typeof record.text === "string" ? record.text : "";
722
+ }).join("");
723
+ }
724
+
725
+ // src/session-entry-tree.ts
726
+ function createReadonlyEntryTree(entries) {
727
+ const orderedEntries = [...entries];
728
+ const entriesById = new Map(orderedEntries.map((entry) => [entry.id, entry]));
729
+ const childrenByParentId = /* @__PURE__ */ new Map();
730
+ for (const entry of orderedEntries) {
731
+ if (typeof entry.parentId !== "string" || entry.parentId.trim() === "") {
732
+ continue;
733
+ }
734
+ const siblings = childrenByParentId.get(entry.parentId) ?? [];
735
+ siblings.push(entry);
736
+ childrenByParentId.set(entry.parentId, siblings);
737
+ }
738
+ const leafId = orderedEntries.at(-1)?.id ?? null;
739
+ const getEntry = (id) => entriesById.get(id);
740
+ const getChildren = (parentId) => (childrenByParentId.get(parentId) ?? []).slice();
741
+ const getBranch = (fromId) => {
742
+ const resolvedFromId = fromId ?? leafId ?? void 0;
743
+ if (!resolvedFromId) {
744
+ return [];
745
+ }
746
+ const branch = [];
747
+ const visited = /* @__PURE__ */ new Set();
748
+ let currentEntry = entriesById.get(resolvedFromId);
749
+ while (currentEntry) {
750
+ if (visited.has(currentEntry.id)) {
751
+ break;
752
+ }
753
+ visited.add(currentEntry.id);
754
+ branch.unshift(currentEntry);
755
+ currentEntry = currentEntry.parentId ? entriesById.get(currentEntry.parentId) : void 0;
756
+ }
757
+ return branch;
758
+ };
759
+ return {
760
+ entries: orderedEntries,
761
+ leafId,
762
+ getEntry,
763
+ getChildren,
764
+ getBranch
765
+ };
766
+ }
767
+
768
+ // src/streamable-events.ts
769
+ var STREAMABLE_WORKER_EVENT_TYPES = [
770
+ "pi.stream.delta",
771
+ "pi.turn.start",
772
+ "pi.turn.end",
773
+ "pi.tool.call",
774
+ "pi.tool.result",
775
+ "pi.label.changed",
776
+ "pi.error",
777
+ "pi.retry.start",
778
+ "pi.retry.end",
779
+ "pi.usage",
780
+ "pi.compaction.start",
781
+ "pi.compaction.end"
782
+ ];
783
+ var STREAMABLE_EVENT_TYPES = new Set(STREAMABLE_WORKER_EVENT_TYPES);
784
+ function isStreamableEvent(eventType) {
785
+ return STREAMABLE_EVENT_TYPES.has(eventType);
786
+ }
787
+
788
+ // src/text-preview.ts
789
+ function truncateTextPreview(value, maxLength) {
790
+ return value.length <= maxLength ? { text: value, truncated: false } : { text: value.slice(0, maxLength).trimEnd(), truncated: true };
791
+ }
792
+ function buildTrailingLinePreview(value, lineCount, maxLength) {
793
+ const lines = value.replace(/\r\n?/g, "\n").split("\n");
794
+ if (lines.length === 1 && lines[0] === "") return { text: "", truncated: false };
795
+ let text = lines.slice(-lineCount).join("\n");
796
+ let truncated = lines.length > lineCount;
797
+ if (text.length > maxLength) {
798
+ text = text.slice(-maxLength);
799
+ truncated = true;
800
+ }
801
+ if (truncated) {
802
+ const previewLines = text.split("\n");
803
+ previewLines[0] = previewLines[0] ? `\u2026 ${previewLines[0]}` : "\u2026";
804
+ text = previewLines.join("\n");
805
+ }
806
+ return { text, truncated };
807
+ }
808
+
809
+ // src/timeline-projection.ts
810
+ function timelinePresentationForTurnType(turnType) {
811
+ if (turnType === "external") return "external_trigger";
812
+ if (turnType === "human") return "operator_decision";
813
+ return turnType === "automatic" ? "automatic_turn" : "llm_turn";
814
+ }
815
+ function buildActiveTimelineTurnSummary(activeTurn, input = { summary: `Current step: ${activeTurn.turnId}`, output: activeTurn.assistant.text.trim() }) {
816
+ return {
817
+ id: activeTurn.turnRecordId,
818
+ turnId: activeTurn.turnId,
819
+ turnType: activeTurn.turnType,
820
+ displayTurn: activeTurn.turnId,
821
+ outcome: "in_progress",
822
+ summary: input.summary,
823
+ output: input.output,
824
+ turnResultMarkdown: "",
825
+ pathType: activeTurn.pathType,
826
+ createdAt: activeTurn.startedAt,
827
+ presentation: timelinePresentationForTurnType(activeTurn.turnType),
828
+ status: "in_progress",
829
+ modelProfileId: null,
830
+ attemptNumber: 1,
831
+ parentTurnRecordId: null,
832
+ startedAt: activeTurn.startedAt,
833
+ endedAt: null,
834
+ actionSource: input.actionSource ?? null,
835
+ progress: null
836
+ };
837
+ }
838
+
839
+ // src/tool-result-truncation.ts
840
+ import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
841
+ var TOOL_TRUNCATION_BOOLEAN_KEYS = [
842
+ "truncated",
843
+ "isTruncated",
844
+ "wasTruncated",
845
+ "outputTruncated",
846
+ "resultTruncated"
847
+ ];
848
+ var TOOL_TRUNCATION_TEXT_MARKERS = [
849
+ "output truncated",
850
+ "result truncated",
851
+ "response was too big",
852
+ "too large to display",
853
+ "truncated after",
854
+ "truncated to last",
855
+ "truncated since"
856
+ ];
857
+ function readTruncationPayload(value) {
858
+ const record = asUnknownRecord2(value);
859
+ if (!record) {
860
+ return null;
861
+ }
862
+ if ("truncation" in record) {
863
+ return record.truncation;
864
+ }
865
+ for (const key of TOOL_TRUNCATION_BOOLEAN_KEYS) {
866
+ if (key in record) {
867
+ return record[key];
868
+ }
869
+ }
870
+ return null;
871
+ }
872
+ function isExplicitFalseTruncationString(value) {
873
+ const normalized = value.trim().toLowerCase();
874
+ return normalized === "" || normalized === "false" || normalized === "none" || normalized === "null" || normalized === "no" || normalized === "0";
875
+ }
876
+ function isTruthyTruncationValue(value) {
877
+ if (value === null || value === void 0) {
878
+ return false;
879
+ }
880
+ if (typeof value === "boolean") {
881
+ return value;
882
+ }
883
+ if (typeof value === "number") {
884
+ return Number.isFinite(value) && value > 0;
885
+ }
886
+ if (typeof value === "string") {
887
+ return !isExplicitFalseTruncationString(value);
888
+ }
889
+ if (Array.isArray(value)) {
890
+ return value.length > 0;
891
+ }
892
+ const record = asUnknownRecord2(value);
893
+ if (!record) {
894
+ return true;
895
+ }
896
+ for (const key of TOOL_TRUNCATION_BOOLEAN_KEYS) {
897
+ if (record[key] === true) {
898
+ return true;
899
+ }
900
+ }
901
+ return Object.keys(record).some((key) => {
902
+ if (TOOL_TRUNCATION_BOOLEAN_KEYS.includes(key)) {
903
+ return false;
904
+ }
905
+ return isTruthyTruncationValue(record[key]);
906
+ });
907
+ }
908
+ function isToolResultTruncated(input) {
909
+ const normalizedText = input.resultText?.toLowerCase() ?? "";
910
+ return TOOL_TRUNCATION_TEXT_MARKERS.some((marker) => normalizedText.includes(marker)) || isTruthyTruncationValue(readTruncationPayload(input.resultDetails)) || isTruthyTruncationValue(readTruncationPayload(input.resultValue));
911
+ }
912
+
913
+ // src/turn-continuation.ts
914
+ import { trimToNull } from "@leitwerk-dev/domain";
915
+ function branchContainsAncestor(entriesById, entryId, ancestorId) {
916
+ const visited = /* @__PURE__ */ new Set();
917
+ let current = entriesById.get(entryId);
918
+ while (current) {
919
+ if (visited.has(current.id)) {
920
+ return false;
921
+ }
922
+ visited.add(current.id);
923
+ if (current.id === ancestorId) {
924
+ return true;
925
+ }
926
+ current = current.parentId ? entriesById.get(current.parentId) : void 0;
927
+ }
928
+ return false;
929
+ }
930
+ function happenedOnOrBeforeEnd(entryTimestamp, endedAt) {
931
+ if (!endedAt) {
932
+ return true;
933
+ }
934
+ return compareTimestampStrings(entryTimestamp, endedAt) <= 0;
935
+ }
936
+ function isContinuableEntryWithinBounds(entry, startedAt, endedAt) {
937
+ return (isPiSessionMessageEntryType(entry) || entry?.type === "compaction") && happenedOnOrAfterStart(entry.timestamp, startedAt) && happenedOnOrBeforeEnd(entry.timestamp, endedAt);
938
+ }
939
+ function isExplicitLeafUsable(entriesById, leafId, forkPiEntryId, startedAt, endedAt) {
940
+ const leafEntry = entriesById.get(leafId);
941
+ if (!isContinuableEntryWithinBounds(leafEntry, startedAt, endedAt)) {
942
+ return false;
943
+ }
944
+ return !forkPiEntryId || branchContainsAncestor(entriesById, leafId, forkPiEntryId);
945
+ }
946
+ function findLatestContinuableEntryIdOnBranch(entries, entriesById, options) {
947
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
948
+ const entry = entries[index];
949
+ if (!isContinuableEntryWithinBounds(entry, options.startedAt, options.endedAt)) {
950
+ continue;
951
+ }
952
+ if (options.ancestorId && !branchContainsAncestor(entriesById, entry.id, options.ancestorId)) {
953
+ continue;
954
+ }
955
+ return entry.id;
956
+ }
957
+ return null;
958
+ }
959
+ function resolveTurnContinuationLeafEntryIdFromIndex(entries, entriesById, turnRecord, bounds = {}) {
960
+ const startedAt = trimToNull(turnRecord.startedAt);
961
+ const endedAt = trimToNull(bounds.endedAt);
962
+ const forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);
963
+ const explicitLeafId = trimToNull(turnRecord.resultPiEntryId);
964
+ if (explicitLeafId && isExplicitLeafUsable(entriesById, explicitLeafId, forkPiEntryId, startedAt, endedAt)) {
965
+ if (turnRecord.status !== "failed") {
966
+ return explicitLeafId;
967
+ }
968
+ return findLatestContinuableEntryIdOnBranch(entries, entriesById, {
969
+ startedAt,
970
+ endedAt,
971
+ ancestorId: explicitLeafId
972
+ });
973
+ }
974
+ return findLatestContinuableEntryIdOnBranch(entries, entriesById, {
975
+ startedAt,
976
+ endedAt,
977
+ ancestorId: forkPiEntryId
978
+ });
979
+ }
980
+ function createTurnContinuationIndex(entries) {
981
+ const entriesById = new Map(entries.map((entry) => [entry.id, entry]));
982
+ const resolveLeafEntryId = (turnRecord, bounds = {}) => resolveTurnContinuationLeafEntryIdFromIndex(entries, entriesById, turnRecord, bounds);
983
+ const buildSlice = (turnRecord, bounds = {}) => {
984
+ const continuationLeafId = resolveLeafEntryId(turnRecord, bounds);
985
+ if (!continuationLeafId) {
986
+ return [];
987
+ }
988
+ const forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);
989
+ const reversedSlice = [];
990
+ const visited = /* @__PURE__ */ new Set();
991
+ let current = entriesById.get(continuationLeafId);
992
+ let foundFork = forkPiEntryId === null;
993
+ while (current && !visited.has(current.id)) {
994
+ visited.add(current.id);
995
+ if (current.id === forkPiEntryId) {
996
+ foundFork = true;
997
+ break;
998
+ }
999
+ reversedSlice.push(current);
1000
+ current = current.parentId ? entriesById.get(current.parentId) : void 0;
1001
+ }
1002
+ if (!foundFork) {
1003
+ return [];
1004
+ }
1005
+ const startedAt = trimToNull(turnRecord.startedAt);
1006
+ const endedAt = trimToNull(bounds.endedAt);
1007
+ return reversedSlice.reverse().filter(
1008
+ (entry) => happenedOnOrAfterStart(entry.timestamp, startedAt) && happenedOnOrBeforeEnd(entry.timestamp, endedAt)
1009
+ );
1010
+ };
1011
+ return { resolveLeafEntryId, buildSlice };
1012
+ }
1013
+ function resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds = {}) {
1014
+ return createTurnContinuationIndex(entries).resolveLeafEntryId(turnRecord, bounds);
1015
+ }
1016
+ function buildTurnContinuationSliceFromTree(tree, turnRecord, bounds = {}) {
1017
+ return createTurnContinuationIndex(tree.entries).buildSlice(turnRecord, bounds);
1018
+ }
1019
+ function buildTurnContinuationSlice(entries, turnRecord, bounds = {}) {
1020
+ return createTurnContinuationIndex(entries).buildSlice(turnRecord, bounds);
1021
+ }
1022
+ function extractFirstUserPromptOnBranch(tree, leafId) {
1023
+ const resolvedLeafId = trimToNull(leafId);
1024
+ if (!resolvedLeafId) {
1025
+ return { text: null, createdAt: null };
1026
+ }
1027
+ const branch = tree.getBranch(resolvedLeafId);
1028
+ for (const entry of branch) {
1029
+ if (!isPiSessionMessageEntryWithRecord(entry) || entry.message.role !== "user") {
1030
+ continue;
1031
+ }
1032
+ const text = extractPiSessionMessageText(entry.message.content).trim();
1033
+ if (text === "") {
1034
+ continue;
1035
+ }
1036
+ return {
1037
+ text,
1038
+ createdAt: entry.timestamp
1039
+ };
1040
+ }
1041
+ return { text: null, createdAt: null };
1042
+ }
1043
+ function resolveTurnContinuationUserPrompt(entries, turnRecord, bounds = {}) {
1044
+ const continuationLeafId = resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds);
1045
+ if (!continuationLeafId) {
1046
+ return null;
1047
+ }
1048
+ const continuationLeaf = new Map(entries.map((entry) => [entry.id, entry])).get(
1049
+ continuationLeafId
1050
+ );
1051
+ if (!isPiSessionMessageEntryWithRecord(continuationLeaf) || continuationLeaf.message.role !== "user") {
1052
+ return null;
1053
+ }
1054
+ const promptText = extractPiSessionMessageText(continuationLeaf.message.content).trim();
1055
+ return promptText !== "" ? promptText : null;
1056
+ }
1057
+ function hasTurnContinuationProgress(entries, turnRecord, bounds = {}) {
1058
+ return resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds) !== null;
1059
+ }
1060
+
1061
+ // src/turn-trace-projection.ts
1062
+ function snapshotTurnTrace(projection, piInput = null) {
1063
+ const snapshot = snapshotLiveTurnProjection(projection);
1064
+ return {
1065
+ ...snapshot,
1066
+ piInput,
1067
+ toolCalls: snapshot.toolCalls.map(({ result, ...tool }) => {
1068
+ const record = result && typeof result === "object" ? result : null;
1069
+ const resultText = result == null ? null : typeof result === "string" ? result : record && "content" in record ? extractPiSessionMessageText(record.content) : JSON.stringify(result, null, 2);
1070
+ return {
1071
+ ...tool,
1072
+ resultText,
1073
+ truncated: "truncated" in tool && tool.truncated === true || isToolResultTruncated({
1074
+ resultText,
1075
+ resultDetails: record?.details,
1076
+ resultValue: result
1077
+ })
1078
+ };
1079
+ })
1080
+ };
1081
+ }
1082
+
1083
+ // src/usage-by-turn-record.ts
1084
+ function buildUsageSnapshotsByTurnRecordId(events) {
1085
+ const snapshots = {};
1086
+ for (const event of events) {
1087
+ if (event.eventType !== "pi.usage") {
1088
+ continue;
1089
+ }
1090
+ const payload = asWsEventPayloadRecord(event.data);
1091
+ const turnRecordId = readWsEventTurnRecordId(payload);
1092
+ if (!turnRecordId) {
1093
+ continue;
1094
+ }
1095
+ const usage = normalizeUsageSnapshot(payload);
1096
+ if (!usage) {
1097
+ continue;
1098
+ }
1099
+ const merged = mergeUsageSnapshots(snapshots[turnRecordId] ?? null, usage);
1100
+ if (merged) {
1101
+ snapshots[turnRecordId] = merged;
1102
+ }
1103
+ }
1104
+ return snapshots;
1105
+ }
1106
+ export {
1107
+ INITIAL_PROMPT_FIELD_PRIORITY,
1108
+ PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES,
1109
+ REASONING_PREVIEW_MAX_CHARS,
1110
+ STREAMABLE_WORKER_EVENT_TYPES,
1111
+ TOOL_CALL_RENDERER_VALUE_KINDS,
1112
+ TOOL_CALL_RENDERER_VALUE_SOURCES,
1113
+ WS_FRAME_DURABILITY,
1114
+ WS_PI_STREAM_TYPES,
1115
+ WS_PRIMARY_PATH_TYPES,
1116
+ WS_PROCESS_TYPES,
1117
+ WS_PROTOCOL_VERSION,
1118
+ applyEventToCompactTurnSummary,
1119
+ applyPiEventToLiveTurnProjection,
1120
+ asWsEventPayloadRecord,
1121
+ browserUiExtensionDescriptorSchema,
1122
+ buildActiveTimelineTurnSummary,
1123
+ buildLiveTurnProjectionFromEvents,
1124
+ buildPrimaryPathOperationalTraceItem,
1125
+ buildTrailingLinePreview,
1126
+ buildTurnContinuationSlice,
1127
+ buildTurnContinuationSliceFromTree,
1128
+ buildUsageSnapshotsByTurnRecordId,
1129
+ cloneUsageSnapshot,
1130
+ compareTimestampStrings,
1131
+ createDurableWsFrame,
1132
+ createEphemeralWsFrame,
1133
+ createMutableLiveTurnProjection,
1134
+ createReadonlyEntryTree,
1135
+ createTurnContinuationIndex,
1136
+ emptyCompactTurnSummary,
1137
+ err,
1138
+ extractFirstUserPromptOnBranch,
1139
+ extractInitialPromptFromParamsJson,
1140
+ extractInitialPromptFromValue,
1141
+ extractInitialPromptPreviewFromParamsJson,
1142
+ extractPiSessionMessageText,
1143
+ happenedOnOrAfterStart,
1144
+ hasTurnContinuationProgress,
1145
+ isPiSessionMessageEntryType,
1146
+ isPiSessionMessageEntryWithRecord,
1147
+ isPiSessionMessageRecord,
1148
+ isStreamableEvent,
1149
+ isToolResultTruncated,
1150
+ leafOutcomeRendererDescriptorSchema,
1151
+ leafOutcomeRendererFailureSchema,
1152
+ mapWorkerEventToWsType,
1153
+ mergeUsageSnapshots,
1154
+ normalizeUsageSnapshot,
1155
+ nullableStringSchema,
1156
+ ok,
1157
+ optionalNullableStringSchema,
1158
+ parseActionRequestBody,
1159
+ parseFutureActionPayloadJson,
1160
+ parseFutureActionPayloadObject,
1161
+ parseFutureLaunchPayloadJson,
1162
+ parseFutureLaunchPayloadObject,
1163
+ parseLauncherInputJson,
1164
+ parseLauncherModelConfigInput,
1165
+ parseLauncherRequestBody,
1166
+ parseLauncherTurnConfigsJson,
1167
+ parseLiteral,
1168
+ parsePrimaryPathWsFrameInput,
1169
+ parseScheduleRequestInput,
1170
+ parseSchema,
1171
+ parseWsFrame,
1172
+ projectFutureExecutionOverview,
1173
+ readValueAtPath,
1174
+ readWsEventNonEmptyString,
1175
+ readWsEventPiTurnId,
1176
+ readWsEventStreamText,
1177
+ readWsEventTimestamp,
1178
+ readWsEventToolArguments,
1179
+ readWsEventToolCallId,
1180
+ readWsEventToolName,
1181
+ readWsEventTurnRecordId,
1182
+ reasoningPreviewTail,
1183
+ resolvePromptCacheSwitch,
1184
+ resolveTurnContinuationLeafEntryId,
1185
+ resolveTurnContinuationUserPrompt,
1186
+ resolveWsEventToolCallId,
1187
+ serializeFutureActionPayload,
1188
+ serializeFutureLaunchPayload,
1189
+ snapshotLiveTurnProjection,
1190
+ snapshotTurnTrace,
1191
+ timelinePresentationForTurnType,
1192
+ truncatePromptPreview,
1193
+ truncateTextPreview,
1194
+ unknownRecordSchema,
1195
+ validateScheduleRequestInput
1196
+ };
21
1197
  //# sourceMappingURL=index.js.map