sentinelayer-cli 0.1.2 → 0.3.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 (127) 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 +62 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +319 -319
  12. package/src/agents/jules/stream.js +186 -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 +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +226 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +493 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/ai/aidenid.js +972 -945
  30. package/src/ai/client.js +508 -508
  31. package/src/ai/domain-target-store.js +268 -268
  32. package/src/ai/identity-store.js +270 -270
  33. package/src/ai/site-store.js +145 -145
  34. package/src/audit/agents/architecture.js +180 -180
  35. package/src/audit/agents/compliance.js +179 -179
  36. package/src/audit/agents/documentation.js +165 -165
  37. package/src/audit/agents/performance.js +145 -145
  38. package/src/audit/agents/security.js +215 -215
  39. package/src/audit/agents/testing.js +172 -172
  40. package/src/audit/orchestrator.js +557 -557
  41. package/src/audit/package.js +204 -204
  42. package/src/audit/registry.js +284 -284
  43. package/src/audit/replay.js +103 -103
  44. package/src/auth/http.js +113 -113
  45. package/src/auth/service.js +891 -848
  46. package/src/auth/session-store.js +359 -345
  47. package/src/cli.js +252 -252
  48. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  49. package/src/commands/ai/provision-governance.js +1272 -1246
  50. package/src/commands/ai/shared.js +147 -147
  51. package/src/commands/ai.js +11 -11
  52. package/src/commands/apply.js +12 -12
  53. package/src/commands/audit.js +1166 -1166
  54. package/src/commands/auth.js +375 -366
  55. package/src/commands/chat.js +191 -191
  56. package/src/commands/config.js +184 -184
  57. package/src/commands/cost.js +311 -311
  58. package/src/commands/daemon/core.js +850 -850
  59. package/src/commands/daemon/extended.js +1048 -1048
  60. package/src/commands/daemon/shared.js +213 -213
  61. package/src/commands/daemon.js +11 -11
  62. package/src/commands/guide.js +174 -174
  63. package/src/commands/ingest.js +58 -58
  64. package/src/commands/init.js +55 -55
  65. package/src/commands/legacy-args.js +10 -10
  66. package/src/commands/mcp.js +461 -404
  67. package/src/commands/omargate.js +15 -15
  68. package/src/commands/persona.js +20 -20
  69. package/src/commands/plugin.js +260 -260
  70. package/src/commands/policy.js +132 -132
  71. package/src/commands/prompt.js +238 -238
  72. package/src/commands/review.js +704 -704
  73. package/src/commands/scan.js +866 -788
  74. package/src/commands/spec.js +716 -716
  75. package/src/commands/swarm.js +651 -651
  76. package/src/commands/telemetry.js +202 -202
  77. package/src/commands/watch.js +510 -510
  78. package/src/config/agent-dictionary.js +182 -182
  79. package/src/config/io.js +56 -56
  80. package/src/config/paths.js +18 -18
  81. package/src/config/schema.js +55 -55
  82. package/src/config/service.js +184 -184
  83. package/src/cost/budget.js +235 -235
  84. package/src/cost/history.js +188 -188
  85. package/src/cost/tracker.js +171 -171
  86. package/src/daemon/artifact-lineage.js +534 -534
  87. package/src/daemon/assignment-ledger.js +770 -770
  88. package/src/daemon/ast-parser-layer.js +258 -258
  89. package/src/daemon/budget-governor.js +633 -633
  90. package/src/daemon/callgraph-overlay.js +646 -646
  91. package/src/daemon/error-worker.js +626 -626
  92. package/src/daemon/hybrid-mapper.js +929 -929
  93. package/src/daemon/jira-lifecycle.js +632 -632
  94. package/src/daemon/operator-control.js +657 -657
  95. package/src/daemon/reliability-lane.js +471 -471
  96. package/src/daemon/watchdog.js +971 -971
  97. package/src/guide/generator.js +316 -316
  98. package/src/ingest/engine.js +918 -918
  99. package/src/legacy-cli.js +2548 -2435
  100. package/src/mcp/registry.js +695 -695
  101. package/src/memory/blackboard.js +301 -301
  102. package/src/memory/retrieval.js +581 -581
  103. package/src/plugin/manifest.js +553 -553
  104. package/src/policy/packs.js +144 -144
  105. package/src/prompt/generator.js +118 -106
  106. package/src/review/ai-review.js +669 -669
  107. package/src/review/local-review.js +1284 -1284
  108. package/src/review/replay.js +235 -235
  109. package/src/review/report.js +664 -664
  110. package/src/review/spec-binding.js +487 -487
  111. package/src/scaffold/generator.js +67 -0
  112. package/src/scaffold/templates.js +150 -0
  113. package/src/scan/generator.js +418 -351
  114. package/src/scan/gh-secrets.js +107 -0
  115. package/src/spec/generator.js +519 -519
  116. package/src/spec/regenerate.js +237 -237
  117. package/src/spec/templates.js +91 -91
  118. package/src/swarm/dashboard.js +247 -247
  119. package/src/swarm/factory.js +363 -363
  120. package/src/swarm/pentest.js +934 -934
  121. package/src/swarm/registry.js +419 -419
  122. package/src/swarm/report.js +158 -158
  123. package/src/swarm/runtime.js +576 -576
  124. package/src/swarm/scenario-dsl.js +272 -272
  125. package/src/telemetry/ledger.js +302 -302
  126. package/src/telemetry/sync.js +96 -59
  127. 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
+