sentinelayer-cli 0.4.4 → 0.6.2

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 (149) hide show
  1. package/README.md +996 -998
  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 +63 -63
  6. package/src/agents/jules/config/definition.js +160 -209
  7. package/src/agents/jules/config/system-prompt.js +182 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -377
  10. package/src/agents/jules/loop.js +450 -367
  11. package/src/agents/jules/pulse.js +10 -327
  12. package/src/agents/jules/stream.js +186 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +309 -308
  18. package/src/agents/jules/tools/aidenid-email.js +189 -0
  19. package/src/agents/jules/tools/auth-audit.js +1691 -557
  20. package/src/agents/jules/tools/dispatch.js +335 -327
  21. package/src/agents/jules/tools/file-edit.js +2 -180
  22. package/src/agents/jules/tools/file-read.js +2 -100
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -168
  25. package/src/agents/jules/tools/grep.js +2 -228
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -161
  28. package/src/agents/jules/tools/runtime-audit.js +507 -503
  29. package/src/agents/jules/tools/shell.js +2 -383
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +61 -0
  32. package/src/agents/shared-tools/dispatch-core.js +315 -0
  33. package/src/agents/shared-tools/file-edit.js +180 -0
  34. package/src/agents/shared-tools/file-read.js +100 -0
  35. package/src/agents/shared-tools/glob.js +168 -0
  36. package/src/agents/shared-tools/grep.js +228 -0
  37. package/src/agents/shared-tools/index.js +46 -0
  38. package/src/agents/shared-tools/path-guards.js +161 -0
  39. package/src/agents/shared-tools/shell.js +383 -0
  40. package/src/ai/aidenid.js +1009 -972
  41. package/src/ai/client.js +553 -508
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -0
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +371 -126
  57. package/src/auth/http.js +611 -270
  58. package/src/auth/service.js +1106 -891
  59. package/src/auth/session-store.js +813 -359
  60. package/src/cli.js +252 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1166 -1166
  67. package/src/commands/auth.js +419 -375
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -21
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -866
  87. package/src/commands/spec.js +716 -716
  88. package/src/commands/swarm.js +651 -651
  89. package/src/commands/telemetry.js +202 -202
  90. package/src/commands/watch.js +511 -510
  91. package/src/config/agent-dictionary.js +182 -182
  92. package/src/config/io.js +56 -56
  93. package/src/config/paths.js +18 -18
  94. package/src/config/schema.js +55 -55
  95. package/src/config/service.js +184 -184
  96. package/src/cost/budget.js +235 -235
  97. package/src/cost/history.js +188 -188
  98. package/src/cost/tracker.js +171 -171
  99. package/src/daemon/artifact-lineage.js +534 -534
  100. package/src/daemon/assignment-ledger.js +770 -770
  101. package/src/daemon/ast-parser-layer.js +258 -258
  102. package/src/daemon/budget-governor.js +633 -633
  103. package/src/daemon/callgraph-overlay.js +646 -646
  104. package/src/daemon/error-worker.js +626 -626
  105. package/src/daemon/fix-cycle.js +377 -0
  106. package/src/daemon/hybrid-mapper.js +929 -929
  107. package/src/daemon/jira-lifecycle.js +632 -632
  108. package/src/daemon/operator-control.js +657 -657
  109. package/src/daemon/pulse.js +327 -0
  110. package/src/daemon/reliability-lane.js +471 -471
  111. package/src/daemon/watchdog.js +971 -971
  112. package/src/guide/generator.js +316 -316
  113. package/src/ingest/engine.js +918 -918
  114. package/src/interactive/index.js +97 -95
  115. package/src/legacy-cli.js +2994 -2592
  116. package/src/mcp/registry.js +695 -695
  117. package/src/memory/blackboard.js +301 -301
  118. package/src/memory/retrieval.js +581 -581
  119. package/src/plugin/manifest.js +553 -553
  120. package/src/policy/packs.js +144 -144
  121. package/src/prompt/generator.js +118 -118
  122. package/src/review/ai-review.js +679 -669
  123. package/src/review/local-review.js +1305 -1295
  124. package/src/review/omargate-interactive.js +68 -0
  125. package/src/review/omargate-orchestrator.js +300 -0
  126. package/src/review/persona-prompts.js +296 -0
  127. package/src/review/replay.js +235 -235
  128. package/src/review/report.js +664 -664
  129. package/src/review/scan-modes.js +42 -0
  130. package/src/review/spec-binding.js +487 -487
  131. package/src/scaffold/generator.js +67 -67
  132. package/src/scaffold/templates.js +150 -150
  133. package/src/scan/generator.js +418 -418
  134. package/src/scan/gh-secrets.js +107 -107
  135. package/src/spec/generator.js +519 -519
  136. package/src/spec/regenerate.js +237 -237
  137. package/src/spec/templates.js +91 -91
  138. package/src/swarm/dashboard.js +247 -247
  139. package/src/swarm/factory.js +363 -363
  140. package/src/swarm/pentest.js +934 -934
  141. package/src/swarm/registry.js +419 -419
  142. package/src/swarm/report.js +158 -158
  143. package/src/swarm/runtime.js +576 -576
  144. package/src/swarm/scenario-dsl.js +272 -272
  145. package/src/telemetry/ledger.js +302 -302
  146. package/src/telemetry/session-tracker.js +234 -118
  147. package/src/telemetry/sync.js +203 -199
  148. package/src/ui/command-hints.js +13 -0
  149. package/src/ui/markdown.js +220 -220
