@leitwerk-dev/protocol 0.1.9 → 0.2.1

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