sentinelayer-cli 0.6.2 → 0.8.1

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 (280) hide show
  1. package/README.md +1009 -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/ai-governance/index.js +12 -0
  7. package/src/agents/ai-governance/tools/base.js +171 -0
  8. package/src/agents/ai-governance/tools/eval-regression.js +47 -0
  9. package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
  10. package/src/agents/ai-governance/tools/index.js +52 -0
  11. package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
  12. package/src/agents/ai-governance/tools/provenance-check.js +69 -0
  13. package/src/agents/backend/index.js +12 -0
  14. package/src/agents/backend/tools/base.js +189 -0
  15. package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
  16. package/src/agents/backend/tools/idempotency-audit.js +105 -0
  17. package/src/agents/backend/tools/index.js +87 -0
  18. package/src/agents/backend/tools/retry-audit.js +132 -0
  19. package/src/agents/backend/tools/timeout-audit.js +144 -0
  20. package/src/agents/code-quality/index.js +12 -0
  21. package/src/agents/code-quality/tools/base.js +159 -0
  22. package/src/agents/code-quality/tools/complexity-measure.js +197 -0
  23. package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
  24. package/src/agents/code-quality/tools/cycle-detect.js +49 -0
  25. package/src/agents/code-quality/tools/dep-graph.js +196 -0
  26. package/src/agents/code-quality/tools/index.js +89 -0
  27. package/src/agents/data-layer/index.js +12 -0
  28. package/src/agents/data-layer/tools/base.js +181 -0
  29. package/src/agents/data-layer/tools/index-audit.js +165 -0
  30. package/src/agents/data-layer/tools/index.js +83 -0
  31. package/src/agents/data-layer/tools/migration-scan.js +135 -0
  32. package/src/agents/data-layer/tools/query-explain.js +120 -0
  33. package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
  34. package/src/agents/documentation/index.js +12 -0
  35. package/src/agents/documentation/tools/api-diff.js +91 -0
  36. package/src/agents/documentation/tools/base.js +151 -0
  37. package/src/agents/documentation/tools/dead-link-check.js +58 -0
  38. package/src/agents/documentation/tools/docstring-coverage.js +78 -0
  39. package/src/agents/documentation/tools/index.js +52 -0
  40. package/src/agents/documentation/tools/readme-freshness.js +61 -0
  41. package/src/agents/envelope/fix-cycle.js +45 -0
  42. package/src/agents/envelope/index.js +31 -0
  43. package/src/agents/envelope/loop.js +150 -0
  44. package/src/agents/envelope/pulse.js +18 -0
  45. package/src/agents/envelope/stream.js +40 -0
  46. package/src/agents/infrastructure/index.js +12 -0
  47. package/src/agents/infrastructure/tools/base.js +171 -0
  48. package/src/agents/infrastructure/tools/checkov-run.js +32 -0
  49. package/src/agents/infrastructure/tools/drift-detect.js +59 -0
  50. package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
  51. package/src/agents/infrastructure/tools/index.js +52 -0
  52. package/src/agents/infrastructure/tools/tflint-run.js +31 -0
  53. package/src/agents/jules/config/definition.js +160 -160
  54. package/src/agents/jules/config/system-prompt.js +182 -182
  55. package/src/agents/jules/error-intake.js +51 -51
  56. package/src/agents/jules/fix-cycle.js +17 -17
  57. package/src/agents/jules/loop.js +460 -450
  58. package/src/agents/jules/pulse.js +10 -10
  59. package/src/agents/jules/stream.js +187 -186
  60. package/src/agents/jules/swarm/file-scanner.js +74 -74
  61. package/src/agents/jules/swarm/index.js +11 -11
  62. package/src/agents/jules/swarm/orchestrator.js +362 -362
  63. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  64. package/src/agents/jules/swarm/sub-agent.js +315 -309
  65. package/src/agents/jules/tools/aidenid-email.js +189 -189
  66. package/src/agents/jules/tools/auth-audit.js +1708 -1691
  67. package/src/agents/jules/tools/dispatch.js +340 -335
  68. package/src/agents/jules/tools/file-edit.js +2 -2
  69. package/src/agents/jules/tools/file-read.js +2 -2
  70. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  71. package/src/agents/jules/tools/glob.js +2 -2
  72. package/src/agents/jules/tools/grep.js +2 -2
  73. package/src/agents/jules/tools/index.js +29 -29
  74. package/src/agents/jules/tools/path-guards.js +2 -2
  75. package/src/agents/jules/tools/runtime-audit.js +507 -507
  76. package/src/agents/jules/tools/shell.js +2 -2
  77. package/src/agents/jules/tools/url-policy.js +100 -100
  78. package/src/agents/mode.js +113 -0
  79. package/src/agents/observability/index.js +12 -0
  80. package/src/agents/observability/tools/alert-audit.js +39 -0
  81. package/src/agents/observability/tools/base.js +181 -0
  82. package/src/agents/observability/tools/dashboard-gap.js +42 -0
  83. package/src/agents/observability/tools/index.js +54 -0
  84. package/src/agents/observability/tools/log-schema-check.js +74 -0
  85. package/src/agents/observability/tools/span-coverage.js +74 -0
  86. package/src/agents/persona-visuals.js +102 -61
  87. package/src/agents/release/index.js +12 -0
  88. package/src/agents/release/tools/base.js +181 -0
  89. package/src/agents/release/tools/changelog-diff.js +86 -0
  90. package/src/agents/release/tools/feature-flag-audit.js +126 -0
  91. package/src/agents/release/tools/index.js +61 -0
  92. package/src/agents/release/tools/rollback-verify.js +129 -0
  93. package/src/agents/release/tools/semver-check.js +109 -0
  94. package/src/agents/reliability/index.js +12 -0
  95. package/src/agents/reliability/tools/backpressure-check.js +129 -0
  96. package/src/agents/reliability/tools/base.js +181 -0
  97. package/src/agents/reliability/tools/chaos-probe.js +109 -0
  98. package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
  99. package/src/agents/reliability/tools/health-check-audit.js +111 -0
  100. package/src/agents/reliability/tools/index.js +87 -0
  101. package/src/agents/run-persona.js +109 -0
  102. package/src/agents/security/index.js +12 -0
  103. package/src/agents/security/tools/authz-audit.js +134 -0
  104. package/src/agents/security/tools/base.js +190 -0
  105. package/src/agents/security/tools/crypto-review.js +175 -0
  106. package/src/agents/security/tools/index.js +97 -0
  107. package/src/agents/security/tools/sast-scan.js +175 -0
  108. package/src/agents/security/tools/secrets-scan.js +216 -0
  109. package/src/agents/shared-tools/dispatch-core.js +320 -315
  110. package/src/agents/shared-tools/file-edit.js +180 -180
  111. package/src/agents/shared-tools/file-read.js +100 -100
  112. package/src/agents/shared-tools/glob.js +168 -168
  113. package/src/agents/shared-tools/grep.js +228 -228
  114. package/src/agents/shared-tools/index.js +46 -46
  115. package/src/agents/shared-tools/path-guards.js +161 -161
  116. package/src/agents/shared-tools/shell.js +383 -383
  117. package/src/agents/supply-chain/index.js +12 -0
  118. package/src/agents/supply-chain/tools/attestation-check.js +42 -0
  119. package/src/agents/supply-chain/tools/base.js +151 -0
  120. package/src/agents/supply-chain/tools/index.js +52 -0
  121. package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
  122. package/src/agents/supply-chain/tools/package-verify.js +56 -0
  123. package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
  124. package/src/agents/testing/index.js +12 -0
  125. package/src/agents/testing/tools/base.js +202 -0
  126. package/src/agents/testing/tools/coverage-gap.js +144 -0
  127. package/src/agents/testing/tools/flake-detect.js +125 -0
  128. package/src/agents/testing/tools/index.js +85 -0
  129. package/src/agents/testing/tools/mutation-test.js +143 -0
  130. package/src/agents/testing/tools/snapshot-diff.js +103 -0
  131. package/src/ai/aidenid.js +1021 -1009
  132. package/src/ai/client.js +553 -553
  133. package/src/ai/domain-target-store.js +268 -268
  134. package/src/ai/identity-store.js +270 -270
  135. package/src/ai/proxy.js +137 -137
  136. package/src/ai/site-store.js +145 -145
  137. package/src/audit/agents/architecture.js +180 -180
  138. package/src/audit/agents/compliance.js +179 -179
  139. package/src/audit/agents/documentation.js +165 -165
  140. package/src/audit/agents/performance.js +145 -145
  141. package/src/audit/agents/security.js +215 -215
  142. package/src/audit/agents/testing.js +172 -172
  143. package/src/audit/orchestrator.js +557 -557
  144. package/src/audit/package.js +204 -204
  145. package/src/audit/registry.js +284 -284
  146. package/src/audit/replay.js +103 -103
  147. package/src/auth/gate.js +428 -371
  148. package/src/auth/http.js +681 -611
  149. package/src/auth/service.js +1106 -1106
  150. package/src/auth/session-store.js +813 -813
  151. package/src/cli.js +257 -252
  152. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  153. package/src/commands/ai/provision-governance.js +1272 -1272
  154. package/src/commands/ai/shared.js +147 -147
  155. package/src/commands/ai.js +11 -11
  156. package/src/commands/apply.js +12 -12
  157. package/src/commands/audit.js +1171 -1166
  158. package/src/commands/auth.js +419 -419
  159. package/src/commands/chat.js +184 -191
  160. package/src/commands/config.js +184 -184
  161. package/src/commands/cost.js +311 -311
  162. package/src/commands/daemon/core.js +850 -850
  163. package/src/commands/daemon/extended.js +1048 -1048
  164. package/src/commands/daemon/shared.js +213 -213
  165. package/src/commands/daemon.js +11 -11
  166. package/src/commands/guide.js +174 -174
  167. package/src/commands/ingest.js +58 -58
  168. package/src/commands/init.js +55 -55
  169. package/src/commands/legacy-args.js +20 -10
  170. package/src/commands/mcp.js +461 -461
  171. package/src/commands/omargate.js +63 -29
  172. package/src/commands/persona.js +65 -20
  173. package/src/commands/plugin.js +260 -260
  174. package/src/commands/policy.js +132 -132
  175. package/src/commands/prompt.js +238 -238
  176. package/src/commands/review.js +704 -704
  177. package/src/commands/scan.js +865 -872
  178. package/src/commands/session.js +1238 -0
  179. package/src/commands/spec.js +771 -716
  180. package/src/commands/swarm.js +651 -651
  181. package/src/commands/telemetry.js +202 -202
  182. package/src/commands/watch.js +511 -511
  183. package/src/config/agent-dictionary.js +182 -182
  184. package/src/config/io.js +56 -56
  185. package/src/config/paths.js +18 -18
  186. package/src/config/schema.js +55 -55
  187. package/src/config/service.js +184 -184
  188. package/src/coord/events-log.js +141 -0
  189. package/src/coord/handshake.js +719 -0
  190. package/src/coord/index.js +35 -0
  191. package/src/coord/paths.js +84 -0
  192. package/src/coord/priority.js +62 -0
  193. package/src/coord/tarjan.js +157 -0
  194. package/src/cost/budget.js +235 -235
  195. package/src/cost/history.js +188 -188
  196. package/src/cost/tokenizer.js +160 -0
  197. package/src/cost/tracker.js +232 -171
  198. package/src/daemon/artifact-lineage.js +896 -534
  199. package/src/daemon/assignment-ledger.js +1083 -770
  200. package/src/daemon/ast-drift.js +496 -0
  201. package/src/daemon/ast-parser-layer.js +258 -258
  202. package/src/daemon/budget-governor.js +633 -633
  203. package/src/daemon/callgraph-overlay.js +646 -646
  204. package/src/daemon/error-worker.js +1209 -626
  205. package/src/daemon/fix-cycle.js +384 -377
  206. package/src/daemon/hybrid-mapper.js +929 -929
  207. package/src/daemon/ingest-refresh.js +79 -11
  208. package/src/daemon/jira-lifecycle.js +767 -632
  209. package/src/daemon/operator-control.js +657 -657
  210. package/src/daemon/pulse.js +327 -327
  211. package/src/daemon/reliability-lane.js +471 -471
  212. package/src/daemon/scope-engine.js +1068 -0
  213. package/src/daemon/watchdog.js +971 -971
  214. package/src/events/schema.js +190 -0
  215. package/src/guide/generator.js +316 -316
  216. package/src/ingest/engine.js +933 -918
  217. package/src/ingest/ownership.js +380 -0
  218. package/src/interactive/index.js +97 -97
  219. package/src/legacy-cli.js +3228 -2994
  220. package/src/mcp/registry.js +695 -695
  221. package/src/memory/blackboard.js +301 -301
  222. package/src/memory/retrieval.js +581 -581
  223. package/src/orchestrator/kai-chen.js +126 -0
  224. package/src/plugin/manifest.js +553 -553
  225. package/src/policy/packs.js +144 -144
  226. package/src/prompt/generator.js +136 -118
  227. package/src/review/ai-review.js +672 -679
  228. package/src/review/compliance-pack.js +389 -0
  229. package/src/review/investor-dd-config.js +54 -0
  230. package/src/review/investor-dd-file-loop.js +303 -0
  231. package/src/review/investor-dd-file-router.js +406 -0
  232. package/src/review/investor-dd-html-report.js +233 -0
  233. package/src/review/investor-dd-notification.js +120 -0
  234. package/src/review/investor-dd-orchestrator.js +405 -0
  235. package/src/review/investor-dd-persona-runner.js +275 -0
  236. package/src/review/live-validator.js +253 -0
  237. package/src/review/local-review.js +1351 -1305
  238. package/src/review/omargate-interactive.js +68 -68
  239. package/src/review/omargate-orchestrator.js +492 -300
  240. package/src/review/persona-prompts.js +484 -296
  241. package/src/review/reconciliation-rules.js +329 -0
  242. package/src/review/replay.js +235 -235
  243. package/src/review/report.js +664 -664
  244. package/src/review/reproducibility-chain.js +136 -0
  245. package/src/review/scan-modes.js +147 -42
  246. package/src/review/spec-binding.js +487 -487
  247. package/src/scaffold/generator.js +67 -67
  248. package/src/scaffold/templates.js +150 -150
  249. package/src/scan/generator.js +418 -418
  250. package/src/scan/gh-secrets.js +107 -107
  251. package/src/session/agent-registry.js +359 -0
  252. package/src/session/analytics.js +479 -0
  253. package/src/session/daemon.js +1396 -0
  254. package/src/session/file-locks.js +666 -0
  255. package/src/session/paths.js +37 -0
  256. package/src/session/recap.js +567 -0
  257. package/src/session/redact.js +82 -0
  258. package/src/session/runtime-bridge.js +762 -0
  259. package/src/session/scoring.js +406 -0
  260. package/src/session/setup-guides.js +304 -0
  261. package/src/session/store.js +704 -0
  262. package/src/session/stream.js +333 -0
  263. package/src/session/sync.js +753 -0
  264. package/src/session/tasks.js +1054 -0
  265. package/src/session/templates.js +188 -0
  266. package/src/spec/generator.js +619 -519
  267. package/src/spec/regenerate.js +237 -237
  268. package/src/spec/templates.js +91 -91
  269. package/src/swarm/dashboard.js +247 -247
  270. package/src/swarm/factory.js +363 -363
  271. package/src/swarm/pentest.js +934 -934
  272. package/src/swarm/registry.js +419 -419
  273. package/src/swarm/report.js +158 -158
  274. package/src/swarm/runtime.js +569 -576
  275. package/src/swarm/scenario-dsl.js +272 -272
  276. package/src/telemetry/ledger.js +302 -302
  277. package/src/telemetry/session-tracker.js +234 -234
  278. package/src/telemetry/sync.js +203 -203
  279. package/src/ui/command-hints.js +13 -13
  280. package/src/ui/markdown.js +220 -220
