@leitwerk-dev/protocol 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/chunk-6L4W7WPV.js +1 -0
  3. package/dist/chunk-6L4W7WPV.js.map +1 -0
  4. package/dist/chunk-7PCFBAV4.js +740 -0
  5. package/dist/chunk-7PCFBAV4.js.map +1 -0
  6. package/dist/chunk-AAV3AAOF.js +1 -0
  7. package/dist/chunk-AAV3AAOF.js.map +1 -0
  8. package/dist/chunk-IEMT3JG4.js +1 -0
  9. package/dist/chunk-IEMT3JG4.js.map +1 -0
  10. package/dist/chunk-IWVU76M5.js +26 -0
  11. package/dist/chunk-IWVU76M5.js.map +1 -0
  12. package/dist/config-snapshot.d.ts +211 -0
  13. package/dist/config-snapshot.d.ts.map +1 -0
  14. package/dist/config-snapshot.js +2 -0
  15. package/dist/config-snapshot.js.map +1 -0
  16. package/dist/external-review.d.ts +8 -0
  17. package/dist/external-review.d.ts.map +1 -0
  18. package/dist/external-review.js +2 -0
  19. package/dist/external-review.js.map +1 -0
  20. package/dist/form-contract.d.ts +41 -0
  21. package/dist/form-contract.d.ts.map +1 -0
  22. package/dist/form-contract.js +2 -0
  23. package/dist/form-contract.js.map +1 -0
  24. package/dist/http-contracts-C8IXe8MU.d.ts +1483 -0
  25. package/dist/http-contracts.d.ts +959 -0
  26. package/dist/http-contracts.d.ts.map +1 -0
  27. package/dist/http-contracts.js +434 -0
  28. package/dist/http-contracts.js.map +1 -0
  29. package/dist/index.d.ts +21 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +21 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/initial-prompt.d.ts +8 -0
  34. package/dist/initial-prompt.d.ts.map +1 -0
  35. package/dist/initial-prompt.js +103 -0
  36. package/dist/initial-prompt.js.map +1 -0
  37. package/dist/launcher-contract.d.ts +34 -0
  38. package/dist/launcher-contract.d.ts.map +1 -0
  39. package/dist/launcher-contract.js +2 -0
  40. package/dist/launcher-contract.js.map +1 -0
  41. package/dist/live-turn-projection.d.ts +39 -0
  42. package/dist/live-turn-projection.d.ts.map +1 -0
  43. package/dist/live-turn-projection.js +395 -0
  44. package/dist/live-turn-projection.js.map +1 -0
  45. package/dist/pi-session-message.d.ts +25 -0
  46. package/dist/pi-session-message.d.ts.map +1 -0
  47. package/dist/pi-session-message.js +27 -0
  48. package/dist/pi-session-message.js.map +1 -0
  49. package/dist/primary-path-snapshot.d.ts +77 -0
  50. package/dist/primary-path-snapshot.d.ts.map +1 -0
  51. package/dist/primary-path-snapshot.js +2 -0
  52. package/dist/primary-path-snapshot.js.map +1 -0
  53. package/dist/protocol.d.ts +428 -0
  54. package/dist/protocol.d.ts.map +1 -0
  55. package/dist/protocol.js +261 -0
  56. package/dist/protocol.js.map +1 -0
  57. package/dist/session-entry-tree.d.ts +15 -0
  58. package/dist/session-entry-tree.d.ts.map +1 -0
  59. package/dist/session-entry-tree.js +42 -0
  60. package/dist/session-entry-tree.js.map +1 -0
  61. package/dist/streamable-events.d.ts +4 -0
  62. package/dist/streamable-events.d.ts.map +1 -0
  63. package/dist/streamable-events.js +17 -0
  64. package/dist/streamable-events.js.map +1 -0
  65. package/dist/text-preview.d.ts +7 -0
  66. package/dist/text-preview.d.ts.map +1 -0
  67. package/dist/text-preview.js +23 -0
  68. package/dist/text-preview.js.map +1 -0
  69. package/dist/timeline-projection.d.ts +9 -0
  70. package/dist/timeline-projection.d.ts.map +1 -0
  71. package/dist/timeline-projection.js +30 -0
  72. package/dist/timeline-projection.js.map +1 -0
  73. package/dist/timestamp-ordering.d.ts +3 -0
  74. package/dist/timestamp-ordering.d.ts.map +1 -0
  75. package/dist/timestamp-ordering.js +15 -0
  76. package/dist/timestamp-ordering.js.map +1 -0
  77. package/dist/tool-renderer-contract.d.ts +18 -0
  78. package/dist/tool-renderer-contract.d.ts.map +1 -0
  79. package/dist/tool-renderer-contract.js +22 -0
  80. package/dist/tool-renderer-contract.js.map +1 -0
  81. package/dist/turn-continuation.d.ts +36 -0
  82. package/dist/turn-continuation.d.ts.map +1 -0
  83. package/dist/turn-continuation.js +179 -0
  84. package/dist/turn-continuation.js.map +1 -0
  85. package/dist/usage-by-turn-record.d.ts +5 -0
  86. package/dist/usage-by-turn-record.d.ts.map +1 -0
  87. package/dist/usage-by-turn-record.js +25 -0
  88. package/dist/usage-by-turn-record.js.map +1 -0
  89. package/dist/usage-snapshot.d.ts +25 -0
  90. package/dist/usage-snapshot.d.ts.map +1 -0
  91. package/dist/usage-snapshot.js +120 -0
  92. package/dist/usage-snapshot.js.map +1 -0
  93. package/dist/ws-event-payloads.d.ts +18 -0
  94. package/dist/ws-event-payloads.d.ts.map +1 -0
  95. package/dist/ws-event-payloads.js +47 -0
  96. package/dist/ws-event-payloads.js.map +1 -0
  97. package/package.json +65 -0
  98. package/src/config-snapshot.ts +244 -0
  99. package/src/external-review.ts +7 -0
  100. package/src/form-contract.ts +50 -0
  101. package/src/http-contracts.ts +1497 -0
  102. package/src/index.ts +20 -0
  103. package/src/initial-prompt.ts +127 -0
  104. package/src/launcher-contract.ts +43 -0
  105. package/src/live-turn-projection.ts +501 -0
  106. package/src/pi-session-message.ts +48 -0
  107. package/src/primary-path-snapshot.ts +98 -0
  108. package/src/protocol.ts +503 -0
  109. package/src/session-entry-tree.ts +63 -0
  110. package/src/streamable-events.ts +20 -0
  111. package/src/text-preview.ts +32 -0
  112. package/src/timeline-projection.ts +43 -0
  113. package/src/timestamp-ordering.ts +15 -0
  114. package/src/tool-renderer-contract.ts +41 -0
  115. package/src/turn-continuation.ts +298 -0
  116. package/src/usage-by-turn-record.ts +34 -0
  117. package/src/usage-snapshot.ts +174 -0
  118. package/src/ws-event-payloads.ts +73 -0
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
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";
@@ -0,0 +1,127 @@
1
+ import type { FutureExecutionOverviewItem, FutureExecutionSummary } from "./http-contracts.js";
2
+
3
+ // Best-effort extraction of an operator-facing prompt/command from launch params
4
+ // for compact overview and detail read models. Process launchers use several
5
+ // established field names; keep this priority list shared so server and browser
6
+ // projections cannot drift.
7
+ export const INITIAL_PROMPT_FIELD_PRIORITY = [
8
+ "initialPrompt",
9
+ "prompt",
10
+ "taskPrompt",
11
+ "userPrompt",
12
+ "instructions",
13
+ "instruction",
14
+ "initialCommand",
15
+ "command",
16
+ "query",
17
+ "message",
18
+ "requestedChange",
19
+ "request",
20
+ "description",
21
+ ] as const;
22
+
23
+ function isRecord(value: unknown): value is Record<string, unknown> {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+
27
+ function normalizePromptValue(value: string): string | null {
28
+ const normalized = value.replace(/\s+/g, " ").trim();
29
+ return normalized.length > 0 ? normalized : null;
30
+ }
31
+
32
+ export function truncatePromptPreview(
33
+ value: string | null | undefined,
34
+ maxLength = 180,
35
+ ): string | null {
36
+ const normalized = typeof value === "string" ? normalizePromptValue(value) : null;
37
+ return normalized && normalized.length > maxLength
38
+ ? `${normalized.slice(0, maxLength).trimEnd()}…`
39
+ : normalized;
40
+ }
41
+
42
+ function readStringField(record: Record<string, unknown>, fieldName: string): string | null {
43
+ const exact = record[fieldName];
44
+ if (typeof exact === "string") {
45
+ return normalizePromptValue(exact);
46
+ }
47
+
48
+ const normalizedFieldName = fieldName.toLowerCase();
49
+ for (const [key, value] of Object.entries(record)) {
50
+ if (key.toLowerCase() !== normalizedFieldName || typeof value !== "string") {
51
+ continue;
52
+ }
53
+ return normalizePromptValue(value);
54
+ }
55
+
56
+ return null;
57
+ }
58
+
59
+ export function extractInitialPromptFromValue(value: unknown): string | null {
60
+ if (!isRecord(value)) {
61
+ return null;
62
+ }
63
+
64
+ for (const fieldName of INITIAL_PROMPT_FIELD_PRIORITY) {
65
+ const prompt = readStringField(value, fieldName);
66
+ if (prompt) {
67
+ return prompt;
68
+ }
69
+ }
70
+
71
+ return null;
72
+ }
73
+
74
+ export function extractInitialPromptFromParamsJson(
75
+ paramsJson: string | null | undefined,
76
+ ): string | null {
77
+ if (!paramsJson) {
78
+ return null;
79
+ }
80
+
81
+ try {
82
+ return extractInitialPromptFromValue(JSON.parse(paramsJson));
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ export function extractInitialPromptPreviewFromParamsJson(
89
+ paramsJson: string | null | undefined,
90
+ maxLength = 180,
91
+ ): string | null {
92
+ return truncatePromptPreview(extractInitialPromptFromParamsJson(paramsJson), maxLength);
93
+ }
94
+
95
+ export function projectFutureExecutionOverview(
96
+ summary: FutureExecutionSummary,
97
+ ): FutureExecutionOverviewItem {
98
+ const common = {
99
+ id: summary.id,
100
+ scheduleKind: summary.scheduleKind,
101
+ processId: summary.processId,
102
+ nextRunAt: summary.nextRunAt,
103
+ cronExpression: summary.cronExpression,
104
+ title: summary.title,
105
+ status: summary.status ?? "scheduled",
106
+ blockedReason: summary.blockedReason ?? null,
107
+ initialPromptPreview:
108
+ summary.kind === "launch"
109
+ ? truncatePromptPreview(extractInitialPromptFromValue(summary.launcherInput))
110
+ : null,
111
+ };
112
+ return summary.kind === "action"
113
+ ? {
114
+ ...common,
115
+ kind: "action",
116
+ instanceId: summary.instanceId,
117
+ actionId: summary.actionId,
118
+ actionLabel: summary.actionLabel,
119
+ }
120
+ : {
121
+ ...common,
122
+ kind: "launch",
123
+ instanceId: null,
124
+ launcherId: summary.launcherId,
125
+ launcherLabel: summary.launcherLabel,
126
+ };
127
+ }
@@ -0,0 +1,43 @@
1
+ import type {
2
+ FormDefinition,
3
+ FormFieldDefinition,
4
+ FormFieldOptionDefinition,
5
+ } from "./form-contract.js";
6
+
7
+ export interface LauncherCardMetadata {
8
+ title?: string;
9
+ description?: string;
10
+ }
11
+
12
+ export type LauncherFieldOptionDefinition = FormFieldOptionDefinition;
13
+ export type LauncherFieldDefinition = FormFieldDefinition;
14
+ export type LauncherSchemaDefinition = FormDefinition<LauncherFieldDefinition>;
15
+
16
+ export interface LauncherValidationError {
17
+ code: string;
18
+ message: string;
19
+ fieldId?: string;
20
+ }
21
+
22
+ export interface SkillOptionSummary {
23
+ id: string;
24
+ label: string;
25
+ description: string | null;
26
+ }
27
+
28
+ export interface SkillSelection {
29
+ skillId: string;
30
+ revisionId: string;
31
+ }
32
+
33
+ export interface UiLauncherSummaryBase {
34
+ id: string;
35
+ processId: string;
36
+ displayName: string;
37
+ label: string;
38
+ description: string;
39
+ card: LauncherCardMetadata;
40
+ launchConfigSchema: LauncherSchemaDefinition;
41
+ /** Safe summaries of currently available opt-in skills. */
42
+ skills?: readonly SkillOptionSummary[];
43
+ }
@@ -0,0 +1,501 @@
1
+ import type { ProcessEvent } from "@leitwerk-dev/domain";
2
+ import type {
3
+ PrimaryPathOperationalTraceItemSnapshot,
4
+ PrimaryPathStreamingAssistantSnapshot,
5
+ PrimaryPathToolCallSnapshot,
6
+ PrimaryPathTraceItemSnapshot,
7
+ } from "./primary-path-snapshot.js";
8
+ import { compareTimestampStrings } from "./timestamp-ordering.js";
9
+ import {
10
+ cloneUsageSnapshot,
11
+ mergeUsageSnapshots,
12
+ normalizeUsageSnapshot,
13
+ type UsageSnapshot,
14
+ } from "./usage-snapshot.js";
15
+ import {
16
+ asWsEventPayloadRecord,
17
+ readWsEventNonEmptyString,
18
+ readWsEventStreamText,
19
+ readWsEventTimestamp,
20
+ readWsEventToolArguments,
21
+ readWsEventToolCallId,
22
+ readWsEventToolName,
23
+ resolveWsEventToolCallId,
24
+ type WsEventPayloadRecord,
25
+ } from "./ws-event-payloads.js";
26
+
27
+ export interface MutableLiveTurnProjection {
28
+ assistant: PrimaryPathStreamingAssistantSnapshot;
29
+ toolCalls: PrimaryPathToolCallSnapshot[];
30
+ traceItems: PrimaryPathTraceItemSnapshot[];
31
+ usage: UsageSnapshot | null;
32
+ toolCallsById: Map<string, PrimaryPathToolCallSnapshot>;
33
+ openToolCallIdsByName: Map<string, string[]>;
34
+ nextFallbackOrdinal: number;
35
+ }
36
+
37
+ export interface AppliedLiveTurnProjectionEvent {
38
+ canonicalData: WsEventPayloadRecord;
39
+ timestamp: string;
40
+ toolCallId: string | null;
41
+ toolName: string | null;
42
+ }
43
+
44
+ export const PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES = [
45
+ "pi.error",
46
+ "pi.retry.start",
47
+ "pi.retry.end",
48
+ "pi.compaction.start",
49
+ "pi.compaction.end",
50
+ ] as const;
51
+
52
+ const PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPE_SET = new Set<string>(
53
+ PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES,
54
+ );
55
+
56
+ function cloneAssistant(
57
+ assistant: PrimaryPathStreamingAssistantSnapshot,
58
+ ): PrimaryPathStreamingAssistantSnapshot {
59
+ return { ...assistant };
60
+ }
61
+
62
+ function cloneToolCall(toolCall: PrimaryPathToolCallSnapshot): PrimaryPathToolCallSnapshot {
63
+ return {
64
+ ...toolCall,
65
+ ...(toolCall.arguments ? { arguments: { ...toolCall.arguments } } : {}),
66
+ };
67
+ }
68
+
69
+ function cloneTraceItem(traceItem: PrimaryPathTraceItemSnapshot): PrimaryPathTraceItemSnapshot {
70
+ return { ...traceItem };
71
+ }
72
+
73
+ function readString(value: unknown): string | null {
74
+ return typeof value === "string" && value.trim() !== "" ? value : null;
75
+ }
76
+
77
+ function readNumber(value: unknown): number | null {
78
+ if (typeof value === "number" && Number.isFinite(value)) {
79
+ return value;
80
+ }
81
+ if (typeof value === "string" && value.trim() !== "") {
82
+ const parsed = Number(value);
83
+ return Number.isFinite(parsed) ? parsed : null;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ function formatReason(value: unknown): string | null {
89
+ const reason = readString(value);
90
+ return reason ? reason.replace(/[_-]+/g, " ") : null;
91
+ }
92
+
93
+ function firstMessage(data: WsEventPayloadRecord, keys: readonly string[]): string | null {
94
+ for (const key of keys) {
95
+ const value = readString(data[key]);
96
+ if (value) {
97
+ return value;
98
+ }
99
+ }
100
+ return null;
101
+ }
102
+
103
+ function retryStartFallbackMessage(data: WsEventPayloadRecord): string {
104
+ const attempt = readNumber(data.attempt);
105
+ const maxAttempts = readNumber(data.maxAttempts);
106
+ const delayMs = readNumber(data.delayMs);
107
+ const attemptLabel = attempt !== null && maxAttempts !== null ? ` ${attempt}/${maxAttempts}` : "";
108
+ const delayLabel = delayMs !== null && delayMs > 0 ? ` in ${delayMs}ms` : "";
109
+ return `Retry${attemptLabel} scheduled${delayLabel}.`;
110
+ }
111
+
112
+ function retryEndFallbackMessage(data: WsEventPayloadRecord): string {
113
+ const attempt = readNumber(data.attempt);
114
+ if (data.success === true) {
115
+ return attempt !== null
116
+ ? `Retry sequence succeeded after ${attempt} ${attempt === 1 ? "retry" : "retries"}.`
117
+ : "Retry sequence succeeded.";
118
+ }
119
+ return attempt !== null
120
+ ? `Retry sequence ended after ${attempt} ${attempt === 1 ? "retry" : "retries"}.`
121
+ : "Retry sequence ended.";
122
+ }
123
+
124
+ export function buildPrimaryPathOperationalTraceItem(input: {
125
+ eventType: string;
126
+ data: WsEventPayloadRecord;
127
+ fallbackTimestamp: string;
128
+ }): PrimaryPathOperationalTraceItemSnapshot | null {
129
+ if (!PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPE_SET.has(input.eventType)) {
130
+ return null;
131
+ }
132
+ const timestamp = readWsEventTimestamp(input.data, input.fallbackTimestamp);
133
+ if (input.eventType === "pi.error") {
134
+ return {
135
+ kind: "operational_event",
136
+ eventType: input.eventType,
137
+ severity: "error",
138
+ title: "Pi request failed",
139
+ message:
140
+ firstMessage(input.data, ["message", "errorMessage", "finalError"]) ??
141
+ "Pi reported an error.",
142
+ timestamp,
143
+ };
144
+ }
145
+ if (input.eventType === "pi.retry.start") {
146
+ return {
147
+ kind: "operational_event",
148
+ eventType: input.eventType,
149
+ severity: "warning",
150
+ title: "Retry scheduled",
151
+ message:
152
+ firstMessage(input.data, ["message", "errorMessage"]) ??
153
+ retryStartFallbackMessage(input.data),
154
+ timestamp,
155
+ };
156
+ }
157
+ if (input.eventType === "pi.retry.end") {
158
+ const success = input.data.success === true;
159
+ return {
160
+ kind: "operational_event",
161
+ eventType: input.eventType,
162
+ severity: success ? "success" : "error",
163
+ title: success ? "Retry succeeded" : "Retry exhausted",
164
+ message:
165
+ firstMessage(input.data, ["message", "finalError", "errorMessage"]) ??
166
+ retryEndFallbackMessage(input.data),
167
+ timestamp,
168
+ };
169
+ }
170
+ if (input.eventType === "pi.compaction.start") {
171
+ const reason = formatReason(input.data.reason);
172
+ return {
173
+ kind: "operational_event",
174
+ eventType: input.eventType,
175
+ severity: "info",
176
+ title: "Context compaction started",
177
+ message: reason
178
+ ? `Pi started compacting context (${reason}).`
179
+ : "Pi started compacting context.",
180
+ timestamp,
181
+ };
182
+ }
183
+ if (input.eventType === "pi.compaction.end") {
184
+ const reason = formatReason(input.data.reason);
185
+ const errorMessage = firstMessage(input.data, ["errorMessage", "message"]);
186
+ const aborted = input.data.aborted === true;
187
+ const willRetry = input.data.willRetry === true;
188
+ const statusMessage = errorMessage
189
+ ? errorMessage
190
+ : aborted
191
+ ? "Context compaction was cancelled."
192
+ : `Pi compacted context${reason ? ` (${reason})` : ""}.${willRetry ? " Pi will continue automatically." : ""}`;
193
+ return {
194
+ kind: "operational_event",
195
+ eventType: input.eventType,
196
+ severity: errorMessage ? "error" : aborted ? "warning" : "success",
197
+ title: errorMessage
198
+ ? "Context compaction failed"
199
+ : aborted
200
+ ? "Context compaction cancelled"
201
+ : "Context compacted",
202
+ message: statusMessage,
203
+ timestamp,
204
+ };
205
+ }
206
+ return null;
207
+ }
208
+
209
+ function addOpenToolCallId(
210
+ projection: MutableLiveTurnProjection,
211
+ toolName: string,
212
+ toolCallId: string,
213
+ ) {
214
+ const ids = projection.openToolCallIdsByName.get(toolName) ?? [];
215
+ ids.push(toolCallId);
216
+ projection.openToolCallIdsByName.set(toolName, ids);
217
+ }
218
+
219
+ function consumeLatestOpenToolCallId(
220
+ projection: MutableLiveTurnProjection,
221
+ toolName: string,
222
+ ): string | null {
223
+ const ids = projection.openToolCallIdsByName.get(toolName);
224
+ if (!ids || ids.length === 0) {
225
+ return null;
226
+ }
227
+ const toolCallId = ids.pop() ?? null;
228
+ if (ids.length === 0) {
229
+ projection.openToolCallIdsByName.delete(toolName);
230
+ } else {
231
+ projection.openToolCallIdsByName.set(toolName, ids);
232
+ }
233
+ return toolCallId;
234
+ }
235
+
236
+ function removeOpenToolCallId(projection: MutableLiveTurnProjection, toolCallId: string) {
237
+ for (const [toolName, ids] of projection.openToolCallIdsByName.entries()) {
238
+ const nextIds = ids.filter((candidate) => candidate !== toolCallId);
239
+ if (nextIds.length === ids.length) {
240
+ continue;
241
+ }
242
+ if (nextIds.length === 0) {
243
+ projection.openToolCallIdsByName.delete(toolName);
244
+ } else {
245
+ projection.openToolCallIdsByName.set(toolName, nextIds);
246
+ }
247
+ return;
248
+ }
249
+ }
250
+
251
+ function canonicalizeToolCallId(input: {
252
+ projection: MutableLiveTurnProjection;
253
+ data: WsEventPayloadRecord;
254
+ timestamp: string;
255
+ toolName: string;
256
+ preferOpenCall: boolean;
257
+ }): string {
258
+ const explicitToolCallId = readWsEventToolCallId(input.data);
259
+ if (explicitToolCallId) {
260
+ if (input.preferOpenCall) {
261
+ removeOpenToolCallId(input.projection, explicitToolCallId);
262
+ }
263
+ return explicitToolCallId;
264
+ }
265
+ if (input.preferOpenCall) {
266
+ const openToolCallId = consumeLatestOpenToolCallId(input.projection, input.toolName);
267
+ if (openToolCallId) {
268
+ return openToolCallId;
269
+ }
270
+ }
271
+ return resolveWsEventToolCallId(input.data, {
272
+ timestamp: input.timestamp,
273
+ toolName: input.toolName,
274
+ ordinal: input.projection.nextFallbackOrdinal++,
275
+ });
276
+ }
277
+
278
+ function appendThinkingTraceText(projection: MutableLiveTurnProjection, text: string): void {
279
+ if (text.length === 0) {
280
+ return;
281
+ }
282
+ const lastTraceItem = projection.traceItems.at(-1);
283
+ if (lastTraceItem?.kind === "thinking") {
284
+ lastTraceItem.text += text;
285
+ return;
286
+ }
287
+ projection.traceItems.push({
288
+ kind: "thinking",
289
+ text,
290
+ });
291
+ }
292
+
293
+ function ensureToolTraceItem(projection: MutableLiveTurnProjection, toolCallId: string): void {
294
+ if (
295
+ projection.traceItems.some(
296
+ (traceItem) => traceItem.kind === "tool_call" && traceItem.toolCallId === toolCallId,
297
+ )
298
+ ) {
299
+ return;
300
+ }
301
+ projection.traceItems.push({
302
+ kind: "tool_call",
303
+ toolCallId,
304
+ });
305
+ }
306
+
307
+ export function createMutableLiveTurnProjection(): MutableLiveTurnProjection {
308
+ return {
309
+ assistant: {
310
+ text: "",
311
+ thinking: "",
312
+ lastUpdatedAt: null,
313
+ },
314
+ toolCalls: [],
315
+ traceItems: [],
316
+ usage: null,
317
+ toolCallsById: new Map<string, PrimaryPathToolCallSnapshot>(),
318
+ openToolCallIdsByName: new Map<string, string[]>(),
319
+ nextFallbackOrdinal: 1,
320
+ };
321
+ }
322
+
323
+ export function snapshotLiveTurnProjection(projection: MutableLiveTurnProjection): {
324
+ assistant: PrimaryPathStreamingAssistantSnapshot;
325
+ toolCalls: PrimaryPathToolCallSnapshot[];
326
+ traceItems: PrimaryPathTraceItemSnapshot[];
327
+ usage: UsageSnapshot | null;
328
+ } {
329
+ return {
330
+ assistant: cloneAssistant(projection.assistant),
331
+ toolCalls: projection.toolCalls.map(cloneToolCall),
332
+ traceItems: projection.traceItems.map(cloneTraceItem),
333
+ usage: cloneUsageSnapshot(projection.usage),
334
+ };
335
+ }
336
+
337
+ export function applyPiEventToLiveTurnProjection(
338
+ projection: MutableLiveTurnProjection,
339
+ input: {
340
+ eventType: string;
341
+ data: WsEventPayloadRecord;
342
+ fallbackTimestamp: string;
343
+ },
344
+ ): AppliedLiveTurnProjectionEvent {
345
+ const timestamp = readWsEventTimestamp(input.data, input.fallbackTimestamp);
346
+ if (input.eventType === "pi.stream.delta") {
347
+ const text = readWsEventStreamText(input.data);
348
+ if (text) {
349
+ if (readWsEventNonEmptyString(input.data.streamType) === "thinking") {
350
+ projection.assistant.thinking += text;
351
+ appendThinkingTraceText(projection, text);
352
+ } else {
353
+ projection.assistant.text += text;
354
+ }
355
+ projection.assistant.lastUpdatedAt = timestamp;
356
+ }
357
+ return {
358
+ canonicalData: input.data,
359
+ timestamp,
360
+ toolCallId: null,
361
+ toolName: null,
362
+ };
363
+ }
364
+
365
+ if (input.eventType === "pi.tool.call") {
366
+ const toolName = readWsEventToolName(input.data);
367
+ const toolCallId = canonicalizeToolCallId({
368
+ projection,
369
+ data: input.data,
370
+ timestamp,
371
+ toolName,
372
+ preferOpenCall: false,
373
+ });
374
+ const canonicalData =
375
+ readWsEventToolCallId(input.data) === toolCallId ? input.data : { ...input.data, toolCallId };
376
+ const existingToolCall = projection.toolCallsById.get(toolCallId);
377
+ if (!existingToolCall) {
378
+ const toolCall: PrimaryPathToolCallSnapshot = {
379
+ toolCallId,
380
+ toolName,
381
+ status: "running",
382
+ startedAt: timestamp,
383
+ completedAt: null,
384
+ arguments: readWsEventToolArguments(canonicalData),
385
+ result: null,
386
+ isError: false,
387
+ };
388
+ projection.toolCalls.push(toolCall);
389
+ projection.toolCallsById.set(toolCallId, toolCall);
390
+ }
391
+ ensureToolTraceItem(projection, toolCallId);
392
+ addOpenToolCallId(projection, toolName, toolCallId);
393
+ return {
394
+ canonicalData,
395
+ timestamp,
396
+ toolCallId,
397
+ toolName,
398
+ };
399
+ }
400
+
401
+ if (input.eventType === "pi.tool.result") {
402
+ const toolName = readWsEventToolName(input.data);
403
+ const toolCallId = canonicalizeToolCallId({
404
+ projection,
405
+ data: input.data,
406
+ timestamp,
407
+ toolName,
408
+ preferOpenCall: true,
409
+ });
410
+ const canonicalData =
411
+ readWsEventToolCallId(input.data) === toolCallId ? input.data : { ...input.data, toolCallId };
412
+ const existingToolCall = projection.toolCallsById.get(toolCallId);
413
+ if (existingToolCall) {
414
+ existingToolCall.status = "completed";
415
+ existingToolCall.completedAt = timestamp;
416
+ existingToolCall.result = canonicalData.result ?? null;
417
+ existingToolCall.isError = canonicalData.isError === true;
418
+ removeOpenToolCallId(projection, toolCallId);
419
+ } else {
420
+ const completedToolCall: PrimaryPathToolCallSnapshot = {
421
+ toolCallId,
422
+ toolName,
423
+ status: "completed",
424
+ startedAt: timestamp,
425
+ completedAt: timestamp,
426
+ arguments: null,
427
+ result: canonicalData.result ?? null,
428
+ isError: canonicalData.isError === true,
429
+ };
430
+ projection.toolCalls.push(completedToolCall);
431
+ projection.toolCallsById.set(toolCallId, completedToolCall);
432
+ }
433
+ ensureToolTraceItem(projection, toolCallId);
434
+ return {
435
+ canonicalData,
436
+ timestamp,
437
+ toolCallId,
438
+ toolName,
439
+ };
440
+ }
441
+
442
+ if (input.eventType === "pi.usage") {
443
+ projection.usage = mergeUsageSnapshots(projection.usage, normalizeUsageSnapshot(input.data));
444
+ return {
445
+ canonicalData: input.data,
446
+ timestamp,
447
+ toolCallId: null,
448
+ toolName: null,
449
+ };
450
+ }
451
+
452
+ const operationalTraceItem = buildPrimaryPathOperationalTraceItem({
453
+ eventType: input.eventType,
454
+ data: input.data,
455
+ fallbackTimestamp: input.fallbackTimestamp,
456
+ });
457
+ if (operationalTraceItem) {
458
+ projection.traceItems.push(operationalTraceItem);
459
+ return {
460
+ canonicalData: input.data,
461
+ timestamp: operationalTraceItem.timestamp,
462
+ toolCallId: null,
463
+ toolName: null,
464
+ };
465
+ }
466
+
467
+ return {
468
+ canonicalData: input.data,
469
+ timestamp,
470
+ toolCallId: null,
471
+ toolName: null,
472
+ };
473
+ }
474
+
475
+ function compareProcessEventsChronologically(left: ProcessEvent, right: ProcessEvent): number {
476
+ const leftTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(left.data), left.createdAt);
477
+ const rightTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(right.data), right.createdAt);
478
+ const timestampComparison = compareTimestampStrings(leftTimestamp, rightTimestamp);
479
+ if (timestampComparison !== 0) {
480
+ return timestampComparison;
481
+ }
482
+ const createdAtComparison = compareTimestampStrings(left.createdAt, right.createdAt);
483
+ if (createdAtComparison !== 0) {
484
+ return createdAtComparison;
485
+ }
486
+ return left.id.localeCompare(right.id);
487
+ }
488
+
489
+ export function buildLiveTurnProjectionFromEvents(
490
+ events: readonly ProcessEvent[],
491
+ ): MutableLiveTurnProjection {
492
+ const projection = createMutableLiveTurnProjection();
493
+ for (const event of [...events].sort(compareProcessEventsChronologically)) {
494
+ applyPiEventToLiveTurnProjection(projection, {
495
+ eventType: event.eventType,
496
+ data: asWsEventPayloadRecord(event.data),
497
+ fallbackTimestamp: event.createdAt,
498
+ });
499
+ }
500
+ return projection;
501
+ }