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
@@ -0,0 +1,739 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+ import process from "node:process";
5
+
6
+ import { createAgentEvent } from "../events/schema.js";
7
+ import { resolveSessionPaths } from "./paths.js";
8
+ import { appendToStream } from "./stream.js";
9
+
10
+ const RUNTIME_BRIDGE_AGENT_ID = "runtime-bridge";
11
+ const DEFAULT_HEARTBEAT_MS = 30_000;
12
+
13
+ const STOP_CLASSES = Object.freeze([
14
+ "clean",
15
+ "budget_exhausted",
16
+ "blocked_by_policy",
17
+ "awaiting_hitl",
18
+ "infra_error",
19
+ "validation_error",
20
+ "manual_stop",
21
+ ]);
22
+
23
+ const ACTIVE_RUNTIME_RUNS = new Map();
24
+
25
+ function normalizeString(value) {
26
+ return String(value || "").trim();
27
+ }
28
+
29
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
30
+ const normalized = normalizeString(value);
31
+ if (!normalized) {
32
+ return fallbackIso;
33
+ }
34
+ const epoch = Date.parse(normalized);
35
+ if (!Number.isFinite(epoch)) {
36
+ return fallbackIso;
37
+ }
38
+ return new Date(epoch).toISOString();
39
+ }
40
+
41
+ function normalizeNonNegativeNumber(value, fallbackValue = 0) {
42
+ const normalized = Number(value);
43
+ if (!Number.isFinite(normalized) || normalized < 0) {
44
+ return fallbackValue;
45
+ }
46
+ return normalized;
47
+ }
48
+
49
+ function normalizePositiveInteger(value, fallbackValue = 1) {
50
+ const normalized = Number(value);
51
+ if (!Number.isFinite(normalized) || normalized <= 0) {
52
+ return fallbackValue;
53
+ }
54
+ return Math.max(1, Math.floor(normalized));
55
+ }
56
+
57
+ function normalizeStringArray(values) {
58
+ if (!Array.isArray(values)) {
59
+ return [];
60
+ }
61
+ const deduped = new Set();
62
+ for (const value of values) {
63
+ const normalized = normalizeString(value);
64
+ if (normalized) {
65
+ deduped.add(normalized);
66
+ }
67
+ }
68
+ return [...deduped];
69
+ }
70
+
71
+ function escapeRegex(value) {
72
+ return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
73
+ }
74
+
75
+ function wildcardToRegex(pattern) {
76
+ const escaped = escapeRegex(pattern);
77
+ const withDoubleWildcard = escaped.replace(/\\\*\\\*/g, ".*");
78
+ const withSingleWildcard = withDoubleWildcard.replace(/\\\*/g, "[^/]*");
79
+ return new RegExp(`^${withSingleWildcard}$`, "i");
80
+ }
81
+
82
+ function matchWildcard(value, patterns = []) {
83
+ const normalizedValue = normalizeString(value).replace(/\\/g, "/");
84
+ if (!normalizedValue) {
85
+ return false;
86
+ }
87
+ return patterns.some((pattern) => {
88
+ const normalizedPattern = normalizeString(pattern).replace(/\\/g, "/");
89
+ if (!normalizedPattern) {
90
+ return false;
91
+ }
92
+ return wildcardToRegex(normalizedPattern).test(normalizedValue);
93
+ });
94
+ }
95
+
96
+ function buildRuntimeRunKey(sessionId, runId, targetPath) {
97
+ return `${path.resolve(String(targetPath || "."))}::${normalizeString(sessionId)}::${normalizeString(runId)}`;
98
+ }
99
+
100
+ function normalizeScopeEnvelope(scopeEnvelope = {}) {
101
+ const normalized = scopeEnvelope && typeof scopeEnvelope === "object" && !Array.isArray(scopeEnvelope)
102
+ ? { ...scopeEnvelope }
103
+ : {};
104
+ const allowedTools = normalizeStringArray(normalized.allowedTools || normalized.allowed_tools || []);
105
+ const allowedPaths = normalizeStringArray(normalized.allowedPaths || normalized.allowed_paths || []);
106
+ const deniedPaths = normalizeStringArray(normalized.deniedPaths || normalized.denied_paths || []);
107
+
108
+ if (allowedTools.length === 0) {
109
+ throw new Error("scopeEnvelope.allowedTools (or allowed_tools) must include at least one tool.");
110
+ }
111
+
112
+ return {
113
+ allowedTools,
114
+ allowedPaths,
115
+ deniedPaths,
116
+ };
117
+ }
118
+
119
+ function normalizeBudgetEnvelope(budgetEnvelope = {}) {
120
+ const normalized = budgetEnvelope && typeof budgetEnvelope === "object" && !Array.isArray(budgetEnvelope)
121
+ ? { ...budgetEnvelope }
122
+ : {};
123
+ const maxTokens = normalizePositiveInteger(
124
+ normalized.maxTokens ?? normalized.max_tokens,
125
+ 1
126
+ );
127
+ const maxCostUsd = normalizeNonNegativeNumber(
128
+ normalized.maxCostUsd ?? normalized.max_cost_usd,
129
+ 0
130
+ );
131
+ const maxRuntimeMinutes = normalizePositiveInteger(
132
+ normalized.maxRuntimeMinutes ?? normalized.max_runtime_minutes,
133
+ 1
134
+ );
135
+ const maxToolCalls = normalizePositiveInteger(
136
+ normalized.maxToolCalls ?? normalized.max_tool_calls,
137
+ 1
138
+ );
139
+ const networkDomainAllowlist = normalizeStringArray(
140
+ normalized.networkDomainAllowlist ?? normalized.network_domain_allowlist ?? []
141
+ );
142
+
143
+ if (maxCostUsd <= 0) {
144
+ throw new Error("budgetEnvelope.maxCostUsd (or max_cost_usd) must be > 0.");
145
+ }
146
+
147
+ return {
148
+ maxTokens,
149
+ maxCostUsd,
150
+ maxRuntimeMinutes,
151
+ maxToolCalls,
152
+ networkDomainAllowlist,
153
+ };
154
+ }
155
+
156
+ function createInitialUsage(nowIso) {
157
+ return {
158
+ tokensUsed: 0,
159
+ costUsd: 0,
160
+ runtimeMs: 0,
161
+ toolCalls: 0,
162
+ pathOutOfScopeHits: 0,
163
+ networkDomainViolations: 0,
164
+ lastHeartbeatAt: normalizeIsoTimestamp(nowIso, nowIso),
165
+ };
166
+ }
167
+
168
+ function copyUsage(usage = {}, fallbackIso = new Date().toISOString()) {
169
+ return {
170
+ tokensUsed: normalizeNonNegativeNumber(usage.tokensUsed, 0),
171
+ costUsd: Number(normalizeNonNegativeNumber(usage.costUsd, 0).toFixed(6)),
172
+ runtimeMs: normalizeNonNegativeNumber(usage.runtimeMs, 0),
173
+ toolCalls: normalizeNonNegativeNumber(usage.toolCalls, 0),
174
+ pathOutOfScopeHits: normalizeNonNegativeNumber(usage.pathOutOfScopeHits, 0),
175
+ networkDomainViolations: normalizeNonNegativeNumber(usage.networkDomainViolations, 0),
176
+ lastHeartbeatAt: normalizeIsoTimestamp(usage.lastHeartbeatAt, fallbackIso),
177
+ };
178
+ }
179
+
180
+ function mergeUsage(stateUsage = {}, usageUpdate = {}, nowIso = new Date().toISOString()) {
181
+ const usage = copyUsage(stateUsage, nowIso);
182
+ const update = usageUpdate && typeof usageUpdate === "object" && !Array.isArray(usageUpdate)
183
+ ? usageUpdate
184
+ : {};
185
+ const delta = update.delta && typeof update.delta === "object" && !Array.isArray(update.delta)
186
+ ? update.delta
187
+ : {};
188
+
189
+ const absolutePairs = [
190
+ "tokensUsed",
191
+ "costUsd",
192
+ "runtimeMs",
193
+ "toolCalls",
194
+ "pathOutOfScopeHits",
195
+ "networkDomainViolations",
196
+ ];
197
+ for (const key of absolutePairs) {
198
+ if (update[key] !== undefined) {
199
+ usage[key] = Math.max(usage[key], normalizeNonNegativeNumber(update[key], usage[key]));
200
+ }
201
+ }
202
+ for (const key of absolutePairs) {
203
+ if (delta[key] !== undefined) {
204
+ usage[key] += normalizeNonNegativeNumber(delta[key], 0);
205
+ }
206
+ }
207
+
208
+ usage.costUsd = Number(normalizeNonNegativeNumber(usage.costUsd, 0).toFixed(6));
209
+ usage.lastHeartbeatAt = normalizeIsoTimestamp(
210
+ update.lastHeartbeatAt || update.last_heartbeat_at || nowIso,
211
+ nowIso
212
+ );
213
+ return usage;
214
+ }
215
+
216
+ function isPathInScope(candidatePath, scopeEnvelope = {}) {
217
+ const normalizedPath = normalizeString(candidatePath).replace(/\\/g, "/");
218
+ if (!normalizedPath) {
219
+ return true;
220
+ }
221
+ if (matchWildcard(normalizedPath, scopeEnvelope.deniedPaths)) {
222
+ return false;
223
+ }
224
+ if (!Array.isArray(scopeEnvelope.allowedPaths) || scopeEnvelope.allowedPaths.length === 0) {
225
+ return true;
226
+ }
227
+ return matchWildcard(normalizedPath, scopeEnvelope.allowedPaths);
228
+ }
229
+
230
+ function isDomainAllowed(candidateDomain, budgetEnvelope = {}) {
231
+ const normalizedDomain = normalizeString(candidateDomain).toLowerCase();
232
+ if (!normalizedDomain) {
233
+ return true;
234
+ }
235
+ if (
236
+ !Array.isArray(budgetEnvelope.networkDomainAllowlist) ||
237
+ budgetEnvelope.networkDomainAllowlist.length === 0
238
+ ) {
239
+ return true;
240
+ }
241
+ return budgetEnvelope.networkDomainAllowlist.some((allowedPattern) => {
242
+ const normalizedPattern = normalizeString(allowedPattern).toLowerCase();
243
+ if (!normalizedPattern) {
244
+ return false;
245
+ }
246
+ if (normalizedPattern.startsWith("*.")) {
247
+ const suffix = normalizedPattern.slice(1);
248
+ return normalizedDomain.endsWith(suffix);
249
+ }
250
+ return normalizedDomain === normalizedPattern;
251
+ });
252
+ }
253
+
254
+ function evaluateStopPredicate(runtimeState, nowIso) {
255
+ const usage = runtimeState.usage;
256
+ const budget = runtimeState.budgetEnvelope;
257
+ const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
258
+ const startedEpoch = Date.parse(normalizeIsoTimestamp(runtimeState.startedAt, nowIso));
259
+ const elapsedMs =
260
+ Number.isFinite(nowEpoch) && Number.isFinite(startedEpoch)
261
+ ? Math.max(0, nowEpoch - startedEpoch)
262
+ : usage.runtimeMs;
263
+ usage.runtimeMs = Math.max(usage.runtimeMs, elapsedMs);
264
+
265
+ if (usage.pathOutOfScopeHits >= 1) {
266
+ return {
267
+ shouldStop: true,
268
+ stopClass: "blocked_by_policy",
269
+ stopCode: "PATH_OUT_OF_SCOPE",
270
+ reason: "Path access attempted outside allowed scope envelope.",
271
+ };
272
+ }
273
+ if (usage.networkDomainViolations >= 1) {
274
+ return {
275
+ shouldStop: true,
276
+ stopClass: "blocked_by_policy",
277
+ stopCode: "NETWORK_DOMAIN_VIOLATION",
278
+ reason: "Network domain attempted outside allowlist.",
279
+ };
280
+ }
281
+ if (usage.tokensUsed >= budget.maxTokens) {
282
+ return {
283
+ shouldStop: true,
284
+ stopClass: "budget_exhausted",
285
+ stopCode: "MAX_TOKENS_EXCEEDED",
286
+ reason: "Token ceiling reached.",
287
+ };
288
+ }
289
+ if (usage.costUsd >= budget.maxCostUsd) {
290
+ return {
291
+ shouldStop: true,
292
+ stopClass: "budget_exhausted",
293
+ stopCode: "MAX_COST_EXCEEDED",
294
+ reason: "Cost ceiling reached.",
295
+ };
296
+ }
297
+ if (usage.runtimeMs >= budget.maxRuntimeMinutes * 60_000) {
298
+ return {
299
+ shouldStop: true,
300
+ stopClass: "budget_exhausted",
301
+ stopCode: "MAX_RUNTIME_EXCEEDED",
302
+ reason: "Runtime ceiling reached.",
303
+ };
304
+ }
305
+ if (usage.toolCalls >= budget.maxToolCalls) {
306
+ return {
307
+ shouldStop: true,
308
+ stopClass: "budget_exhausted",
309
+ stopCode: "MAX_TOOL_CALLS_EXCEEDED",
310
+ reason: "Tool-call ceiling reached.",
311
+ };
312
+ }
313
+ return {
314
+ shouldStop: false,
315
+ stopClass: "clean",
316
+ stopCode: "NONE",
317
+ reason: "",
318
+ };
319
+ }
320
+
321
+ function toRuntimeSnapshot(runtimeState) {
322
+ return {
323
+ sessionId: runtimeState.sessionId,
324
+ runId: runtimeState.runId,
325
+ workItemId: runtimeState.workItemId,
326
+ targetPath: runtimeState.targetPath,
327
+ startedAt: runtimeState.startedAt,
328
+ stoppedAt: runtimeState.stoppedAt,
329
+ running: runtimeState.running,
330
+ stopClass: runtimeState.stopClass,
331
+ stopCode: runtimeState.stopCode,
332
+ stopReason: runtimeState.stopReason,
333
+ scopeEnvelope: runtimeState.scopeEnvelope,
334
+ budgetEnvelope: runtimeState.budgetEnvelope,
335
+ usage: copyUsage(runtimeState.usage, runtimeState.startedAt),
336
+ runtimePath: runtimeState.runtimePath,
337
+ };
338
+ }
339
+
340
+ async function persistRuntimeState(runtimeState) {
341
+ const payload = {
342
+ schemaVersion: "1.0.0",
343
+ generatedAt: new Date().toISOString(),
344
+ ...toRuntimeSnapshot(runtimeState),
345
+ };
346
+ await fsp.mkdir(path.dirname(runtimeState.runtimePath), { recursive: true });
347
+ await fsp.writeFile(runtimeState.runtimePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
348
+ }
349
+
350
+ async function emitRuntimeEvent(
351
+ sessionId,
352
+ event,
353
+ payload = {},
354
+ { targetPath = process.cwd(), workItemId = "", nowIso = new Date().toISOString() } = {}
355
+ ) {
356
+ const envelope = createAgentEvent({
357
+ event,
358
+ agentId: RUNTIME_BRIDGE_AGENT_ID,
359
+ sessionId,
360
+ workItemId: normalizeString(workItemId) || undefined,
361
+ ts: normalizeIsoTimestamp(nowIso, new Date().toISOString()),
362
+ payload,
363
+ });
364
+ await appendToStream(sessionId, envelope, {
365
+ targetPath,
366
+ });
367
+ return envelope;
368
+ }
369
+
370
+ function clearHeartbeatTimer(runtimeState) {
371
+ if (runtimeState.heartbeatTimer) {
372
+ clearInterval(runtimeState.heartbeatTimer);
373
+ runtimeState.heartbeatTimer = null;
374
+ }
375
+ }
376
+
377
+ function resolveRuntimeState(sessionId, runId, targetPath) {
378
+ const key = buildRuntimeRunKey(sessionId, runId, targetPath);
379
+ const runtimeState = ACTIVE_RUNTIME_RUNS.get(key);
380
+ if (!runtimeState) {
381
+ throw new Error(`Runtime run '${normalizeString(runId)}' was not found in session '${normalizeString(sessionId)}'.`);
382
+ }
383
+ return runtimeState;
384
+ }
385
+
386
+ function validateStopClass(value) {
387
+ const normalized = normalizeString(value);
388
+ if (!STOP_CLASSES.includes(normalized)) {
389
+ throw new Error(`stopClass must be one of: ${STOP_CLASSES.join(", ")}.`);
390
+ }
391
+ return normalized;
392
+ }
393
+
394
+ function normalizePathAccesses(pathAccesses = []) {
395
+ if (!Array.isArray(pathAccesses)) {
396
+ return [];
397
+ }
398
+ return pathAccesses
399
+ .map((entry) => {
400
+ if (typeof entry === "string") {
401
+ return { path: normalizeString(entry) };
402
+ }
403
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
404
+ return null;
405
+ }
406
+ return {
407
+ path: normalizeString(entry.path || entry.file || entry.filePath),
408
+ };
409
+ })
410
+ .filter((entry) => entry && entry.path);
411
+ }
412
+
413
+ function normalizeNetworkDomains(networkDomains = []) {
414
+ if (!Array.isArray(networkDomains)) {
415
+ return [];
416
+ }
417
+ return networkDomains
418
+ .map((entry) => normalizeString(entry).toLowerCase())
419
+ .filter(Boolean);
420
+ }
421
+
422
+ export async function createRuntimeRun({
423
+ sessionId,
424
+ workItemId,
425
+ scopeEnvelope,
426
+ budgetEnvelope,
427
+ targetPath = ".",
428
+ runId = "",
429
+ autoHeartbeat = false,
430
+ heartbeatMs = DEFAULT_HEARTBEAT_MS,
431
+ } = {}) {
432
+ const normalizedSessionId = normalizeString(sessionId);
433
+ const normalizedWorkItemId = normalizeString(workItemId);
434
+ if (!normalizedSessionId) {
435
+ throw new Error("sessionId is required.");
436
+ }
437
+ if (!normalizedWorkItemId) {
438
+ throw new Error("workItemId is required.");
439
+ }
440
+
441
+ const normalizedScope = normalizeScopeEnvelope(scopeEnvelope);
442
+ const normalizedBudget = normalizeBudgetEnvelope(budgetEnvelope);
443
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
444
+ const normalizedRunId = normalizeString(runId) || `runtime-${randomUUID()}`;
445
+ const runtimeKey = buildRuntimeRunKey(normalizedSessionId, normalizedRunId, normalizedTargetPath);
446
+ if (ACTIVE_RUNTIME_RUNS.has(runtimeKey)) {
447
+ return toRuntimeSnapshot(ACTIVE_RUNTIME_RUNS.get(runtimeKey));
448
+ }
449
+
450
+ const nowIso = new Date().toISOString();
451
+ const sessionPaths = resolveSessionPaths(normalizedSessionId, {
452
+ targetPath: normalizedTargetPath,
453
+ });
454
+ const runtimePath = path.join(sessionPaths.runtimeRunsDir, `${normalizedRunId}.json`);
455
+ const runtimeState = {
456
+ sessionId: normalizedSessionId,
457
+ runId: normalizedRunId,
458
+ workItemId: normalizedWorkItemId,
459
+ targetPath: normalizedTargetPath,
460
+ startedAt: nowIso,
461
+ stoppedAt: null,
462
+ running: true,
463
+ stopClass: "clean",
464
+ stopCode: "NONE",
465
+ stopReason: "",
466
+ usage: createInitialUsage(nowIso),
467
+ scopeEnvelope: normalizedScope,
468
+ budgetEnvelope: normalizedBudget,
469
+ runtimePath,
470
+ heartbeatTimer: null,
471
+ };
472
+
473
+ ACTIVE_RUNTIME_RUNS.set(runtimeKey, runtimeState);
474
+ await persistRuntimeState(runtimeState);
475
+ await emitRuntimeEvent(
476
+ normalizedSessionId,
477
+ "runtime_run_started",
478
+ {
479
+ runId: normalizedRunId,
480
+ workItemId: normalizedWorkItemId,
481
+ scopeEnvelope: normalizedScope,
482
+ budgetEnvelope: normalizedBudget,
483
+ stopClass: "clean",
484
+ stopCode: "NONE",
485
+ },
486
+ {
487
+ targetPath: normalizedTargetPath,
488
+ workItemId: normalizedWorkItemId,
489
+ nowIso,
490
+ }
491
+ );
492
+
493
+ if (autoHeartbeat) {
494
+ const intervalMs = normalizePositiveInteger(heartbeatMs, DEFAULT_HEARTBEAT_MS);
495
+ runtimeState.heartbeatTimer = setInterval(() => {
496
+ void heartbeatRuntimeRun(normalizedSessionId, normalizedRunId, {
497
+ targetPath: normalizedTargetPath,
498
+ }).catch(() => {});
499
+ }, intervalMs);
500
+ if (typeof runtimeState.heartbeatTimer.unref === "function") {
501
+ runtimeState.heartbeatTimer.unref();
502
+ }
503
+ }
504
+
505
+ return toRuntimeSnapshot(runtimeState);
506
+ }
507
+
508
+ export async function heartbeatRuntimeRun(
509
+ sessionId,
510
+ runId,
511
+ {
512
+ targetPath = ".",
513
+ nowIso = new Date().toISOString(),
514
+ usage = {},
515
+ pathAccesses = [],
516
+ networkDomains = [],
517
+ } = {}
518
+ ) {
519
+ const normalizedSessionId = normalizeString(sessionId);
520
+ const normalizedRunId = normalizeString(runId);
521
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
522
+ const runtimeState = resolveRuntimeState(normalizedSessionId, normalizedRunId, normalizedTargetPath);
523
+ if (!runtimeState.running) {
524
+ return toRuntimeSnapshot(runtimeState);
525
+ }
526
+
527
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
528
+ const normalizedPathAccesses = normalizePathAccesses(pathAccesses);
529
+ const normalizedDomains = normalizeNetworkDomains(networkDomains);
530
+
531
+ for (const access of normalizedPathAccesses) {
532
+ if (!isPathInScope(access.path, runtimeState.scopeEnvelope)) {
533
+ runtimeState.usage.pathOutOfScopeHits += 1;
534
+ }
535
+ }
536
+ for (const domain of normalizedDomains) {
537
+ if (!isDomainAllowed(domain, runtimeState.budgetEnvelope)) {
538
+ runtimeState.usage.networkDomainViolations += 1;
539
+ }
540
+ }
541
+
542
+ runtimeState.usage = mergeUsage(runtimeState.usage, usage, normalizedNow);
543
+ const predicate = evaluateStopPredicate(runtimeState, normalizedNow);
544
+ if (predicate.shouldStop) {
545
+ runtimeState.running = false;
546
+ runtimeState.stoppedAt = normalizedNow;
547
+ runtimeState.stopClass = validateStopClass(predicate.stopClass);
548
+ runtimeState.stopCode = normalizeString(predicate.stopCode) || "STOP_TRIGGERED";
549
+ runtimeState.stopReason = normalizeString(predicate.reason) || "Runtime stop predicate triggered.";
550
+ clearHeartbeatTimer(runtimeState);
551
+ await persistRuntimeState(runtimeState);
552
+ await emitRuntimeEvent(
553
+ normalizedSessionId,
554
+ "runtime_run_stop",
555
+ {
556
+ runId: runtimeState.runId,
557
+ workItemId: runtimeState.workItemId,
558
+ stopClass: runtimeState.stopClass,
559
+ stopCode: runtimeState.stopCode,
560
+ reason: runtimeState.stopReason,
561
+ usage: copyUsage(runtimeState.usage, normalizedNow),
562
+ },
563
+ {
564
+ targetPath: normalizedTargetPath,
565
+ workItemId: runtimeState.workItemId,
566
+ nowIso: normalizedNow,
567
+ }
568
+ );
569
+ return toRuntimeSnapshot(runtimeState);
570
+ }
571
+
572
+ await persistRuntimeState(runtimeState);
573
+ await emitRuntimeEvent(
574
+ normalizedSessionId,
575
+ "runtime_run_heartbeat",
576
+ {
577
+ runId: runtimeState.runId,
578
+ workItemId: runtimeState.workItemId,
579
+ usage: copyUsage(runtimeState.usage, normalizedNow),
580
+ predicateState: {
581
+ pathOutOfScopeHits: runtimeState.usage.pathOutOfScopeHits,
582
+ networkDomainViolations: runtimeState.usage.networkDomainViolations,
583
+ },
584
+ },
585
+ {
586
+ targetPath: normalizedTargetPath,
587
+ workItemId: runtimeState.workItemId,
588
+ nowIso: normalizedNow,
589
+ }
590
+ );
591
+ return toRuntimeSnapshot(runtimeState);
592
+ }
593
+
594
+ export async function stopRuntimeRun(
595
+ sessionId,
596
+ runId,
597
+ {
598
+ targetPath = ".",
599
+ reason = "manual_stop",
600
+ nowIso = new Date().toISOString(),
601
+ } = {}
602
+ ) {
603
+ const normalizedSessionId = normalizeString(sessionId);
604
+ const normalizedRunId = normalizeString(runId);
605
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
606
+ const runtimeState = resolveRuntimeState(normalizedSessionId, normalizedRunId, normalizedTargetPath);
607
+ if (!runtimeState.running) {
608
+ return toRuntimeSnapshot(runtimeState);
609
+ }
610
+
611
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
612
+ runtimeState.running = false;
613
+ runtimeState.stoppedAt = normalizedNow;
614
+ runtimeState.stopClass = "manual_stop";
615
+ runtimeState.stopCode = "MANUAL_STOP";
616
+ runtimeState.stopReason = normalizeString(reason) || "Runtime run manually stopped.";
617
+ clearHeartbeatTimer(runtimeState);
618
+ await persistRuntimeState(runtimeState);
619
+ await emitRuntimeEvent(
620
+ normalizedSessionId,
621
+ "runtime_run_stop",
622
+ {
623
+ runId: runtimeState.runId,
624
+ workItemId: runtimeState.workItemId,
625
+ stopClass: runtimeState.stopClass,
626
+ stopCode: runtimeState.stopCode,
627
+ reason: runtimeState.stopReason,
628
+ usage: copyUsage(runtimeState.usage, normalizedNow),
629
+ },
630
+ {
631
+ targetPath: normalizedTargetPath,
632
+ workItemId: runtimeState.workItemId,
633
+ nowIso: normalizedNow,
634
+ }
635
+ );
636
+ return toRuntimeSnapshot(runtimeState);
637
+ }
638
+
639
+ export async function stopRuntimeRunsForSession(
640
+ sessionId,
641
+ {
642
+ targetPath = ".",
643
+ reason = "manual_stop",
644
+ nowIso = new Date().toISOString(),
645
+ } = {}
646
+ ) {
647
+ const normalizedSessionId = normalizeString(sessionId);
648
+ if (!normalizedSessionId) {
649
+ throw new Error("sessionId is required.");
650
+ }
651
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
652
+ const stoppedRuns = [];
653
+
654
+ for (const runtimeState of ACTIVE_RUNTIME_RUNS.values()) {
655
+ if (
656
+ runtimeState.sessionId !== normalizedSessionId ||
657
+ runtimeState.targetPath !== normalizedTargetPath ||
658
+ runtimeState.running !== true
659
+ ) {
660
+ continue;
661
+ }
662
+ const stopped = await stopRuntimeRun(normalizedSessionId, runtimeState.runId, {
663
+ targetPath: normalizedTargetPath,
664
+ reason,
665
+ nowIso,
666
+ });
667
+ stoppedRuns.push(stopped);
668
+ }
669
+
670
+ return {
671
+ sessionId: normalizedSessionId,
672
+ targetPath: normalizedTargetPath,
673
+ stoppedCount: stoppedRuns.length,
674
+ runs: stoppedRuns,
675
+ };
676
+ }
677
+
678
+ export function getRuntimeRun(
679
+ sessionId,
680
+ runId,
681
+ {
682
+ targetPath = ".",
683
+ } = {}
684
+ ) {
685
+ const normalizedSessionId = normalizeString(sessionId);
686
+ const normalizedRunId = normalizeString(runId);
687
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
688
+ const key = buildRuntimeRunKey(normalizedSessionId, normalizedRunId, normalizedTargetPath);
689
+ const runtimeState = ACTIVE_RUNTIME_RUNS.get(key);
690
+ return runtimeState ? toRuntimeSnapshot(runtimeState) : null;
691
+ }
692
+
693
+ export function listRuntimeRuns({
694
+ sessionId = "",
695
+ targetPath = ".",
696
+ includeStopped = true,
697
+ } = {}) {
698
+ const normalizedSessionId = normalizeString(sessionId);
699
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
700
+ const runs = [];
701
+ for (const runtimeState of ACTIVE_RUNTIME_RUNS.values()) {
702
+ if (runtimeState.targetPath !== normalizedTargetPath) {
703
+ continue;
704
+ }
705
+ if (normalizedSessionId && runtimeState.sessionId !== normalizedSessionId) {
706
+ continue;
707
+ }
708
+ if (!includeStopped && runtimeState.running !== true) {
709
+ continue;
710
+ }
711
+ runs.push(toRuntimeSnapshot(runtimeState));
712
+ }
713
+ runs.sort((left, right) => right.startedAt.localeCompare(left.startedAt));
714
+ return runs;
715
+ }
716
+
717
+ export function validateScopeEnvelope(scopeEnvelope = {}) {
718
+ try {
719
+ normalizeScopeEnvelope(scopeEnvelope);
720
+ return true;
721
+ } catch {
722
+ return false;
723
+ }
724
+ }
725
+
726
+ export function validateBudgetEnvelope(budgetEnvelope = {}) {
727
+ try {
728
+ normalizeBudgetEnvelope(budgetEnvelope);
729
+ return true;
730
+ } catch {
731
+ return false;
732
+ }
733
+ }
734
+
735
+ export {
736
+ DEFAULT_HEARTBEAT_MS,
737
+ RUNTIME_BRIDGE_AGENT_ID,
738
+ STOP_CLASSES,
739
+ };