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,753 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import process from "node:process";
5
+
6
+ import { resolveActiveAuthSession } from "../auth/service.js";
7
+ import { createAgentEvent } from "../events/schema.js";
8
+
9
+ const DEFAULT_API_BASE_URL = "https://api.sentinelayer.com";
10
+ const DEFAULT_SYNC_TIMEOUT_MS = 5_000;
11
+ const MAX_CONSECUTIVE_FAILURES = 3;
12
+ const CIRCUIT_RESET_MS = 60_000;
13
+ const SESSION_INGEST_LIMIT_PER_MINUTE = 500;
14
+ const HUMAN_MESSAGE_LIMIT_PER_MINUTE = 10;
15
+ const HUMAN_MESSAGE_MAX_LENGTH = 2_000;
16
+ const HUMAN_MESSAGE_FETCH_LIMIT = 50;
17
+
18
+ // Audit §2.9: crash-recovery contract for in-memory circuit state.
19
+ // Persist outbound/inbound circuit state to disk so a process restart
20
+ // doesn't drop an open circuit, causing thundering-herd retries against a
21
+ // still-degraded API. The on-disk envelope carries acquiredAt so that the
22
+ // hydrator can reject entries older than CIRCUIT_RESET_MS — after the
23
+ // reset window the circuit is considered closed regardless of persisted
24
+ // state. Write-through is best-effort; failure never blocks local CLI.
25
+ const CIRCUIT_STATE_FILE_DIR = ".sentinelayer";
26
+ const CIRCUIT_STATE_FILE_NAME = "circuit-state.json";
27
+ const CIRCUIT_STATE_SCHEMA_VERSION = "1.0.0";
28
+
29
+ function resolveCircuitStateFilePath(homeDir) {
30
+ const resolvedHome = path.resolve(String(homeDir || os.homedir()));
31
+ return path.join(resolvedHome, CIRCUIT_STATE_FILE_DIR, CIRCUIT_STATE_FILE_NAME);
32
+ }
33
+
34
+ function hydrateCircuitFromDisk(homeDir) {
35
+ try {
36
+ const filePath = resolveCircuitStateFilePath(homeDir);
37
+ const raw = fs.readFileSync(filePath, "utf-8");
38
+ const parsed = JSON.parse(raw);
39
+ if (!parsed || typeof parsed !== "object") {
40
+ return { outbound: null, inbound: null };
41
+ }
42
+ if (String(parsed.schemaVersion || "") !== CIRCUIT_STATE_SCHEMA_VERSION) {
43
+ return { outbound: null, inbound: null };
44
+ }
45
+ const nowMs = Date.now();
46
+ const reviveEntry = (entry) => {
47
+ if (!entry || typeof entry !== "object") return null;
48
+ const failures = Number(entry.consecutiveFailures || 0);
49
+ const openedAtMs = Number(entry.openedAtMs || 0);
50
+ if (!Number.isFinite(failures) || !Number.isFinite(openedAtMs)) return null;
51
+ if (failures < MAX_CONSECUTIVE_FAILURES) return null;
52
+ if (openedAtMs <= 0) return null;
53
+ if (nowMs - openedAtMs >= CIRCUIT_RESET_MS) return null;
54
+ return { consecutiveFailures: failures, openedAtMs };
55
+ };
56
+ return {
57
+ outbound: reviveEntry(parsed.outbound),
58
+ inbound: reviveEntry(parsed.inbound),
59
+ };
60
+ } catch {
61
+ return { outbound: null, inbound: null };
62
+ }
63
+ }
64
+
65
+ function persistCircuitState(homeDir) {
66
+ try {
67
+ const filePath = resolveCircuitStateFilePath(homeDir);
68
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
69
+ const payload = {
70
+ schemaVersion: CIRCUIT_STATE_SCHEMA_VERSION,
71
+ writtenAtMs: Date.now(),
72
+ writerPid: process.pid,
73
+ writerHostname: os.hostname(),
74
+ outbound: {
75
+ consecutiveFailures: outboundCircuit.consecutiveFailures,
76
+ openedAtMs: outboundCircuit.openedAtMs,
77
+ },
78
+ inbound: {
79
+ consecutiveFailures: inboundCircuit.consecutiveFailures,
80
+ openedAtMs: inboundCircuit.openedAtMs,
81
+ },
82
+ };
83
+ const tmpPath = `${filePath}.${process.pid}.tmp`;
84
+ fs.writeFileSync(tmpPath, JSON.stringify(payload), { encoding: "utf-8", mode: 0o600 });
85
+ fs.renameSync(tmpPath, filePath);
86
+ } catch {
87
+ // Best-effort only; local CLI must not crash on telemetry persistence.
88
+ }
89
+ }
90
+
91
+ const _hydrated = hydrateCircuitFromDisk();
92
+
93
+ const outboundCircuit = {
94
+ consecutiveFailures: _hydrated.outbound?.consecutiveFailures ?? 0,
95
+ openedAtMs: _hydrated.outbound?.openedAtMs ?? 0,
96
+ };
97
+
98
+ const inboundCircuit = {
99
+ consecutiveFailures: _hydrated.inbound?.consecutiveFailures ?? 0,
100
+ openedAtMs: _hydrated.inbound?.openedAtMs ?? 0,
101
+ };
102
+
103
+ const sessionIngestWindowBySessionId = new Map();
104
+ const humanRelayWindowBySessionId = new Map();
105
+
106
+ const SECRET_LIKE_PATTERN =
107
+ /(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]+PRIVATE KEY-----|SENTINELAYER_TOKEN|AIDENID_API_KEY|NPM_TOKEN|xox[baprs]-[A-Za-z0-9-]+)/i;
108
+
109
+ function normalizeString(value) {
110
+ return String(value || "").trim();
111
+ }
112
+
113
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
114
+ const normalized = normalizeString(value);
115
+ if (!normalized) {
116
+ return fallbackIso;
117
+ }
118
+ const epoch = Date.parse(normalized);
119
+ if (!Number.isFinite(epoch)) {
120
+ return fallbackIso;
121
+ }
122
+ return new Date(epoch).toISOString();
123
+ }
124
+
125
+ function normalizePositiveInteger(value, fallbackValue) {
126
+ const normalized = Number(value);
127
+ if (!Number.isFinite(normalized) || normalized <= 0) {
128
+ return fallbackValue;
129
+ }
130
+ return Math.floor(normalized);
131
+ }
132
+
133
+ // Session-apiUrl allowlist. A session file is an untrusted input: if an
134
+ // attacker can write to .sentinelayer/sessions/<id>/meta.json (or trick a user
135
+ // into joining a crafted session), they can redirect every outbound fetch.
136
+ // Hard-coded list + override via SENTINELAYER_API_ALLOWED_HOSTS.
137
+ const BUILTIN_API_ALLOWED_HOSTS = new Set([
138
+ "api.sentinelayer.com",
139
+ "api.staging.sentinelayer.com",
140
+ "localhost",
141
+ "127.0.0.1",
142
+ ]);
143
+
144
+ function resolveAllowedApiHosts() {
145
+ const extras = normalizeString(process.env.SENTINELAYER_API_ALLOWED_HOSTS || "");
146
+ const set = new Set(BUILTIN_API_ALLOWED_HOSTS);
147
+ if (extras) {
148
+ for (const host of extras.split(",")) {
149
+ const trimmed = host.trim().toLowerCase();
150
+ if (trimmed) set.add(trimmed);
151
+ }
152
+ }
153
+ return set;
154
+ }
155
+
156
+ function isApiHostAllowed(urlString) {
157
+ try {
158
+ const parsed = new URL(urlString);
159
+ if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
160
+ return false;
161
+ }
162
+ return resolveAllowedApiHosts().has(parsed.hostname.toLowerCase());
163
+ } catch {
164
+ return false;
165
+ }
166
+ }
167
+
168
+ function resolveApiBaseUrl(session = {}) {
169
+ const apiUrl = normalizeString(session.apiUrl) || DEFAULT_API_BASE_URL;
170
+ const normalized = apiUrl.replace(/\/+$/, "");
171
+ if (!isApiHostAllowed(normalized)) {
172
+ // Reject tampered session.apiUrl and fall back to the default.
173
+ // Caller will see API calls land on the canonical host, not an attacker's.
174
+ return DEFAULT_API_BASE_URL;
175
+ }
176
+ return normalized;
177
+ }
178
+
179
+ function isCircuitOpen(circuit, nowMs) {
180
+ if (!circuit || circuit.consecutiveFailures < MAX_CONSECUTIVE_FAILURES) {
181
+ return false;
182
+ }
183
+ const openedAtMs = Number(circuit.openedAtMs || 0);
184
+ if (!Number.isFinite(openedAtMs) || openedAtMs <= 0) {
185
+ return false;
186
+ }
187
+ if (nowMs - openedAtMs >= CIRCUIT_RESET_MS) {
188
+ circuit.consecutiveFailures = 0;
189
+ circuit.openedAtMs = 0;
190
+ return false;
191
+ }
192
+ return true;
193
+ }
194
+
195
+ function recordCircuitFailure(circuit, nowMs) {
196
+ if (!circuit) {
197
+ return;
198
+ }
199
+ circuit.consecutiveFailures += 1;
200
+ if (circuit.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
201
+ circuit.openedAtMs = nowMs;
202
+ }
203
+ persistCircuitState();
204
+ }
205
+
206
+ function recordCircuitSuccess(circuit) {
207
+ if (!circuit) {
208
+ return;
209
+ }
210
+ circuit.consecutiveFailures = 0;
211
+ circuit.openedAtMs = 0;
212
+ persistCircuitState();
213
+ }
214
+
215
+ // Test-only helper. Resets both circuits in memory AND on disk so unit
216
+ // tests that exercise hydration don't leak state across runs.
217
+ export function __resetCircuitStateForTests(homeDir) {
218
+ outboundCircuit.consecutiveFailures = 0;
219
+ outboundCircuit.openedAtMs = 0;
220
+ inboundCircuit.consecutiveFailures = 0;
221
+ inboundCircuit.openedAtMs = 0;
222
+ try {
223
+ const filePath = resolveCircuitStateFilePath(homeDir);
224
+ fs.rmSync(filePath, { force: true });
225
+ } catch {
226
+ // ignore
227
+ }
228
+ }
229
+
230
+ export function __hydrateCircuitStateFromDiskForTests(homeDir) {
231
+ const hydrated = hydrateCircuitFromDisk(homeDir);
232
+ outboundCircuit.consecutiveFailures = hydrated.outbound?.consecutiveFailures ?? 0;
233
+ outboundCircuit.openedAtMs = hydrated.outbound?.openedAtMs ?? 0;
234
+ inboundCircuit.consecutiveFailures = hydrated.inbound?.consecutiveFailures ?? 0;
235
+ inboundCircuit.openedAtMs = hydrated.inbound?.openedAtMs ?? 0;
236
+ }
237
+
238
+ function enforceRollingLimit(windowByKey, key, {
239
+ nowMs = Date.now(),
240
+ limit = 1,
241
+ windowMs = 60_000,
242
+ } = {}) {
243
+ const normalizedKey = normalizeString(key);
244
+ if (!normalizedKey) {
245
+ return {
246
+ allowed: true,
247
+ remaining: limit,
248
+ count: 0,
249
+ };
250
+ }
251
+
252
+ const existing = windowByKey.get(normalizedKey) || [];
253
+ const recent = existing.filter((ts) => Number.isFinite(ts) && ts >= nowMs - windowMs);
254
+ if (recent.length >= limit) {
255
+ windowByKey.set(normalizedKey, recent);
256
+ return {
257
+ allowed: false,
258
+ remaining: 0,
259
+ count: recent.length,
260
+ };
261
+ }
262
+
263
+ recent.push(nowMs);
264
+ windowByKey.set(normalizedKey, recent);
265
+ return {
266
+ allowed: true,
267
+ remaining: Math.max(0, limit - recent.length),
268
+ count: recent.length,
269
+ };
270
+ }
271
+
272
+ async function fetchWithTimeout(url, options, timeoutMs) {
273
+ const controller = new AbortController();
274
+ const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
275
+ if (typeof timeoutHandle.unref === "function") {
276
+ timeoutHandle.unref();
277
+ }
278
+ try {
279
+ return await fetch(url, {
280
+ ...options,
281
+ signal: controller.signal,
282
+ });
283
+ } finally {
284
+ clearTimeout(timeoutHandle);
285
+ }
286
+ }
287
+
288
+ function sanitizeHumanMessage(rawMessage) {
289
+ const stripped = String(rawMessage || "")
290
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "")
291
+ .replace(/\r/g, "")
292
+ .trim();
293
+ if (!stripped) {
294
+ return {
295
+ accepted: false,
296
+ reason: "empty_message",
297
+ message: "",
298
+ };
299
+ }
300
+ if (SECRET_LIKE_PATTERN.test(stripped)) {
301
+ return {
302
+ accepted: false,
303
+ reason: "secret_like_pattern",
304
+ message: "",
305
+ };
306
+ }
307
+ const truncated = stripped.length > HUMAN_MESSAGE_MAX_LENGTH
308
+ ? stripped.slice(0, HUMAN_MESSAGE_MAX_LENGTH)
309
+ : stripped;
310
+ return {
311
+ accepted: true,
312
+ reason: "",
313
+ message: truncated,
314
+ truncated: truncated.length < stripped.length,
315
+ };
316
+ }
317
+
318
+ function normalizeHumanMessageItems(payload) {
319
+ if (Array.isArray(payload)) {
320
+ return payload;
321
+ }
322
+ if (payload && typeof payload === "object") {
323
+ if (Array.isArray(payload.messages)) {
324
+ return payload.messages;
325
+ }
326
+ if (Array.isArray(payload.items)) {
327
+ return payload.items;
328
+ }
329
+ }
330
+ return [];
331
+ }
332
+
333
+ function extractCursor(payload, fallbackCursor) {
334
+ if (payload && typeof payload === "object") {
335
+ const explicit = normalizeString(payload.cursor || payload.nextCursor || payload.next_cursor);
336
+ if (explicit) {
337
+ return explicit;
338
+ }
339
+ }
340
+ return normalizeString(fallbackCursor) || null;
341
+ }
342
+
343
+ function buildHumanRelayEvent(sessionId, message = {}) {
344
+ const agentId =
345
+ normalizeString(message.agentId || message.authorId || message.senderId || "human-operator")
346
+ .toLowerCase()
347
+ .replace(/[^a-z0-9._-]+/g, "-")
348
+ .replace(/^-+|-+$/g, "") || "human-operator";
349
+ const messageId = normalizeString(message.id || message.messageId || message.message_id) || null;
350
+ const ts = normalizeIsoTimestamp(
351
+ message.ts || message.timestamp || message.createdAt || message.created_at,
352
+ new Date().toISOString()
353
+ );
354
+ const sanitization = sanitizeHumanMessage(message.message || message.text || message.body || "");
355
+ if (!sanitization.accepted) {
356
+ return {
357
+ accepted: false,
358
+ reason: sanitization.reason,
359
+ event: null,
360
+ messageId,
361
+ ts,
362
+ };
363
+ }
364
+ const event = createAgentEvent({
365
+ event: "session_message",
366
+ agentId,
367
+ sessionId,
368
+ ts,
369
+ payload: {
370
+ message: sanitization.message,
371
+ channel: "session",
372
+ source: "human",
373
+ priority: "high",
374
+ relayedFromApi: true,
375
+ messageId,
376
+ directive: normalizeString(message.directive || ""),
377
+ command: normalizeString(message.command || ""),
378
+ truncated: Boolean(sanitization.truncated),
379
+ },
380
+ });
381
+ return {
382
+ accepted: true,
383
+ reason: "",
384
+ event,
385
+ messageId,
386
+ ts,
387
+ };
388
+ }
389
+
390
+ /**
391
+ * Sync one local session event to sentinelayer-api.
392
+ * This function is best-effort and never throws.
393
+ */
394
+ export async function syncSessionEventToApi(
395
+ sessionId,
396
+ event,
397
+ {
398
+ targetPath = process.cwd(),
399
+ timeoutMs = DEFAULT_SYNC_TIMEOUT_MS,
400
+ resolveAuthSession = resolveActiveAuthSession,
401
+ fetchImpl = fetchWithTimeout,
402
+ nowMs = Date.now,
403
+ } = {}
404
+ ) {
405
+ const normalizedSessionId = normalizeString(sessionId);
406
+ if (!normalizedSessionId || !event || typeof event !== "object" || Array.isArray(event)) {
407
+ return { synced: false, reason: "invalid_input" };
408
+ }
409
+
410
+ const normalizedNowMs = Number(nowMs()) || Date.now();
411
+ if (isCircuitOpen(outboundCircuit, normalizedNowMs)) {
412
+ return { synced: false, reason: "circuit_breaker_open" };
413
+ }
414
+
415
+ const rateLimit = enforceRollingLimit(sessionIngestWindowBySessionId, normalizedSessionId, {
416
+ nowMs: normalizedNowMs,
417
+ limit: SESSION_INGEST_LIMIT_PER_MINUTE,
418
+ });
419
+ if (!rateLimit.allowed) {
420
+ return {
421
+ synced: false,
422
+ reason: "local_ingest_rate_limited",
423
+ limit: SESSION_INGEST_LIMIT_PER_MINUTE,
424
+ };
425
+ }
426
+
427
+ if (event?.payload?.relayedFromApi) {
428
+ return { synced: false, reason: "relay_event_skip" };
429
+ }
430
+
431
+ let session = null;
432
+ try {
433
+ session = await resolveAuthSession({
434
+ cwd: targetPath,
435
+ env: process.env,
436
+ autoRotate: false,
437
+ });
438
+ } catch {
439
+ return { synced: false, reason: "no_session" };
440
+ }
441
+
442
+ if (!session || !session.token) {
443
+ return { synced: false, reason: "not_authenticated" };
444
+ }
445
+
446
+ const apiBaseUrl = resolveApiBaseUrl(session);
447
+ const endpoint = `${apiBaseUrl}/api/v1/sessions/${encodeURIComponent(normalizedSessionId)}/events`;
448
+
449
+ try {
450
+ const response = await fetchImpl(
451
+ endpoint,
452
+ {
453
+ method: "POST",
454
+ headers: {
455
+ "Content-Type": "application/json",
456
+ Authorization: `Bearer ${session.token}`,
457
+ },
458
+ body: JSON.stringify({
459
+ event,
460
+ source: "cli",
461
+ }),
462
+ },
463
+ normalizePositiveInteger(timeoutMs, DEFAULT_SYNC_TIMEOUT_MS)
464
+ );
465
+
466
+ if (!response || !response.ok) {
467
+ recordCircuitFailure(outboundCircuit, normalizedNowMs);
468
+ return {
469
+ synced: false,
470
+ reason: `api_${response ? response.status : "no_response"}`,
471
+ };
472
+ }
473
+ recordCircuitSuccess(outboundCircuit);
474
+ return {
475
+ synced: true,
476
+ status: response.status,
477
+ };
478
+ } catch (error) {
479
+ recordCircuitFailure(outboundCircuit, normalizedNowMs);
480
+ return {
481
+ synced: false,
482
+ reason: normalizeString(error?.message) || "sync_failed",
483
+ };
484
+ }
485
+ }
486
+
487
+ async function syncSessionAuxPayload(
488
+ sessionId,
489
+ pathSuffix,
490
+ payload,
491
+ {
492
+ targetPath = process.cwd(),
493
+ timeoutMs = DEFAULT_SYNC_TIMEOUT_MS,
494
+ resolveAuthSession = resolveActiveAuthSession,
495
+ fetchImpl = fetchWithTimeout,
496
+ nowMs = Date.now,
497
+ } = {}
498
+ ) {
499
+ const normalizedSessionId = normalizeString(sessionId);
500
+ if (!normalizedSessionId || !pathSuffix || !payload || typeof payload !== "object" || Array.isArray(payload)) {
501
+ return { synced: false, reason: "invalid_input" };
502
+ }
503
+
504
+ const normalizedNowMs = Number(nowMs()) || Date.now();
505
+ if (isCircuitOpen(outboundCircuit, normalizedNowMs)) {
506
+ return { synced: false, reason: "circuit_breaker_open" };
507
+ }
508
+
509
+ const rateLimit = enforceRollingLimit(sessionIngestWindowBySessionId, normalizedSessionId, {
510
+ nowMs: normalizedNowMs,
511
+ limit: SESSION_INGEST_LIMIT_PER_MINUTE,
512
+ });
513
+ if (!rateLimit.allowed) {
514
+ return {
515
+ synced: false,
516
+ reason: "local_ingest_rate_limited",
517
+ limit: SESSION_INGEST_LIMIT_PER_MINUTE,
518
+ };
519
+ }
520
+
521
+ let session = null;
522
+ try {
523
+ session = await resolveAuthSession({
524
+ cwd: targetPath,
525
+ env: process.env,
526
+ autoRotate: false,
527
+ });
528
+ } catch {
529
+ return { synced: false, reason: "no_session" };
530
+ }
531
+ if (!session || !session.token) {
532
+ return { synced: false, reason: "not_authenticated" };
533
+ }
534
+
535
+ const apiBaseUrl = resolveApiBaseUrl(session);
536
+ const endpoint = `${apiBaseUrl}/api/v1/sessions/${encodeURIComponent(normalizedSessionId)}${pathSuffix}`;
537
+ try {
538
+ const response = await fetchImpl(
539
+ endpoint,
540
+ {
541
+ method: "POST",
542
+ headers: {
543
+ "Content-Type": "application/json",
544
+ Authorization: `Bearer ${session.token}`,
545
+ },
546
+ body: JSON.stringify({
547
+ ...payload,
548
+ source: "cli",
549
+ }),
550
+ },
551
+ normalizePositiveInteger(timeoutMs, DEFAULT_SYNC_TIMEOUT_MS)
552
+ );
553
+ if (!response || !response.ok) {
554
+ recordCircuitFailure(outboundCircuit, normalizedNowMs);
555
+ return {
556
+ synced: false,
557
+ reason: `api_${response ? response.status : "no_response"}`,
558
+ };
559
+ }
560
+ recordCircuitSuccess(outboundCircuit);
561
+ return {
562
+ synced: true,
563
+ status: response.status,
564
+ };
565
+ } catch (error) {
566
+ recordCircuitFailure(outboundCircuit, normalizedNowMs);
567
+ return {
568
+ synced: false,
569
+ reason: normalizeString(error?.message) || "sync_failed",
570
+ };
571
+ }
572
+ }
573
+
574
+ /**
575
+ * Sync local session metadata to sentinelayer-api for admin visibility.
576
+ * This function is best-effort and never throws.
577
+ */
578
+ export async function syncSessionMetadataToApi(sessionId, metadata, options = {}) {
579
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
580
+ return { synced: false, reason: "invalid_input" };
581
+ }
582
+ return syncSessionAuxPayload(sessionId, "/metadata", { metadata }, options);
583
+ }
584
+
585
+ /**
586
+ * Sync local session error envelopes to sentinelayer-api for admin visibility.
587
+ * This function is best-effort and never throws.
588
+ */
589
+ export async function syncSessionErrorToApi(sessionId, error, options = {}) {
590
+ if (!error || typeof error !== "object" || Array.isArray(error)) {
591
+ return { synced: false, reason: "invalid_input" };
592
+ }
593
+ return syncSessionAuxPayload(sessionId, "/errors", { error }, options);
594
+ }
595
+
596
+ /**
597
+ * Poll human messages for a session from sentinelayer-api and map them into
598
+ * canonical high-priority session events for local relay.
599
+ */
600
+ export async function pollHumanMessages(
601
+ sessionId,
602
+ {
603
+ targetPath = process.cwd(),
604
+ since = null,
605
+ timeoutMs = DEFAULT_SYNC_TIMEOUT_MS,
606
+ limit = HUMAN_MESSAGE_FETCH_LIMIT,
607
+ resolveAuthSession = resolveActiveAuthSession,
608
+ fetchImpl = fetchWithTimeout,
609
+ nowMs = Date.now,
610
+ } = {}
611
+ ) {
612
+ const normalizedSessionId = normalizeString(sessionId);
613
+ if (!normalizedSessionId) {
614
+ return {
615
+ ok: false,
616
+ reason: "invalid_session_id",
617
+ events: [],
618
+ cursor: normalizeString(since) || null,
619
+ };
620
+ }
621
+
622
+ const normalizedNowMs = Number(nowMs()) || Date.now();
623
+ if (isCircuitOpen(inboundCircuit, normalizedNowMs)) {
624
+ return {
625
+ ok: false,
626
+ reason: "circuit_breaker_open",
627
+ events: [],
628
+ cursor: normalizeString(since) || null,
629
+ };
630
+ }
631
+
632
+ let session = null;
633
+ try {
634
+ session = await resolveAuthSession({
635
+ cwd: targetPath,
636
+ env: process.env,
637
+ autoRotate: false,
638
+ });
639
+ } catch {
640
+ return {
641
+ ok: false,
642
+ reason: "no_session",
643
+ events: [],
644
+ cursor: normalizeString(since) || null,
645
+ };
646
+ }
647
+ if (!session || !session.token) {
648
+ return {
649
+ ok: false,
650
+ reason: "not_authenticated",
651
+ events: [],
652
+ cursor: normalizeString(since) || null,
653
+ };
654
+ }
655
+
656
+ const apiBaseUrl = resolveApiBaseUrl(session);
657
+ const query = new URLSearchParams();
658
+ const normalizedSince = normalizeString(since);
659
+ if (normalizedSince) {
660
+ query.set("since", normalizedSince);
661
+ }
662
+ query.set("limit", String(Math.max(1, Math.min(HUMAN_MESSAGE_FETCH_LIMIT, normalizePositiveInteger(limit, HUMAN_MESSAGE_FETCH_LIMIT)))));
663
+ const endpoint = `${apiBaseUrl}/api/v1/sessions/${encodeURIComponent(normalizedSessionId)}/human-messages?${query.toString()}`;
664
+
665
+ try {
666
+ const response = await fetchImpl(
667
+ endpoint,
668
+ {
669
+ method: "GET",
670
+ headers: {
671
+ Authorization: `Bearer ${session.token}`,
672
+ },
673
+ },
674
+ normalizePositiveInteger(timeoutMs, DEFAULT_SYNC_TIMEOUT_MS)
675
+ );
676
+ if (!response || !response.ok) {
677
+ recordCircuitFailure(inboundCircuit, normalizedNowMs);
678
+ return {
679
+ ok: false,
680
+ reason: `api_${response ? response.status : "no_response"}`,
681
+ events: [],
682
+ cursor: normalizedSince || null,
683
+ };
684
+ }
685
+ const payload = await response.json().catch(() => ({}));
686
+ recordCircuitSuccess(inboundCircuit);
687
+
688
+ const items = normalizeHumanMessageItems(payload);
689
+ const acceptedEvents = [];
690
+ const dropped = [];
691
+ let fallbackCursor = normalizedSince || null;
692
+ for (const item of items) {
693
+ const normalizedTs = normalizeIsoTimestamp(
694
+ item?.ts || item?.timestamp || item?.createdAt || item?.created_at,
695
+ fallbackCursor || new Date().toISOString()
696
+ );
697
+ fallbackCursor = normalizedTs;
698
+ const built = buildHumanRelayEvent(normalizedSessionId, item || {});
699
+ if (!built.accepted || !built.event) {
700
+ dropped.push({
701
+ messageId: built.messageId,
702
+ reason: built.reason || "rejected",
703
+ });
704
+ continue;
705
+ }
706
+ const localRate = enforceRollingLimit(humanRelayWindowBySessionId, normalizedSessionId, {
707
+ nowMs: normalizedNowMs,
708
+ limit: HUMAN_MESSAGE_LIMIT_PER_MINUTE,
709
+ });
710
+ if (!localRate.allowed) {
711
+ dropped.push({
712
+ messageId: built.messageId,
713
+ reason: "local_human_rate_limited",
714
+ });
715
+ continue;
716
+ }
717
+ acceptedEvents.push(built.event);
718
+ }
719
+
720
+ return {
721
+ ok: true,
722
+ reason: "",
723
+ events: acceptedEvents,
724
+ cursor: extractCursor(payload, fallbackCursor),
725
+ dropped,
726
+ };
727
+ } catch (error) {
728
+ recordCircuitFailure(inboundCircuit, normalizedNowMs);
729
+ return {
730
+ ok: false,
731
+ reason: normalizeString(error?.message) || "poll_failed",
732
+ events: [],
733
+ cursor: normalizedSince || null,
734
+ };
735
+ }
736
+ }
737
+
738
+ export function resetSessionSyncStateForTests() {
739
+ outboundCircuit.consecutiveFailures = 0;
740
+ outboundCircuit.openedAtMs = 0;
741
+ inboundCircuit.consecutiveFailures = 0;
742
+ inboundCircuit.openedAtMs = 0;
743
+ sessionIngestWindowBySessionId.clear();
744
+ humanRelayWindowBySessionId.clear();
745
+ }
746
+
747
+ export {
748
+ CIRCUIT_RESET_MS,
749
+ HUMAN_MESSAGE_LIMIT_PER_MINUTE,
750
+ HUMAN_MESSAGE_MAX_LENGTH,
751
+ MAX_CONSECUTIVE_FAILURES,
752
+ SESSION_INGEST_LIMIT_PER_MINUTE,
753
+ };