sentinelayer-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +996 -0
- package/bin/create-sentinelayer.js +5 -0
- package/bin/sentinelayer-cli.js +5 -0
- package/bin/sl.js +5 -0
- package/package.json +54 -0
- package/src/agents/jules/config/definition.js +209 -0
- package/src/agents/jules/config/system-prompt.js +175 -0
- package/src/agents/jules/error-intake.js +51 -0
- package/src/agents/jules/fix-cycle.js +377 -0
- package/src/agents/jules/loop.js +367 -0
- package/src/agents/jules/pulse.js +319 -0
- package/src/agents/jules/stream.js +186 -0
- package/src/agents/jules/swarm/file-scanner.js +74 -0
- package/src/agents/jules/swarm/index.js +11 -0
- package/src/agents/jules/swarm/orchestrator.js +362 -0
- package/src/agents/jules/swarm/pattern-hunter.js +123 -0
- package/src/agents/jules/swarm/sub-agent.js +308 -0
- package/src/agents/jules/tools/auth-audit.js +222 -0
- package/src/agents/jules/tools/dispatch.js +327 -0
- package/src/agents/jules/tools/file-edit.js +180 -0
- package/src/agents/jules/tools/file-read.js +100 -0
- package/src/agents/jules/tools/frontend-analyze.js +570 -0
- package/src/agents/jules/tools/glob.js +168 -0
- package/src/agents/jules/tools/grep.js +228 -0
- package/src/agents/jules/tools/index.js +29 -0
- package/src/agents/jules/tools/path-guards.js +161 -0
- package/src/agents/jules/tools/runtime-audit.js +409 -0
- package/src/agents/jules/tools/shell.js +383 -0
- package/src/ai/aidenid.js +945 -0
- package/src/ai/client.js +508 -0
- package/src/ai/domain-target-store.js +268 -0
- package/src/ai/identity-store.js +270 -0
- package/src/ai/site-store.js +145 -0
- package/src/audit/agents/architecture.js +180 -0
- package/src/audit/agents/compliance.js +179 -0
- package/src/audit/agents/documentation.js +165 -0
- package/src/audit/agents/performance.js +145 -0
- package/src/audit/agents/security.js +215 -0
- package/src/audit/agents/testing.js +172 -0
- package/src/audit/orchestrator.js +557 -0
- package/src/audit/package.js +204 -0
- package/src/audit/registry.js +284 -0
- package/src/audit/replay.js +103 -0
- package/src/auth/http.js +113 -0
- package/src/auth/service.js +848 -0
- package/src/auth/session-store.js +345 -0
- package/src/cli.js +244 -0
- package/src/commands/ai/identity-lifecycle.js +1337 -0
- package/src/commands/ai/provision-governance.js +1246 -0
- package/src/commands/ai/shared.js +147 -0
- package/src/commands/ai.js +11 -0
- package/src/commands/apply.js +19 -0
- package/src/commands/audit.js +1147 -0
- package/src/commands/auth.js +366 -0
- package/src/commands/chat.js +191 -0
- package/src/commands/config.js +184 -0
- package/src/commands/cost.js +311 -0
- package/src/commands/daemon/core.js +850 -0
- package/src/commands/daemon/extended.js +1048 -0
- package/src/commands/daemon/shared.js +213 -0
- package/src/commands/daemon.js +11 -0
- package/src/commands/guide.js +174 -0
- package/src/commands/ingest.js +58 -0
- package/src/commands/init.js +55 -0
- package/src/commands/legacy-args.js +30 -0
- package/src/commands/mcp.js +404 -0
- package/src/commands/omargate.js +21 -0
- package/src/commands/persona.js +27 -0
- package/src/commands/plugin.js +260 -0
- package/src/commands/policy.js +132 -0
- package/src/commands/prompt.js +238 -0
- package/src/commands/review.js +704 -0
- package/src/commands/scan.js +788 -0
- package/src/commands/spec.js +716 -0
- package/src/commands/swarm.js +651 -0
- package/src/commands/telemetry.js +202 -0
- package/src/commands/watch.js +510 -0
- package/src/config/agent-dictionary.js +182 -0
- package/src/config/io.js +56 -0
- package/src/config/paths.js +18 -0
- package/src/config/schema.js +55 -0
- package/src/config/service.js +184 -0
- package/src/cost/budget.js +235 -0
- package/src/cost/history.js +188 -0
- package/src/cost/tracker.js +171 -0
- package/src/daemon/artifact-lineage.js +534 -0
- package/src/daemon/assignment-ledger.js +770 -0
- package/src/daemon/ast-parser-layer.js +258 -0
- package/src/daemon/budget-governor.js +633 -0
- package/src/daemon/callgraph-overlay.js +646 -0
- package/src/daemon/error-worker.js +626 -0
- package/src/daemon/hybrid-mapper.js +929 -0
- package/src/daemon/jira-lifecycle.js +632 -0
- package/src/daemon/operator-control.js +657 -0
- package/src/daemon/reliability-lane.js +471 -0
- package/src/daemon/watchdog.js +971 -0
- package/src/guide/generator.js +316 -0
- package/src/ingest/engine.js +918 -0
- package/src/legacy-cli.js +2435 -0
- package/src/mcp/registry.js +695 -0
- package/src/memory/blackboard.js +301 -0
- package/src/memory/retrieval.js +581 -0
- package/src/plugin/manifest.js +553 -0
- package/src/policy/packs.js +144 -0
- package/src/prompt/generator.js +106 -0
- package/src/review/ai-review.js +669 -0
- package/src/review/local-review.js +1284 -0
- package/src/review/replay.js +235 -0
- package/src/review/report.js +664 -0
- package/src/review/spec-binding.js +487 -0
- package/src/scan/generator.js +351 -0
- package/src/spec/generator.js +519 -0
- package/src/spec/regenerate.js +237 -0
- package/src/spec/templates.js +91 -0
- package/src/swarm/dashboard.js +247 -0
- package/src/swarm/factory.js +363 -0
- package/src/swarm/pentest.js +934 -0
- package/src/swarm/registry.js +419 -0
- package/src/swarm/report.js +158 -0
- package/src/swarm/runtime.js +576 -0
- package/src/swarm/scenario-dsl.js +272 -0
- package/src/telemetry/ledger.js +302 -0
- package/src/ui/markdown.js +220 -0
- package/src/ui/progress.js +100 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import fsp from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
const SUPPORTED_ACTIONS = new Set(["goto", "click", "fill", "wait", "screenshot"]);
|
|
5
|
+
|
|
6
|
+
function normalizeString(value) {
|
|
7
|
+
return String(value || "").trim();
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function decodeQuoted(value) {
|
|
11
|
+
return String(value || "")
|
|
12
|
+
.replace(/^"/, "")
|
|
13
|
+
.replace(/"$/, "")
|
|
14
|
+
.replace(/\\"/g, '"')
|
|
15
|
+
.replace(/\\n/g, "\n")
|
|
16
|
+
.replace(/\\t/g, "\t");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function tokenizeLine(line = "") {
|
|
20
|
+
const tokens = [];
|
|
21
|
+
let cursor = 0;
|
|
22
|
+
while (cursor < line.length) {
|
|
23
|
+
while (cursor < line.length && /\s/.test(line[cursor])) {
|
|
24
|
+
cursor += 1;
|
|
25
|
+
}
|
|
26
|
+
if (cursor >= line.length) {
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
if (line[cursor] === "#") {
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (line[cursor] === '"') {
|
|
34
|
+
let token = '"';
|
|
35
|
+
cursor += 1;
|
|
36
|
+
let escaped = false;
|
|
37
|
+
while (cursor < line.length) {
|
|
38
|
+
const char = line[cursor];
|
|
39
|
+
token += char;
|
|
40
|
+
cursor += 1;
|
|
41
|
+
if (escaped) {
|
|
42
|
+
escaped = false;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (char === "\\") {
|
|
46
|
+
escaped = true;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (char === '"') {
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (!token.endsWith('"')) {
|
|
54
|
+
throw new Error("Unterminated quoted string.");
|
|
55
|
+
}
|
|
56
|
+
tokens.push(decodeQuoted(token));
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const start = cursor;
|
|
61
|
+
while (cursor < line.length && !/\s/.test(line[cursor])) {
|
|
62
|
+
cursor += 1;
|
|
63
|
+
}
|
|
64
|
+
tokens.push(line.slice(start, cursor));
|
|
65
|
+
}
|
|
66
|
+
return tokens;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function parseAction(tokens = [], lineNumber = 0) {
|
|
70
|
+
const type = normalizeString(tokens[0]).toLowerCase();
|
|
71
|
+
if (!SUPPORTED_ACTIONS.has(type)) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`Line ${lineNumber}: unsupported action '${type}'. Supported: ${[...SUPPORTED_ACTIONS].join(
|
|
74
|
+
", "
|
|
75
|
+
)}.`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (type === "goto") {
|
|
80
|
+
if (tokens.length < 2) {
|
|
81
|
+
throw new Error(`Line ${lineNumber}: action goto requires <url>.`);
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
type,
|
|
85
|
+
url: normalizeString(tokens[1]),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (type === "click") {
|
|
90
|
+
if (tokens.length < 2) {
|
|
91
|
+
throw new Error(`Line ${lineNumber}: action click requires <selector>.`);
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
type,
|
|
95
|
+
selector: normalizeString(tokens[1]),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (type === "fill") {
|
|
100
|
+
if (tokens.length < 3) {
|
|
101
|
+
throw new Error(`Line ${lineNumber}: action fill requires <selector> <text>.`);
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
type,
|
|
105
|
+
selector: normalizeString(tokens[1]),
|
|
106
|
+
text: normalizeString(tokens[2]),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (type === "wait") {
|
|
111
|
+
if (tokens.length < 2) {
|
|
112
|
+
throw new Error(`Line ${lineNumber}: action wait requires <ms>.`);
|
|
113
|
+
}
|
|
114
|
+
const ms = Number(tokens[1]);
|
|
115
|
+
if (!Number.isFinite(ms) || ms < 0) {
|
|
116
|
+
throw new Error(`Line ${lineNumber}: action wait requires non-negative milliseconds.`);
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
type,
|
|
120
|
+
ms: Math.floor(ms),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (type === "screenshot") {
|
|
125
|
+
return {
|
|
126
|
+
type,
|
|
127
|
+
path: normalizeString(tokens[1] || ""),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
throw new Error(`Line ${lineNumber}: unsupported action '${type}'.`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function parseScenarioDsl(content = "", { source = "" } = {}) {
|
|
135
|
+
const raw = String(content || "");
|
|
136
|
+
const lines = raw.split(/\r?\n/);
|
|
137
|
+
const spec = {
|
|
138
|
+
id: "",
|
|
139
|
+
startUrl: "",
|
|
140
|
+
tags: [],
|
|
141
|
+
actions: [],
|
|
142
|
+
source: normalizeString(source),
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
146
|
+
const lineNumber = index + 1;
|
|
147
|
+
const line = lines[index];
|
|
148
|
+
const trimmed = normalizeString(line);
|
|
149
|
+
if (!trimmed || trimmed.startsWith("#")) {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
let tokens;
|
|
154
|
+
try {
|
|
155
|
+
tokens = tokenizeLine(line);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw new Error(`Line ${lineNumber}: ${error.message}`);
|
|
158
|
+
}
|
|
159
|
+
if (tokens.length === 0) {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const command = normalizeString(tokens[0]).toLowerCase();
|
|
163
|
+
|
|
164
|
+
if (command === "scenario") {
|
|
165
|
+
if (tokens.length < 2) {
|
|
166
|
+
throw new Error(`Line ${lineNumber}: scenario requires <id>.`);
|
|
167
|
+
}
|
|
168
|
+
spec.id = normalizeString(tokens[1]);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (command === "start_url") {
|
|
173
|
+
if (tokens.length < 2) {
|
|
174
|
+
throw new Error(`Line ${lineNumber}: start_url requires <url>.`);
|
|
175
|
+
}
|
|
176
|
+
spec.startUrl = normalizeString(tokens[1]);
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (command === "tag") {
|
|
181
|
+
if (tokens.length < 2) {
|
|
182
|
+
throw new Error(`Line ${lineNumber}: tag requires <value>.`);
|
|
183
|
+
}
|
|
184
|
+
spec.tags.push(normalizeString(tokens[1]));
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (command === "action") {
|
|
189
|
+
const action = parseAction(tokens.slice(1), lineNumber);
|
|
190
|
+
spec.actions.push(action);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
throw new Error(`Line ${lineNumber}: unknown command '${command}'.`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return spec;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function validateScenarioSpec(spec = {}) {
|
|
201
|
+
const errors = [];
|
|
202
|
+
const id = normalizeString(spec.id);
|
|
203
|
+
if (!id) {
|
|
204
|
+
errors.push("scenario id is required.");
|
|
205
|
+
}
|
|
206
|
+
if (!Array.isArray(spec.actions) || spec.actions.length === 0) {
|
|
207
|
+
errors.push("at least one action is required.");
|
|
208
|
+
}
|
|
209
|
+
for (const action of spec.actions || []) {
|
|
210
|
+
if (!SUPPORTED_ACTIONS.has(normalizeString(action.type).toLowerCase())) {
|
|
211
|
+
errors.push(`unsupported action type: ${action.type}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
valid: errors.length === 0,
|
|
216
|
+
errors,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export async function parseScenarioFile(filePath = "") {
|
|
221
|
+
const normalizedPath = normalizeString(filePath);
|
|
222
|
+
if (!normalizedPath) {
|
|
223
|
+
throw new Error("scenario file path is required.");
|
|
224
|
+
}
|
|
225
|
+
const resolved = path.resolve(process.cwd(), normalizedPath);
|
|
226
|
+
const content = await fsp.readFile(resolved, "utf-8");
|
|
227
|
+
const spec = parseScenarioDsl(content, { source: resolved });
|
|
228
|
+
return {
|
|
229
|
+
spec,
|
|
230
|
+
filePath: resolved,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function renderScenarioTemplate({
|
|
235
|
+
scenarioId = "nightly_smoke",
|
|
236
|
+
startUrl = "https://example.com",
|
|
237
|
+
} = {}) {
|
|
238
|
+
const id = normalizeString(scenarioId) || "nightly_smoke";
|
|
239
|
+
const url = normalizeString(startUrl) || "https://example.com";
|
|
240
|
+
return `# Sentinelayer swarm scenario DSL
|
|
241
|
+
scenario "${id}"
|
|
242
|
+
start_url "${url}"
|
|
243
|
+
tag "smoke"
|
|
244
|
+
tag "runtime"
|
|
245
|
+
|
|
246
|
+
action goto "${url}"
|
|
247
|
+
action wait 500
|
|
248
|
+
action screenshot "${id}-home.png"
|
|
249
|
+
`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export async function writeScenarioTemplate({
|
|
253
|
+
scenarioId,
|
|
254
|
+
targetPath = ".",
|
|
255
|
+
outputFile = "",
|
|
256
|
+
startUrl = "https://example.com",
|
|
257
|
+
} = {}) {
|
|
258
|
+
const normalizedTargetPath = path.resolve(String(targetPath || "."));
|
|
259
|
+
const resolvedOutputFile = normalizeString(outputFile)
|
|
260
|
+
? path.resolve(normalizedTargetPath, outputFile)
|
|
261
|
+
: path.join(normalizedTargetPath, ".sentinelayer", "scenarios", `${scenarioId}.sls`);
|
|
262
|
+
const content = renderScenarioTemplate({
|
|
263
|
+
scenarioId,
|
|
264
|
+
startUrl,
|
|
265
|
+
});
|
|
266
|
+
await fsp.mkdir(path.dirname(resolvedOutputFile), { recursive: true });
|
|
267
|
+
await fsp.writeFile(resolvedOutputFile, `${content.trim()}\n`, "utf-8");
|
|
268
|
+
return {
|
|
269
|
+
filePath: resolvedOutputFile,
|
|
270
|
+
content,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
@@ -0,0 +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
|
+
|