package/src/auth/http.js CHANGED
@@ -1,270 +1,611 @@
1
- import { setTimeout as sleep } from "node:timers/promises";
2
-
3
- /**
4
- * Default timeout applied to Sentinelayer API requests when no override is provided.
5
- * @type {number}
6
- */
7
- export const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
8
- export const DEFAULT_MAX_RETRIES = 2;
9
- export const DEFAULT_RETRY_DELAY_MS = 250;
10
- export const MAX_RETRY_DELAY_MS = 2_000;
11
- export const CIRCUIT_BREAKER_THRESHOLD = 5;
12
- export const CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;
13
-
14
- const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
15
- const CIRCUIT_TRACK_STATUS_CODES = new Set([401, 403, 408, 425, 429, 500, 502, 503, 504]);
16
- const circuitState = {
17
- consecutiveFailures: 0,
18
- openedAtMs: 0,
19
- };
20
-
21
- function normalizeApiError(errorPayload = {}) {
22
- if (!errorPayload || typeof errorPayload !== "object" || Array.isArray(errorPayload)) {
23
- return {
24
- code: "UNKNOWN",
25
- message: "Unknown API error",
26
- requestId: null,
27
- };
28
- }
29
- return {
30
- code: String(errorPayload.code || "UNKNOWN"),
31
- message: String(errorPayload.message || "Unknown API error"),
32
- requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
33
- };
34
- }
35
-
36
- export class SentinelayerApiError extends Error {
37
- /**
38
- * @param {string} message
39
- * @param {{ status?: number, code?: string, requestId?: string | null }} [options]
40
- */
41
- constructor(message, { status = 500, code = "UNKNOWN", requestId = null } = {}) {
42
- super(String(message || "Sentinelayer API error"));
43
- this.name = "SentinelayerApiError";
44
- this.status = Number(status || 500);
45
- this.code = String(code || "UNKNOWN");
46
- this.requestId = requestId ? String(requestId) : null;
47
- }
48
- }
49
-
50
- function normalizePositiveNumber(value, fallback) {
51
- const parsed = Number(value);
52
- if (!Number.isFinite(parsed) || parsed <= 0) {
53
- return fallback;
54
- }
55
- return parsed;
56
- }
57
-
58
- function normalizeNonNegativeInteger(value, fallback) {
59
- const parsed = Number(value);
60
- if (!Number.isFinite(parsed) || parsed < 0) {
61
- return fallback;
62
- }
63
- return Math.floor(parsed);
64
- }
65
-
66
- function parseRetryAfterMs(value) {
67
- const raw = String(value || "").trim();
68
- if (!raw) {
69
- return null;
70
- }
71
- const seconds = Number(raw);
72
- if (Number.isFinite(seconds) && seconds >= 0) {
73
- return Math.round(seconds * 1000);
74
- }
75
- const parsedDate = Date.parse(raw);
76
- if (Number.isFinite(parsedDate)) {
77
- const delta = parsedDate - Date.now();
78
- if (delta > 0) {
79
- return delta;
80
- }
81
- }
82
- return null;
83
- }
84
-
85
- function computeBackoffMs({ attempt, retryDelayMs, retryAfterHeader }) {
86
- const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
87
- if (retryAfterMs !== null) {
88
- return Math.min(retryAfterMs, MAX_RETRY_DELAY_MS);
89
- }
90
- const exponent = Math.max(0, Number(attempt) - 1);
91
- const computed = Math.round(retryDelayMs * Math.pow(2, exponent));
92
- return Math.min(Math.max(1, computed), MAX_RETRY_DELAY_MS);
93
- }
94
-
95
- function isCircuitOpen() {
96
- if (circuitState.openedAtMs <= 0) {
97
- return false;
98
- }
99
- if (Date.now() - circuitState.openedAtMs >= CIRCUIT_BREAKER_COOLDOWN_MS) {
100
- circuitState.openedAtMs = 0;
101
- circuitState.consecutiveFailures = 0;
102
- return false;
103
- }
104
- return true;
105
- }
106
-
107
- function recordFailureForCircuit() {
108
- circuitState.consecutiveFailures += 1;
109
- if (circuitState.consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) {
110
- circuitState.openedAtMs = Date.now();
111
- }
112
- }
113
-
114
- function recordSuccessForCircuit() {
115
- circuitState.consecutiveFailures = 0;
116
- circuitState.openedAtMs = 0;
117
- }
118
-
119
- function shouldRetryStatus(statusCode) {
120
- return RETRYABLE_STATUS_CODES.has(Number(statusCode || 0));
121
- }
122
-
123
- function shouldRecordFailureForStatus(statusCode) {
124
- return CIRCUIT_TRACK_STATUS_CODES.has(Number(statusCode || 0));
125
- }
126
-
127
- export function __resetRequestCircuitForTests() {
128
- circuitState.consecutiveFailures = 0;
129
- circuitState.openedAtMs = 0;
130
- }
131
-
132
- /**
133
- * Execute an HTTP request against the Sentinelayer API and parse a JSON response.
134
- * Throws `SentinelayerApiError` for transport errors, timeouts, API failures, and invalid JSON.
135
- *
136
- * @param {string} url
137
- * @param {{
138
- * method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
139
- * headers?: Record<string, string>,
140
- * body?: unknown,
141
- * timeoutMs?: number
142
- * maxRetries?: number,
143
- * retryDelayMs?: number
144
- * }} [options]
145
- * @returns {Promise<any>}
146
- */
147
- export async function requestJson(
148
- url,
149
- {
150
- method = "GET",
151
- headers = {},
152
- body,
153
- timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
154
- maxRetries = DEFAULT_MAX_RETRIES,
155
- retryDelayMs = DEFAULT_RETRY_DELAY_MS,
156
- } = {}
157
- ) {
158
- if (isCircuitOpen()) {
159
- throw new SentinelayerApiError("Request circuit breaker is open after consecutive API failures.", {
160
- status: 503,
161
- code: "CIRCUIT_OPEN",
162
- });
163
- }
164
-
165
- const normalizedTimeoutMs = normalizePositiveNumber(timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
166
- const normalizedMaxRetries = normalizeNonNegativeInteger(maxRetries, DEFAULT_MAX_RETRIES);
167
- const normalizedRetryDelayMs = normalizePositiveNumber(retryDelayMs, DEFAULT_RETRY_DELAY_MS);
168
-
169
- let lastRetryableError = null;
170
- for (let attempt = 0; attempt <= normalizedMaxRetries; attempt += 1) {
171
- const controller = new AbortController();
172
- const timeout = setTimeout(() => controller.abort(), normalizedTimeoutMs);
173
-
174
- try {
175
- const response = await fetch(String(url), {
176
- method,
177
- headers: {
178
- "Content-Type": "application/json",
179
- ...headers,
180
- },
181
- body: body === undefined ? undefined : JSON.stringify(body),
182
- signal: controller.signal,
183
- });
184
-
185
- const rawBody = await response.text();
186
- let json = {};
187
- if (rawBody.trim()) {
188
- try {
189
- json = JSON.parse(rawBody);
190
- } catch {
191
- if (response.ok) {
192
- throw new SentinelayerApiError("Invalid JSON returned by API.", {
193
- status: response.status,
194
- code: "INVALID_JSON",
195
- });
196
- }
197
- }
198
- }
199
-
200
- if (response.ok) {
201
- recordSuccessForCircuit();
202
- return json;
203
- }
204
-
205
- const apiError = normalizeApiError(json && typeof json === "object" ? json.error : {});
206
- const statusCode = Number(response.status || 500);
207
- const retryable = shouldRetryStatus(statusCode);
208
- const shouldRecordCircuitFailure = shouldRecordFailureForStatus(statusCode);
209
- const error = new SentinelayerApiError(apiError.message, {
210
- status: statusCode,
211
- code: apiError.code,
212
- requestId: apiError.requestId,
213
- });
214
-
215
- if (!retryable || attempt >= normalizedMaxRetries) {
216
- if (shouldRecordCircuitFailure) {
217
- recordFailureForCircuit();
218
- }
219
- throw error;
220
- }
221
-
222
- lastRetryableError = error;
223
- const delayMs = computeBackoffMs({
224
- attempt: attempt + 1,
225
- retryDelayMs: normalizedRetryDelayMs,
226
- retryAfterHeader: response.headers.get("retry-after"),
227
- });
228
- await sleep(delayMs);
229
- continue;
230
- } catch (error) {
231
- if (error instanceof SentinelayerApiError) {
232
- throw error;
233
- }
234
-
235
- const isAbortError = Boolean(error && typeof error === "object" && error.name === "AbortError");
236
- const normalizedError = new SentinelayerApiError(
237
- isAbortError ? "Request timed out." : (error instanceof Error ? error.message : String(error || "Request failed")),
238
- {
239
- status: isAbortError ? 408 : 503,
240
- code: isAbortError ? "TIMEOUT" : "NETWORK_ERROR",
241
- }
242
- );
243
-
244
- if (attempt >= normalizedMaxRetries) {
245
- recordFailureForCircuit();
246
- throw normalizedError;
247
- }
248
-
249
- lastRetryableError = normalizedError;
250
- const delayMs = computeBackoffMs({
251
- attempt: attempt + 1,
252
- retryDelayMs: normalizedRetryDelayMs,
253
- retryAfterHeader: null,
254
- });
255
- await sleep(delayMs);
256
- continue;
257
- } finally {
258
- clearTimeout(timeout);
259
- await sleep(0);
260
- }
261
- }
262
-
263
- if (lastRetryableError instanceof SentinelayerApiError) {
264
- throw lastRetryableError;
265
- }
266
- throw new SentinelayerApiError("Request failed without a terminal response.", {
267
- status: 503,
268
- code: "NETWORK_ERROR",
269
- });
270
- }
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import crypto from "node:crypto";
3
+
4
+ /**
5
+ * Default timeout applied to Sentinelayer API requests when no override is provided.
6
+ * @type {number}
7
+ */
8
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
9
+ export const DEFAULT_MAX_RETRIES = 2;
10
+ export const DEFAULT_RETRY_DELAY_MS = 250;
11
+ export const MAX_RETRY_DELAY_MS = 2_000;
12
+ export const CIRCUIT_BREAKER_THRESHOLD = 5;
13
+ export const CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;
14
+
15
+ const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
16
+ const CIRCUIT_TRACK_STATUS_CODES = new Set([401, 403, 408, 425, 429, 500, 502, 503, 504]);
17
+ const circuitStateByScope = new Map();
18
+ const REQUEST_ID_HEADERS = ["x-request-id", "request-id", "x-correlation-id"];
19
+ const DEBUG_API_ERRORS_ENV = "SENTINELAYER_DEBUG_ERRORS";
20
+ const MAX_API_ERROR_MESSAGE_LENGTH = 512;
21
+ const IDEMPOTENCY_KEY_MIN_LENGTH = 32;
22
+ const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
23
+ const PREFIXED_UUID_V4_PATTERN = /^[a-z0-9][a-z0-9_-]{1,48}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
24
+
25
+ function resolveCircuitScope(url) {
26
+ try {
27
+ const parsed = new URL(String(url));
28
+ return parsed.origin;
29
+ } catch {
30
+ return "unknown";
31
+ }
32
+ }
33
+
34
+ function getCircuitState(scope) {
35
+ const key = String(scope || "unknown");
36
+ if (!circuitStateByScope.has(key)) {
37
+ circuitStateByScope.set(key, { consecutiveFailures: 0, openedAtMs: 0 });
38
+ }
39
+ return circuitStateByScope.get(key);
40
+ }
41
+
42
+ function normalizeApiError(errorPayload = {}) {
43
+ const fallbackMessage = "Unknown API error";
44
+ if (!errorPayload || typeof errorPayload !== "object" || Array.isArray(errorPayload)) {
45
+ return {
46
+ code: "UNKNOWN",
47
+ message: sanitizeApiErrorMessage(fallbackMessage, fallbackMessage),
48
+ requestId: null,
49
+ };
50
+ }
51
+ const rawMessage = String(errorPayload.message || fallbackMessage);
52
+ const safeMessage = sanitizeApiErrorMessage(rawMessage, fallbackMessage);
53
+ const message = appendDebugContext(safeMessage, {
54
+ code: String(errorPayload.code || "UNKNOWN"),
55
+ requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
56
+ });
57
+ return {
58
+ code: String(errorPayload.code || "UNKNOWN"),
59
+ message,
60
+ requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
61
+ };
62
+ }
63
+
64
+ function resolveRequestId(headers) {
65
+ if (!headers || typeof headers.get !== "function") {
66
+ return null;
67
+ }
68
+ for (const headerName of REQUEST_ID_HEADERS) {
69
+ const value = headers.get(headerName);
70
+ if (value) {
71
+ return String(value);
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ function resolveIdempotencyKey(headers) {
78
+ if (!headers) {
79
+ return null;
80
+ }
81
+ if (typeof headers.get === "function") {
82
+ const value =
83
+ headers.get("idempotency-key") ||
84
+ headers.get("Idempotency-Key") ||
85
+ headers.get("IDEMPOTENCY-KEY");
86
+ return String(value || "").trim() || null;
87
+ }
88
+ if (typeof headers !== "object") {
89
+ return null;
90
+ }
91
+ for (const [key, value] of Object.entries(headers)) {
92
+ if (String(key || "").toLowerCase() === "idempotency-key") {
93
+ const normalized = String(value || "").trim();
94
+ return normalized || null;
95
+ }
96
+ }
97
+ return null;
98
+ }
99
+
100
+ function isValidIdempotencyKey(value) {
101
+ const normalized = String(value || "").trim();
102
+ if (!normalized) {
103
+ return false;
104
+ }
105
+ if (UUID_V4_PATTERN.test(normalized)) {
106
+ return true;
107
+ }
108
+ if (PREFIXED_UUID_V4_PATTERN.test(normalized)) {
109
+ return true;
110
+ }
111
+ if (normalized.length < IDEMPOTENCY_KEY_MIN_LENGTH) {
112
+ return false;
113
+ }
114
+ return /^[A-Za-z0-9_-]+$/.test(normalized);
115
+ }
116
+
117
+ function validateIdempotencyKey(value) {
118
+ if (!isValidIdempotencyKey(value)) {
119
+ throw new SentinelayerApiError("Idempotency-Key must be a UUIDv4 or a prefixed UUID.", {
120
+ status: 400,
121
+ code: "IDEMPOTENCY_KEY_INVALID",
122
+ });
123
+ }
124
+ }
125
+
126
+ function sanitizeOperationName(value) {
127
+ const normalized = String(value || "").toLowerCase();
128
+ const cleaned = normalized.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
129
+ return cleaned.slice(0, 32) || "mutation";
130
+ }
131
+
132
+ function createIdempotencyKeyForOperation(operationName) {
133
+ const op = sanitizeOperationName(operationName);
134
+ let suffix;
135
+ try {
136
+ suffix = crypto.randomUUID();
137
+ } catch {
138
+ suffix = crypto.randomBytes(16).toString("hex");
139
+ }
140
+ return `sl-cli-${op}-${suffix}`;
141
+ }
142
+
143
+ function normalizeHeaderObject(headers) {
144
+ if (!headers) {
145
+ return {};
146
+ }
147
+ if (typeof headers.get === "function") {
148
+ const normalized = {};
149
+ for (const [key, value] of headers.entries()) {
150
+ normalized[key] = value;
151
+ }
152
+ return normalized;
153
+ }
154
+ if (typeof headers !== "object") {
155
+ return {};
156
+ }
157
+ return { ...headers };
158
+ }
159
+
160
+ function isMutationVerb(method) {
161
+ const normalized = String(method || "").trim().toUpperCase();
162
+ return (
163
+ normalized === "POST" ||
164
+ normalized === "PUT" ||
165
+ normalized === "PATCH" ||
166
+ normalized === "DELETE"
167
+ );
168
+ }
169
+
170
+ function applyIdempotencyKey(headers, idempotencyKey) {
171
+ const normalized = normalizeHeaderObject(headers);
172
+ if (idempotencyKey && !resolveIdempotencyKey(normalized)) {
173
+ normalized["Idempotency-Key"] = idempotencyKey;
174
+ }
175
+ return normalized;
176
+ }
177
+
178
+ export class SentinelayerApiError extends Error {
179
+ /**
180
+ * @param {string} message
181
+ * @param {{ status?: number, code?: string, requestId?: string | null }} [options]
182
+ */
183
+ constructor(message, { status = 500, code = "UNKNOWN", requestId = null } = {}) {
184
+ const safeMessage = sanitizeApiErrorMessage(message, "Sentinelayer API error");
185
+ super(appendDebugContext(safeMessage, { code, status, requestId }));
186
+ this.name = "SentinelayerApiError";
187
+ this.status = Number(status || 500);
188
+ this.code = String(code || "UNKNOWN");
189
+ this.requestId = requestId ? String(requestId) : null;
190
+ }
191
+ }
192
+
193
+ function normalizePositiveNumber(value, fallback) {
194
+ const parsed = Number(value);
195
+ if (!Number.isFinite(parsed) || parsed <= 0) {
196
+ return fallback;
197
+ }
198
+ return parsed;
199
+ }
200
+
201
+ function normalizeNonNegativeInteger(value, fallback) {
202
+ const parsed = Number(value);
203
+ if (!Number.isFinite(parsed) || parsed < 0) {
204
+ return fallback;
205
+ }
206
+ return Math.floor(parsed);
207
+ }
208
+
209
+ function parseRetryAfterMs(value) {
210
+ const raw = String(value || "").trim();
211
+ if (!raw) {
212
+ return null;
213
+ }
214
+ const seconds = Number(raw);
215
+ if (Number.isFinite(seconds) && seconds >= 0) {
216
+ return Math.round(seconds * 1000);
217
+ }
218
+ const parsedDate = Date.parse(raw);
219
+ if (Number.isFinite(parsedDate)) {
220
+ const delta = parsedDate - Date.now();
221
+ if (delta > 0) {
222
+ return delta;
223
+ }
224
+ }
225
+ return null;
226
+ }
227
+
228
+ function computeBackoffMs({ attempt, retryDelayMs, retryAfterHeader }) {
229
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
230
+ if (retryAfterMs !== null) {
231
+ return Math.min(retryAfterMs, MAX_RETRY_DELAY_MS);
232
+ }
233
+ const exponent = Math.max(0, Number(attempt) - 1);
234
+ const computed = Math.round(retryDelayMs * Math.pow(2, exponent));
235
+ return Math.min(Math.max(1, computed), MAX_RETRY_DELAY_MS);
236
+ }
237
+
238
+ function isCircuitOpen(scope) {
239
+ const circuitState = getCircuitState(scope);
240
+ if (circuitState.openedAtMs <= 0) {
241
+ return false;
242
+ }
243
+ if (Date.now() - circuitState.openedAtMs >= CIRCUIT_BREAKER_COOLDOWN_MS) {
244
+ circuitState.openedAtMs = 0;
245
+ circuitState.consecutiveFailures = 0;
246
+ return false;
247
+ }
248
+ return true;
249
+ }
250
+
251
+ function recordFailureForCircuit(scope) {
252
+ const circuitState = getCircuitState(scope);
253
+ circuitState.consecutiveFailures += 1;
254
+ if (circuitState.consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) {
255
+ circuitState.openedAtMs = Date.now();
256
+ }
257
+ }
258
+
259
+ function shouldExposeApiErrorDetails() {
260
+ const normalized = String(process.env[DEBUG_API_ERRORS_ENV] || "").trim().toLowerCase();
261
+ return normalized === "true" || normalized === "1" || normalized === "yes";
262
+ }
263
+
264
+ function isTestNonIdempotentAllowed() {
265
+ return (
266
+ process.env.NODE_ENV === "test" &&
267
+ process.env.SENTINELAYER_ALLOW_NON_IDEMPOTENT === "1" &&
268
+ process.env.SENTINELAYER_CLI_TEST_MODE === "1" &&
269
+ !process.env.CI
270
+ );
271
+ }
272
+
273
+ function sanitizeApiErrorMessage(message, fallback = "Sentinelayer API error") {
274
+ const fallbackMessage = String(fallback || "Sentinelayer API error");
275
+ const normalized = String(message || "").trim();
276
+ const candidate = normalized || fallbackMessage;
277
+ const sanitized = candidate
278
+ .replace(/\bbearer\s+[a-z0-9._~+/=-]+\b/gi, "bearer [REDACTED]")
279
+ .replace(/\b(token|secret|password|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)\b\s*[:=]\s*["']?[^"'\s,;]+["']?/gi, "$1=[REDACTED]")
280
+ .replace(/\b[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+\b/gi, "[REDACTED_JWT]")
281
+ .replace(/\bhttps?:\/\/[^\s"'`]+/gi, () => "<redacted-url>")
282
+ .replace(/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/gi, "<redacted-email>");
283
+ if (sanitized.length <= MAX_API_ERROR_MESSAGE_LENGTH) {
284
+ return sanitized;
285
+ }
286
+ return `${sanitized.slice(0, MAX_API_ERROR_MESSAGE_LENGTH - 3)}...`;
287
+ }
288
+
289
+ function anonymizeRequestIdForDebug(requestId) {
290
+ const normalized = String(requestId || "").trim();
291
+ if (!normalized) {
292
+ return "";
293
+ }
294
+ return crypto.createHash("sha256").update(normalized).digest("hex").slice(0, 12);
295
+ }
296
+
297
+ function appendDebugContext(safeMessage, { code, status, requestId } = {}) {
298
+ if (!shouldExposeApiErrorDetails()) {
299
+ return safeMessage;
300
+ }
301
+ const parts = [];
302
+ const normalizedCode = String(code || "").trim();
303
+ const normalizedStatus = Number.isFinite(Number(status)) ? Number(status) : null;
304
+ const requestIdHash = anonymizeRequestIdForDebug(requestId);
305
+ if (normalizedCode) parts.push(`code=${normalizedCode}`);
306
+ if (normalizedStatus) parts.push(`status=${normalizedStatus}`);
307
+ if (requestIdHash) parts.push(`request_id_hash=${requestIdHash}`);
308
+ if (parts.length === 0) return safeMessage;
309
+ return `${safeMessage} (${parts.join(", ")})`;
310
+ }
311
+
312
+ function recordSuccessForCircuit(scope) {
313
+ const circuitState = getCircuitState(scope);
314
+ circuitState.consecutiveFailures = 0;
315
+ circuitState.openedAtMs = 0;
316
+ }
317
+
318
+ function shouldRetryStatus(statusCode) {
319
+ return RETRYABLE_STATUS_CODES.has(Number(statusCode || 0));
320
+ }
321
+
322
+ function shouldRecordFailureForStatus(statusCode) {
323
+ return CIRCUIT_TRACK_STATUS_CODES.has(Number(statusCode || 0));
324
+ }
325
+
326
+ export function __resetRequestCircuitForTests(scope) {
327
+ if (scope) {
328
+ const circuitState = getCircuitState(scope);
329
+ circuitState.consecutiveFailures = 0;
330
+ circuitState.openedAtMs = 0;
331
+ return;
332
+ }
333
+ circuitStateByScope.clear();
334
+ }
335
+
336
+ /**
337
+ * Execute an HTTP request against the Sentinelayer API and parse a JSON response.
338
+ * Throws `SentinelayerApiError` for transport errors, timeouts, API failures, and invalid JSON.
339
+ *
340
+ * @param {string} url
341
+ * @param {{
342
+ * method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
343
+ * headers?: Record<string, string>,
344
+ * body?: unknown,
345
+ * idempotencyKey?: string | null,
346
+ * allowNonIdempotent?: boolean,
347
+ * timeoutMs?: number
348
+ * maxRetries?: number,
349
+ * retryDelayMs?: number
350
+ * allowEmptyBody?: boolean
351
+ * }} [options]
352
+ * @returns {Promise<any>}
353
+ */
354
+ export async function requestJson(
355
+ url,
356
+ {
357
+ method = "GET",
358
+ headers = {},
359
+ body,
360
+ idempotencyKey = null,
361
+ allowNonIdempotent = false,
362
+ timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
363
+ maxRetries = DEFAULT_MAX_RETRIES,
364
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS,
365
+ allowEmptyBody = false,
366
+ } = {}
367
+ ) {
368
+ const normalizedMethod = String(method || "GET").trim().toUpperCase();
369
+ const explicitIdempotencyKey = String(idempotencyKey || "").trim() || null;
370
+ const existingIdempotencyKey = explicitIdempotencyKey || resolveIdempotencyKey(headers);
371
+ const isMutationMethod = isMutationVerb(normalizedMethod);
372
+ const resolvedIdempotencyKey = existingIdempotencyKey;
373
+ const requestHeaders = applyIdempotencyKey(headers, resolvedIdempotencyKey);
374
+ const outgoingHeaders = { ...requestHeaders };
375
+ if (body !== undefined) {
376
+ outgoingHeaders["Content-Type"] = "application/json";
377
+ }
378
+ const isIdempotentMutation = Boolean(resolvedIdempotencyKey);
379
+ const allowUnsafeMutation = Boolean(allowNonIdempotent) && isTestNonIdempotentAllowed();
380
+ if (isMutationMethod && !isIdempotentMutation && !allowUnsafeMutation) {
381
+ throw new SentinelayerApiError("Idempotency-Key is required for mutation requests.", {
382
+ status: 400,
383
+ code: "IDEMPOTENCY_KEY_REQUIRED",
384
+ });
385
+ }
386
+ if (isMutationMethod && isIdempotentMutation) {
387
+ validateIdempotencyKey(resolvedIdempotencyKey);
388
+ }
389
+ const retryableMethod =
390
+ normalizedMethod === "GET" ||
391
+ normalizedMethod === "HEAD" ||
392
+ normalizedMethod === "OPTIONS" ||
393
+ (isIdempotentMutation &&
394
+ (normalizedMethod === "POST" ||
395
+ normalizedMethod === "PUT" ||
396
+ normalizedMethod === "PATCH" ||
397
+ normalizedMethod === "DELETE"));
398
+ const circuitScope = resolveCircuitScope(url);
399
+ if (isCircuitOpen(circuitScope)) {
400
+ throw new SentinelayerApiError("Request circuit breaker is open after consecutive API failures.", {
401
+ status: 503,
402
+ code: "CIRCUIT_OPEN",
403
+ });
404
+ }
405
+
406
+ const normalizedTimeoutMs = normalizePositiveNumber(timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
407
+ const normalizedMaxRetries = normalizeNonNegativeInteger(maxRetries, DEFAULT_MAX_RETRIES);
408
+ const normalizedRetryDelayMs = normalizePositiveNumber(retryDelayMs, DEFAULT_RETRY_DELAY_MS);
409
+
410
+ let lastRetryableError = null;
411
+ for (let attempt = 0; attempt <= normalizedMaxRetries; attempt += 1) {
412
+ const controller = new AbortController();
413
+ let timeoutTriggered = false;
414
+ let timeoutHandle;
415
+ timeoutHandle = setTimeout(() => {
416
+ timeoutTriggered = true;
417
+ controller.abort();
418
+ }, normalizedTimeoutMs);
419
+
420
+ try {
421
+ const response = await fetch(String(url), {
422
+ method: normalizedMethod,
423
+ headers: outgoingHeaders,
424
+ body: body === undefined ? undefined : JSON.stringify(body),
425
+ redirect: "error",
426
+ signal: controller.signal,
427
+ });
428
+
429
+ const rawBody = await response.text();
430
+ const trimmedBody = rawBody.trim();
431
+ const contentType = response.headers.get("content-type") || "";
432
+ const isJson = /application\/json/i.test(contentType);
433
+ let json = {};
434
+ if (!trimmedBody) {
435
+ const statusCode = Number(response.status || 0);
436
+ const allowEmpty = Boolean(allowEmptyBody) || statusCode === 204 || statusCode === 205;
437
+ if (response.ok && !allowEmpty) {
438
+ const requestId = resolveRequestId(response.headers);
439
+ throw new SentinelayerApiError("Empty response body returned by API.", {
440
+ status: response.status,
441
+ code: "EMPTY_BODY",
442
+ requestId,
443
+ });
444
+ }
445
+ } else {
446
+ if (response.ok && !isJson) {
447
+ const requestId = resolveRequestId(response.headers);
448
+ throw new SentinelayerApiError("Invalid content-type returned by API.", {
449
+ status: response.status,
450
+ code: "INVALID_CONTENT_TYPE",
451
+ requestId,
452
+ });
453
+ }
454
+ if (isJson) {
455
+ try {
456
+ json = JSON.parse(rawBody);
457
+ } catch {
458
+ const requestId = resolveRequestId(response.headers);
459
+ if (response.ok) {
460
+ throw new SentinelayerApiError("Invalid JSON returned by API.", {
461
+ status: response.status,
462
+ code: "INVALID_JSON",
463
+ requestId,
464
+ });
465
+ }
466
+ }
467
+ }
468
+ }
469
+
470
+ if (response.ok) {
471
+ recordSuccessForCircuit(circuitScope);
472
+ return json;
473
+ }
474
+
475
+ const apiError = normalizeApiError(json && typeof json === "object" ? json.error : {});
476
+ const requestId = apiError.requestId || resolveRequestId(response.headers);
477
+ const statusCode = Number(response.status || 500);
478
+ const retryable = retryableMethod && shouldRetryStatus(statusCode);
479
+ const shouldRecordCircuitFailure = shouldRecordFailureForStatus(statusCode);
480
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
481
+ const error = new SentinelayerApiError(apiError.message, {
482
+ status: statusCode,
483
+ code: apiError.code,
484
+ requestId,
485
+ });
486
+ error.retryAfterMs = retryAfterMs;
487
+
488
+ if (!retryable || attempt >= normalizedMaxRetries) {
489
+ if (shouldRecordCircuitFailure) {
490
+ recordFailureForCircuit(circuitScope);
491
+ }
492
+ throw error;
493
+ }
494
+
495
+ lastRetryableError = error;
496
+ const delayMs = computeBackoffMs({
497
+ attempt: attempt + 1,
498
+ retryDelayMs: normalizedRetryDelayMs,
499
+ retryAfterHeader: response.headers.get("retry-after"),
500
+ });
501
+ await sleep(delayMs);
502
+ continue;
503
+ } catch (error) {
504
+ if (error instanceof SentinelayerApiError) {
505
+ throw error;
506
+ }
507
+
508
+ const isAbortError = Boolean(error && typeof error === "object" && error.name === "AbortError");
509
+ const abortMessage = error instanceof Error ? error.message : String(error || "");
510
+ const abortReason =
511
+ isAbortError && !timeoutTriggered && /cancel/i.test(abortMessage) ? "CANCELLED" : "TIMEOUT";
512
+ const abortCode = isAbortError ? abortReason : "NETWORK_ERROR";
513
+ const abortStatus = isAbortError ? (abortReason === "CANCELLED" ? 499 : 408) : 503;
514
+ const normalizedError = new SentinelayerApiError(
515
+ isAbortError
516
+ ? (abortReason === "CANCELLED" ? "Request cancelled." : "Request timed out.")
517
+ : (error instanceof Error ? error.message : String(error || "Request failed")),
518
+ {
519
+ status: abortStatus,
520
+ code: abortCode,
521
+ }
522
+ );
523
+
524
+ if (!retryableMethod || attempt >= normalizedMaxRetries) {
525
+ recordFailureForCircuit(circuitScope);
526
+ throw normalizedError;
527
+ }
528
+
529
+ lastRetryableError = normalizedError;
530
+ const delayMs = computeBackoffMs({
531
+ attempt: attempt + 1,
532
+ retryDelayMs: normalizedRetryDelayMs,
533
+ retryAfterHeader: null,
534
+ });
535
+ await sleep(delayMs);
536
+ continue;
537
+ } finally {
538
+ if (timeoutHandle) {
539
+ clearTimeout(timeoutHandle);
540
+ }
541
+ await sleep(0);
542
+ }
543
+ }
544
+
545
+ if (lastRetryableError instanceof SentinelayerApiError) {
546
+ throw lastRetryableError;
547
+ }
548
+ throw new SentinelayerApiError("Request failed without a terminal response.", {
549
+ status: 503,
550
+ code: "NETWORK_ERROR",
551
+ });
552
+ }
553
+
554
+ /**
555
+ * Execute an HTTP mutation request and auto-derive an idempotency key when missing.
556
+ *
557
+ * @param {string} url
558
+ * @param {{
559
+ * method?: "POST" | "PUT" | "PATCH" | "DELETE",
560
+ * headers?: Record<string, string>,
561
+ * body?: unknown,
562
+ * idempotencyKey?: string | null,
563
+ * operationName: string,
564
+ * timeoutMs?: number
565
+ * maxRetries?: number,
566
+ * retryDelayMs?: number
567
+ * allowEmptyBody?: boolean
568
+ * }} options
569
+ * @returns {Promise<any>}
570
+ */
571
+ export async function requestJsonMutation(
572
+ url,
573
+ {
574
+ method = "POST",
575
+ headers = {},
576
+ body,
577
+ idempotencyKey = null,
578
+ operationName,
579
+ timeoutMs,
580
+ maxRetries,
581
+ retryDelayMs,
582
+ allowEmptyBody = false,
583
+ } = {}
584
+ ) {
585
+ const normalizedMethod = String(method || "POST").trim().toUpperCase();
586
+ if (!isMutationVerb(normalizedMethod)) {
587
+ throw new SentinelayerApiError("requestJsonMutation requires a mutation HTTP method.", {
588
+ status: 400,
589
+ code: "INVALID_MUTATION_METHOD",
590
+ });
591
+ }
592
+ const resolvedOperation = String(operationName || "").trim();
593
+ if (!resolvedOperation) {
594
+ throw new SentinelayerApiError("requestJsonMutation requires an operationName.", {
595
+ status: 400,
596
+ code: "OPERATION_NAME_REQUIRED",
597
+ });
598
+ }
599
+ const resolvedIdempotencyKey =
600
+ String(idempotencyKey || "").trim() || createIdempotencyKeyForOperation(resolvedOperation);
601
+ return requestJson(url, {
602
+ method: normalizedMethod,
603
+ headers,
604
+ body,
605
+ idempotencyKey: resolvedIdempotencyKey,
606
+ timeoutMs,
607
+ maxRetries,
608
+ retryDelayMs,
609
+ allowEmptyBody,
610
+ });
611
+ }