sentinelayer-cli 0.4.5 → 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 (72) hide show
  1. package/README.md +16 -18
  2. package/package.json +7 -6
  3. package/src/agents/jules/config/definition.js +13 -62
  4. package/src/agents/jules/config/system-prompt.js +8 -1
  5. package/src/agents/jules/fix-cycle.js +12 -372
  6. package/src/agents/jules/loop.js +116 -26
  7. package/src/agents/jules/pulse.js +10 -327
  8. package/src/agents/jules/stream.js +13 -12
  9. package/src/agents/jules/swarm/orchestrator.js +3 -3
  10. package/src/agents/jules/swarm/sub-agent.js +6 -3
  11. package/src/agents/jules/tools/aidenid-email.js +189 -0
  12. package/src/agents/jules/tools/auth-audit.js +1187 -45
  13. package/src/agents/jules/tools/dispatch.js +25 -12
  14. package/src/agents/jules/tools/file-edit.js +2 -180
  15. package/src/agents/jules/tools/file-read.js +2 -100
  16. package/src/agents/jules/tools/glob.js +2 -168
  17. package/src/agents/jules/tools/grep.js +2 -228
  18. package/src/agents/jules/tools/path-guards.js +2 -161
  19. package/src/agents/jules/tools/runtime-audit.js +6 -2
  20. package/src/agents/jules/tools/shell.js +2 -383
  21. package/src/agents/persona-visuals.js +64 -0
  22. package/src/agents/shared-tools/dispatch-core.js +320 -0
  23. package/src/agents/shared-tools/file-edit.js +180 -0
  24. package/src/agents/shared-tools/file-read.js +100 -0
  25. package/src/agents/shared-tools/glob.js +168 -0
  26. package/src/agents/shared-tools/grep.js +228 -0
  27. package/src/agents/shared-tools/index.js +46 -0
  28. package/src/agents/shared-tools/path-guards.js +161 -0
  29. package/src/agents/shared-tools/shell.js +383 -0
  30. package/src/ai/aidenid.js +56 -7
  31. package/src/ai/client.js +45 -0
  32. package/src/ai/proxy.js +137 -0
  33. package/src/auth/gate.js +290 -16
  34. package/src/auth/http.js +450 -39
  35. package/src/auth/service.js +262 -47
  36. package/src/auth/session-store.js +475 -21
  37. package/src/cli.js +5 -0
  38. package/src/commands/audit.js +13 -8
  39. package/src/commands/auth.js +53 -9
  40. package/src/commands/omargate.js +10 -2
  41. package/src/commands/scan.js +10 -4
  42. package/src/commands/session.js +590 -0
  43. package/src/commands/spec.js +62 -0
  44. package/src/commands/watch.js +3 -2
  45. package/src/daemon/assignment-ledger.js +196 -0
  46. package/src/daemon/error-worker.js +599 -16
  47. package/src/daemon/fix-cycle.js +384 -0
  48. package/src/daemon/ingest-refresh.js +10 -9
  49. package/src/daemon/jira-lifecycle.js +135 -0
  50. package/src/daemon/pulse.js +327 -0
  51. package/src/daemon/scope-engine.js +1068 -0
  52. package/src/events/schema.js +190 -0
  53. package/src/interactive/index.js +18 -16
  54. package/src/legacy-cli.js +606 -37
  55. package/src/prompt/generator.js +19 -1
  56. package/src/review/ai-review.js +11 -1
  57. package/src/review/local-review.js +75 -19
  58. package/src/review/omargate-interactive.js +68 -0
  59. package/src/review/omargate-orchestrator.js +404 -0
  60. package/src/review/persona-prompts.js +296 -0
  61. package/src/review/scan-modes.js +48 -0
  62. package/src/scan/generator.js +1 -1
  63. package/src/session/agent-registry.js +352 -0
  64. package/src/session/daemon.js +801 -0
  65. package/src/session/paths.js +33 -0
  66. package/src/session/runtime-bridge.js +739 -0
  67. package/src/session/store.js +388 -0
  68. package/src/session/stream.js +325 -0
  69. package/src/spec/generator.js +100 -0
  70. package/src/telemetry/session-tracker.js +148 -32
  71. package/src/telemetry/sync.js +6 -2
  72. package/src/ui/command-hints.js +13 -0
@@ -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
+ };