@tangle-network/agent-eval 0.131.1 → 0.133.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 (133) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/analyst/index.d.ts +5 -5
  3. package/dist/analyst/index.js +3 -3
  4. package/dist/{analyze-runs-CBnCgfse.d.ts → analyze-runs-DZr7JW-m.d.ts} +5 -5
  5. package/dist/{analyze-runs-CBnCgfse.d.ts.map → analyze-runs-DZr7JW-m.d.ts.map} +1 -1
  6. package/dist/benchmarks/index.d.ts +1 -1
  7. package/dist/benchmarks/index.js +1 -1
  8. package/dist/{benchmarks-BDtRiOvE.js → benchmarks-DncrVrSr.js} +3 -3
  9. package/dist/{benchmarks-BDtRiOvE.js.map → benchmarks-DncrVrSr.js.map} +1 -1
  10. package/dist/campaign/index.d.ts +4 -4
  11. package/dist/campaign/index.js +2 -2
  12. package/dist/{campaign-CLG6y9jF.js → campaign-CyQMCCEU.js} +4 -4
  13. package/dist/{campaign-CLG6y9jF.js.map → campaign-CyQMCCEU.js.map} +1 -1
  14. package/dist/cli.js +1 -1
  15. package/dist/{client-w90OcvvR.d.ts → client-D4F9hdzR.d.ts} +4 -4
  16. package/dist/{client-w90OcvvR.d.ts.map → client-D4F9hdzR.d.ts.map} +1 -1
  17. package/dist/contract/index.d.ts +188 -22
  18. package/dist/contract/index.d.ts.map +1 -1
  19. package/dist/contract/index.js +1663 -65
  20. package/dist/contract/index.js.map +1 -1
  21. package/dist/control.d.ts +1 -1
  22. package/dist/{cost-ledger-DIgQUFZZ.js → cost-ledger-BrJxbrMy.js} +278 -9
  23. package/dist/cost-ledger-BrJxbrMy.js.map +1 -0
  24. package/dist/{cost-ledger-Dye6jCgg.d.ts → cost-ledger-fGS_u_O1.d.ts} +18 -2
  25. package/dist/cost-ledger-fGS_u_O1.d.ts.map +1 -0
  26. package/dist/{default-registry-Cj1oUpLN.d.ts → default-registry-Cl3pHo4n.d.ts} +4 -4
  27. package/dist/{default-registry-Cj1oUpLN.d.ts.map → default-registry-Cl3pHo4n.d.ts.map} +1 -1
  28. package/dist/{default-registry-C-vFCSEc.js → default-registry-D3T9XbuY.js} +4 -13
  29. package/dist/default-registry-D3T9XbuY.js.map +1 -0
  30. package/dist/{eval-campaign-C2k-m4aY.js → eval-campaign-CYkUME2T.js} +2 -2
  31. package/dist/{eval-campaign-C2k-m4aY.js.map → eval-campaign-CYkUME2T.js.map} +1 -1
  32. package/dist/{task-failure-attributes-CQZlB3et.js → extract-usage-2j25whHw.js} +154 -2
  33. package/dist/extract-usage-2j25whHw.js.map +1 -0
  34. package/dist/fuzz.d.ts +1 -1
  35. package/dist/fuzz.js +1 -1
  36. package/dist/hosted/index.d.ts +2 -2
  37. package/dist/{index-B11XCkdf2.d.ts → index-3cdlURSk.d.ts} +2 -2
  38. package/dist/index-3cdlURSk.d.ts.map +1 -0
  39. package/dist/{index-VTypFU3t.d.ts → index-B_eUhU9K.d.ts} +7 -7
  40. package/dist/{index-VTypFU3t.d.ts.map → index-B_eUhU9K.d.ts.map} +1 -1
  41. package/dist/{index-DNXoNaFF.d.ts → index-C2fkZhv_.d.ts} +2 -2
  42. package/dist/{index-DNXoNaFF.d.ts.map → index-C2fkZhv_.d.ts.map} +1 -1
  43. package/dist/{index-NPeSWD98.d.ts → index-CiP2DRCj.d.ts} +5 -5
  44. package/dist/{index-NPeSWD98.d.ts.map → index-CiP2DRCj.d.ts.map} +1 -1
  45. package/dist/index.d.ts +69 -23
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +100 -12
  48. package/dist/index.js.map +1 -1
  49. package/dist/{llm-client-B_nIBlYo.d.ts → llm-client-BiK4HW0u.d.ts} +2 -2
  50. package/dist/{llm-client-B_nIBlYo.d.ts.map → llm-client-BiK4HW0u.d.ts.map} +1 -1
  51. package/dist/{llm-client--GR4JbZE.js → llm-client-ClPW-dWB.js} +2 -2
  52. package/dist/{llm-client--GR4JbZE.js.map → llm-client-ClPW-dWB.js.map} +1 -1
  53. package/dist/meta-eval/index.d.ts +216 -3
  54. package/dist/{index-D_F6VAKe.d.ts.map → meta-eval/index.d.ts.map} +1 -1
  55. package/dist/meta-eval/index.js +91 -1
  56. package/dist/meta-eval/index.js.map +1 -1
  57. package/dist/multishot/index.d.ts +1 -1
  58. package/dist/openapi.json +1 -1
  59. package/dist/{release-report-Crg9oFJ0.d.ts → release-report-DfmKSIEE.d.ts} +3 -3
  60. package/dist/{release-report-Crg9oFJ0.d.ts.map → release-report-DfmKSIEE.d.ts.map} +1 -1
  61. package/dist/{replay-RE97Ckjl.d.ts → replay-BI6CVKkp.d.ts} +2 -2
  62. package/dist/{replay-RE97Ckjl.d.ts.map → replay-BI6CVKkp.d.ts.map} +1 -1
  63. package/dist/{replay-D18-pBAA.js → replay-BMR4TEYY.js} +2 -3
  64. package/dist/{replay-D18-pBAA.js.map → replay-BMR4TEYY.js.map} +1 -1
  65. package/dist/reporting.d.ts +4 -4
  66. package/dist/{researcher-Q5rpPqZY.d.ts → researcher-DMimgHtN.d.ts} +4 -4
  67. package/dist/{researcher-Q5rpPqZY.d.ts.map → researcher-DMimgHtN.d.ts.map} +1 -1
  68. package/dist/{reward-hacking-CW-3HN0n.d.ts → reward-hacking-D-QqXvg-.d.ts} +2 -2
  69. package/dist/{reward-hacking-CW-3HN0n.d.ts.map → reward-hacking-D-QqXvg-.d.ts.map} +1 -1
  70. package/dist/rl.d.ts +156 -6
  71. package/dist/rl.d.ts.map +1 -1
  72. package/dist/rl.js +217 -2
  73. package/dist/rl.js.map +1 -1
  74. package/dist/rollout/index.d.ts +1 -1
  75. package/dist/{rubric-predictive-validity-lXLmashy.d.ts → rubric-predictive-validity-C1dCLcvb.d.ts} +2 -2
  76. package/dist/{rubric-predictive-validity-lXLmashy.d.ts.map → rubric-predictive-validity-C1dCLcvb.d.ts.map} +1 -1
  77. package/dist/{run-evidence-oByzm-dE.d.ts → run-evidence-DokQtX0-.d.ts} +2 -2
  78. package/dist/{run-evidence-oByzm-dE.d.ts.map → run-evidence-DokQtX0-.d.ts.map} +1 -1
  79. package/dist/run-record-CN8Zd21B.js.map +1 -1
  80. package/dist/{run-record-BJnYdTxO.d.ts → run-record-DcObtIGh.d.ts} +4 -14
  81. package/dist/run-record-DcObtIGh.d.ts.map +1 -0
  82. package/dist/{semantic-concept-judge-b5m3irbR.js → semantic-concept-judge-BypLt6Fw.js} +4 -4
  83. package/dist/{semantic-concept-judge-b5m3irbR.js.map → semantic-concept-judge-BypLt6Fw.js.map} +1 -1
  84. package/dist/{server-m5D9cvnG.js → server-BPqlDBWK.js} +3 -3
  85. package/dist/{server-m5D9cvnG.js.map → server-BPqlDBWK.js.map} +1 -1
  86. package/dist/{skill-usage-D5mlWdAJ.d.ts → skill-usage-BaaxFSJR.d.ts} +5 -5
  87. package/dist/{skill-usage-D5mlWdAJ.d.ts.map → skill-usage-BaaxFSJR.d.ts.map} +1 -1
  88. package/dist/{skillopt-optimization-method-D0MVjJdP.d.ts → skillopt-optimization-method-CAASpcS3.d.ts} +9 -9
  89. package/dist/{skillopt-optimization-method-D0MVjJdP.d.ts.map → skillopt-optimization-method-CAASpcS3.d.ts.map} +1 -1
  90. package/dist/{skillopt-optimization-method-eOJL2570.js → skillopt-optimization-method-DgN7U9iR.js} +3 -3
  91. package/dist/{skillopt-optimization-method-eOJL2570.js.map → skillopt-optimization-method-DgN7U9iR.js.map} +1 -1
  92. package/dist/{statistics-Cmj6nynr.d.ts → statistics-DbvkkDPa.d.ts} +2 -2
  93. package/dist/{statistics-Cmj6nynr.d.ts.map → statistics-DbvkkDPa.d.ts.map} +1 -1
  94. package/dist/{summary-report-CWwB_LiV.d.ts → summary-report-DnUcjVpV.d.ts} +2 -2
  95. package/dist/{summary-report-CWwB_LiV.d.ts.map → summary-report-DnUcjVpV.d.ts.map} +1 -1
  96. package/dist/traces.d.ts +2 -2
  97. package/dist/traces.js +2 -2
  98. package/dist/{types-CsD5nTfV.d.ts → types-BokuXvOG.d.ts} +4 -4
  99. package/dist/{types-CsD5nTfV.d.ts.map → types-BokuXvOG.d.ts.map} +1 -1
  100. package/dist/{types-DGsxbAEd.d.ts → types-Cc3qbqzj.d.ts} +3 -3
  101. package/dist/{types-DGsxbAEd.d.ts.map → types-Cc3qbqzj.d.ts.map} +1 -1
  102. package/dist/wire/index.d.ts +2 -2
  103. package/dist/wire/index.js +1 -1
  104. package/package.json +3 -8
  105. package/dist/belief-state/index.d.ts +0 -622
  106. package/dist/belief-state/index.d.ts.map +0 -1
  107. package/dist/belief-state/index.js +0 -1819
  108. package/dist/belief-state/index.js.map +0 -1
  109. package/dist/calibration-CNWWA6K8.js +0 -94
  110. package/dist/calibration-CNWWA6K8.js.map +0 -1
  111. package/dist/code-agent-session-BjkMTQ7H.js +0 -1390
  112. package/dist/code-agent-session-BjkMTQ7H.js.map +0 -1
  113. package/dist/code-agent-session-aYa3SGKz.d.ts +0 -143
  114. package/dist/code-agent-session-aYa3SGKz.d.ts.map +0 -1
  115. package/dist/cost-ledger-DIgQUFZZ.js.map +0 -1
  116. package/dist/cost-ledger-Dye6jCgg.d.ts.map +0 -1
  117. package/dist/default-registry-C-vFCSEc.js.map +0 -1
  118. package/dist/extract-usage-BrQ8mCLX.js +0 -155
  119. package/dist/extract-usage-BrQ8mCLX.js.map +0 -1
  120. package/dist/index-B11XCkdf2.d.ts.map +0 -1
  121. package/dist/index-D_F6VAKe.d.ts +0 -217
  122. package/dist/metrics-C9YY1OcL.js +0 -239
  123. package/dist/metrics-C9YY1OcL.js.map +0 -1
  124. package/dist/off-policy-DvgzvtIx.js +0 -220
  125. package/dist/off-policy-DvgzvtIx.js.map +0 -1
  126. package/dist/off-policy-mskQw8Mb.d.ts +0 -153
  127. package/dist/off-policy-mskQw8Mb.d.ts.map +0 -1
  128. package/dist/run-record-BJnYdTxO.d.ts.map +0 -1
  129. package/dist/runtime-trajectory-1gyaTOoC.js +0 -93
  130. package/dist/runtime-trajectory-1gyaTOoC.js.map +0 -1
  131. package/dist/runtime-trajectory-BXxG4lyi.d.ts +0 -50
  132. package/dist/runtime-trajectory-BXxG4lyi.d.ts.map +0 -1
  133. package/dist/task-failure-attributes-CQZlB3et.js.map +0 -1