@@ -0,0 +1,762 @@
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
+ // SSRF hardening (Phase G, 2026-04-17): empty allowlist is default-DENY,
236
+ // not default-allow. A runtime caller that forgot to set the allowlist
237
+ // should hit a block, not silently let all egress through. Private/
238
+ // loopback/metadata ranges are ALWAYS blocked regardless of allowlist.
239
+ const PRIVATE_OR_METADATA = [
240
+ /^localhost$/,
241
+ /^127\./,
242
+ /^0\./,
243
+ /^10\./,
244
+ /^172\.(1[6-9]|2\d|3[01])\./,
245
+ /^192\.168\./,
246
+ /^169\.254\./, // link-local + cloud metadata
247
+ /^::1$/,
248
+ /^fe80:/i,
249
+ /^fc00:/i,
250
+ /^fd00:/i,
251
+ ];
252
+ if (PRIVATE_OR_METADATA.some((re) => re.test(normalizedDomain))) {
253
+ return false;
254
+ }
255
+ if (
256
+ !Array.isArray(budgetEnvelope.networkDomainAllowlist) ||
257
+ budgetEnvelope.networkDomainAllowlist.length === 0
258
+ ) {
259
+ // Default-deny on empty allowlist. Callers MUST set a non-empty list
260
+ // to authorize egress. Opt-out via explicit `allowAllDomains: true`
261
+ // on the budget envelope (callers should be visible in code review).
262
+ return budgetEnvelope.allowAllDomains === true;
263
+ }
264
+ return budgetEnvelope.networkDomainAllowlist.some((allowedPattern) => {
265
+ const normalizedPattern = normalizeString(allowedPattern).toLowerCase();
266
+ if (!normalizedPattern) {
267
+ return false;
268
+ }
269
+ if (normalizedPattern.startsWith("*.")) {
270
+ const suffix = normalizedPattern.slice(1);
271
+ return normalizedDomain.endsWith(suffix);
272
+ }
273
+ return normalizedDomain === normalizedPattern;
274
+ });
275
+ }
276
+
277
+ function evaluateStopPredicate(runtimeState, nowIso) {
278
+ const usage = runtimeState.usage;
279
+ const budget = runtimeState.budgetEnvelope;
280
+ const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
281
+ const startedEpoch = Date.parse(normalizeIsoTimestamp(runtimeState.startedAt, nowIso));
282
+ const elapsedMs =
283
+ Number.isFinite(nowEpoch) && Number.isFinite(startedEpoch)
284
+ ? Math.max(0, nowEpoch - startedEpoch)
285
+ : usage.runtimeMs;
286
+ usage.runtimeMs = Math.max(usage.runtimeMs, elapsedMs);
287
+
288
+ if (usage.pathOutOfScopeHits >= 1) {
289
+ return {
290
+ shouldStop: true,
291
+ stopClass: "blocked_by_policy",
292
+ stopCode: "PATH_OUT_OF_SCOPE",
293
+ reason: "Path access attempted outside allowed scope envelope.",
294
+ };
295
+ }
296
+ if (usage.networkDomainViolations >= 1) {
297
+ return {
298
+ shouldStop: true,
299
+ stopClass: "blocked_by_policy",
300
+ stopCode: "NETWORK_DOMAIN_VIOLATION",
301
+ reason: "Network domain attempted outside allowlist.",
302
+ };
303
+ }
304
+ if (usage.tokensUsed >= budget.maxTokens) {
305
+ return {
306
+ shouldStop: true,
307
+ stopClass: "budget_exhausted",
308
+ stopCode: "MAX_TOKENS_EXCEEDED",
309
+ reason: "Token ceiling reached.",
310
+ };
311
+ }
312
+ if (usage.costUsd >= budget.maxCostUsd) {
313
+ return {
314
+ shouldStop: true,
315
+ stopClass: "budget_exhausted",
316
+ stopCode: "MAX_COST_EXCEEDED",
317
+ reason: "Cost ceiling reached.",
318
+ };
319
+ }
320
+ if (usage.runtimeMs >= budget.maxRuntimeMinutes * 60_000) {
321
+ return {
322
+ shouldStop: true,
323
+ stopClass: "budget_exhausted",
324
+ stopCode: "MAX_RUNTIME_EXCEEDED",
325
+ reason: "Runtime ceiling reached.",
326
+ };
327
+ }
328
+ if (usage.toolCalls >= budget.maxToolCalls) {
329
+ return {
330
+ shouldStop: true,
331
+ stopClass: "budget_exhausted",
332
+ stopCode: "MAX_TOOL_CALLS_EXCEEDED",
333
+ reason: "Tool-call ceiling reached.",
334
+ };
335
+ }
336
+ return {
337
+ shouldStop: false,
338
+ stopClass: "clean",
339
+ stopCode: "NONE",
340
+ reason: "",
341
+ };
342
+ }
343
+
344
+ function toRuntimeSnapshot(runtimeState) {
345
+ return {
346
+ sessionId: runtimeState.sessionId,
347
+ runId: runtimeState.runId,
348
+ workItemId: runtimeState.workItemId,
349
+ targetPath: runtimeState.targetPath,
350
+ startedAt: runtimeState.startedAt,
351
+ stoppedAt: runtimeState.stoppedAt,
352
+ running: runtimeState.running,
353
+ stopClass: runtimeState.stopClass,
354
+ stopCode: runtimeState.stopCode,
355
+ stopReason: runtimeState.stopReason,
356
+ scopeEnvelope: runtimeState.scopeEnvelope,
357
+ budgetEnvelope: runtimeState.budgetEnvelope,
358
+ usage: copyUsage(runtimeState.usage, runtimeState.startedAt),
359
+ runtimePath: runtimeState.runtimePath,
360
+ };
361
+ }
362
+
363
+ async function persistRuntimeState(runtimeState) {
364
+ const payload = {
365
+ schemaVersion: "1.0.0",
366
+ generatedAt: new Date().toISOString(),
367
+ ...toRuntimeSnapshot(runtimeState),
368
+ };
369
+ await fsp.mkdir(path.dirname(runtimeState.runtimePath), { recursive: true });
370
+ await fsp.writeFile(runtimeState.runtimePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
371
+ }
372
+
373
+ async function emitRuntimeEvent(
374
+ sessionId,
375
+ event,
376
+ payload = {},
377
+ { targetPath = process.cwd(), workItemId = "", nowIso = new Date().toISOString() } = {}
378
+ ) {
379
+ const envelope = createAgentEvent({
380
+ event,
381
+ agentId: RUNTIME_BRIDGE_AGENT_ID,
382
+ sessionId,
383
+ workItemId: normalizeString(workItemId) || undefined,
384
+ ts: normalizeIsoTimestamp(nowIso, new Date().toISOString()),
385
+ payload,
386
+ });
387
+ await appendToStream(sessionId, envelope, {
388
+ targetPath,
389
+ });
390
+ return envelope;
391
+ }
392
+
393
+ function clearHeartbeatTimer(runtimeState) {
394
+ if (runtimeState.heartbeatTimer) {
395
+ clearInterval(runtimeState.heartbeatTimer);
396
+ runtimeState.heartbeatTimer = null;
397
+ }
398
+ }
399
+
400
+ function resolveRuntimeState(sessionId, runId, targetPath) {
401
+ const key = buildRuntimeRunKey(sessionId, runId, targetPath);
402
+ const runtimeState = ACTIVE_RUNTIME_RUNS.get(key);
403
+ if (!runtimeState) {
404
+ throw new Error(`Runtime run '${normalizeString(runId)}' was not found in session '${normalizeString(sessionId)}'.`);
405
+ }
406
+ return runtimeState;
407
+ }
408
+
409
+ function validateStopClass(value) {
410
+ const normalized = normalizeString(value);
411
+ if (!STOP_CLASSES.includes(normalized)) {
412
+ throw new Error(`stopClass must be one of: ${STOP_CLASSES.join(", ")}.`);
413
+ }
414
+ return normalized;
415
+ }
416
+
417
+ function normalizePathAccesses(pathAccesses = []) {
418
+ if (!Array.isArray(pathAccesses)) {
419
+ return [];
420
+ }
421
+ return pathAccesses
422
+ .map((entry) => {
423
+ if (typeof entry === "string") {
424
+ return { path: normalizeString(entry) };
425
+ }
426
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
427
+ return null;
428
+ }
429
+ return {
430
+ path: normalizeString(entry.path || entry.file || entry.filePath),
431
+ };
432
+ })
433
+ .filter((entry) => entry && entry.path);
434
+ }
435
+
436
+ function normalizeNetworkDomains(networkDomains = []) {
437
+ if (!Array.isArray(networkDomains)) {
438
+ return [];
439
+ }
440
+ return networkDomains
441
+ .map((entry) => normalizeString(entry).toLowerCase())
442
+ .filter(Boolean);
443
+ }
444
+
445
+ export async function createRuntimeRun({
446
+ sessionId,
447
+ workItemId,
448
+ scopeEnvelope,
449
+ budgetEnvelope,
450
+ targetPath = ".",
451
+ runId = "",
452
+ autoHeartbeat = false,
453
+ heartbeatMs = DEFAULT_HEARTBEAT_MS,
454
+ } = {}) {
455
+ const normalizedSessionId = normalizeString(sessionId);
456
+ const normalizedWorkItemId = normalizeString(workItemId);
457
+ if (!normalizedSessionId) {
458
+ throw new Error("sessionId is required.");
459
+ }
460
+ if (!normalizedWorkItemId) {
461
+ throw new Error("workItemId is required.");
462
+ }
463
+
464
+ const normalizedScope = normalizeScopeEnvelope(scopeEnvelope);
465
+ const normalizedBudget = normalizeBudgetEnvelope(budgetEnvelope);
466
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
467
+ const normalizedRunId = normalizeString(runId) || `runtime-${randomUUID()}`;
468
+ const runtimeKey = buildRuntimeRunKey(normalizedSessionId, normalizedRunId, normalizedTargetPath);
469
+ if (ACTIVE_RUNTIME_RUNS.has(runtimeKey)) {
470
+ return toRuntimeSnapshot(ACTIVE_RUNTIME_RUNS.get(runtimeKey));
471
+ }
472
+
473
+ const nowIso = new Date().toISOString();
474
+ const sessionPaths = resolveSessionPaths(normalizedSessionId, {
475
+ targetPath: normalizedTargetPath,
476
+ });
477
+ const runtimePath = path.join(sessionPaths.runtimeRunsDir, `${normalizedRunId}.json`);
478
+ const runtimeState = {
479
+ sessionId: normalizedSessionId,
480
+ runId: normalizedRunId,
481
+ workItemId: normalizedWorkItemId,
482
+ targetPath: normalizedTargetPath,
483
+ startedAt: nowIso,
484
+ stoppedAt: null,
485
+ running: true,
486
+ stopClass: "clean",
487
+ stopCode: "NONE",
488
+ stopReason: "",
489
+ usage: createInitialUsage(nowIso),
490
+ scopeEnvelope: normalizedScope,
491
+ budgetEnvelope: normalizedBudget,
492
+ runtimePath,
493
+ heartbeatTimer: null,
494
+ };
495
+
496
+ ACTIVE_RUNTIME_RUNS.set(runtimeKey, runtimeState);
497
+ await persistRuntimeState(runtimeState);
498
+ await emitRuntimeEvent(
499
+ normalizedSessionId,
500
+ "runtime_run_started",
501
+ {
502
+ runId: normalizedRunId,
503
+ workItemId: normalizedWorkItemId,
504
+ scopeEnvelope: normalizedScope,
505
+ budgetEnvelope: normalizedBudget,
506
+ stopClass: "clean",
507
+ stopCode: "NONE",
508
+ },
509
+ {
510
+ targetPath: normalizedTargetPath,
511
+ workItemId: normalizedWorkItemId,
512
+ nowIso,
513
+ }
514
+ );
515
+
516
+ if (autoHeartbeat) {
517
+ const intervalMs = normalizePositiveInteger(heartbeatMs, DEFAULT_HEARTBEAT_MS);
518
+ runtimeState.heartbeatTimer = setInterval(() => {
519
+ void heartbeatRuntimeRun(normalizedSessionId, normalizedRunId, {
520
+ targetPath: normalizedTargetPath,
521
+ }).catch(() => {});
522
+ }, intervalMs);
523
+ if (typeof runtimeState.heartbeatTimer.unref === "function") {
524
+ runtimeState.heartbeatTimer.unref();
525
+ }
526
+ }
527
+
528
+ return toRuntimeSnapshot(runtimeState);
529
+ }
530
+
531
+ export async function heartbeatRuntimeRun(
532
+ sessionId,
533
+ runId,
534
+ {
535
+ targetPath = ".",
536
+ nowIso = new Date().toISOString(),
537
+ usage = {},
538
+ pathAccesses = [],
539
+ networkDomains = [],
540
+ } = {}
541
+ ) {
542
+ const normalizedSessionId = normalizeString(sessionId);
543
+ const normalizedRunId = normalizeString(runId);
544
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
545
+ const runtimeState = resolveRuntimeState(normalizedSessionId, normalizedRunId, normalizedTargetPath);
546
+ if (!runtimeState.running) {
547
+ return toRuntimeSnapshot(runtimeState);
548
+ }
549
+
550
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
551
+ const normalizedPathAccesses = normalizePathAccesses(pathAccesses);
552
+ const normalizedDomains = normalizeNetworkDomains(networkDomains);
553
+
554
+ for (const access of normalizedPathAccesses) {
555
+ if (!isPathInScope(access.path, runtimeState.scopeEnvelope)) {
556
+ runtimeState.usage.pathOutOfScopeHits += 1;
557
+ }
558
+ }
559
+ for (const domain of normalizedDomains) {
560
+ if (!isDomainAllowed(domain, runtimeState.budgetEnvelope)) {
561
+ runtimeState.usage.networkDomainViolations += 1;
562
+ }
563
+ }
564
+
565
+ runtimeState.usage = mergeUsage(runtimeState.usage, usage, normalizedNow);
566
+ const predicate = evaluateStopPredicate(runtimeState, normalizedNow);
567
+ if (predicate.shouldStop) {
568
+ runtimeState.running = false;
569
+ runtimeState.stoppedAt = normalizedNow;
570
+ runtimeState.stopClass = validateStopClass(predicate.stopClass);
571
+ runtimeState.stopCode = normalizeString(predicate.stopCode) || "STOP_TRIGGERED";
572
+ runtimeState.stopReason = normalizeString(predicate.reason) || "Runtime stop predicate triggered.";
573
+ clearHeartbeatTimer(runtimeState);
574
+ await persistRuntimeState(runtimeState);
575
+ await emitRuntimeEvent(
576
+ normalizedSessionId,
577
+ "runtime_run_stop",
578
+ {
579
+ runId: runtimeState.runId,
580
+ workItemId: runtimeState.workItemId,
581
+ stopClass: runtimeState.stopClass,
582
+ stopCode: runtimeState.stopCode,
583
+ reason: runtimeState.stopReason,
584
+ usage: copyUsage(runtimeState.usage, normalizedNow),
585
+ },
586
+ {
587
+ targetPath: normalizedTargetPath,
588
+ workItemId: runtimeState.workItemId,
589
+ nowIso: normalizedNow,
590
+ }
591
+ );
592
+ return toRuntimeSnapshot(runtimeState);
593
+ }
594
+
595
+ await persistRuntimeState(runtimeState);
596
+ await emitRuntimeEvent(
597
+ normalizedSessionId,
598
+ "runtime_run_heartbeat",
599
+ {
600
+ runId: runtimeState.runId,
601
+ workItemId: runtimeState.workItemId,
602
+ usage: copyUsage(runtimeState.usage, normalizedNow),
603
+ predicateState: {
604
+ pathOutOfScopeHits: runtimeState.usage.pathOutOfScopeHits,
605
+ networkDomainViolations: runtimeState.usage.networkDomainViolations,
606
+ },
607
+ },
608
+ {
609
+ targetPath: normalizedTargetPath,
610
+ workItemId: runtimeState.workItemId,
611
+ nowIso: normalizedNow,
612
+ }
613
+ );
614
+ return toRuntimeSnapshot(runtimeState);
615
+ }
616
+
617
+ export async function stopRuntimeRun(
618
+ sessionId,
619
+ runId,
620
+ {
621
+ targetPath = ".",
622
+ reason = "manual_stop",
623
+ nowIso = new Date().toISOString(),
624
+ } = {}
625
+ ) {
626
+ const normalizedSessionId = normalizeString(sessionId);
627
+ const normalizedRunId = normalizeString(runId);
628
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
629
+ const runtimeState = resolveRuntimeState(normalizedSessionId, normalizedRunId, normalizedTargetPath);
630
+ if (!runtimeState.running) {
631
+ return toRuntimeSnapshot(runtimeState);
632
+ }
633
+
634
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
635
+ runtimeState.running = false;
636
+ runtimeState.stoppedAt = normalizedNow;
637
+ runtimeState.stopClass = "manual_stop";
638
+ runtimeState.stopCode = "MANUAL_STOP";
639
+ runtimeState.stopReason = normalizeString(reason) || "Runtime run manually stopped.";
640
+ clearHeartbeatTimer(runtimeState);
641
+ await persistRuntimeState(runtimeState);
642
+ await emitRuntimeEvent(
643
+ normalizedSessionId,
644
+ "runtime_run_stop",
645
+ {
646
+ runId: runtimeState.runId,
647
+ workItemId: runtimeState.workItemId,
648
+ stopClass: runtimeState.stopClass,
649
+ stopCode: runtimeState.stopCode,
650
+ reason: runtimeState.stopReason,
651
+ usage: copyUsage(runtimeState.usage, normalizedNow),
652
+ },
653
+ {
654
+ targetPath: normalizedTargetPath,
655
+ workItemId: runtimeState.workItemId,
656
+ nowIso: normalizedNow,
657
+ }
658
+ );
659
+ return toRuntimeSnapshot(runtimeState);
660
+ }
661
+
662
+ export async function stopRuntimeRunsForSession(
663
+ sessionId,
664
+ {
665
+ targetPath = ".",
666
+ reason = "manual_stop",
667
+ nowIso = new Date().toISOString(),
668
+ } = {}
669
+ ) {
670
+ const normalizedSessionId = normalizeString(sessionId);
671
+ if (!normalizedSessionId) {
672
+ throw new Error("sessionId is required.");
673
+ }
674
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
675
+ const stoppedRuns = [];
676
+
677
+ for (const runtimeState of ACTIVE_RUNTIME_RUNS.values()) {
678
+ if (
679
+ runtimeState.sessionId !== normalizedSessionId ||
680
+ runtimeState.targetPath !== normalizedTargetPath ||
681
+ runtimeState.running !== true
682
+ ) {
683
+ continue;
684
+ }
685
+ const stopped = await stopRuntimeRun(normalizedSessionId, runtimeState.runId, {
686
+ targetPath: normalizedTargetPath,
687
+ reason,
688
+ nowIso,
689
+ });
690
+ stoppedRuns.push(stopped);
691
+ }
692
+
693
+ return {
694
+ sessionId: normalizedSessionId,
695
+ targetPath: normalizedTargetPath,
696
+ stoppedCount: stoppedRuns.length,
697
+ runs: stoppedRuns,
698
+ };
699
+ }
700
+
701
+ export function getRuntimeRun(
702
+ sessionId,
703
+ runId,
704
+ {
705
+ targetPath = ".",
706
+ } = {}
707
+ ) {
708
+ const normalizedSessionId = normalizeString(sessionId);
709
+ const normalizedRunId = normalizeString(runId);
710
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
711
+ const key = buildRuntimeRunKey(normalizedSessionId, normalizedRunId, normalizedTargetPath);
712
+ const runtimeState = ACTIVE_RUNTIME_RUNS.get(key);
713
+ return runtimeState ? toRuntimeSnapshot(runtimeState) : null;
714
+ }
715
+
716
+ export function listRuntimeRuns({
717
+ sessionId = "",
718
+ targetPath = ".",
719
+ includeStopped = true,
720
+ } = {}) {
721
+ const normalizedSessionId = normalizeString(sessionId);
722
+ const normalizedTargetPath = path.resolve(String(targetPath || "."));
723
+ const runs = [];
724
+ for (const runtimeState of ACTIVE_RUNTIME_RUNS.values()) {
725
+ if (runtimeState.targetPath !== normalizedTargetPath) {
726
+ continue;
727
+ }
728
+ if (normalizedSessionId && runtimeState.sessionId !== normalizedSessionId) {
729
+ continue;
730
+ }
731
+ if (!includeStopped && runtimeState.running !== true) {
732
+ continue;
733
+ }
734
+ runs.push(toRuntimeSnapshot(runtimeState));
735
+ }
736
+ runs.sort((left, right) => right.startedAt.localeCompare(left.startedAt));
737
+ return runs;
738
+ }
739
+
740
+ export function validateScopeEnvelope(scopeEnvelope = {}) {
741
+ try {
742
+ normalizeScopeEnvelope(scopeEnvelope);
743
+ return true;
744
+ } catch {
745
+ return false;
746
+ }
747
+ }
748
+
749
+ export function validateBudgetEnvelope(budgetEnvelope = {}) {
750
+ try {
751
+ normalizeBudgetEnvelope(budgetEnvelope);
752
+ return true;
753
+ } catch {
754
+ return false;
755
+ }
756
+ }
757
+
758
+ export {
759
+ DEFAULT_HEARTBEAT_MS,
760
+ RUNTIME_BRIDGE_AGENT_ID,
761
+ STOP_CLASSES,
762
+ };