@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
@@ -0,0 +1,20 @@
1
+ export const STREAMABLE_WORKER_EVENT_TYPES = [
2
+ "pi.stream.delta",
3
+ "pi.turn.start",
4
+ "pi.turn.end",
5
+ "pi.tool.call",
6
+ "pi.tool.result",
7
+ "pi.label.changed",
8
+ "pi.error",
9
+ "pi.retry.start",
10
+ "pi.retry.end",
11
+ "pi.usage",
12
+ ] as const;
13
+
14
+ export type StreamableWorkerEventType = (typeof STREAMABLE_WORKER_EVENT_TYPES)[number];
15
+
16
+ const STREAMABLE_EVENT_TYPES = new Set<string>(STREAMABLE_WORKER_EVENT_TYPES);
17
+
18
+ export function isStreamableEvent(eventType: string): eventType is StreamableWorkerEventType {
19
+ return STREAMABLE_EVENT_TYPES.has(eventType);
20
+ }
@@ -0,0 +1,32 @@
1
+ export interface TextPreview {
2
+ text: string;
3
+ truncated: boolean;
4
+ }
5
+
6
+ export function truncateTextPreview(value: string, maxLength: number): TextPreview {
7
+ return value.length <= maxLength
8
+ ? { text: value, truncated: false }
9
+ : { text: value.slice(0, maxLength).trimEnd(), truncated: true };
10
+ }
11
+
12
+ export function buildTrailingLinePreview(
13
+ value: string,
14
+ lineCount: number,
15
+ maxLength: number,
16
+ ): TextPreview {
17
+ const lines = value.replace(/\r\n?/g, "\n").split("\n");
18
+ if (lines.length === 1 && lines[0] === "") return { text: "", truncated: false };
19
+
20
+ let text = lines.slice(-lineCount).join("\n");
21
+ let truncated = lines.length > lineCount;
22
+ if (text.length > maxLength) {
23
+ text = text.slice(-maxLength);
24
+ truncated = true;
25
+ }
26
+ if (truncated) {
27
+ const previewLines = text.split("\n");
28
+ previewLines[0] = previewLines[0] ? `… ${previewLines[0]}` : "…";
29
+ text = previewLines.join("\n");
30
+ }
31
+ return { text, truncated };
32
+ }
@@ -0,0 +1,43 @@
1
+ import type {
2
+ ProcessTimelineTurnPresentation,
3
+ ProcessTimelineTurnSummary,
4
+ } from "./http-contracts.js";
5
+ import type { PrimaryPathActiveTurnSnapshot } from "./primary-path-snapshot.js";
6
+
7
+ export function timelinePresentationForTurnType(
8
+ turnType: ProcessTimelineTurnSummary["turnType"],
9
+ ): ProcessTimelineTurnPresentation {
10
+ if (turnType === "external") return "external_trigger";
11
+ if (turnType === "human") return "operator_decision";
12
+ return turnType === "automatic" ? "automatic_turn" : "llm_turn";
13
+ }
14
+
15
+ export function buildActiveTimelineTurnSummary(
16
+ activeTurn: PrimaryPathActiveTurnSnapshot,
17
+ input: {
18
+ summary: string;
19
+ output: string;
20
+ actionSource?: ProcessTimelineTurnSummary["actionSource"];
21
+ } = { summary: `Current step: ${activeTurn.turnId}`, output: activeTurn.assistant.text.trim() },
22
+ ): ProcessTimelineTurnSummary {
23
+ return {
24
+ id: activeTurn.turnRecordId,
25
+ turnId: activeTurn.turnId,
26
+ turnType: activeTurn.turnType,
27
+ displayTurn: activeTurn.turnId,
28
+ outcome: "in_progress",
29
+ summary: input.summary,
30
+ output: input.output,
31
+ turnResultMarkdown: "",
32
+ pathType: activeTurn.pathType,
33
+ createdAt: activeTurn.startedAt,
34
+ presentation: timelinePresentationForTurnType(activeTurn.turnType),
35
+ status: "in_progress",
36
+ modelProfileId: null,
37
+ attemptNumber: 1,
38
+ parentTurnRecordId: null,
39
+ startedAt: activeTurn.startedAt,
40
+ endedAt: null,
41
+ actionSource: input.actionSource ?? null,
42
+ };
43
+ }
@@ -0,0 +1,15 @@
1
+ export function compareTimestampStrings(left: string, right: string): number {
2
+ const leftMs = Date.parse(left);
3
+ const rightMs = Date.parse(right);
4
+ if (Number.isFinite(leftMs) && Number.isFinite(rightMs)) {
5
+ return leftMs - rightMs;
6
+ }
7
+ return left.localeCompare(right);
8
+ }
9
+
10
+ export function happenedOnOrAfterStart(entryTimestamp: string, startedAt: string | null): boolean {
11
+ if (!startedAt) {
12
+ return true;
13
+ }
14
+ return compareTimestampStrings(entryTimestamp, startedAt) >= 0;
15
+ }
@@ -0,0 +1,41 @@
1
+ export const TOOL_CALL_RENDERER_VALUE_KINDS = ["markdown", "plaintext", "json"] as const;
2
+ export type ToolCallRendererValueKind = (typeof TOOL_CALL_RENDERER_VALUE_KINDS)[number];
3
+
4
+ export const TOOL_CALL_RENDERER_VALUE_SOURCES = ["arguments", "result"] as const;
5
+ export type ToolCallRendererValueSource = (typeof TOOL_CALL_RENDERER_VALUE_SOURCES)[number];
6
+
7
+ export interface ToolCallRendererFieldDefinition {
8
+ id: string;
9
+ label: string;
10
+ kind: ToolCallRendererValueKind;
11
+ source: ToolCallRendererValueSource;
12
+ path?: string;
13
+ }
14
+
15
+ export interface ToolCallRendererDefinition {
16
+ toolName: string;
17
+ title?: string;
18
+ fields: readonly ToolCallRendererFieldDefinition[];
19
+ }
20
+
21
+ import * as v from "valibot";
22
+
23
+ const unknownRecordSchema = v.record(v.string(), v.unknown());
24
+
25
+ export function readValueAtPath(value: unknown, path: string | undefined): unknown {
26
+ if (!path || path.trim() === "") {
27
+ return value;
28
+ }
29
+ let current: unknown = value;
30
+ for (const segment of path
31
+ .split(".")
32
+ .map((part) => part.trim())
33
+ .filter(Boolean)) {
34
+ const parsedCurrent = v.safeParse(unknownRecordSchema, current);
35
+ if (!parsedCurrent.success || !(segment in parsedCurrent.output)) {
36
+ return undefined;
37
+ }
38
+ current = parsedCurrent.output[segment];
39
+ }
40
+ return current;
41
+ }
@@ -0,0 +1,298 @@
1
+ import { trimToNull } from "@leitwerk-dev/domain";
2
+ import {
3
+ extractPiSessionMessageText,
4
+ isPiSessionMessageEntryType,
5
+ isPiSessionMessageEntryWithRecord,
6
+ } from "./pi-session-message.js";
7
+ import { createReadonlyEntryTree, type ReadonlyEntryTree } from "./session-entry-tree.js";
8
+ import { compareTimestampStrings, happenedOnOrAfterStart } from "./timestamp-ordering.js";
9
+
10
+ export interface ContinuationTreeEntry {
11
+ id: string;
12
+ parentId: string | null;
13
+ timestamp: string;
14
+ type: string;
15
+ message?: {
16
+ role?: string;
17
+ content?: unknown;
18
+ };
19
+ }
20
+
21
+ export interface ContinuationTurnRecordLike {
22
+ forkPiEntryId?: string | null;
23
+ resultPiEntryId?: string | null;
24
+ startedAt?: string | null;
25
+ status?: string | null;
26
+ }
27
+
28
+ export interface ContinuationSliceBounds {
29
+ endedAt?: string | null;
30
+ }
31
+
32
+ export interface TurnContinuationIndex<TEntry extends ContinuationTreeEntry> {
33
+ resolveLeafEntryId(
34
+ turnRecord: ContinuationTurnRecordLike,
35
+ bounds?: ContinuationSliceBounds,
36
+ ): string | null;
37
+ buildSlice(turnRecord: ContinuationTurnRecordLike, bounds?: ContinuationSliceBounds): TEntry[];
38
+ }
39
+
40
+ function createEntriesById(
41
+ entries: readonly ContinuationTreeEntry[],
42
+ ): Map<string, ContinuationTreeEntry> {
43
+ return new Map(entries.map((entry) => [entry.id, entry]));
44
+ }
45
+
46
+ function branchContainsAncestor(
47
+ entriesById: ReadonlyMap<string, ContinuationTreeEntry>,
48
+ entryId: string,
49
+ ancestorId: string,
50
+ ): boolean {
51
+ const visited = new Set<string>();
52
+ let current = entriesById.get(entryId);
53
+ while (current) {
54
+ if (visited.has(current.id)) {
55
+ return false;
56
+ }
57
+ visited.add(current.id);
58
+ if (current.id === ancestorId) {
59
+ return true;
60
+ }
61
+ current = current.parentId ? entriesById.get(current.parentId) : undefined;
62
+ }
63
+ return false;
64
+ }
65
+
66
+ function happenedOnOrBeforeEnd(entryTimestamp: string, endedAt: string | null): boolean {
67
+ if (!endedAt) {
68
+ return true;
69
+ }
70
+ return compareTimestampStrings(entryTimestamp, endedAt) <= 0;
71
+ }
72
+
73
+ function isContinuableEntryType(
74
+ entry: ContinuationTreeEntry | undefined,
75
+ ): entry is ContinuationTreeEntry {
76
+ return isPiSessionMessageEntryType(entry) || entry?.type === "compaction";
77
+ }
78
+
79
+ function isExplicitLeafUsable(
80
+ entriesById: ReadonlyMap<string, ContinuationTreeEntry>,
81
+ leafId: string,
82
+ forkPiEntryId: string | null,
83
+ startedAt: string | null,
84
+ endedAt: string | null,
85
+ ): boolean {
86
+ const leafEntry = entriesById.get(leafId);
87
+ if (!isContinuableEntryType(leafEntry)) {
88
+ return false;
89
+ }
90
+ if (!happenedOnOrAfterStart(leafEntry.timestamp, startedAt)) {
91
+ return false;
92
+ }
93
+ if (!happenedOnOrBeforeEnd(leafEntry.timestamp, endedAt)) {
94
+ return false;
95
+ }
96
+ if (!forkPiEntryId) {
97
+ return true;
98
+ }
99
+ return branchContainsAncestor(entriesById, leafId, forkPiEntryId);
100
+ }
101
+
102
+ function findLatestContinuableEntryIdOnBranch(
103
+ entries: readonly ContinuationTreeEntry[],
104
+ entriesById: ReadonlyMap<string, ContinuationTreeEntry>,
105
+ options: { startedAt: string | null; endedAt: string | null; ancestorId: string | null },
106
+ ): string | null {
107
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
108
+ const entry = entries[index];
109
+ if (!entry) {
110
+ continue;
111
+ }
112
+ if (!isContinuableEntryType(entry)) {
113
+ continue;
114
+ }
115
+ if (!happenedOnOrAfterStart(entry.timestamp, options.startedAt)) {
116
+ continue;
117
+ }
118
+ if (!happenedOnOrBeforeEnd(entry.timestamp, options.endedAt)) {
119
+ continue;
120
+ }
121
+ if (options.ancestorId && !branchContainsAncestor(entriesById, entry.id, options.ancestorId)) {
122
+ continue;
123
+ }
124
+ return entry.id;
125
+ }
126
+ return null;
127
+ }
128
+
129
+ function readMessageRole(entry: ContinuationTreeEntry | undefined): string | null {
130
+ const role = entry?.message?.role;
131
+ return typeof role === "string" && role.trim() !== "" ? role : null;
132
+ }
133
+
134
+ function resolveTurnContinuationLeafEntryIdFromIndex(
135
+ entries: readonly ContinuationTreeEntry[],
136
+ entriesById: ReadonlyMap<string, ContinuationTreeEntry>,
137
+ turnRecord: ContinuationTurnRecordLike,
138
+ bounds: ContinuationSliceBounds = {},
139
+ ): string | null {
140
+ const startedAt = trimToNull(turnRecord.startedAt);
141
+ const endedAt = trimToNull(bounds.endedAt);
142
+ const forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);
143
+ const explicitLeafId = trimToNull(turnRecord.resultPiEntryId);
144
+ if (
145
+ explicitLeafId &&
146
+ isExplicitLeafUsable(entriesById, explicitLeafId, forkPiEntryId, startedAt, endedAt)
147
+ ) {
148
+ if (turnRecord.status !== "failed") {
149
+ return explicitLeafId;
150
+ }
151
+ return findLatestContinuableEntryIdOnBranch(entries, entriesById, {
152
+ startedAt,
153
+ endedAt,
154
+ ancestorId: explicitLeafId,
155
+ });
156
+ }
157
+
158
+ return findLatestContinuableEntryIdOnBranch(entries, entriesById, {
159
+ startedAt,
160
+ endedAt,
161
+ ancestorId: forkPiEntryId,
162
+ });
163
+ }
164
+
165
+ export function createTurnContinuationIndex<TEntry extends ContinuationTreeEntry>(
166
+ entries: readonly TEntry[],
167
+ ): TurnContinuationIndex<TEntry> {
168
+ const orderedEntries = entries;
169
+ const entriesById = createEntriesById(orderedEntries);
170
+
171
+ const resolveLeafEntryId = (
172
+ turnRecord: ContinuationTurnRecordLike,
173
+ bounds: ContinuationSliceBounds = {},
174
+ ): string | null =>
175
+ resolveTurnContinuationLeafEntryIdFromIndex(orderedEntries, entriesById, turnRecord, bounds);
176
+
177
+ const buildSlice = (
178
+ turnRecord: ContinuationTurnRecordLike,
179
+ bounds: ContinuationSliceBounds = {},
180
+ ): TEntry[] => {
181
+ const continuationLeafId = resolveLeafEntryId(turnRecord, bounds);
182
+ if (!continuationLeafId) {
183
+ return [];
184
+ }
185
+ const forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);
186
+ const reversedSlice: TEntry[] = [];
187
+ const visited = new Set<string>();
188
+ let current = entriesById.get(continuationLeafId) as TEntry | undefined;
189
+ let foundFork = forkPiEntryId === null;
190
+ while (current && !visited.has(current.id)) {
191
+ visited.add(current.id);
192
+ if (current.id === forkPiEntryId) {
193
+ foundFork = true;
194
+ break;
195
+ }
196
+ reversedSlice.push(current);
197
+ current = current.parentId
198
+ ? (entriesById.get(current.parentId) as TEntry | undefined)
199
+ : undefined;
200
+ }
201
+ if (!foundFork) {
202
+ return [];
203
+ }
204
+ const startedAt = trimToNull(turnRecord.startedAt);
205
+ const endedAt = trimToNull(bounds.endedAt);
206
+ return reversedSlice
207
+ .reverse()
208
+ .filter(
209
+ (entry) =>
210
+ happenedOnOrAfterStart(entry.timestamp, startedAt) &&
211
+ happenedOnOrBeforeEnd(entry.timestamp, endedAt),
212
+ );
213
+ };
214
+
215
+ return { resolveLeafEntryId, buildSlice };
216
+ }
217
+
218
+ export function resolveTurnContinuationLeafEntryId(
219
+ entries: readonly ContinuationTreeEntry[],
220
+ turnRecord: ContinuationTurnRecordLike,
221
+ bounds: ContinuationSliceBounds = {},
222
+ ): string | null {
223
+ return createTurnContinuationIndex(entries).resolveLeafEntryId(turnRecord, bounds);
224
+ }
225
+
226
+ export function buildTurnContinuationSliceFromTree<TEntry extends ContinuationTreeEntry>(
227
+ tree: ReadonlyEntryTree<TEntry>,
228
+ turnRecord: ContinuationTurnRecordLike,
229
+ bounds: ContinuationSliceBounds = {},
230
+ ): TEntry[] {
231
+ return createTurnContinuationIndex(tree.entries).buildSlice(turnRecord, bounds);
232
+ }
233
+
234
+ export function buildTurnContinuationSlice<TEntry extends ContinuationTreeEntry>(
235
+ entries: readonly TEntry[],
236
+ turnRecord: ContinuationTurnRecordLike,
237
+ bounds: ContinuationSliceBounds = {},
238
+ ): TEntry[] {
239
+ return buildTurnContinuationSliceFromTree(createReadonlyEntryTree(entries), turnRecord, bounds);
240
+ }
241
+
242
+ export interface BranchUserPromptSnapshot {
243
+ text: string | null;
244
+ createdAt: string | null;
245
+ }
246
+
247
+ export function extractFirstUserPromptOnBranch<TEntry extends ContinuationTreeEntry>(
248
+ tree: ReadonlyEntryTree<TEntry>,
249
+ leafId: string | null | undefined,
250
+ ): BranchUserPromptSnapshot {
251
+ const resolvedLeafId = trimToNull(leafId);
252
+ if (!resolvedLeafId) {
253
+ return { text: null, createdAt: null };
254
+ }
255
+ const branch = tree.getBranch(resolvedLeafId);
256
+ for (const entry of branch) {
257
+ if (!isPiSessionMessageEntryWithRecord(entry) || readMessageRole(entry) !== "user") {
258
+ continue;
259
+ }
260
+ const text = extractPiSessionMessageText(entry.message.content).trim();
261
+ if (text === "") {
262
+ continue;
263
+ }
264
+ return {
265
+ text,
266
+ createdAt: entry.timestamp,
267
+ };
268
+ }
269
+ return { text: null, createdAt: null };
270
+ }
271
+
272
+ export function resolveTurnContinuationUserPrompt(
273
+ entries: readonly ContinuationTreeEntry[],
274
+ turnRecord: ContinuationTurnRecordLike,
275
+ bounds: ContinuationSliceBounds = {},
276
+ ): string | null {
277
+ const continuationLeafId = resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds);
278
+ if (!continuationLeafId) {
279
+ return null;
280
+ }
281
+ const continuationLeaf = createEntriesById(entries).get(continuationLeafId);
282
+ if (
283
+ !isPiSessionMessageEntryWithRecord(continuationLeaf) ||
284
+ readMessageRole(continuationLeaf) !== "user"
285
+ ) {
286
+ return null;
287
+ }
288
+ const promptText = extractPiSessionMessageText(continuationLeaf.message.content).trim();
289
+ return promptText !== "" ? promptText : null;
290
+ }
291
+
292
+ export function hasTurnContinuationProgress(
293
+ entries: readonly ContinuationTreeEntry[],
294
+ turnRecord: ContinuationTurnRecordLike,
295
+ bounds: ContinuationSliceBounds = {},
296
+ ): boolean {
297
+ return resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds) !== null;
298
+ }
@@ -0,0 +1,34 @@
1
+ import type { ProcessEvent } from "@leitwerk-dev/domain";
2
+ import {
3
+ mergeUsageSnapshots,
4
+ normalizeUsageSnapshot,
5
+ type UsageSnapshot,
6
+ } from "./usage-snapshot.js";
7
+ import { asWsEventPayloadRecord, readWsEventTurnRecordId } from "./ws-event-payloads.js";
8
+
9
+ export type UsageSnapshotByTurnRecordId = Record<string, UsageSnapshot>;
10
+
11
+ export function buildUsageSnapshotsByTurnRecordId(
12
+ events: readonly ProcessEvent[],
13
+ ): UsageSnapshotByTurnRecordId {
14
+ const snapshots: UsageSnapshotByTurnRecordId = {};
15
+ for (const event of events) {
16
+ if (event.eventType !== "pi.usage") {
17
+ continue;
18
+ }
19
+ const payload = asWsEventPayloadRecord(event.data);
20
+ const turnRecordId = readWsEventTurnRecordId(payload);
21
+ if (!turnRecordId) {
22
+ continue;
23
+ }
24
+ const usage = normalizeUsageSnapshot(payload);
25
+ if (!usage) {
26
+ continue;
27
+ }
28
+ const merged = mergeUsageSnapshots(snapshots[turnRecordId] ?? null, usage);
29
+ if (merged) {
30
+ snapshots[turnRecordId] = merged;
31
+ }
32
+ }
33
+ return snapshots;
34
+ }
@@ -0,0 +1,174 @@
1
+ import * as v from "valibot";
2
+
3
+ export interface UsageCostSnapshot {
4
+ input: number;
5
+ output: number;
6
+ cacheRead: number;
7
+ cacheWrite: number;
8
+ total: number;
9
+ }
10
+
11
+ export interface UsageSnapshot {
12
+ input: number;
13
+ output: number;
14
+ /** Provider-reported reasoning/thinking tokens. This is a subset of output tokens. */
15
+ reasoning?: number;
16
+ cacheRead: number;
17
+ cacheWrite: number;
18
+ totalTokens: number;
19
+ cost: UsageCostSnapshot | null;
20
+ /** Number of model requests represented by this aggregate, when known. */
21
+ requestCount?: number;
22
+ /** Largest input-token count for a single represented model request, when known. */
23
+ maxInputTokens?: number;
24
+ }
25
+
26
+ const unknownRecordSchema = v.pipe(
27
+ v.unknown(),
28
+ v.check(
29
+ (value) => typeof value === "object" && value !== null && !Array.isArray(value),
30
+ "Expected object",
31
+ ),
32
+ v.record(v.string(), v.unknown()),
33
+ );
34
+
35
+ function readNumber(value: unknown): number {
36
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
37
+ }
38
+
39
+ function normalizeUsageCostSnapshot(value: unknown): UsageCostSnapshot | null {
40
+ const parsedValue = v.safeParse(unknownRecordSchema, value);
41
+ if (!parsedValue.success) {
42
+ return null;
43
+ }
44
+ const record = parsedValue.output;
45
+ const input = readNumber(record.input);
46
+ const output = readNumber(record.output);
47
+ const cacheRead = readNumber(record.cacheRead);
48
+ const cacheWrite = readNumber(record.cacheWrite);
49
+ const total =
50
+ typeof record.total === "number" && Number.isFinite(record.total)
51
+ ? record.total
52
+ : input + output + cacheRead + cacheWrite;
53
+ return {
54
+ input,
55
+ output,
56
+ cacheRead,
57
+ cacheWrite,
58
+ total,
59
+ };
60
+ }
61
+
62
+ function cloneUsageCostSnapshot(cost: UsageCostSnapshot): UsageCostSnapshot {
63
+ return { ...cost };
64
+ }
65
+
66
+ export function cloneUsageSnapshot(usage: UsageSnapshot | null | undefined): UsageSnapshot | null {
67
+ if (!usage) {
68
+ return null;
69
+ }
70
+ return {
71
+ ...usage,
72
+ cost: usage.cost ? cloneUsageCostSnapshot(usage.cost) : null,
73
+ };
74
+ }
75
+
76
+ export function normalizeUsageSnapshot(value: unknown): UsageSnapshot | null {
77
+ const parsedValue = v.safeParse(unknownRecordSchema, value);
78
+ if (!parsedValue.success) {
79
+ return null;
80
+ }
81
+ const record = parsedValue.output;
82
+ const input = readNumber(record.input);
83
+ const output = readNumber(record.output);
84
+ const reasoning =
85
+ typeof record.reasoning === "number" && Number.isFinite(record.reasoning)
86
+ ? record.reasoning
87
+ : undefined;
88
+ const cacheRead = readNumber(record.cacheRead);
89
+ const cacheWrite = readNumber(record.cacheWrite);
90
+ const totalTokens =
91
+ typeof record.totalTokens === "number" && Number.isFinite(record.totalTokens)
92
+ ? record.totalTokens
93
+ : input + output + cacheRead + cacheWrite;
94
+ const cost = normalizeUsageCostSnapshot(record.cost);
95
+ const requestCount =
96
+ typeof record.requestCount === "number" && Number.isFinite(record.requestCount)
97
+ ? Math.max(0, Math.floor(record.requestCount))
98
+ : 1;
99
+ const maxInputTokens =
100
+ typeof record.maxInputTokens === "number" && Number.isFinite(record.maxInputTokens)
101
+ ? Math.max(0, record.maxInputTokens)
102
+ : input;
103
+ const hasExplicitUsageTelemetry =
104
+ ["input", "output", "reasoning", "cacheRead", "cacheWrite", "totalTokens"].some(
105
+ (key) => typeof record[key] === "number" && Number.isFinite(record[key]),
106
+ ) || cost !== null;
107
+ if (
108
+ !hasExplicitUsageTelemetry &&
109
+ input === 0 &&
110
+ output === 0 &&
111
+ cacheRead === 0 &&
112
+ cacheWrite === 0 &&
113
+ totalTokens === 0
114
+ ) {
115
+ return null;
116
+ }
117
+ return {
118
+ input,
119
+ output,
120
+ ...(reasoning !== undefined ? { reasoning } : {}),
121
+ cacheRead,
122
+ cacheWrite,
123
+ totalTokens,
124
+ cost,
125
+ requestCount,
126
+ maxInputTokens,
127
+ };
128
+ }
129
+
130
+ export function mergeUsageSnapshots(
131
+ total: UsageSnapshot | null,
132
+ usage: UsageSnapshot | null,
133
+ ): UsageSnapshot | null {
134
+ if (!usage) {
135
+ return total ? cloneUsageSnapshot(total) : null;
136
+ }
137
+ if (!total) {
138
+ return cloneUsageSnapshot(usage);
139
+ }
140
+ const hasRequestMetrics =
141
+ total.requestCount !== undefined ||
142
+ usage.requestCount !== undefined ||
143
+ total.maxInputTokens !== undefined ||
144
+ usage.maxInputTokens !== undefined;
145
+ return {
146
+ input: total.input + usage.input,
147
+ output: total.output + usage.output,
148
+ ...(total.reasoning !== undefined || usage.reasoning !== undefined
149
+ ? { reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0) }
150
+ : {}),
151
+ cacheRead: total.cacheRead + usage.cacheRead,
152
+ cacheWrite: total.cacheWrite + usage.cacheWrite,
153
+ totalTokens: total.totalTokens + usage.totalTokens,
154
+ cost:
155
+ total.cost && usage.cost
156
+ ? {
157
+ input: total.cost.input + usage.cost.input,
158
+ output: total.cost.output + usage.cost.output,
159
+ cacheRead: total.cost.cacheRead + usage.cost.cacheRead,
160
+ cacheWrite: total.cost.cacheWrite + usage.cost.cacheWrite,
161
+ total: total.cost.total + usage.cost.total,
162
+ }
163
+ : null,
164
+ ...(hasRequestMetrics
165
+ ? {
166
+ requestCount: (total.requestCount ?? 1) + (usage.requestCount ?? 1),
167
+ maxInputTokens: Math.max(
168
+ total.maxInputTokens ?? total.input,
169
+ usage.maxInputTokens ?? usage.input,
170
+ ),
171
+ }
172
+ : {}),
173
+ };
174
+ }