sentinelayer-cli 0.6.2 → 0.8.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 (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,302 +1,302 @@
1
- import fsp from "node:fs/promises";
2
- import path from "node:path";
3
- import { randomUUID } from "node:crypto";
4
-
5
- import { resolveOutputRoot } from "../config/service.js";
6
-
7
- const OBSERVABILITY_DIR_NAME = "observability";
8
- const RUN_EVENTS_FILE_NAME = "run-events.jsonl";
9
- const SCHEMA_VERSION = 1;
10
-
11
- export const RUN_EVENT_TYPES = Object.freeze([
12
- "run_start",
13
- "run_step",
14
- "tool_call",
15
- "usage",
16
- "budget_check",
17
- "run_stop",
18
- ]);
19
-
20
- export const STOP_CLASSES = Object.freeze([
21
- "NONE",
22
- "MAX_COST_EXCEEDED",
23
- "MAX_OUTPUT_TOKENS_EXCEEDED",
24
- "DIMINISHING_RETURNS",
25
- "MAX_RUNTIME_MS_EXCEEDED",
26
- "MAX_TOOL_CALLS_EXCEEDED",
27
- "MANUAL_STOP",
28
- "ERROR",
29
- "UNKNOWN",
30
- ]);
31
-
32
- const RUN_EVENT_TYPE_SET = new Set(RUN_EVENT_TYPES);
33
- const STOP_CLASS_SET = new Set(STOP_CLASSES);
34
-
35
- function normalizeNonNegativeNumber(value, field) {
36
- const normalized = Number(value || 0);
37
- if (!Number.isFinite(normalized) || normalized < 0) {
38
- throw new Error(`${field} must be a non-negative number.`);
39
- }
40
- return normalized;
41
- }
42
-
43
- function normalizeReasonCodes(reasonCodes = []) {
44
- if (reasonCodes === undefined || reasonCodes === null) {
45
- return [];
46
- }
47
- if (!Array.isArray(reasonCodes)) {
48
- throw new Error("stop.reasonCodes must be an array of strings.");
49
- }
50
-
51
- const unique = new Set();
52
- for (const reasonCode of reasonCodes) {
53
- const normalized = String(reasonCode || "").trim().toUpperCase();
54
- if (normalized) {
55
- unique.add(normalized);
56
- }
57
- }
58
-
59
- return [...unique];
60
- }
61
-
62
- function normalizeStop(stop = null) {
63
- if (!stop) {
64
- return null;
65
- }
66
- if (typeof stop !== "object" || Array.isArray(stop)) {
67
- throw new Error("stop must be an object when provided.");
68
- }
69
-
70
- const stopClass = String(stop.stopClass || "NONE").trim().toUpperCase() || "NONE";
71
- if (!STOP_CLASS_SET.has(stopClass)) {
72
- throw new Error(`Unsupported stop class '${stopClass}'.`);
73
- }
74
-
75
- return {
76
- stopClass,
77
- blocking: Boolean(stop.blocking),
78
- reasonCodes: normalizeReasonCodes(stop.reasonCodes),
79
- };
80
- }
81
-
82
- function normalizeMetadata(metadata = {}) {
83
- if (metadata === undefined || metadata === null) {
84
- return {};
85
- }
86
- if (typeof metadata !== "object" || Array.isArray(metadata)) {
87
- throw new Error("metadata must be an object when provided.");
88
- }
89
- return { ...metadata };
90
- }
91
-
92
- function normalizeUsage(usage = {}) {
93
- if (usage === undefined || usage === null) {
94
- return {
95
- inputTokens: 0,
96
- outputTokens: 0,
97
- cacheReadTokens: 0,
98
- cacheWriteTokens: 0,
99
- costUsd: 0,
100
- durationMs: 0,
101
- toolCalls: 0,
102
- };
103
- }
104
-
105
- if (typeof usage !== "object" || Array.isArray(usage)) {
106
- throw new Error("usage must be an object when provided.");
107
- }
108
-
109
- return {
110
- inputTokens: normalizeNonNegativeNumber(usage.inputTokens, "usage.inputTokens"),
111
- outputTokens: normalizeNonNegativeNumber(usage.outputTokens, "usage.outputTokens"),
112
- cacheReadTokens: normalizeNonNegativeNumber(usage.cacheReadTokens, "usage.cacheReadTokens"),
113
- cacheWriteTokens: normalizeNonNegativeNumber(usage.cacheWriteTokens, "usage.cacheWriteTokens"),
114
- costUsd: normalizeNonNegativeNumber(usage.costUsd, "usage.costUsd"),
115
- durationMs: normalizeNonNegativeNumber(usage.durationMs, "usage.durationMs"),
116
- toolCalls: normalizeNonNegativeNumber(usage.toolCalls, "usage.toolCalls"),
117
- };
118
- }
119
-
120
- export function mapBudgetReasonToStopClass(reasonCode = "") {
121
- const normalized = String(reasonCode || "").trim().toUpperCase();
122
- switch (normalized) {
123
- case "MAX_COST_EXCEEDED":
124
- return "MAX_COST_EXCEEDED";
125
- case "MAX_OUTPUT_TOKENS_EXCEEDED":
126
- return "MAX_OUTPUT_TOKENS_EXCEEDED";
127
- case "DIMINISHING_RETURNS":
128
- return "DIMINISHING_RETURNS";
129
- case "MAX_RUNTIME_MS_EXCEEDED":
130
- return "MAX_RUNTIME_MS_EXCEEDED";
131
- case "MAX_TOOL_CALLS_EXCEEDED":
132
- return "MAX_TOOL_CALLS_EXCEEDED";
133
- default:
134
- return "UNKNOWN";
135
- }
136
- }
137
-
138
- export function deriveStopClassFromBudget(budget = {}) {
139
- if (!budget || !Array.isArray(budget.reasons) || budget.reasons.length === 0) {
140
- return "NONE";
141
- }
142
- const firstReasonCode = String(budget.reasons[0]?.code || "").trim().toUpperCase();
143
- return mapBudgetReasonToStopClass(firstReasonCode);
144
- }
145
-
146
- export function normalizeRunEvent(event = {}) {
147
- if (!event || typeof event !== "object" || Array.isArray(event)) {
148
- throw new Error("Run event must be an object.");
149
- }
150
-
151
- const eventType = String(event.eventType || "").trim();
152
- if (!RUN_EVENT_TYPE_SET.has(eventType)) {
153
- throw new Error(
154
- `Unsupported event type '${eventType}'. Allowed: ${RUN_EVENT_TYPES.join(", ")}.`
155
- );
156
- }
157
-
158
- return {
159
- schemaVersion: SCHEMA_VERSION,
160
- eventId: String(event.eventId || "").trim() || randomUUID(),
161
- timestamp: String(event.timestamp || "").trim() || new Date().toISOString(),
162
- sessionId: String(event.sessionId || "").trim() || "default",
163
- runId: String(event.runId || "").trim() || "default",
164
- eventType,
165
- usage: normalizeUsage(event.usage),
166
- stop: normalizeStop(event.stop),
167
- metadata: normalizeMetadata(event.metadata),
168
- };
169
- }
170
-
171
- function getInitialSummary() {
172
- return {
173
- eventCount: 0,
174
- runCount: 0,
175
- sessionCount: 0,
176
- earliestTimestamp: null,
177
- latestTimestamp: null,
178
- eventTypeCounts: {},
179
- stopClassCounts: {},
180
- reasonCodeCounts: {},
181
- usageTotals: {
182
- inputTokens: 0,
183
- outputTokens: 0,
184
- cacheReadTokens: 0,
185
- cacheWriteTokens: 0,
186
- costUsd: 0,
187
- durationMs: 0,
188
- toolCalls: 0,
189
- },
190
- };
191
- }
192
-
193
- function incrementCounter(container, key) {
194
- const normalizedKey = String(key || "").trim();
195
- if (!normalizedKey) {
196
- return;
197
- }
198
- container[normalizedKey] = Number(container[normalizedKey] || 0) + 1;
199
- }
200
-
201
- function mergeUsageTotals(totals, usage = {}) {
202
- totals.inputTokens += normalizeNonNegativeNumber(usage.inputTokens, "usage.inputTokens");
203
- totals.outputTokens += normalizeNonNegativeNumber(usage.outputTokens, "usage.outputTokens");
204
- totals.cacheReadTokens += normalizeNonNegativeNumber(usage.cacheReadTokens, "usage.cacheReadTokens");
205
- totals.cacheWriteTokens += normalizeNonNegativeNumber(
206
- usage.cacheWriteTokens,
207
- "usage.cacheWriteTokens"
208
- );
209
- totals.costUsd += normalizeNonNegativeNumber(usage.costUsd, "usage.costUsd");
210
- totals.durationMs += normalizeNonNegativeNumber(usage.durationMs, "usage.durationMs");
211
- totals.toolCalls += normalizeNonNegativeNumber(usage.toolCalls, "usage.toolCalls");
212
- }
213
-
214
- export function summarizeRunEvents(events = []) {
215
- if (!Array.isArray(events)) {
216
- throw new Error("events must be an array.");
217
- }
218
-
219
- const summary = getInitialSummary();
220
- const runIds = new Set();
221
- const sessionIds = new Set();
222
-
223
- for (const rawEvent of events) {
224
- const event = normalizeRunEvent(rawEvent);
225
- summary.eventCount += 1;
226
- runIds.add(event.runId);
227
- sessionIds.add(event.sessionId);
228
- incrementCounter(summary.eventTypeCounts, event.eventType);
229
- mergeUsageTotals(summary.usageTotals, event.usage);
230
-
231
- if (!summary.earliestTimestamp || event.timestamp < summary.earliestTimestamp) {
232
- summary.earliestTimestamp = event.timestamp;
233
- }
234
- if (!summary.latestTimestamp || event.timestamp > summary.latestTimestamp) {
235
- summary.latestTimestamp = event.timestamp;
236
- }
237
-
238
- if (event.stop) {
239
- incrementCounter(summary.stopClassCounts, event.stop.stopClass);
240
- for (const reasonCode of event.stop.reasonCodes || []) {
241
- incrementCounter(summary.reasonCodeCounts, reasonCode);
242
- }
243
- }
244
- }
245
-
246
- summary.runCount = runIds.size;
247
- summary.sessionCount = sessionIds.size;
248
- return summary;
249
- }
250
-
251
- export async function resolveRunEventsPath({
252
- targetPath = ".",
253
- outputDirOverride = "",
254
- env,
255
- homeDir,
256
- } = {}) {
257
- const outputRoot = await resolveOutputRoot({
258
- cwd: path.resolve(targetPath),
259
- outputDirOverride,
260
- env,
261
- homeDir,
262
- });
263
- return path.join(outputRoot, OBSERVABILITY_DIR_NAME, RUN_EVENTS_FILE_NAME);
264
- }
265
-
266
- export async function appendRunEvent(options = {}, event = {}) {
267
- const normalizedEvent = normalizeRunEvent(event);
268
- const filePath = await resolveRunEventsPath(options);
269
- await fsp.mkdir(path.dirname(filePath), { recursive: true });
270
- await fsp.appendFile(filePath, `${JSON.stringify(normalizedEvent)}\n`, "utf-8");
271
- return {
272
- filePath,
273
- event: normalizedEvent,
274
- };
275
- }
276
-
277
- export async function loadRunEvents(options = {}) {
278
- const filePath = await resolveRunEventsPath(options);
279
- try {
280
- const raw = await fsp.readFile(filePath, "utf-8");
281
- const lines = raw
282
- .split(/\r?\n/)
283
- .map((line) => line.trim())
284
- .filter(Boolean);
285
- const events = lines.map((line, index) => {
286
- try {
287
- return JSON.parse(line);
288
- } catch (error) {
289
- throw new Error(
290
- `Invalid run event JSON at ${filePath}:${index + 1} (${error instanceof Error ? error.message : String(error)}).`
291
- );
292
- }
293
- });
294
- return { filePath, events };
295
- } catch (error) {
296
- if (error && typeof error === "object" && error.code === "ENOENT") {
297
- return { filePath, events: [] };
298
- }
299
- throw error;
300
- }
301
- }
302
-
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+
5
+ import { resolveOutputRoot } from "../config/service.js";
6
+
7
+ const OBSERVABILITY_DIR_NAME = "observability";
8
+ const RUN_EVENTS_FILE_NAME = "run-events.jsonl";
9
+ const SCHEMA_VERSION = 1;
10
+
11
+ export const RUN_EVENT_TYPES = Object.freeze([
12
+ "run_start",
13
+ "run_step",
14
+ "tool_call",
15
+ "usage",
16
+ "budget_check",
17
+ "run_stop",
18
+ ]);
19
+
20
+ export const STOP_CLASSES = Object.freeze([
21
+ "NONE",
22
+ "MAX_COST_EXCEEDED",
23
+ "MAX_OUTPUT_TOKENS_EXCEEDED",
24
+ "DIMINISHING_RETURNS",
25
+ "MAX_RUNTIME_MS_EXCEEDED",
26
+ "MAX_TOOL_CALLS_EXCEEDED",
27
+ "MANUAL_STOP",
28
+ "ERROR",
29
+ "UNKNOWN",
30
+ ]);
31
+
32
+ const RUN_EVENT_TYPE_SET = new Set(RUN_EVENT_TYPES);
33
+ const STOP_CLASS_SET = new Set(STOP_CLASSES);
34
+
35
+ function normalizeNonNegativeNumber(value, field) {
36
+ const normalized = Number(value || 0);
37
+ if (!Number.isFinite(normalized) || normalized < 0) {
38
+ throw new Error(`${field} must be a non-negative number.`);
39
+ }
40
+ return normalized;
41
+ }
42
+
43
+ function normalizeReasonCodes(reasonCodes = []) {
44
+ if (reasonCodes === undefined || reasonCodes === null) {
45
+ return [];
46
+ }
47
+ if (!Array.isArray(reasonCodes)) {
48
+ throw new Error("stop.reasonCodes must be an array of strings.");
49
+ }
50
+
51
+ const unique = new Set();
52
+ for (const reasonCode of reasonCodes) {
53
+ const normalized = String(reasonCode || "").trim().toUpperCase();
54
+ if (normalized) {
55
+ unique.add(normalized);
56
+ }
57
+ }
58
+
59
+ return [...unique];
60
+ }
61
+
62
+ function normalizeStop(stop = null) {
63
+ if (!stop) {
64
+ return null;
65
+ }
66
+ if (typeof stop !== "object" || Array.isArray(stop)) {
67
+ throw new Error("stop must be an object when provided.");
68
+ }
69
+
70
+ const stopClass = String(stop.stopClass || "NONE").trim().toUpperCase() || "NONE";
71
+ if (!STOP_CLASS_SET.has(stopClass)) {
72
+ throw new Error(`Unsupported stop class '${stopClass}'.`);
73
+ }
74
+
75
+ return {
76
+ stopClass,
77
+ blocking: Boolean(stop.blocking),
78
+ reasonCodes: normalizeReasonCodes(stop.reasonCodes),
79
+ };
80
+ }
81
+
82
+ function normalizeMetadata(metadata = {}) {
83
+ if (metadata === undefined || metadata === null) {
84
+ return {};
85
+ }
86
+ if (typeof metadata !== "object" || Array.isArray(metadata)) {
87
+ throw new Error("metadata must be an object when provided.");
88
+ }
89
+ return { ...metadata };
90
+ }
91
+
92
+ function normalizeUsage(usage = {}) {
93
+ if (usage === undefined || usage === null) {
94
+ return {
95
+ inputTokens: 0,
96
+ outputTokens: 0,
97
+ cacheReadTokens: 0,
98
+ cacheWriteTokens: 0,
99
+ costUsd: 0,
100
+ durationMs: 0,
101
+ toolCalls: 0,
102
+ };
103
+ }
104
+
105
+ if (typeof usage !== "object" || Array.isArray(usage)) {
106
+ throw new Error("usage must be an object when provided.");
107
+ }
108
+
109
+ return {
110
+ inputTokens: normalizeNonNegativeNumber(usage.inputTokens, "usage.inputTokens"),
111
+ outputTokens: normalizeNonNegativeNumber(usage.outputTokens, "usage.outputTokens"),
112
+ cacheReadTokens: normalizeNonNegativeNumber(usage.cacheReadTokens, "usage.cacheReadTokens"),
113
+ cacheWriteTokens: normalizeNonNegativeNumber(usage.cacheWriteTokens, "usage.cacheWriteTokens"),
114
+ costUsd: normalizeNonNegativeNumber(usage.costUsd, "usage.costUsd"),
115
+ durationMs: normalizeNonNegativeNumber(usage.durationMs, "usage.durationMs"),
116
+ toolCalls: normalizeNonNegativeNumber(usage.toolCalls, "usage.toolCalls"),
117
+ };
118
+ }
119
+
120
+ export function mapBudgetReasonToStopClass(reasonCode = "") {
121
+ const normalized = String(reasonCode || "").trim().toUpperCase();
122
+ switch (normalized) {
123
+ case "MAX_COST_EXCEEDED":
124
+ return "MAX_COST_EXCEEDED";
125
+ case "MAX_OUTPUT_TOKENS_EXCEEDED":
126
+ return "MAX_OUTPUT_TOKENS_EXCEEDED";
127
+ case "DIMINISHING_RETURNS":
128
+ return "DIMINISHING_RETURNS";
129
+ case "MAX_RUNTIME_MS_EXCEEDED":
130
+ return "MAX_RUNTIME_MS_EXCEEDED";
131
+ case "MAX_TOOL_CALLS_EXCEEDED":
132
+ return "MAX_TOOL_CALLS_EXCEEDED";
133
+ default:
134
+ return "UNKNOWN";
135
+ }
136
+ }
137
+
138
+ export function deriveStopClassFromBudget(budget = {}) {
139
+ if (!budget || !Array.isArray(budget.reasons) || budget.reasons.length === 0) {
140
+ return "NONE";
141
+ }
142
+ const firstReasonCode = String(budget.reasons[0]?.code || "").trim().toUpperCase();
143
+ return mapBudgetReasonToStopClass(firstReasonCode);
144
+ }
145
+
146
+ export function normalizeRunEvent(event = {}) {
147
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
148
+ throw new Error("Run event must be an object.");
149
+ }
150
+
151
+ const eventType = String(event.eventType || "").trim();
152
+ if (!RUN_EVENT_TYPE_SET.has(eventType)) {
153
+ throw new Error(
154
+ `Unsupported event type '${eventType}'. Allowed: ${RUN_EVENT_TYPES.join(", ")}.`
155
+ );
156
+ }
157
+
158
+ return {
159
+ schemaVersion: SCHEMA_VERSION,
160
+ eventId: String(event.eventId || "").trim() || randomUUID(),
161
+ timestamp: String(event.timestamp || "").trim() || new Date().toISOString(),
162
+ sessionId: String(event.sessionId || "").trim() || "default",
163
+ runId: String(event.runId || "").trim() || "default",
164
+ eventType,
165
+ usage: normalizeUsage(event.usage),
166
+ stop: normalizeStop(event.stop),
167
+ metadata: normalizeMetadata(event.metadata),
168
+ };
169
+ }
170
+
171
+ function getInitialSummary() {
172
+ return {
173
+ eventCount: 0,
174
+ runCount: 0,
175
+ sessionCount: 0,
176
+ earliestTimestamp: null,
177
+ latestTimestamp: null,
178
+ eventTypeCounts: {},
179
+ stopClassCounts: {},
180
+ reasonCodeCounts: {},
181
+ usageTotals: {
182
+ inputTokens: 0,
183
+ outputTokens: 0,
184
+ cacheReadTokens: 0,
185
+ cacheWriteTokens: 0,
186
+ costUsd: 0,
187
+ durationMs: 0,
188
+ toolCalls: 0,
189
+ },
190
+ };
191
+ }
192
+
193
+ function incrementCounter(container, key) {
194
+ const normalizedKey = String(key || "").trim();
195
+ if (!normalizedKey) {
196
+ return;
197
+ }
198
+ container[normalizedKey] = Number(container[normalizedKey] || 0) + 1;
199
+ }
200
+
201
+ function mergeUsageTotals(totals, usage = {}) {
202
+ totals.inputTokens += normalizeNonNegativeNumber(usage.inputTokens, "usage.inputTokens");
203
+ totals.outputTokens += normalizeNonNegativeNumber(usage.outputTokens, "usage.outputTokens");
204
+ totals.cacheReadTokens += normalizeNonNegativeNumber(usage.cacheReadTokens, "usage.cacheReadTokens");
205
+ totals.cacheWriteTokens += normalizeNonNegativeNumber(
206
+ usage.cacheWriteTokens,
207
+ "usage.cacheWriteTokens"
208
+ );
209
+ totals.costUsd += normalizeNonNegativeNumber(usage.costUsd, "usage.costUsd");
210
+ totals.durationMs += normalizeNonNegativeNumber(usage.durationMs, "usage.durationMs");
211
+ totals.toolCalls += normalizeNonNegativeNumber(usage.toolCalls, "usage.toolCalls");
212
+ }
213
+
214
+ export function summarizeRunEvents(events = []) {
215
+ if (!Array.isArray(events)) {
216
+ throw new Error("events must be an array.");
217
+ }
218
+
219
+ const summary = getInitialSummary();
220
+ const runIds = new Set();
221
+ const sessionIds = new Set();
222
+
223
+ for (const rawEvent of events) {
224
+ const event = normalizeRunEvent(rawEvent);
225
+ summary.eventCount += 1;
226
+ runIds.add(event.runId);
227
+ sessionIds.add(event.sessionId);
228
+ incrementCounter(summary.eventTypeCounts, event.eventType);
229
+ mergeUsageTotals(summary.usageTotals, event.usage);
230
+
231
+ if (!summary.earliestTimestamp || event.timestamp < summary.earliestTimestamp) {
232
+ summary.earliestTimestamp = event.timestamp;
233
+ }
234
+ if (!summary.latestTimestamp || event.timestamp > summary.latestTimestamp) {
235
+ summary.latestTimestamp = event.timestamp;
236
+ }
237
+
238
+ if (event.stop) {
239
+ incrementCounter(summary.stopClassCounts, event.stop.stopClass);
240
+ for (const reasonCode of event.stop.reasonCodes || []) {
241
+ incrementCounter(summary.reasonCodeCounts, reasonCode);
242
+ }
243
+ }
244
+ }
245
+
246
+ summary.runCount = runIds.size;
247
+ summary.sessionCount = sessionIds.size;
248
+ return summary;
249
+ }
250
+
251
+ export async function resolveRunEventsPath({
252
+ targetPath = ".",
253
+ outputDirOverride = "",
254
+ env,
255
+ homeDir,
256
+ } = {}) {
257
+ const outputRoot = await resolveOutputRoot({
258
+ cwd: path.resolve(targetPath),
259
+ outputDirOverride,
260
+ env,
261
+ homeDir,
262
+ });
263
+ return path.join(outputRoot, OBSERVABILITY_DIR_NAME, RUN_EVENTS_FILE_NAME);
264
+ }
265
+
266
+ export async function appendRunEvent(options = {}, event = {}) {
267
+ const normalizedEvent = normalizeRunEvent(event);
268
+ const filePath = await resolveRunEventsPath(options);
269
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
270
+ await fsp.appendFile(filePath, `${JSON.stringify(normalizedEvent)}\n`, "utf-8");
271
+ return {
272
+ filePath,
273
+ event: normalizedEvent,
274
+ };
275
+ }
276
+
277
+ export async function loadRunEvents(options = {}) {
278
+ const filePath = await resolveRunEventsPath(options);
279
+ try {
280
+ const raw = await fsp.readFile(filePath, "utf-8");
281
+ const lines = raw
282
+ .split(/\r?\n/)
283
+ .map((line) => line.trim())
284
+ .filter(Boolean);
285
+ const events = lines.map((line, index) => {
286
+ try {
287
+ return JSON.parse(line);
288
+ } catch (error) {
289
+ throw new Error(
290
+ `Invalid run event JSON at ${filePath}:${index + 1} (${error instanceof Error ? error.message : String(error)}).`
291
+ );
292
+ }
293
+ });
294
+ return { filePath, events };
295
+ } catch (error) {
296
+ if (error && typeof error === "object" && error.code === "ENOENT") {
297
+ return { filePath, events: [] };
298
+ }
299
+ throw error;
300
+ }
301
+ }
302
+