@@ -1,1390 +0,0 @@
1
- import { i as estimateCost, o as isModelPriced } from "./metrics-C9YY1OcL.js";
2
- import { t as extractUsage } from "./extract-usage-BrQ8mCLX.js";
3
- import { createHash } from "node:crypto";
4
- //#region src/contract/intake/code-agent-observation.ts
5
- /**
6
- * Project one provider session into the exact user-visible answer and a
7
- * provider-neutral action stream. Raw prompts, tool inputs, and tool outputs
8
- * stay out of this projection; callers retain the source JSONL as evidence.
9
- */
10
- function observeCodeAgentSession(options) {
11
- const entries = options.entries.filter(isRecord$1);
12
- const projection = projectionFor(options.source, entries);
13
- const terminal = terminalWithExecution(projection, options.execution);
14
- return {
15
- source: options.source,
16
- sessionId: sessionIdFromEntries$1(options.source, entries) ?? fallbackSessionId$1(options.source, options.sourcePath),
17
- finalText: projection.finalText,
18
- terminal,
19
- actions: projection.actions
20
- };
21
- }
22
- function projectionFor(source, entries) {
23
- switch (source) {
24
- case "codex": return codexProjection(entries);
25
- case "claude-code": return claudeProjection(entries);
26
- case "opencode": return openCodeProjection(entries);
27
- case "kimi-code": return kimiProjection(entries);
28
- case "pi": return piProjection(entries);
29
- }
30
- }
31
- function codexProjection(entries) {
32
- const actions = [];
33
- const calls = /* @__PURE__ */ new Map();
34
- let finalText = null;
35
- let terminal = "unknown";
36
- let explicitTerminal = false;
37
- for (const entry of entries) {
38
- const entryType = stringField$1(entry, "type");
39
- const payload = record$1(entry.payload) ?? {};
40
- const payloadType = stringField$1(payload, "type");
41
- const timestampMs = timestamp(entry.timestamp);
42
- const item = record$1(entry.item);
43
- if (entryType === "item.started" && item) {
44
- const itemType = stringField$1(item, "type");
45
- if (isCodexActionItem(itemType)) {
46
- const id = stringField$1(item, "id") ?? `item-${actions.length}`;
47
- const action = actionFor({
48
- id,
49
- stepIndex: actions.length,
50
- kind: itemType === "file_change" ? "patch" : "tool",
51
- surface: codexItemSurface(itemType, item),
52
- name: codexItemName(itemType, item),
53
- status: "started",
54
- timestampMs,
55
- metadata: compactMetadata({
56
- sourceEventType: entryType,
57
- itemType
58
- })
59
- });
60
- calls.set(id, action);
61
- actions.push(action);
62
- }
63
- }
64
- if (entryType === "item.completed" && item) {
65
- const itemType = stringField$1(item, "type");
66
- if (itemType === "agent_message" || itemType === "message") finalText = nonEmpty(stringField$1(item, "text")) ?? finalText;
67
- if (isCodexActionItem(itemType)) {
68
- const id = stringField$1(item, "id") ?? `item-${actions.length}`;
69
- const status = codexItemStatus(itemType, item);
70
- const existing = calls.get(id);
71
- if (existing) existing.status = status;
72
- else {
73
- const action = actionFor({
74
- id,
75
- stepIndex: actions.length,
76
- kind: itemType === "file_change" ? "patch" : "tool",
77
- surface: codexItemSurface(itemType, item),
78
- name: codexItemName(itemType, item),
79
- status,
80
- timestampMs,
81
- metadata: compactMetadata({
82
- sourceEventType: entryType,
83
- itemType
84
- })
85
- });
86
- calls.set(id, action);
87
- actions.push(action);
88
- }
89
- }
90
- }
91
- if (entryType === "response_item") {
92
- if (payloadType === "message" || payloadType === "agent_message") finalText = textFromMessagePayload(payload) ?? finalText;
93
- if (payloadType === "function_call" || payloadType === "custom_tool_call") {
94
- const id = stringField$1(payload, "call_id") ?? stringField$1(payload, "id") ?? `call-${actions.length}`;
95
- const name = stringField$1(payload, "name") ?? payloadType;
96
- const action = actionFor({
97
- id,
98
- stepIndex: actions.length,
99
- kind: "tool",
100
- surface: surfaceForTool(name),
101
- name,
102
- status: "started",
103
- timestampMs,
104
- metadata: compactMetadata({
105
- sourceEventType: entryType,
106
- payloadType
107
- })
108
- });
109
- calls.set(id, action);
110
- actions.push(action);
111
- }
112
- if (payloadType === "function_call_output" || payloadType === "custom_tool_call_output") {
113
- const id = stringField$1(payload, "call_id") ?? stringField$1(payload, "id");
114
- const existing = id ? calls.get(id) : void 0;
115
- if (existing) existing.status = looksLikeError(payload.output) ? "failed" : "completed";
116
- }
117
- }
118
- if (entryType === "event_msg") {
119
- if (payloadType === "agent_message") finalText = nonEmpty(stringField$1(payload, "message")) ?? nonEmpty(stringField$1(payload, "text")) ?? finalText;
120
- if (payloadType === "patch_apply_end") {
121
- const patchStatus = typeof payload.success === "boolean" ? payload.success ? "completed" : "failed" : "unknown";
122
- actions.push(actionFor({
123
- id: stringField$1(payload, "call_id") ?? `patch-${actions.length}`,
124
- stepIndex: actions.length,
125
- kind: "patch",
126
- surface: "code",
127
- name: "patch",
128
- status: patchStatus,
129
- timestampMs,
130
- metadata: compactMetadata({
131
- sourceEventType: entryType,
132
- payloadType
133
- })
134
- }));
135
- }
136
- if (payloadType === "sub_agent_activity") {
137
- const name = stringField$1(payload, "kind") ?? "subagent";
138
- actions.push(actionFor({
139
- id: stringField$1(payload, "event_id") ?? `subagent-${actions.length}`,
140
- stepIndex: actions.length,
141
- kind: "tool",
142
- surface: "subagent",
143
- name,
144
- status: statusFrom(payload),
145
- timestampMs,
146
- metadata: compactMetadata({
147
- sourceEventType: entryType,
148
- payloadType
149
- })
150
- }));
151
- }
152
- if (payloadType === "task_complete" || payloadType === "turn_aborted") {
153
- const completed = payloadType === "task_complete";
154
- terminal = completed ? "completed" : "failed";
155
- explicitTerminal = true;
156
- actions.push(terminalAction(actions.length, payloadType, completed, timestampMs));
157
- }
158
- }
159
- if (entryType === "turn.completed" || entryType === "exec_done") {
160
- const completed = entry.success !== false;
161
- terminal = completed ? "completed" : "failed";
162
- explicitTerminal = true;
163
- finalText = nonEmpty(stringField$1(entry, "message")) ?? finalText;
164
- actions.push(terminalAction(actions.length, entryType, completed, timestampMs));
165
- }
166
- if (entryType === "turn.failed" || entryType === "error") {
167
- terminal = "failed";
168
- explicitTerminal = true;
169
- actions.push(terminalAction(actions.length, entryType, false, timestampMs));
170
- }
171
- }
172
- return {
173
- finalText,
174
- terminal,
175
- explicitTerminal,
176
- actions
177
- };
178
- }
179
- function claudeProjection(entries) {
180
- const actions = [];
181
- const calls = /* @__PURE__ */ new Map();
182
- let finalText = null;
183
- let resultText = null;
184
- let terminal = "unknown";
185
- let explicitTerminal = false;
186
- for (const entry of entries) {
187
- const entryType = stringField$1(entry, "type");
188
- const timestampMs = timestamp(entry.timestamp);
189
- const message = record$1(entry.message);
190
- const content = Array.isArray(message?.content) ? message.content : [];
191
- if (entryType === "assistant") {
192
- const text = textBlocks(content);
193
- if (text !== null) finalText = text;
194
- for (const value of content) {
195
- const part = record$1(value);
196
- if (!part) continue;
197
- const partType = stringField$1(part, "type");
198
- if (partType === "tool_use") {
199
- const id = stringField$1(part, "id") ?? `tool-${actions.length}`;
200
- const name = stringField$1(part, "name") ?? "tool";
201
- const action = actionFor({
202
- id,
203
- stepIndex: actions.length,
204
- kind: "tool",
205
- surface: surfaceForTool(name),
206
- name,
207
- status: "started",
208
- timestampMs,
209
- metadata: compactMetadata({
210
- sourceEventType: entryType,
211
- partType
212
- })
213
- });
214
- calls.set(id, action);
215
- actions.push(action);
216
- }
217
- }
218
- completeClaudeTools(content, calls);
219
- const stopReason = stringField$1(message ?? {}, "stop_reason");
220
- if (stopReason === "end_turn") {
221
- terminal = "completed";
222
- explicitTerminal = true;
223
- actions.push(terminalAction(actions.length, stopReason, true, timestampMs));
224
- }
225
- }
226
- if (entryType === "user") completeClaudeTools(content, calls);
227
- if (entryType === "tool_use") {
228
- const id = stringField$1(entry, "id") ?? `tool-${actions.length}`;
229
- const name = stringField$1(entry, "name") ?? "tool";
230
- const action = actionFor({
231
- id,
232
- stepIndex: actions.length,
233
- kind: "tool",
234
- surface: surfaceForTool(name),
235
- name,
236
- status: "started",
237
- timestampMs,
238
- metadata: { sourceEventType: entryType }
239
- });
240
- calls.set(id, action);
241
- actions.push(action);
242
- }
243
- if (entryType === "tool_result") {
244
- const id = stringField$1(entry, "tool_use_id");
245
- const action = id ? calls.get(id) : void 0;
246
- if (action) action.status = entry.is_error === true ? "failed" : "completed";
247
- }
248
- if (entryType === "system") {
249
- const subtype = stringField$1(entry, "subtype");
250
- const hookName = stringField$1(entry, "hook_name") ?? stringField$1(entry, "hookName");
251
- if (subtype?.toLowerCase().includes("hook") || hookName) actions.push(actionFor({
252
- id: stringField$1(entry, "uuid") ?? `hook-${actions.length}`,
253
- stepIndex: actions.length,
254
- kind: "tool",
255
- surface: "hook",
256
- name: hookName ?? subtype ?? "hook",
257
- status: statusFrom(entry),
258
- timestampMs,
259
- metadata: compactMetadata({
260
- sourceEventType: entryType,
261
- subtype
262
- })
263
- }));
264
- }
265
- if (entryType === "pr-link") actions.push(terminalAction(actions.length, entryType, true, timestampMs));
266
- if (entryType === "result") {
267
- resultText = nonEmpty(stringField$1(entry, "result")) ?? resultText;
268
- const subtype = stringField$1(entry, "subtype");
269
- const completed = entry.is_error !== true && !subtype?.toLowerCase().includes("error");
270
- terminal = completed ? "completed" : "failed";
271
- explicitTerminal = true;
272
- actions.push(terminalAction(actions.length, subtype ?? entryType, completed, timestampMs));
273
- }
274
- if (entryType === "error") {
275
- terminal = "failed";
276
- explicitTerminal = true;
277
- actions.push(terminalAction(actions.length, entryType, false, timestampMs));
278
- }
279
- }
280
- return {
281
- finalText: resultText ?? finalText,
282
- terminal,
283
- explicitTerminal,
284
- actions
285
- };
286
- }
287
- function openCodeProjection(entries) {
288
- const actions = [];
289
- const assistantMessageIds = new Set(entries.filter((entry) => stringField$1(entry, "role") === "assistant").map((entry) => stringField$1(entry, "id")).filter((id) => id !== void 0));
290
- let finalText = null;
291
- let terminal = "unknown";
292
- let explicitTerminal = false;
293
- for (const entry of entries) {
294
- const entryType = stringField$1(entry, "type");
295
- const part = record$1(entry.part) ?? entry;
296
- const partType = stringField$1(part, "type");
297
- const timestampMs = timestamp(entry.timestamp) ?? timestamp(record$1(entry.time)?.created);
298
- if (entryType === "text" && record$1(entry.part)) finalText = nonEmpty(stringField$1(part, "text")) ?? finalText;
299
- else if (partType === "text" && (assistantMessageIds.size === 0 || assistantMessageIds.has(stringField$1(part, "messageID") ?? ""))) finalText = nonEmpty(stringField$1(part, "text")) ?? finalText;
300
- if (entryType === "tool_use" || partType === "tool") {
301
- const state = record$1(part.state) ?? {};
302
- const name = stringField$1(part, "tool") ?? "tool";
303
- actions.push(actionFor({
304
- id: stringField$1(part, "callID") ?? stringField$1(part, "id") ?? `tool-${actions.length}`,
305
- stepIndex: actions.length,
306
- kind: "tool",
307
- surface: surfaceForTool(name),
308
- name,
309
- status: statusFrom(state),
310
- timestampMs,
311
- metadata: compactMetadata({
312
- sourceEventType: entryType,
313
- partType
314
- })
315
- }));
316
- }
317
- if (partType === "patch") actions.push(actionFor({
318
- id: stringField$1(part, "id") ?? `patch-${actions.length}`,
319
- stepIndex: actions.length,
320
- kind: "patch",
321
- surface: "code",
322
- name: "patch",
323
- status: "completed",
324
- timestampMs,
325
- metadata: compactMetadata({
326
- sourceEventType: entryType,
327
- partType
328
- })
329
- }));
330
- if (stringField$1(entry, "role") === "assistant") {
331
- const finish = stringField$1(entry, "finish");
332
- if (finish === "stop" || finish === "error") {
333
- const completed = finish === "stop";
334
- terminal = completed ? "completed" : "failed";
335
- explicitTerminal = true;
336
- actions.push(terminalAction(actions.length, finish, completed, timestampMs));
337
- }
338
- }
339
- if (entryType === "error") {
340
- terminal = "failed";
341
- explicitTerminal = true;
342
- actions.push(terminalAction(actions.length, entryType, false, timestampMs));
343
- }
344
- }
345
- return {
346
- finalText,
347
- terminal,
348
- explicitTerminal,
349
- actions
350
- };
351
- }
352
- function kimiProjection(entries) {
353
- const actions = [];
354
- const calls = /* @__PURE__ */ new Map();
355
- let finalText = null;
356
- let terminal = "unknown";
357
- let explicitTerminal = false;
358
- for (const entry of entries) {
359
- const timestampMs = timestamp(entry.timestamp);
360
- const message = record$1(entry.message);
361
- const messageType = stringField$1(message ?? {}, "type");
362
- const payload = record$1(message?.payload) ?? {};
363
- if (messageType === "ContentPart" && stringField$1(payload, "type") === "text") finalText = nonEmpty(stringField$1(payload, "text")) ?? nonEmpty(stringField$1(payload, "content")) ?? finalText;
364
- if (messageType === "ToolCall") {
365
- const fn = record$1(payload.function) ?? {};
366
- const id = stringField$1(payload, "id") ?? `tool-${actions.length}`;
367
- const name = stringField$1(fn, "name") ?? "tool";
368
- const action = actionFor({
369
- id,
370
- stepIndex: actions.length,
371
- kind: "tool",
372
- surface: surfaceForTool(name),
373
- name,
374
- status: "started",
375
- timestampMs,
376
- metadata: { sourceEventType: messageType }
377
- });
378
- calls.set(id, action);
379
- actions.push(action);
380
- }
381
- if (messageType === "ToolResult") {
382
- const id = stringField$1(payload, "tool_call_id");
383
- const action = id ? calls.get(id) : void 0;
384
- if (action) action.status = record$1(payload.return_value)?.is_error === true ? "failed" : "completed";
385
- }
386
- if (messageType === "TurnEnd" || messageType === "StepInterrupted") {
387
- const completed = messageType === "TurnEnd";
388
- terminal = completed ? "completed" : "failed";
389
- explicitTerminal = true;
390
- actions.push(terminalAction(actions.length, messageType, completed, timestampMs));
391
- }
392
- }
393
- return {
394
- finalText,
395
- terminal,
396
- explicitTerminal,
397
- actions
398
- };
399
- }
400
- function piProjection(entries) {
401
- const actions = [];
402
- let terminal = "unknown";
403
- let explicitTerminal = false;
404
- for (const entry of entries) {
405
- const nodes = Array.isArray(entry.nodes) ? entry.nodes : [];
406
- for (const value of nodes) {
407
- const node = record$1(value);
408
- const ir = record$1(node?.ir) ?? node;
409
- const kind = stringField$1(ir ?? {}, "kind");
410
- if (kind === "ToolInvocation") actions.push(actionFor({
411
- id: stringField$1(ir ?? {}, "id") ?? stringField$1(node ?? {}, "id") ?? `tool-${actions.length}`,
412
- stepIndex: actions.length,
413
- kind: "tool",
414
- surface: "tool",
415
- name: stringField$1(ir ?? {}, "name") ?? "graph-tool",
416
- status: "started",
417
- timestampMs: timestamp(ir?.createdAt),
418
- metadata: {
419
- sourceEventType: "graph-node",
420
- graphKind: kind
421
- }
422
- }));
423
- if (kind === "ToolResult") {
424
- const prior = [...actions].reverse().find((action) => action.kind === "tool");
425
- if (prior) prior.status = "completed";
426
- }
427
- if (kind === "CompletionDecision") {
428
- terminal = "completed";
429
- explicitTerminal = true;
430
- actions.push(actionFor({
431
- id: stringField$1(ir ?? {}, "id") ?? stringField$1(node ?? {}, "id") ?? `completion-${actions.length}`,
432
- stepIndex: actions.length,
433
- kind: "graph-completion",
434
- surface: "tool",
435
- name: "complete",
436
- status: "completed",
437
- timestampMs: timestamp(ir?.createdAt),
438
- metadata: {
439
- sourceEventType: "graph-node",
440
- graphKind: kind
441
- }
442
- }));
443
- }
444
- }
445
- }
446
- return {
447
- finalText: null,
448
- terminal,
449
- explicitTerminal,
450
- actions
451
- };
452
- }
453
- function completeClaudeTools(content, calls) {
454
- for (const value of content) {
455
- const part = record$1(value);
456
- if (!part || stringField$1(part, "type") !== "tool_result") continue;
457
- const id = stringField$1(part, "tool_use_id");
458
- const action = id ? calls.get(id) : void 0;
459
- if (action) action.status = part.is_error === true ? "failed" : "completed";
460
- }
461
- }
462
- function isCodexActionItem(itemType) {
463
- return itemType === "command_execution" || itemType === "mcp_tool_call" || itemType === "collab_tool_call" || itemType === "web_search" || itemType === "file_change";
464
- }
465
- function codexItemSurface(itemType, item) {
466
- if (itemType === "mcp_tool_call") return "mcp";
467
- if (itemType === "collab_tool_call") return "subagent";
468
- if (itemType === "web_search") return "web";
469
- if (itemType === "file_change") return "code";
470
- return surfaceForTool(stringField$1(item, "name") ?? itemType ?? "tool");
471
- }
472
- function codexItemName(itemType, item) {
473
- if (itemType === "mcp_tool_call") return [stringField$1(item, "server"), stringField$1(item, "tool")].filter(Boolean).join("/") || "mcp";
474
- if (itemType === "collab_tool_call") return stringField$1(item, "tool") ?? "subagent";
475
- if (itemType === "web_search") return "web_search";
476
- if (itemType === "file_change") return "file_change";
477
- return stringField$1(item, "name") ?? itemType ?? "tool";
478
- }
479
- function codexItemStatus(itemType, item) {
480
- const status = statusFrom(item);
481
- if (status === "failed") return status;
482
- if (itemType === "command_execution") {
483
- const exitCode = numberField$1(item, "exit_code");
484
- if (exitCode !== void 0) return exitCode === 0 ? "completed" : "failed";
485
- }
486
- if (itemType === "mcp_tool_call" && record$1(item.error)) return "failed";
487
- return status === "unknown" || status === "started" ? "completed" : status;
488
- }
489
- function textFromMessagePayload(payload) {
490
- const direct = nonEmpty(stringField$1(payload, "text"));
491
- if (direct) return direct;
492
- const content = payload.content;
493
- if (typeof content === "string") return nonEmpty(content);
494
- if (Array.isArray(content)) return textBlocks(content);
495
- return null;
496
- }
497
- function textBlocks(values) {
498
- return nonEmpty(values.map((value) => record$1(value)).filter((value) => value !== null).filter((value) => stringField$1(value, "type") === "text").map((value) => stringField$1(value, "text")).filter((value) => value !== void 0).join("\n"));
499
- }
500
- function terminalWithExecution(projection, execution) {
501
- if (!execution) return {
502
- status: projection.terminal,
503
- explicit: projection.explicitTerminal
504
- };
505
- assertExecutionReceipt(execution);
506
- return {
507
- status: execution.exitCode !== 0 || projection.terminal === "failed" ? "failed" : "completed",
508
- explicit: true
509
- };
510
- }
511
- function assertExecutionReceipt(receipt) {
512
- if (!Number.isSafeInteger(receipt.exitCode)) throw new Error("code-agent execution exitCode must be a safe integer");
513
- for (const [name, value] of [["startedAtMs", receipt.startedAtMs], ["completedAtMs", receipt.completedAtMs]]) if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new Error(`code-agent execution ${name} must be a non-negative finite number`);
514
- if (receipt.startedAtMs !== void 0 && receipt.completedAtMs !== void 0 && receipt.completedAtMs < receipt.startedAtMs) throw new Error("code-agent execution completedAtMs precedes startedAtMs");
515
- }
516
- function terminalAction(stepIndex, name, completed, timestampMs) {
517
- return actionFor({
518
- id: `terminal-${stepIndex}`,
519
- stepIndex,
520
- kind: "terminal",
521
- surface: "tool",
522
- name,
523
- status: completed ? "completed" : "failed",
524
- timestampMs,
525
- metadata: { sourceEventType: name }
526
- });
527
- }
528
- function actionFor(input) {
529
- return input;
530
- }
531
- function surfaceForTool(name) {
532
- const normalized = name.toLowerCase();
533
- if (normalized.startsWith("mcp__") || normalized.includes("mcp_tool")) return "mcp";
534
- if (normalized === "task" || normalized === "agent" || normalized.includes("subagent") || normalized.includes("spawn_agent") || normalized.includes("collab") || normalized.startsWith("multi_agent")) return "subagent";
535
- if (normalized === "skill" || normalized.includes("skill")) return "skill";
536
- if (normalized.includes("hook")) return "hook";
537
- if (normalized.includes("web_search") || normalized.includes("webfetch") || normalized === "web") return "web";
538
- if (normalized === "edit" || normalized === "write" || normalized.includes("patch") || normalized.includes("file_change")) return "code";
539
- return "tool";
540
- }
541
- function statusFrom(value) {
542
- const status = (stringField$1(value, "status") ?? "").toLowerCase();
543
- if (status === "completed" || status === "success" || status === "succeeded") return "completed";
544
- if (status === "error" || status === "failed" || status === "declined") return "failed";
545
- if (status === "running" || status === "started" || status === "in_progress") return "started";
546
- return "unknown";
547
- }
548
- function compactMetadata(input) {
549
- return Object.fromEntries(Object.entries(input).filter((entry) => entry[1] !== void 0));
550
- }
551
- function sessionIdFromEntries$1(source, entries) {
552
- for (const entry of entries) {
553
- if (source === "codex") {
554
- const threadId = stringField$1(entry, "thread_id");
555
- if (threadId) return threadId;
556
- const payload = record$1(entry.payload);
557
- const id = payload ? stringField$1(payload, "id") : void 0;
558
- if (id) return id;
559
- }
560
- const payload = record$1(record$1(entry.message)?.payload);
561
- const sessionId = stringField$1(entry, "sessionID") ?? stringField$1(entry, "sessionId") ?? stringField$1(entry, "session_id") ?? stringField$1(payload ?? {}, "session_id");
562
- if (sessionId) return sessionId;
563
- }
564
- }
565
- function fallbackSessionId$1(source, sourcePath) {
566
- return `${source}:${sourcePath ?? "unknown-session"}`;
567
- }
568
- function looksLikeError(value) {
569
- if (isRecord$1(value)) {
570
- if (value.success === false || value.is_error === true) return true;
571
- const exitCode = numberField$1(value, "exit_code");
572
- if (exitCode !== void 0 && exitCode !== 0) return true;
573
- }
574
- const text = typeof value === "string" ? value : JSON.stringify(value ?? "");
575
- return /\b(?:error|failed|failure)\b|exit(?:_| )code["\s:]+[1-9]/i.test(text);
576
- }
577
- function nonEmpty(value) {
578
- return value !== void 0 && value.length > 0 ? value : null;
579
- }
580
- function isRecord$1(value) {
581
- return value !== null && typeof value === "object" && !Array.isArray(value);
582
- }
583
- function record$1(value) {
584
- return isRecord$1(value) ? value : null;
585
- }
586
- function stringField$1(value, key) {
587
- const field = value[key];
588
- return typeof field === "string" && field.length > 0 ? field : void 0;
589
- }
590
- function numberField$1(value, key) {
591
- const field = value[key];
592
- return typeof field === "number" && Number.isFinite(field) ? field : void 0;
593
- }
594
- function timestamp(value) {
595
- if (typeof value === "number" && Number.isFinite(value)) return value > 0xe8d4a51000 ? value : value * 1e3;
596
- if (typeof value === "string" && value.length > 0) {
597
- const parsed = Date.parse(value);
598
- return Number.isFinite(parsed) ? parsed : void 0;
599
- }
600
- }
601
- //#endregion
602
- //#region src/contract/intake/code-agent-session.ts
603
- function parseCodeAgentJsonl(jsonl) {
604
- const entries = [];
605
- let malformedLines = 0;
606
- for (const line of jsonl.split("\n")) {
607
- const trimmed = line.trim();
608
- if (!trimmed) continue;
609
- try {
610
- entries.push(JSON.parse(trimmed));
611
- } catch {
612
- malformedLines += 1;
613
- }
614
- }
615
- return {
616
- entries,
617
- malformedLines
618
- };
619
- }
620
- function fromCodexSession(options) {
621
- return fromCodeAgentSession("codex", options);
622
- }
623
- function fromClaudeCodeSession(options) {
624
- return fromCodeAgentSession("claude-code", options);
625
- }
626
- function fromOpenCodeSession(options) {
627
- return fromCodeAgentSession("opencode", options);
628
- }
629
- function fromKimiCodeSession(options) {
630
- return fromCodeAgentSession("kimi-code", options);
631
- }
632
- function fromPiSession(options) {
633
- return fromCodeAgentSession("pi", options);
634
- }
635
- const fromPigraphSession = fromPiSession;
636
- function fromCodeAgentSession(source, options) {
637
- const entries = options.entries.filter(isRecord);
638
- if (entries.length === 0) return {
639
- runs: [],
640
- diagnostics: [{
641
- source,
642
- sessionId: fallbackSessionId(source, options.sourcePath),
643
- sourcePath: options.sourcePath,
644
- entries: 0,
645
- malformedLines: options.malformedLines ?? 0,
646
- hasExplicitTerminalSignal: false,
647
- hasFinalOutput: false,
648
- hasQualityLabel: false,
649
- hasTokenUsage: false,
650
- hasCost: false,
651
- costKind: "uncaptured",
652
- warnings: ["no parseable session entries"]
653
- }],
654
- metrics: [],
655
- observations: []
656
- };
657
- const metrics = metricsFor(source, entries);
658
- const sessionId = sessionIdFromEntries(source, entries) ?? fallbackSessionId(source, options.sourcePath);
659
- const observation = observeCodeAgentSession({
660
- source,
661
- entries,
662
- sourcePath: options.sourcePath,
663
- execution: options.execution
664
- });
665
- applyObservedSurfaceMetrics(metrics, observation);
666
- const model = withSnapshot(options.model ?? modelFromEntries(source, entries) ?? source);
667
- const tokenUsage = {
668
- input: metrics.inputTokens,
669
- output: metrics.outputTokens,
670
- ...metrics.reasoningTokens > 0 ? { reasoning: metrics.reasoningTokens } : {},
671
- ...metrics.cachedTokens > 0 ? { cached: metrics.cachedTokens } : {},
672
- ...metrics.cacheWriteTokens > 0 ? { cacheWrite: metrics.cacheWriteTokens } : {}
673
- };
674
- const { costUsd, costProvenance } = resolveSessionCost(options.costProvenance, metrics, model);
675
- const qualityScore = finiteScore(options.score);
676
- const invalidQualityScore = options.score !== void 0 && qualityScore === void 0;
677
- const promptHash = options.promptHash ?? hashString(`prompt:${source}:${firstUserText(entries) ?? ""}`);
678
- const configHash = options.configHash ?? hashJson({
679
- source,
680
- model,
681
- sourcePath: options.sourcePath,
682
- cwd: cwdFromEntries(entries),
683
- entryCount: entries.length
684
- });
685
- const explicitTerminal = observation.terminal.explicit;
686
- const warnings = diagnosticsFor(metrics, {
687
- model,
688
- explicitTerminal,
689
- malformedLines: options.malformedLines ?? 0,
690
- hasQualityLabel: qualityScore !== void 0,
691
- invalidQualityScore,
692
- costKind: costProvenance.kind
693
- });
694
- const terminalOutcome = terminalOutcomeFromSession(observation.terminal);
695
- const processExitCode = options.execution?.exitCode;
696
- const splitTag = options.splitTag ?? "holdout";
697
- return {
698
- runs: [{
699
- runId: `${source}:${sessionId}`,
700
- experimentId: options.experimentId ?? `${source}-local-sessions`,
701
- candidateId: options.candidateId ?? model,
702
- seed: options.seed ?? stableSeed(sessionId),
703
- model,
704
- promptHash,
705
- configHash,
706
- commitSha: options.commitSha ?? "local-session",
707
- wallMs: metrics.wallMs,
708
- costUsd,
709
- costProvenance,
710
- tokenUsage,
711
- terminalOutcome,
712
- ...terminalOutcome === "failed" ? { terminalFailureReason: processExitCode !== void 0 && processExitCode !== 0 ? `process exited with code ${processExitCode}` : metrics.turnsAborted > 0 ? "turn aborted" : "session reported terminal failure" } : {},
713
- outcome: {
714
- ...qualityScore === void 0 ? {} : splitTag === "holdout" ? { holdoutScore: qualityScore } : { searchScore: qualityScore },
715
- raw: {
716
- entries: metrics.entries,
717
- user_messages: metrics.userMessages,
718
- assistant_messages: metrics.assistantMessages,
719
- reasoning_items: metrics.reasoningItems,
720
- tool_calls: metrics.toolCalls,
721
- tool_outputs: metrics.toolOutputs,
722
- tool_errors: metrics.toolErrors,
723
- execution_error_count: metrics.toolErrors,
724
- process_error_count: terminalOutcome === "failed" ? 1 : 0,
725
- unclassified_error_count: metrics.unclassifiedErrors,
726
- ...processExitCode !== void 0 ? { process_exit_code: processExitCode } : {},
727
- patch_attempts: metrics.patchAttempts,
728
- patch_successes: metrics.patchSuccesses,
729
- patch_failures: metrics.patchFailures,
730
- turns_started: metrics.turnsStarted,
731
- turns_completed: metrics.turnsCompleted,
732
- turns_aborted: metrics.turnsAborted,
733
- context_compactions: metrics.contextCompactions,
734
- mcp_calls: metrics.mcpCalls,
735
- subagent_calls: metrics.subagentCalls,
736
- skill_calls: metrics.skillCalls,
737
- hook_calls: metrics.hookCalls,
738
- web_calls: metrics.webCalls,
739
- code_actions: metrics.codeActions,
740
- pr_links: metrics.prLinks,
741
- file_snapshots: metrics.fileSnapshots,
742
- graph_nodes: metrics.graphNodes,
743
- graph_edges: metrics.graphEdges,
744
- action_candidates: metrics.actionCandidates,
745
- verification_reports: metrics.verificationReports,
746
- completion_decisions: metrics.completionDecisions,
747
- reliability_rows: metrics.reliabilityRows,
748
- reliability_lift: metrics.reliabilityLift,
749
- input_tokens: metrics.inputTokens,
750
- output_tokens: metrics.outputTokens,
751
- reasoning_tokens: metrics.reasoningTokens,
752
- cached_tokens: metrics.cachedTokens,
753
- cache_write_tokens: metrics.cacheWriteTokens,
754
- observed_cost_usd: metrics.observedCostUsd,
755
- observed_cost_captured: metrics.observedCostCaptured ? 1 : 0,
756
- estimated_cost_usd: costProvenance.kind === "estimated" ? costProvenance.usd : 0,
757
- process_score: metrics.processScore,
758
- explicit_terminal_signal: explicitTerminal ? 1 : 0,
759
- quality_label_present: qualityScore !== void 0 ? 1 : 0,
760
- cost_observed: costProvenance.kind === "observed" ? 1 : 0,
761
- cost_estimated: costProvenance.kind === "estimated" ? 1 : 0,
762
- cost_uncaptured: costProvenance.kind === "uncaptured" ? 1 : 0,
763
- cost_unknown: costProvenance.kind === "uncaptured" ? 1 : 0
764
- }
765
- },
766
- splitTag,
767
- scenarioId: options.scenarioId ?? sessionId
768
- }],
769
- diagnostics: [{
770
- source,
771
- sessionId,
772
- sourcePath: options.sourcePath,
773
- entries: entries.length,
774
- malformedLines: options.malformedLines ?? 0,
775
- hasExplicitTerminalSignal: explicitTerminal,
776
- hasFinalOutput: observation.finalText !== null,
777
- hasQualityLabel: qualityScore !== void 0,
778
- hasTokenUsage: metrics.inputTokens > 0 || metrics.outputTokens > 0 || metrics.reasoningTokens > 0 || metrics.cachedTokens > 0 || metrics.cacheWriteTokens > 0,
779
- hasCost: costProvenance.kind !== "uncaptured",
780
- costKind: costProvenance.kind,
781
- warnings
782
- }],
783
- metrics: [metrics],
784
- observations: [{
785
- ...observation,
786
- sessionId
787
- }]
788
- };
789
- }
790
- function terminalOutcomeFromSession(terminal) {
791
- if (!terminal.explicit) return "unknown";
792
- if (terminal.status === "completed") return "succeeded";
793
- if (terminal.status === "failed") return "failed";
794
- return "unknown";
795
- }
796
- function metricsFor(source, entries) {
797
- switch (source) {
798
- case "codex": return codexMetrics(entries);
799
- case "claude-code": return claudeCodeMetrics(entries);
800
- case "opencode": return openCodeMetrics(entries);
801
- case "kimi-code": return kimiCodeMetrics(entries);
802
- case "pi": return piMetrics(entries);
803
- }
804
- }
805
- function codexMetrics(entries) {
806
- const metrics = emptyMetrics(entries.length);
807
- const startedToolIds = /* @__PURE__ */ new Set();
808
- let startedAt;
809
- let completedAt;
810
- for (const entry of entries) {
811
- const payload = record(entry.payload) ?? {};
812
- const entryType = stringField(entry, "type");
813
- const payloadType = stringField(payload, "type");
814
- const timestamp = timestampMs(entry.timestamp);
815
- if (timestamp !== void 0) {
816
- startedAt = startedAt === void 0 ? timestamp : Math.min(startedAt, timestamp);
817
- completedAt = completedAt === void 0 ? timestamp : Math.max(completedAt, timestamp);
818
- }
819
- if (entryType === "turn.started") metrics.turnsStarted += 1;
820
- if (entryType === "turn.completed") {
821
- metrics.turnsCompleted += 1;
822
- addCodexExecUsage(metrics, record(entry.usage));
823
- }
824
- if (entryType === "turn.failed") metrics.turnsAborted += 1;
825
- if (entryType === "error") metrics.unclassifiedErrors += 1;
826
- const item = record(entry.item);
827
- if (item && (entryType === "item.started" || entryType === "item.completed")) addCodexExecItem(metrics, startedToolIds, entryType, item);
828
- if (entryType === "response_item") {
829
- if (payloadType === "function_call" || payloadType === "custom_tool_call") metrics.toolCalls += 1;
830
- if (payloadType === "function_call_output" || payloadType === "custom_tool_call_output") metrics.toolOutputs += 1;
831
- if (payloadType === "reasoning") metrics.reasoningItems += 1;
832
- if (payloadType === "message" && stringField(payload, "role") === "assistant") metrics.assistantMessages += 1;
833
- }
834
- if (entryType === "event_msg") {
835
- if (payloadType === "user_message") metrics.userMessages += 1;
836
- if (payloadType === "agent_message") metrics.assistantMessages += 1;
837
- if (payloadType === "task_started") {
838
- metrics.turnsStarted += 1;
839
- const started = timestampMs(payload.started_at);
840
- if (started !== void 0) startedAt = startedAt === void 0 ? started : Math.min(startedAt, started);
841
- }
842
- if (payloadType === "task_complete") {
843
- metrics.turnsCompleted += 1;
844
- const completed = timestampMs(payload.completed_at);
845
- if (completed !== void 0) completedAt = completedAt === void 0 ? completed : Math.max(completedAt, completed);
846
- const duration = numberField(payload, "duration_ms");
847
- if (duration !== void 0) metrics.wallMs = Math.max(metrics.wallMs, duration);
848
- }
849
- if (payloadType === "turn_aborted") {
850
- metrics.turnsAborted += 1;
851
- const completed = timestampMs(payload.completed_at);
852
- if (completed !== void 0) completedAt = completedAt === void 0 ? completed : Math.max(completedAt, completed);
853
- }
854
- if (payloadType === "context_compacted") metrics.contextCompactions += 1;
855
- if (payloadType === "patch_apply_end") {
856
- metrics.patchAttempts += 1;
857
- if (payload.success === true) metrics.patchSuccesses += 1;
858
- else {
859
- metrics.patchFailures += 1;
860
- metrics.toolErrors += 1;
861
- }
862
- }
863
- if (payloadType === "token_count") setCodexCumulativeUsage(metrics, record(record(payload.info)?.total_token_usage));
864
- const result = record(payload.result);
865
- if (result && "Err" in result) metrics.unclassifiedErrors += 1;
866
- }
867
- }
868
- if (metrics.wallMs === 0 && startedAt !== void 0 && completedAt !== void 0) metrics.wallMs = Math.max(0, completedAt - startedAt);
869
- metrics.processScore = codexProcessScore(metrics);
870
- return metrics;
871
- }
872
- function addCodexExecItem(metrics, startedToolIds, eventType, item) {
873
- const itemType = stringField(item, "type");
874
- const itemId = stringField(item, "id");
875
- const isTool = itemType === "command_execution" || itemType === "mcp_tool_call" || itemType === "collab_tool_call" || itemType === "web_search";
876
- if (eventType === "item.started" && isTool) {
877
- metrics.toolCalls += 1;
878
- if (itemId) startedToolIds.add(itemId);
879
- }
880
- if (eventType === "item.completed" && isTool) {
881
- if (!itemId || !startedToolIds.has(itemId)) metrics.toolCalls += 1;
882
- metrics.toolOutputs += 1;
883
- }
884
- if (eventType !== "item.completed") return;
885
- if (itemType === "agent_message" || itemType === "message") metrics.assistantMessages += 1;
886
- if (itemType === "reasoning") metrics.reasoningItems += 1;
887
- if (itemType === "file_change") {
888
- metrics.patchAttempts += 1;
889
- const status = stringField(item, "status");
890
- if (status === "completed") metrics.patchSuccesses += 1;
891
- if (status === "failed") {
892
- metrics.patchFailures += 1;
893
- metrics.toolErrors += 1;
894
- }
895
- }
896
- if (itemType === "error") metrics.unclassifiedErrors += 1;
897
- else if (codexExecToolFailed(itemType, item)) metrics.toolErrors += 1;
898
- }
899
- function codexExecToolFailed(itemType, item) {
900
- const status = stringField(item, "status");
901
- if (itemType === "command_execution") {
902
- const exitCode = numberField(item, "exit_code");
903
- return status === "failed" || status === "declined" || exitCode !== void 0 && exitCode !== 0;
904
- }
905
- if (itemType === "mcp_tool_call") return status === "failed" || record(item.error) !== null;
906
- return itemType === "collab_tool_call" && status === "failed";
907
- }
908
- function addCodexExecUsage(metrics, usage) {
909
- const parsed = readUsage(usage);
910
- metrics.inputTokens += parsed.input;
911
- metrics.outputTokens += parsed.output;
912
- metrics.reasoningTokens += parsed.reasoning;
913
- metrics.cachedTokens += parsed.cached;
914
- metrics.cacheWriteTokens += parsed.cacheWrite;
915
- }
916
- function setCodexCumulativeUsage(metrics, usage) {
917
- const parsed = readUsage(usage);
918
- metrics.inputTokens = Math.max(metrics.inputTokens, parsed.input);
919
- metrics.outputTokens = Math.max(metrics.outputTokens, parsed.output);
920
- metrics.reasoningTokens = Math.max(metrics.reasoningTokens, parsed.reasoning);
921
- metrics.cachedTokens = Math.max(metrics.cachedTokens, parsed.cached);
922
- metrics.cacheWriteTokens = Math.max(metrics.cacheWriteTokens, parsed.cacheWrite);
923
- }
924
- function claudeCodeMetrics(entries) {
925
- const metrics = emptyMetrics(entries.length);
926
- let startedAt;
927
- let completedAt;
928
- for (const entry of entries) {
929
- const type = stringField(entry, "type");
930
- const timestamp = timestampMs(entry.timestamp);
931
- if (timestamp !== void 0) {
932
- startedAt = startedAt === void 0 ? timestamp : Math.min(startedAt, timestamp);
933
- completedAt = completedAt === void 0 ? timestamp : Math.max(completedAt, timestamp);
934
- }
935
- if (type === "user") metrics.userMessages += 1;
936
- if (type === "assistant") metrics.assistantMessages += 1;
937
- if (type === "pr-link") metrics.prLinks += 1;
938
- if (type === "file-history-snapshot") metrics.fileSnapshots += 1;
939
- const message = record(entry.message);
940
- if (message) addUsage(metrics, record(message.usage));
941
- const content = Array.isArray(message?.content) ? message.content : [];
942
- for (const item of content) {
943
- const part = record(item);
944
- if (!part) continue;
945
- const partType = stringField(part, "type");
946
- if (partType === "thinking") metrics.reasoningItems += 1;
947
- if (partType === "tool_use") metrics.toolCalls += 1;
948
- if (partType === "tool_result") {
949
- metrics.toolOutputs += 1;
950
- if (part.is_error === true) metrics.toolErrors += 1;
951
- }
952
- }
953
- }
954
- if (startedAt !== void 0 && completedAt !== void 0) metrics.wallMs = Math.max(0, completedAt - startedAt);
955
- metrics.processScore = claudeProcessScore(metrics);
956
- return metrics;
957
- }
958
- function openCodeMetrics(entries) {
959
- const metrics = emptyMetrics(entries.length);
960
- const messageUsage = emptyTokenTotals();
961
- const partUsage = emptyTokenTotals();
962
- let messageCost = 0;
963
- let partCost = 0;
964
- let messageCostCaptured = false;
965
- let partCostCaptured = false;
966
- let startedAt;
967
- let completedAt;
968
- for (const entry of entries) {
969
- const time = record(entry.time);
970
- const created = timestampMs(time?.created);
971
- const completed = timestampMs(time?.completed);
972
- if (created !== void 0) startedAt = startedAt === void 0 ? created : Math.min(startedAt, created);
973
- if (completed !== void 0) completedAt = completedAt === void 0 ? completed : Math.max(completedAt, completed);
974
- const role = stringField(entry, "role");
975
- if (role === "user") metrics.userMessages += 1;
976
- if (role === "assistant") {
977
- metrics.assistantMessages += 1;
978
- const finish = stringField(entry, "finish");
979
- if (finish === "stop") metrics.turnsCompleted += 1;
980
- if (finish === "error") metrics.turnsAborted += 1;
981
- }
982
- const type = stringField(entry, "type");
983
- if (type === "reasoning") metrics.reasoningItems += 1;
984
- if (type === "tool") {
985
- metrics.toolCalls += 1;
986
- const status = stringField(record(entry.state) ?? {}, "status");
987
- if (status === "completed") metrics.toolOutputs += 1;
988
- if (status === "error") {
989
- metrics.toolOutputs += 1;
990
- metrics.toolErrors += 1;
991
- }
992
- }
993
- if (type === "patch") {
994
- metrics.patchAttempts += 1;
995
- metrics.patchSuccesses += 1;
996
- }
997
- const cost = numberField(entry, "cost");
998
- if (record(entry.tokens) && role) {
999
- addUsageTo(messageUsage, record(entry.tokens));
1000
- if (cost !== void 0) {
1001
- messageCost += cost;
1002
- messageCostCaptured = true;
1003
- }
1004
- } else if (record(entry.tokens)) {
1005
- addUsageTo(partUsage, record(entry.tokens));
1006
- if (cost !== void 0) {
1007
- partCost += cost;
1008
- partCostCaptured = true;
1009
- }
1010
- }
1011
- }
1012
- const usage = hasTokenTotals(messageUsage) ? messageUsage : partUsage;
1013
- metrics.inputTokens = usage.input;
1014
- metrics.outputTokens = usage.output;
1015
- metrics.reasoningTokens = usage.reasoning;
1016
- metrics.cachedTokens = usage.cached;
1017
- metrics.cacheWriteTokens = usage.cacheWrite;
1018
- metrics.observedCostUsd = messageCostCaptured ? messageCost : partCost;
1019
- metrics.observedCostCaptured = messageCostCaptured || partCostCaptured;
1020
- if (metrics.wallMs === 0 && startedAt !== void 0 && completedAt !== void 0) metrics.wallMs = Math.max(0, completedAt - startedAt);
1021
- metrics.processScore = terminalProcessScore(metrics);
1022
- return metrics;
1023
- }
1024
- function kimiCodeMetrics(entries) {
1025
- const metrics = emptyMetrics(entries.length);
1026
- let startedAt;
1027
- let completedAt;
1028
- for (const entry of entries) {
1029
- const timestamp = timestampMs(entry.timestamp);
1030
- if (timestamp !== void 0) {
1031
- startedAt = startedAt === void 0 ? timestamp : Math.min(startedAt, timestamp);
1032
- completedAt = completedAt === void 0 ? timestamp : Math.max(completedAt, timestamp);
1033
- }
1034
- const role = stringField(entry, "role");
1035
- if (role === "user") metrics.userMessages += 1;
1036
- if (role === "assistant") metrics.assistantMessages += 1;
1037
- if (role === "_usage") addUsage(metrics, entry);
1038
- const message = record(entry.message);
1039
- const messageType = message ? stringField(message, "type") : void 0;
1040
- const payload = record(message?.payload) ?? {};
1041
- if (messageType === "TurnBegin") {
1042
- metrics.userMessages += 1;
1043
- metrics.turnsStarted += 1;
1044
- }
1045
- if (messageType === "TurnEnd") metrics.turnsCompleted += 1;
1046
- if (messageType === "StepInterrupted") metrics.turnsAborted += 1;
1047
- if (messageType === "StepBegin") metrics.reasoningItems += 1;
1048
- if (messageType === "ContentPart") {
1049
- const payloadType = stringField(payload, "type");
1050
- if (payloadType === "think") metrics.reasoningItems += 1;
1051
- if (payloadType === "text") metrics.assistantMessages += 1;
1052
- }
1053
- if (messageType === "ToolCall") metrics.toolCalls += 1;
1054
- if (messageType === "ToolResult") {
1055
- metrics.toolOutputs += 1;
1056
- if (record(payload.return_value)?.is_error === true) metrics.toolErrors += 1;
1057
- }
1058
- if (messageType === "StatusUpdate") addUsage(metrics, record(payload.token_usage));
1059
- if (messageType === "Notification") {
1060
- const notification = record(payload.payload);
1061
- const exitCode = numberField(notification ?? {}, "exit_code");
1062
- if (notification?.timed_out === true || exitCode !== void 0 && exitCode !== 0) metrics.toolErrors += 1;
1063
- }
1064
- }
1065
- if (startedAt !== void 0 && completedAt !== void 0) metrics.wallMs = Math.max(0, completedAt - startedAt);
1066
- metrics.processScore = terminalProcessScore(metrics);
1067
- return metrics;
1068
- }
1069
- function piMetrics(entries) {
1070
- const metrics = emptyMetrics(entries.length);
1071
- let bestReliabilityScore;
1072
- for (const entry of entries) {
1073
- const nodes = Array.isArray(entry.nodes) ? entry.nodes : [];
1074
- const edges = Array.isArray(entry.edges) ? entry.edges : [];
1075
- metrics.graphNodes += nodes.length;
1076
- metrics.graphEdges += edges.length;
1077
- for (const node of nodes) {
1078
- const obj = record(node);
1079
- const kind = stringField(record(obj?.ir) ?? obj ?? {}, "kind");
1080
- if (kind === "ActionCandidate") metrics.actionCandidates += 1;
1081
- if (kind === "ToolInvocation") metrics.toolCalls += 1;
1082
- if (kind === "ToolResult") metrics.toolOutputs += 1;
1083
- if (kind === "VerificationReport") metrics.verificationReports += 1;
1084
- if (kind === "CompletionDecision") {
1085
- metrics.completionDecisions += 1;
1086
- metrics.turnsCompleted += 1;
1087
- }
1088
- }
1089
- const averageReliability = numberField(entry, "averageNodeReliability");
1090
- if (averageReliability !== void 0) bestReliabilityScore = maxOptional(bestReliabilityScore, averageReliability);
1091
- const pessimisticPath = numberField(entry, "pessimisticPathEstimate");
1092
- if (pessimisticPath !== void 0) bestReliabilityScore = maxOptional(bestReliabilityScore, pessimisticPath);
1093
- const rows = Array.isArray(entry.rows) ? entry.rows : [];
1094
- metrics.reliabilityRows += rows.length;
1095
- for (const row of rows) {
1096
- const obj = record(row);
1097
- if (!obj) continue;
1098
- const lift = numberField(obj, "lift");
1099
- if (lift !== void 0) metrics.reliabilityLift = Math.max(metrics.reliabilityLift, lift);
1100
- const validated = numberField(obj, "validatedSuccessEstimate");
1101
- if (validated !== void 0) bestReliabilityScore = maxOptional(bestReliabilityScore, validated);
1102
- }
1103
- }
1104
- metrics.processScore = bestReliabilityScore !== void 0 ? clamp01(bestReliabilityScore) : metrics.completionDecisions > 0 ? 1 : 0;
1105
- return metrics;
1106
- }
1107
- function emptyMetrics(entries) {
1108
- return {
1109
- entries,
1110
- userMessages: 0,
1111
- assistantMessages: 0,
1112
- reasoningItems: 0,
1113
- toolCalls: 0,
1114
- toolOutputs: 0,
1115
- toolErrors: 0,
1116
- unclassifiedErrors: 0,
1117
- patchAttempts: 0,
1118
- patchSuccesses: 0,
1119
- patchFailures: 0,
1120
- turnsStarted: 0,
1121
- turnsCompleted: 0,
1122
- turnsAborted: 0,
1123
- contextCompactions: 0,
1124
- mcpCalls: 0,
1125
- subagentCalls: 0,
1126
- skillCalls: 0,
1127
- hookCalls: 0,
1128
- webCalls: 0,
1129
- codeActions: 0,
1130
- prLinks: 0,
1131
- fileSnapshots: 0,
1132
- graphNodes: 0,
1133
- graphEdges: 0,
1134
- actionCandidates: 0,
1135
- verificationReports: 0,
1136
- completionDecisions: 0,
1137
- reliabilityRows: 0,
1138
- reliabilityLift: 0,
1139
- inputTokens: 0,
1140
- outputTokens: 0,
1141
- reasoningTokens: 0,
1142
- cachedTokens: 0,
1143
- cacheWriteTokens: 0,
1144
- observedCostUsd: 0,
1145
- observedCostCaptured: false,
1146
- wallMs: 0,
1147
- processScore: 0
1148
- };
1149
- }
1150
- function codexProcessScore(metrics) {
1151
- const terminalTurns = metrics.turnsCompleted + metrics.turnsAborted;
1152
- return penalizeErrors(terminalTurns > 0 ? metrics.turnsCompleted / terminalTurns : metrics.assistantMessages > 0 ? .5 : 0, metrics);
1153
- }
1154
- function claudeProcessScore(metrics) {
1155
- return penalizeErrors(metrics.prLinks > 0 ? 1 : metrics.assistantMessages > 0 ? .75 : 0, metrics);
1156
- }
1157
- function terminalProcessScore(metrics) {
1158
- const terminalTurns = metrics.turnsCompleted + metrics.turnsAborted;
1159
- return penalizeErrors(terminalTurns > 0 ? metrics.turnsCompleted / terminalTurns : metrics.assistantMessages > 0 ? .75 : metrics.toolCalls > 0 ? .5 : 0, metrics);
1160
- }
1161
- function penalizeErrors(base, metrics) {
1162
- const operations = Math.max(1, metrics.toolCalls + metrics.patchAttempts);
1163
- return clamp01(base * (1 - .5 * Math.min(1, (metrics.toolErrors + metrics.patchFailures) / operations)));
1164
- }
1165
- function emptyTokenTotals() {
1166
- return {
1167
- input: 0,
1168
- output: 0,
1169
- reasoning: 0,
1170
- cached: 0,
1171
- cacheWrite: 0
1172
- };
1173
- }
1174
- function hasTokenTotals(usage) {
1175
- return usage.input > 0 || usage.output > 0 || usage.reasoning > 0 || usage.cached > 0 || usage.cacheWrite > 0;
1176
- }
1177
- function addUsage(metrics, usage) {
1178
- const parsed = readUsage(usage);
1179
- metrics.inputTokens += parsed.input;
1180
- metrics.outputTokens += parsed.output;
1181
- metrics.reasoningTokens += parsed.reasoning;
1182
- metrics.cachedTokens += parsed.cached;
1183
- metrics.cacheWriteTokens += parsed.cacheWrite;
1184
- }
1185
- function addUsageTo(totals, usage) {
1186
- const parsed = readUsage(usage);
1187
- totals.input += parsed.input;
1188
- totals.output += parsed.output;
1189
- totals.reasoning += parsed.reasoning;
1190
- totals.cached += parsed.cached;
1191
- totals.cacheWrite += parsed.cacheWrite;
1192
- }
1193
- function readUsage(usage) {
1194
- const parsed = extractUsage(usage);
1195
- return {
1196
- input: parsed?.input ?? 0,
1197
- output: parsed?.output ?? 0,
1198
- reasoning: parsed?.reasoning ?? 0,
1199
- cached: parsed?.cached ?? 0,
1200
- cacheWrite: parsed?.cacheWrite ?? 0
1201
- };
1202
- }
1203
- function resolveSessionCost(explicit, metrics, model) {
1204
- if (explicit) {
1205
- if (explicit.kind === "uncaptured") {
1206
- if (explicit.usd !== null) throw new Error("uncaptured cost must have usd: null");
1207
- return {
1208
- costUsd: null,
1209
- costProvenance: explicit
1210
- };
1211
- }
1212
- if (!Number.isFinite(explicit.usd) || explicit.usd < 0) throw new Error(`${explicit.kind} cost must be a finite, non-negative USD amount`);
1213
- return {
1214
- costUsd: explicit.usd,
1215
- costProvenance: explicit
1216
- };
1217
- }
1218
- if (metrics.observedCostCaptured) {
1219
- const costProvenance = {
1220
- kind: "observed",
1221
- usd: metrics.observedCostUsd
1222
- };
1223
- return {
1224
- costUsd: metrics.observedCostUsd,
1225
- costProvenance
1226
- };
1227
- }
1228
- if ((metrics.inputTokens > 0 || metrics.outputTokens > 0) && isModelPriced(model)) {
1229
- const costUsd = estimateCost(metrics.inputTokens, metrics.outputTokens, model);
1230
- return {
1231
- costUsd,
1232
- costProvenance: {
1233
- kind: "estimated",
1234
- usd: costUsd
1235
- }
1236
- };
1237
- }
1238
- return {
1239
- costUsd: null,
1240
- costProvenance: {
1241
- kind: "uncaptured",
1242
- usd: null
1243
- }
1244
- };
1245
- }
1246
- function diagnosticsFor(metrics, options) {
1247
- const warnings = [];
1248
- if (options.invalidQualityScore) warnings.push("non-finite task quality score omitted");
1249
- else if (!options.hasQualityLabel) warnings.push("task quality score not supplied");
1250
- if (!options.explicitTerminal) warnings.push("no explicit terminal success/failure signal");
1251
- if (metrics.inputTokens === 0 && metrics.outputTokens === 0 && metrics.reasoningTokens === 0 && metrics.cachedTokens === 0 && metrics.cacheWriteTokens === 0) warnings.push("missing token usage");
1252
- if (options.costKind === "estimated") warnings.push("USD cost estimated from token usage and model pricing");
1253
- if (options.costKind === "uncaptured") warnings.push("USD cost uncaptured");
1254
- if (options.costKind === "uncaptured" && !isModelPriced(options.model)) warnings.push("model pricing unknown");
1255
- if (options.malformedLines > 0) warnings.push(`${options.malformedLines} malformed JSONL lines skipped`);
1256
- return warnings;
1257
- }
1258
- function applyObservedSurfaceMetrics(metrics, observation) {
1259
- const actions = observation.actions.filter((action) => action.kind === "tool" || action.kind === "patch");
1260
- metrics.mcpCalls = actions.filter((action) => action.surface === "mcp").length;
1261
- metrics.subagentCalls = actions.filter((action) => action.surface === "subagent").length;
1262
- metrics.skillCalls = actions.filter((action) => action.surface === "skill").length;
1263
- metrics.hookCalls = actions.filter((action) => action.surface === "hook").length;
1264
- metrics.webCalls = actions.filter((action) => action.surface === "web").length;
1265
- metrics.codeActions = actions.filter((action) => action.surface === "code").length;
1266
- }
1267
- function sessionIdFromEntries(source, entries) {
1268
- for (const entry of entries) {
1269
- if (source === "codex") {
1270
- const threadId = stringField(entry, "thread_id");
1271
- if (threadId) return threadId;
1272
- const payload = record(entry.payload);
1273
- const id = payload ? stringField(payload, "id") : void 0;
1274
- if (id) return id;
1275
- }
1276
- const payload = record(record(entry.message)?.payload);
1277
- const sessionId = stringField(entry, "sessionID") ?? stringField(entry, "sessionId") ?? stringField(entry, "session_id") ?? stringField(payload ?? {}, "session_id");
1278
- if (sessionId) return sessionId;
1279
- }
1280
- }
1281
- function modelFromEntries(source, entries) {
1282
- let providerModel;
1283
- for (const entry of entries) {
1284
- if (source === "codex") {
1285
- const payload = record(entry.payload);
1286
- const model = payload ? stringField(payload, "model") : void 0;
1287
- if (model) return model;
1288
- providerModel = providerModel ?? (payload ? stringField(payload, "model_provider") : void 0);
1289
- }
1290
- const openCodeModel = stringField(entry, "modelID");
1291
- if (openCodeModel) {
1292
- const provider = stringField(entry, "providerID");
1293
- return provider ? `${provider}/${openCodeModel}` : openCodeModel;
1294
- }
1295
- const modelObject = record(entry.model);
1296
- const nestedModel = stringField(modelObject ?? {}, "modelID");
1297
- if (nestedModel) {
1298
- const provider = stringField(modelObject ?? {}, "providerID");
1299
- return provider ? `${provider}/${nestedModel}` : nestedModel;
1300
- }
1301
- const message = record(entry.message);
1302
- const model = message ? stringField(message, "model") : void 0;
1303
- if (model) return model;
1304
- }
1305
- return providerModel;
1306
- }
1307
- function cwdFromEntries(entries) {
1308
- for (const entry of entries) {
1309
- const path = record(entry.path);
1310
- const cwd = stringField(entry, "cwd") ?? stringField(path ?? {}, "cwd") ?? stringField(path ?? {}, "root") ?? (record(entry.payload) ? stringField(record(entry.payload), "cwd") : void 0);
1311
- if (cwd) return cwd;
1312
- }
1313
- }
1314
- function firstUserText(entries) {
1315
- for (const entry of entries) {
1316
- const payload = record(entry.payload);
1317
- if ((payload ? stringField(payload, "type") : void 0) === "user_message") return stringField(payload, "message");
1318
- if (stringField(entry, "role") === "user") {
1319
- const content = entry.content;
1320
- if (typeof content === "string") return content;
1321
- }
1322
- const wirePayload = record(record(entry.message)?.payload);
1323
- const userInput = wirePayload ? stringField(wirePayload, "user_input") : void 0;
1324
- if (userInput) return userInput;
1325
- const message = record(entry.message);
1326
- if (message && stringField(message, "role") === "user") {
1327
- const content = message.content;
1328
- if (typeof content === "string") return content;
1329
- if (Array.isArray(content)) {
1330
- const text = content.map((part) => {
1331
- const obj = record(part);
1332
- return obj ? stringField(obj, "text") : void 0;
1333
- }).filter((part) => part !== void 0).join("\n");
1334
- if (text) return text;
1335
- }
1336
- }
1337
- }
1338
- }
1339
- function fallbackSessionId(source, sourcePath) {
1340
- return hashString(`${source}:${sourcePath ?? "unknown-session"}`).slice(7, 27);
1341
- }
1342
- function withSnapshot(model) {
1343
- const trimmed = model.trim() || "unknown";
1344
- if (trimmed.includes("@") || /-\d{8}$/.test(trimmed) || /-\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
1345
- return `${trimmed}@observed-local`;
1346
- }
1347
- function hashJson(value) {
1348
- return hashString(JSON.stringify(value));
1349
- }
1350
- function hashString(value) {
1351
- return `sha256:${createHash("sha256").update(value).digest("hex")}`;
1352
- }
1353
- function stableSeed(value) {
1354
- return createHash("sha256").update(value).digest().readUInt32BE(0);
1355
- }
1356
- function maxOptional(current, next) {
1357
- return current === void 0 ? next : Math.max(current, next);
1358
- }
1359
- function clamp01(value) {
1360
- if (!Number.isFinite(value)) return 0;
1361
- return Math.max(0, Math.min(1, value));
1362
- }
1363
- function finiteScore(value) {
1364
- return value !== void 0 && Number.isFinite(value) ? clamp01(value) : void 0;
1365
- }
1366
- function isRecord(value) {
1367
- return value !== null && typeof value === "object" && !Array.isArray(value);
1368
- }
1369
- function record(value) {
1370
- return isRecord(value) ? value : null;
1371
- }
1372
- function stringField(obj, key) {
1373
- const value = obj[key];
1374
- return typeof value === "string" && value.length > 0 ? value : void 0;
1375
- }
1376
- function numberField(obj, key) {
1377
- const value = obj[key];
1378
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1379
- }
1380
- function timestampMs(value) {
1381
- if (typeof value === "number" && Number.isFinite(value)) return value > 0xe8d4a51000 ? value : value * 1e3;
1382
- if (typeof value === "string" && value.length > 0) {
1383
- const parsed = Date.parse(value);
1384
- return Number.isFinite(parsed) ? parsed : void 0;
1385
- }
1386
- }
1387
- //#endregion
1388
- export { fromPiSession as a, observeCodeAgentSession as c, fromOpenCodeSession as i, fromCodexSession as n, fromPigraphSession as o, fromKimiCodeSession as r, parseCodeAgentJsonl as s, fromClaudeCodeSession as t };
1389
-
1390
- //# sourceMappingURL=code-agent-session-BjkMTQ7H.js.map