sentinelayer-cli 0.1.2 → 0.4.4

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 (129) hide show
  1. package/README.md +998 -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 +63 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +327 -319
  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 +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +557 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +503 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/agents/jules/tools/url-policy.js +100 -0
  30. package/src/ai/aidenid.js +972 -945
  31. package/src/ai/client.js +508 -508
  32. package/src/ai/domain-target-store.js +268 -268
  33. package/src/ai/identity-store.js +270 -270
  34. package/src/ai/site-store.js +145 -145
  35. package/src/audit/agents/architecture.js +180 -180
  36. package/src/audit/agents/compliance.js +179 -179
  37. package/src/audit/agents/documentation.js +165 -165
  38. package/src/audit/agents/performance.js +145 -145
  39. package/src/audit/agents/security.js +215 -215
  40. package/src/audit/agents/testing.js +172 -172
  41. package/src/audit/orchestrator.js +557 -557
  42. package/src/audit/package.js +204 -204
  43. package/src/audit/registry.js +284 -284
  44. package/src/audit/replay.js +103 -103
  45. package/src/auth/gate.js +45 -11
  46. package/src/auth/http.js +270 -113
  47. package/src/auth/service.js +891 -848
  48. package/src/auth/session-store.js +359 -345
  49. package/src/cli.js +252 -252
  50. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  51. package/src/commands/ai/provision-governance.js +1272 -1246
  52. package/src/commands/ai/shared.js +147 -147
  53. package/src/commands/ai.js +11 -11
  54. package/src/commands/apply.js +12 -12
  55. package/src/commands/audit.js +1166 -1166
  56. package/src/commands/auth.js +375 -366
  57. package/src/commands/chat.js +191 -191
  58. package/src/commands/config.js +184 -184
  59. package/src/commands/cost.js +311 -311
  60. package/src/commands/daemon/core.js +850 -850
  61. package/src/commands/daemon/extended.js +1048 -1048
  62. package/src/commands/daemon/shared.js +213 -213
  63. package/src/commands/daemon.js +11 -11
  64. package/src/commands/guide.js +174 -174
  65. package/src/commands/ingest.js +58 -58
  66. package/src/commands/init.js +55 -55
  67. package/src/commands/legacy-args.js +10 -10
  68. package/src/commands/mcp.js +461 -404
  69. package/src/commands/omargate.js +15 -15
  70. package/src/commands/persona.js +20 -20
  71. package/src/commands/plugin.js +260 -260
  72. package/src/commands/policy.js +132 -132
  73. package/src/commands/prompt.js +238 -238
  74. package/src/commands/review.js +704 -704
  75. package/src/commands/scan.js +866 -788
  76. package/src/commands/spec.js +716 -716
  77. package/src/commands/swarm.js +651 -651
  78. package/src/commands/telemetry.js +202 -202
  79. package/src/commands/watch.js +510 -510
  80. package/src/config/agent-dictionary.js +182 -182
  81. package/src/config/io.js +56 -56
  82. package/src/config/paths.js +18 -18
  83. package/src/config/schema.js +55 -55
  84. package/src/config/service.js +184 -184
  85. package/src/cost/budget.js +235 -235
  86. package/src/cost/history.js +188 -188
  87. package/src/cost/tracker.js +171 -171
  88. package/src/daemon/artifact-lineage.js +534 -534
  89. package/src/daemon/assignment-ledger.js +770 -770
  90. package/src/daemon/ast-parser-layer.js +258 -258
  91. package/src/daemon/budget-governor.js +633 -633
  92. package/src/daemon/callgraph-overlay.js +646 -646
  93. package/src/daemon/error-worker.js +626 -626
  94. package/src/daemon/hybrid-mapper.js +929 -929
  95. package/src/daemon/jira-lifecycle.js +632 -632
  96. package/src/daemon/operator-control.js +657 -657
  97. package/src/daemon/reliability-lane.js +471 -471
  98. package/src/daemon/watchdog.js +971 -971
  99. package/src/guide/generator.js +316 -316
  100. package/src/ingest/engine.js +918 -918
  101. package/src/legacy-cli.js +2592 -2435
  102. package/src/mcp/registry.js +695 -695
  103. package/src/memory/blackboard.js +301 -301
  104. package/src/memory/retrieval.js +581 -581
  105. package/src/plugin/manifest.js +553 -553
  106. package/src/policy/packs.js +144 -144
  107. package/src/prompt/generator.js +118 -106
  108. package/src/review/ai-review.js +669 -669
  109. package/src/review/local-review.js +1295 -1284
  110. package/src/review/replay.js +235 -235
  111. package/src/review/report.js +664 -664
  112. package/src/review/spec-binding.js +487 -487
  113. package/src/scaffold/generator.js +67 -0
  114. package/src/scaffold/templates.js +150 -0
  115. package/src/scan/generator.js +418 -351
  116. package/src/scan/gh-secrets.js +107 -0
  117. package/src/spec/generator.js +519 -519
  118. package/src/spec/regenerate.js +237 -237
  119. package/src/spec/templates.js +91 -91
  120. package/src/swarm/dashboard.js +247 -247
  121. package/src/swarm/factory.js +363 -363
  122. package/src/swarm/pentest.js +934 -934
  123. package/src/swarm/registry.js +419 -419
  124. package/src/swarm/report.js +158 -158
  125. package/src/swarm/runtime.js +576 -576
  126. package/src/swarm/scenario-dsl.js +272 -272
  127. package/src/telemetry/ledger.js +302 -302
  128. package/src/telemetry/sync.js +107 -61
  129. package/src/ui/markdown.js +220 -220
package/src/ai/client.js CHANGED
@@ -1,508 +1,508 @@
1
- const PROVIDER_ENV_KEYS = Object.freeze({
2
- openai: "OPENAI_API_KEY",
3
- anthropic: "ANTHROPIC_API_KEY",
4
- google: "GOOGLE_API_KEY",
5
- });
6
-
7
- const DEFAULT_MODELS = Object.freeze({
8
- openai: "gpt-4o",
9
- anthropic: "claude-sonnet-4",
10
- google: "gemini-2.5-pro",
11
- });
12
-
13
- const SUPPORTED_PROVIDERS = Object.freeze(Object.keys(PROVIDER_ENV_KEYS));
14
- const GOOGLE_API_KEY_QUERY_REGEX = /([?&]key=)([^&#\s]+)/gi;
15
-
16
- function normalizeProvider(provider) {
17
- const normalized = String(provider || "")
18
- .trim()
19
- .toLowerCase();
20
- if (!normalized) {
21
- return "";
22
- }
23
- if (!SUPPORTED_PROVIDERS.includes(normalized)) {
24
- throw new Error(
25
- `Unsupported provider '${provider}'. Use one of: ${SUPPORTED_PROVIDERS.join(", ")}`
26
- );
27
- }
28
- return normalized;
29
- }
30
-
31
- function isRetryableStatus(statusCode) {
32
- const numeric = Number(statusCode || 0);
33
- if (!Number.isFinite(numeric)) {
34
- return false;
35
- }
36
- return numeric === 429 || numeric >= 500;
37
- }
38
-
39
- function sleep(ms) {
40
- const normalized = Math.max(0, Number(ms || 0));
41
- return new Promise((resolve) => setTimeout(resolve, normalized));
42
- }
43
-
44
- function normalizePrompt(prompt) {
45
- const normalized = String(prompt || "").trim();
46
- if (!normalized) {
47
- throw new Error("Prompt is required.");
48
- }
49
- return normalized;
50
- }
51
-
52
- function escapeRegExp(value) {
53
- return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
54
- }
55
-
56
- function sanitizeSensitiveText(text, { apiKey } = {}) {
57
- let sanitized = String(text || "");
58
- sanitized = sanitized.replace(GOOGLE_API_KEY_QUERY_REGEX, "$1[REDACTED]");
59
-
60
- const key = String(apiKey || "").trim();
61
- if (!key) {
62
- return sanitized;
63
- }
64
-
65
- sanitized = sanitized.replace(new RegExp(escapeRegExp(key), "g"), "[REDACTED]");
66
- const encodedKey = encodeURIComponent(key);
67
- if (encodedKey && encodedKey !== key) {
68
- sanitized = sanitized.replace(new RegExp(escapeRegExp(encodedKey), "g"), "[REDACTED]");
69
- }
70
- return sanitized;
71
- }
72
-
73
- function parseStreamDataLine(line) {
74
- const trimmed = String(line || "").trim();
75
- if (!trimmed.startsWith("data:")) {
76
- return null;
77
- }
78
- const payload = trimmed.slice(5).trim();
79
- if (!payload || payload === "[DONE]") {
80
- return null;
81
- }
82
- return payload;
83
- }
84
-
85
- function parseStreamChunk(provider, payload) {
86
- try {
87
- const parsed = JSON.parse(payload);
88
- if (provider === "openai") {
89
- const value = parsed?.choices?.[0]?.delta?.content;
90
- return typeof value === "string" ? value : "";
91
- }
92
- if (provider === "anthropic") {
93
- if (parsed?.type === "content_block_delta") {
94
- return typeof parsed?.delta?.text === "string" ? parsed.delta.text : "";
95
- }
96
- return "";
97
- }
98
- if (provider === "google") {
99
- const value = parsed?.candidates?.[0]?.content?.parts?.[0]?.text;
100
- return typeof value === "string" ? value : "";
101
- }
102
- return "";
103
- } catch {
104
- return "";
105
- }
106
- }
107
-
108
- function extractTextFromResponse(provider, payload) {
109
- if (provider === "openai") {
110
- const text = payload?.choices?.[0]?.message?.content;
111
- if (typeof text === "string") {
112
- return text;
113
- }
114
- if (Array.isArray(text)) {
115
- return text
116
- .map((item) => (typeof item?.text === "string" ? item.text : ""))
117
- .join("")
118
- .trim();
119
- }
120
- return "";
121
- }
122
-
123
- if (provider === "anthropic") {
124
- const blocks = Array.isArray(payload?.content) ? payload.content : [];
125
- return blocks
126
- .map((block) => (typeof block?.text === "string" ? block.text : ""))
127
- .join("")
128
- .trim();
129
- }
130
-
131
- if (provider === "google") {
132
- const parts = payload?.candidates?.[0]?.content?.parts;
133
- if (!Array.isArray(parts)) {
134
- return "";
135
- }
136
- return parts
137
- .map((part) => (typeof part?.text === "string" ? part.text : ""))
138
- .join("")
139
- .trim();
140
- }
141
-
142
- return "";
143
- }
144
-
145
- function buildProviderRequest({ provider, apiKey, model, prompt, stream }) {
146
- const normalizedProvider = normalizeProvider(provider);
147
- const normalizedPrompt = normalizePrompt(prompt);
148
-
149
- if (normalizedProvider === "openai") {
150
- return {
151
- url: "https://api.openai.com/v1/chat/completions",
152
- headers: {
153
- "Content-Type": "application/json",
154
- Authorization: `Bearer ${apiKey}`,
155
- },
156
- body: JSON.stringify({
157
- model,
158
- stream,
159
- messages: [{ role: "user", content: normalizedPrompt }],
160
- }),
161
- };
162
- }
163
-
164
- if (normalizedProvider === "anthropic") {
165
- return {
166
- url: "https://api.anthropic.com/v1/messages",
167
- headers: {
168
- "Content-Type": "application/json",
169
- "x-api-key": apiKey,
170
- "anthropic-version": "2023-06-01",
171
- },
172
- body: JSON.stringify({
173
- model,
174
- stream,
175
- max_tokens: 2048,
176
- messages: [{ role: "user", content: normalizedPrompt }],
177
- }),
178
- };
179
- }
180
-
181
- const method = stream ? "streamGenerateContent" : "generateContent";
182
- return {
183
- url: `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:${method}`,
184
- headers: {
185
- "Content-Type": "application/json",
186
- "x-goog-api-key": apiKey,
187
- },
188
- body: JSON.stringify({
189
- contents: [
190
- {
191
- role: "user",
192
- parts: [{ text: normalizedPrompt }],
193
- },
194
- ],
195
- }),
196
- };
197
- }
198
-
199
- async function parseStreamResponse({ provider, response, onChunk }) {
200
- if (!response.body || typeof response.body.getReader !== "function") {
201
- const fallbackPayload = await response.json();
202
- const fallbackText = extractTextFromResponse(provider, fallbackPayload);
203
- if (fallbackText && onChunk) {
204
- onChunk(fallbackText);
205
- }
206
- return fallbackText;
207
- }
208
-
209
- const reader = response.body.getReader();
210
- const decoder = new TextDecoder("utf-8");
211
- let buffered = "";
212
- let aggregated = "";
213
-
214
- while (true) {
215
- const { value, done } = await reader.read();
216
- if (done) {
217
- break;
218
- }
219
- buffered += decoder.decode(value, { stream: true });
220
- const lines = buffered.split(/\r?\n/);
221
- buffered = lines.pop() || "";
222
-
223
- for (const line of lines) {
224
- const dataPayload = parseStreamDataLine(line);
225
- if (!dataPayload) {
226
- continue;
227
- }
228
- const delta = parseStreamChunk(provider, dataPayload);
229
- if (!delta) {
230
- continue;
231
- }
232
- aggregated += delta;
233
- if (onChunk) {
234
- onChunk(delta);
235
- }
236
- }
237
- }
238
-
239
- buffered += decoder.decode();
240
- if (buffered.trim()) {
241
- const dataPayload = parseStreamDataLine(buffered);
242
- if (dataPayload) {
243
- const delta = parseStreamChunk(provider, dataPayload);
244
- if (delta) {
245
- aggregated += delta;
246
- if (onChunk) {
247
- onChunk(delta);
248
- }
249
- }
250
- }
251
- }
252
-
253
- return aggregated.trim();
254
- }
255
-
256
- async function parseErrorBody(response) {
257
- try {
258
- const payload = await response.json();
259
- return JSON.stringify(payload);
260
- } catch {
261
- try {
262
- return await response.text();
263
- } catch {
264
- return "";
265
- }
266
- }
267
- }
268
-
269
- /**
270
- * Infer provider from available API-key environment variables.
271
- *
272
- * @param {NodeJS.ProcessEnv} [env]
273
- * @returns {("openai" | "anthropic" | "google" | null)}
274
- */
275
- export function detectProviderFromEnv(env = process.env) {
276
- for (const provider of SUPPORTED_PROVIDERS) {
277
- const envVar = PROVIDER_ENV_KEYS[provider];
278
- const value = String(env?.[envVar] || "").trim();
279
- if (value) {
280
- return provider;
281
- }
282
- }
283
- return null;
284
- }
285
-
286
- /**
287
- * Resolve provider precedence: explicit -> config -> environment -> default.
288
- *
289
- * @param {{ provider?: string, configProvider?: string, env?: NodeJS.ProcessEnv }} [options]
290
- * @returns {"openai" | "anthropic" | "google"}
291
- */
292
- export function resolveProvider({ provider, configProvider, env = process.env } = {}) {
293
- const explicit = normalizeProvider(provider);
294
- if (explicit) {
295
- return explicit;
296
- }
297
-
298
- const configured = normalizeProvider(configProvider);
299
- if (configured) {
300
- return configured;
301
- }
302
-
303
- const detected = detectProviderFromEnv(env);
304
- if (detected) {
305
- return detected;
306
- }
307
-
308
- return "openai";
309
- }
310
-
311
- /**
312
- * Resolve model precedence for a provider: explicit -> config -> provider default.
313
- *
314
- * @param {{ provider?: string, model?: string, configModel?: string }} [options]
315
- * @returns {string}
316
- */
317
- export function resolveModel({ provider, model, configModel } = {}) {
318
- const normalizedProvider = resolveProvider({ provider });
319
- const explicit = String(model || "").trim();
320
- if (explicit) {
321
- return explicit;
322
- }
323
- const configured = String(configModel || "").trim();
324
- if (configured) {
325
- return configured;
326
- }
327
- return DEFAULT_MODELS[normalizedProvider];
328
- }
329
-
330
- /**
331
- * Resolve provider API key precedence: explicit -> provider-specific environment variable.
332
- *
333
- * @param {{ provider?: string, explicitApiKey?: string, env?: NodeJS.ProcessEnv }} [options]
334
- * @returns {string}
335
- */
336
- export function resolveApiKey({ provider, explicitApiKey, env = process.env } = {}) {
337
- const normalizedProvider = resolveProvider({ provider, env });
338
- const explicit = String(explicitApiKey || "").trim();
339
- if (explicit) {
340
- return explicit;
341
- }
342
- const envKey = PROVIDER_ENV_KEYS[normalizedProvider];
343
- const value = String(env?.[envKey] || "").trim();
344
- if (!value) {
345
- throw new Error(
346
- `Missing API key for provider '${normalizedProvider}'. Set ${envKey} or provide explicitApiKey.`
347
- );
348
- }
349
- return value;
350
- }
351
-
352
- /**
353
- * Lightweight multi-provider text-generation client with retry, timeout, and streaming support.
354
- */
355
- export class MultiProviderApiClient {
356
- /**
357
- * @param {{
358
- * fetchImpl?: typeof fetch,
359
- * maxRetries?: number,
360
- * baseDelayMs?: number,
361
- * requestTimeoutMs?: number
362
- * }} [options]
363
- */
364
- constructor({
365
- fetchImpl = fetch,
366
- maxRetries = 2,
367
- baseDelayMs = 250,
368
- requestTimeoutMs = 120000,
369
- } = {}) {
370
- if (typeof fetchImpl !== "function") {
371
- throw new Error("fetchImpl must be a function.");
372
- }
373
- this.fetchImpl = fetchImpl;
374
- this.maxRetries = Math.max(0, Number(maxRetries || 0));
375
- this.baseDelayMs = Math.max(0, Number(baseDelayMs || 0));
376
- this.requestTimeoutMs = Math.max(1000, Number(requestTimeoutMs || 0));
377
- }
378
-
379
- /**
380
- * Invoke an LLM request for the selected provider/model and return normalized text output.
381
- *
382
- * @param {{
383
- * provider?: string,
384
- * model?: string,
385
- * prompt?: string,
386
- * stream?: boolean,
387
- * apiKey?: string,
388
- * env?: NodeJS.ProcessEnv,
389
- * onChunk?: (chunk: string) => void
390
- * }} [options]
391
- * @returns {Promise<{ provider: string, model: string, text: string }>}
392
- */
393
- async invoke({
394
- provider,
395
- model,
396
- prompt,
397
- stream = false,
398
- apiKey,
399
- env = process.env,
400
- onChunk,
401
- } = {}) {
402
- const resolvedProvider = resolveProvider({ provider, env });
403
- const resolvedModel = resolveModel({ provider: resolvedProvider, model });
404
- const resolvedApiKey = resolveApiKey({
405
- provider: resolvedProvider,
406
- explicitApiKey: apiKey,
407
- env,
408
- });
409
-
410
- const request = buildProviderRequest({
411
- provider: resolvedProvider,
412
- apiKey: resolvedApiKey,
413
- model: resolvedModel,
414
- prompt,
415
- stream: Boolean(stream),
416
- });
417
-
418
- let attempt = 0;
419
- while (true) {
420
- const controller = new AbortController();
421
- const timeoutHandle = setTimeout(() => controller.abort(), this.requestTimeoutMs);
422
- try {
423
- const response = await this.fetchImpl(request.url, {
424
- method: "POST",
425
- headers: request.headers,
426
- body: request.body,
427
- signal: controller.signal,
428
- });
429
-
430
- if (!response.ok) {
431
- if (attempt < this.maxRetries && isRetryableStatus(response.status)) {
432
- const backoff = this.baseDelayMs * 2 ** attempt;
433
- attempt += 1;
434
- await sleep(backoff);
435
- continue;
436
- }
437
-
438
- const errorBody = sanitizeSensitiveText(await parseErrorBody(response), {
439
- apiKey: resolvedApiKey,
440
- });
441
- throw new Error(
442
- `Provider request failed (${resolvedProvider}) with status ${response.status}${
443
- errorBody ? `: ${errorBody}` : ""
444
- }`
445
- );
446
- }
447
-
448
- let text = "";
449
- if (stream) {
450
- text = await parseStreamResponse({
451
- provider: resolvedProvider,
452
- response,
453
- onChunk,
454
- });
455
- } else {
456
- const payload = await response.json();
457
- text = extractTextFromResponse(resolvedProvider, payload);
458
- }
459
-
460
- return {
461
- provider: resolvedProvider,
462
- model: resolvedModel,
463
- text,
464
- };
465
- } catch (error) {
466
- const message = sanitizeSensitiveText(error instanceof Error ? error.message : String(error), {
467
- apiKey: resolvedApiKey,
468
- });
469
- const isAbort = /aborted|abort/i.test(message);
470
- if (attempt < this.maxRetries && !isAbort) {
471
- const backoff = this.baseDelayMs * 2 ** attempt;
472
- attempt += 1;
473
- await sleep(backoff);
474
- continue;
475
- }
476
- if (error instanceof Error) {
477
- if (message === error.message) {
478
- throw error;
479
- }
480
- throw new Error(message);
481
- }
482
- throw new Error(message);
483
- } finally {
484
- clearTimeout(timeoutHandle);
485
- }
486
- }
487
- }
488
- }
489
-
490
- /**
491
- * Factory helper for `MultiProviderApiClient`.
492
- *
493
- * @param {ConstructorParameters<typeof MultiProviderApiClient>[0]} [options]
494
- * @returns {MultiProviderApiClient}
495
- */
496
- export function createMultiProviderApiClient(options = {}) {
497
- return new MultiProviderApiClient(options);
498
- }
499
-
500
- /**
501
- * List provider identifiers currently supported by the client.
502
- *
503
- * @returns {string[]}
504
- */
505
- export function listSupportedProviders() {
506
- return [...SUPPORTED_PROVIDERS];
507
- }
508
-
1
+ const PROVIDER_ENV_KEYS = Object.freeze({
2
+ openai: "OPENAI_API_KEY",
3
+ anthropic: "ANTHROPIC_API_KEY",
4
+ google: "GOOGLE_API_KEY",
5
+ });
6
+
7
+ const DEFAULT_MODELS = Object.freeze({
8
+ openai: "gpt-4o",
9
+ anthropic: "claude-sonnet-4",
10
+ google: "gemini-2.5-pro",
11
+ });
12
+
13
+ const SUPPORTED_PROVIDERS = Object.freeze(Object.keys(PROVIDER_ENV_KEYS));
14
+ const GOOGLE_API_KEY_QUERY_REGEX = /([?&]key=)([^&#\s]+)/gi;
15
+
16
+ function normalizeProvider(provider) {
17
+ const normalized = String(provider || "")
18
+ .trim()
19
+ .toLowerCase();
20
+ if (!normalized) {
21
+ return "";
22
+ }
23
+ if (!SUPPORTED_PROVIDERS.includes(normalized)) {
24
+ throw new Error(
25
+ `Unsupported provider '${provider}'. Use one of: ${SUPPORTED_PROVIDERS.join(", ")}`
26
+ );
27
+ }
28
+ return normalized;
29
+ }
30
+
31
+ function isRetryableStatus(statusCode) {
32
+ const numeric = Number(statusCode || 0);
33
+ if (!Number.isFinite(numeric)) {
34
+ return false;
35
+ }
36
+ return numeric === 429 || numeric >= 500;
37
+ }
38
+
39
+ function sleep(ms) {
40
+ const normalized = Math.max(0, Number(ms || 0));
41
+ return new Promise((resolve) => setTimeout(resolve, normalized));
42
+ }
43
+
44
+ function normalizePrompt(prompt) {
45
+ const normalized = String(prompt || "").trim();
46
+ if (!normalized) {
47
+ throw new Error("Prompt is required.");
48
+ }
49
+ return normalized;
50
+ }
51
+
52
+ function escapeRegExp(value) {
53
+ return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
54
+ }
55
+
56
+ function sanitizeSensitiveText(text, { apiKey } = {}) {
57
+ let sanitized = String(text || "");
58
+ sanitized = sanitized.replace(GOOGLE_API_KEY_QUERY_REGEX, "$1[REDACTED]");
59
+
60
+ const key = String(apiKey || "").trim();
61
+ if (!key) {
62
+ return sanitized;
63
+ }
64
+
65
+ sanitized = sanitized.replace(new RegExp(escapeRegExp(key), "g"), "[REDACTED]");
66
+ const encodedKey = encodeURIComponent(key);
67
+ if (encodedKey && encodedKey !== key) {
68
+ sanitized = sanitized.replace(new RegExp(escapeRegExp(encodedKey), "g"), "[REDACTED]");
69
+ }
70
+ return sanitized;
71
+ }
72
+
73
+ function parseStreamDataLine(line) {
74
+ const trimmed = String(line || "").trim();
75
+ if (!trimmed.startsWith("data:")) {
76
+ return null;
77
+ }
78
+ const payload = trimmed.slice(5).trim();
79
+ if (!payload || payload === "[DONE]") {
80
+ return null;
81
+ }
82
+ return payload;
83
+ }
84
+
85
+ function parseStreamChunk(provider, payload) {
86
+ try {
87
+ const parsed = JSON.parse(payload);
88
+ if (provider === "openai") {
89
+ const value = parsed?.choices?.[0]?.delta?.content;
90
+ return typeof value === "string" ? value : "";
91
+ }
92
+ if (provider === "anthropic") {
93
+ if (parsed?.type === "content_block_delta") {
94
+ return typeof parsed?.delta?.text === "string" ? parsed.delta.text : "";
95
+ }
96
+ return "";
97
+ }
98
+ if (provider === "google") {
99
+ const value = parsed?.candidates?.[0]?.content?.parts?.[0]?.text;
100
+ return typeof value === "string" ? value : "";
101
+ }
102
+ return "";
103
+ } catch {
104
+ return "";
105
+ }
106
+ }
107
+
108
+ function extractTextFromResponse(provider, payload) {
109
+ if (provider === "openai") {
110
+ const text = payload?.choices?.[0]?.message?.content;
111
+ if (typeof text === "string") {
112
+ return text;
113
+ }
114
+ if (Array.isArray(text)) {
115
+ return text
116
+ .map((item) => (typeof item?.text === "string" ? item.text : ""))
117
+ .join("")
118
+ .trim();
119
+ }
120
+ return "";
121
+ }
122
+
123
+ if (provider === "anthropic") {
124
+ const blocks = Array.isArray(payload?.content) ? payload.content : [];
125
+ return blocks
126
+ .map((block) => (typeof block?.text === "string" ? block.text : ""))
127
+ .join("")
128
+ .trim();
129
+ }
130
+
131
+ if (provider === "google") {
132
+ const parts = payload?.candidates?.[0]?.content?.parts;
133
+ if (!Array.isArray(parts)) {
134
+ return "";
135
+ }
136
+ return parts
137
+ .map((part) => (typeof part?.text === "string" ? part.text : ""))
138
+ .join("")
139
+ .trim();
140
+ }
141
+
142
+ return "";
143
+ }
144
+
145
+ function buildProviderRequest({ provider, apiKey, model, prompt, stream }) {
146
+ const normalizedProvider = normalizeProvider(provider);
147
+ const normalizedPrompt = normalizePrompt(prompt);
148
+
149
+ if (normalizedProvider === "openai") {
150
+ return {
151
+ url: "https://api.openai.com/v1/chat/completions",
152
+ headers: {
153
+ "Content-Type": "application/json",
154
+ Authorization: `Bearer ${apiKey}`,
155
+ },
156
+ body: JSON.stringify({
157
+ model,
158
+ stream,
159
+ messages: [{ role: "user", content: normalizedPrompt }],
160
+ }),
161
+ };
162
+ }
163
+
164
+ if (normalizedProvider === "anthropic") {
165
+ return {
166
+ url: "https://api.anthropic.com/v1/messages",
167
+ headers: {
168
+ "Content-Type": "application/json",
169
+ "x-api-key": apiKey,
170
+ "anthropic-version": "2023-06-01",
171
+ },
172
+ body: JSON.stringify({
173
+ model,
174
+ stream,
175
+ max_tokens: 2048,
176
+ messages: [{ role: "user", content: normalizedPrompt }],
177
+ }),
178
+ };
179
+ }
180
+
181
+ const method = stream ? "streamGenerateContent" : "generateContent";
182
+ return {
183
+ url: `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:${method}`,
184
+ headers: {
185
+ "Content-Type": "application/json",
186
+ "x-goog-api-key": apiKey,
187
+ },
188
+ body: JSON.stringify({
189
+ contents: [
190
+ {
191
+ role: "user",
192
+ parts: [{ text: normalizedPrompt }],
193
+ },
194
+ ],
195
+ }),
196
+ };
197
+ }
198
+
199
+ async function parseStreamResponse({ provider, response, onChunk }) {
200
+ if (!response.body || typeof response.body.getReader !== "function") {
201
+ const fallbackPayload = await response.json();
202
+ const fallbackText = extractTextFromResponse(provider, fallbackPayload);
203
+ if (fallbackText && onChunk) {
204
+ onChunk(fallbackText);
205
+ }
206
+ return fallbackText;
207
+ }
208
+
209
+ const reader = response.body.getReader();
210
+ const decoder = new TextDecoder("utf-8");
211
+ let buffered = "";
212
+ let aggregated = "";
213
+
214
+ while (true) {
215
+ const { value, done } = await reader.read();
216
+ if (done) {
217
+ break;
218
+ }
219
+ buffered += decoder.decode(value, { stream: true });
220
+ const lines = buffered.split(/\r?\n/);
221
+ buffered = lines.pop() || "";
222
+
223
+ for (const line of lines) {
224
+ const dataPayload = parseStreamDataLine(line);
225
+ if (!dataPayload) {
226
+ continue;
227
+ }
228
+ const delta = parseStreamChunk(provider, dataPayload);
229
+ if (!delta) {
230
+ continue;
231
+ }
232
+ aggregated += delta;
233
+ if (onChunk) {
234
+ onChunk(delta);
235
+ }
236
+ }
237
+ }
238
+
239
+ buffered += decoder.decode();
240
+ if (buffered.trim()) {
241
+ const dataPayload = parseStreamDataLine(buffered);
242
+ if (dataPayload) {
243
+ const delta = parseStreamChunk(provider, dataPayload);
244
+ if (delta) {
245
+ aggregated += delta;
246
+ if (onChunk) {
247
+ onChunk(delta);
248
+ }
249
+ }
250
+ }
251
+ }
252
+
253
+ return aggregated.trim();
254
+ }
255
+
256
+ async function parseErrorBody(response) {
257
+ try {
258
+ const payload = await response.json();
259
+ return JSON.stringify(payload);
260
+ } catch {
261
+ try {
262
+ return await response.text();
263
+ } catch {
264
+ return "";
265
+ }
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Infer provider from available API-key environment variables.
271
+ *
272
+ * @param {NodeJS.ProcessEnv} [env]
273
+ * @returns {("openai" | "anthropic" | "google" | null)}
274
+ */
275
+ export function detectProviderFromEnv(env = process.env) {
276
+ for (const provider of SUPPORTED_PROVIDERS) {
277
+ const envVar = PROVIDER_ENV_KEYS[provider];
278
+ const value = String(env?.[envVar] || "").trim();
279
+ if (value) {
280
+ return provider;
281
+ }
282
+ }
283
+ return null;
284
+ }
285
+
286
+ /**
287
+ * Resolve provider precedence: explicit -> config -> environment -> default.
288
+ *
289
+ * @param {{ provider?: string, configProvider?: string, env?: NodeJS.ProcessEnv }} [options]
290
+ * @returns {"openai" | "anthropic" | "google"}
291
+ */
292
+ export function resolveProvider({ provider, configProvider, env = process.env } = {}) {
293
+ const explicit = normalizeProvider(provider);
294
+ if (explicit) {
295
+ return explicit;
296
+ }
297
+
298
+ const configured = normalizeProvider(configProvider);
299
+ if (configured) {
300
+ return configured;
301
+ }
302
+
303
+ const detected = detectProviderFromEnv(env);
304
+ if (detected) {
305
+ return detected;
306
+ }
307
+
308
+ return "openai";
309
+ }
310
+
311
+ /**
312
+ * Resolve model precedence for a provider: explicit -> config -> provider default.
313
+ *
314
+ * @param {{ provider?: string, model?: string, configModel?: string }} [options]
315
+ * @returns {string}
316
+ */
317
+ export function resolveModel({ provider, model, configModel } = {}) {
318
+ const normalizedProvider = resolveProvider({ provider });
319
+ const explicit = String(model || "").trim();
320
+ if (explicit) {
321
+ return explicit;
322
+ }
323
+ const configured = String(configModel || "").trim();
324
+ if (configured) {
325
+ return configured;
326
+ }
327
+ return DEFAULT_MODELS[normalizedProvider];
328
+ }
329
+
330
+ /**
331
+ * Resolve provider API key precedence: explicit -> provider-specific environment variable.
332
+ *
333
+ * @param {{ provider?: string, explicitApiKey?: string, env?: NodeJS.ProcessEnv }} [options]
334
+ * @returns {string}
335
+ */
336
+ export function resolveApiKey({ provider, explicitApiKey, env = process.env } = {}) {
337
+ const normalizedProvider = resolveProvider({ provider, env });
338
+ const explicit = String(explicitApiKey || "").trim();
339
+ if (explicit) {
340
+ return explicit;
341
+ }
342
+ const envKey = PROVIDER_ENV_KEYS[normalizedProvider];
343
+ const value = String(env?.[envKey] || "").trim();
344
+ if (!value) {
345
+ throw new Error(
346
+ `Missing API key for provider '${normalizedProvider}'. Set ${envKey} or provide explicitApiKey.`
347
+ );
348
+ }
349
+ return value;
350
+ }
351
+
352
+ /**
353
+ * Lightweight multi-provider text-generation client with retry, timeout, and streaming support.
354
+ */
355
+ export class MultiProviderApiClient {
356
+ /**
357
+ * @param {{
358
+ * fetchImpl?: typeof fetch,
359
+ * maxRetries?: number,
360
+ * baseDelayMs?: number,
361
+ * requestTimeoutMs?: number
362
+ * }} [options]
363
+ */
364
+ constructor({
365
+ fetchImpl = fetch,
366
+ maxRetries = 2,
367
+ baseDelayMs = 250,
368
+ requestTimeoutMs = 120000,
369
+ } = {}) {
370
+ if (typeof fetchImpl !== "function") {
371
+ throw new Error("fetchImpl must be a function.");
372
+ }
373
+ this.fetchImpl = fetchImpl;
374
+ this.maxRetries = Math.max(0, Number(maxRetries || 0));
375
+ this.baseDelayMs = Math.max(0, Number(baseDelayMs || 0));
376
+ this.requestTimeoutMs = Math.max(1000, Number(requestTimeoutMs || 0));
377
+ }
378
+
379
+ /**
380
+ * Invoke an LLM request for the selected provider/model and return normalized text output.
381
+ *
382
+ * @param {{
383
+ * provider?: string,
384
+ * model?: string,
385
+ * prompt?: string,
386
+ * stream?: boolean,
387
+ * apiKey?: string,
388
+ * env?: NodeJS.ProcessEnv,
389
+ * onChunk?: (chunk: string) => void
390
+ * }} [options]
391
+ * @returns {Promise<{ provider: string, model: string, text: string }>}
392
+ */
393
+ async invoke({
394
+ provider,
395
+ model,
396
+ prompt,
397
+ stream = false,
398
+ apiKey,
399
+ env = process.env,
400
+ onChunk,
401
+ } = {}) {
402
+ const resolvedProvider = resolveProvider({ provider, env });
403
+ const resolvedModel = resolveModel({ provider: resolvedProvider, model });
404
+ const resolvedApiKey = resolveApiKey({
405
+ provider: resolvedProvider,
406
+ explicitApiKey: apiKey,
407
+ env,
408
+ });
409
+
410
+ const request = buildProviderRequest({
411
+ provider: resolvedProvider,
412
+ apiKey: resolvedApiKey,
413
+ model: resolvedModel,
414
+ prompt,
415
+ stream: Boolean(stream),
416
+ });
417
+
418
+ let attempt = 0;
419
+ while (true) {
420
+ const controller = new AbortController();
421
+ const timeoutHandle = setTimeout(() => controller.abort(), this.requestTimeoutMs);
422
+ try {
423
+ const response = await this.fetchImpl(request.url, {
424
+ method: "POST",
425
+ headers: request.headers,
426
+ body: request.body,
427
+ signal: controller.signal,
428
+ });
429
+
430
+ if (!response.ok) {
431
+ if (attempt < this.maxRetries && isRetryableStatus(response.status)) {
432
+ const backoff = this.baseDelayMs * 2 ** attempt;
433
+ attempt += 1;
434
+ await sleep(backoff);
435
+ continue;
436
+ }
437
+
438
+ const errorBody = sanitizeSensitiveText(await parseErrorBody(response), {
439
+ apiKey: resolvedApiKey,
440
+ });
441
+ throw new Error(
442
+ `Provider request failed (${resolvedProvider}) with status ${response.status}${
443
+ errorBody ? `: ${errorBody}` : ""
444
+ }`
445
+ );
446
+ }
447
+
448
+ let text = "";
449
+ if (stream) {
450
+ text = await parseStreamResponse({
451
+ provider: resolvedProvider,
452
+ response,
453
+ onChunk,
454
+ });
455
+ } else {
456
+ const payload = await response.json();
457
+ text = extractTextFromResponse(resolvedProvider, payload);
458
+ }
459
+
460
+ return {
461
+ provider: resolvedProvider,
462
+ model: resolvedModel,
463
+ text,
464
+ };
465
+ } catch (error) {
466
+ const message = sanitizeSensitiveText(error instanceof Error ? error.message : String(error), {
467
+ apiKey: resolvedApiKey,
468
+ });
469
+ const isAbort = /aborted|abort/i.test(message);
470
+ if (attempt < this.maxRetries && !isAbort) {
471
+ const backoff = this.baseDelayMs * 2 ** attempt;
472
+ attempt += 1;
473
+ await sleep(backoff);
474
+ continue;
475
+ }
476
+ if (error instanceof Error) {
477
+ if (message === error.message) {
478
+ throw error;
479
+ }
480
+ throw new Error(message);
481
+ }
482
+ throw new Error(message);
483
+ } finally {
484
+ clearTimeout(timeoutHandle);
485
+ }
486
+ }
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Factory helper for `MultiProviderApiClient`.
492
+ *
493
+ * @param {ConstructorParameters<typeof MultiProviderApiClient>[0]} [options]
494
+ * @returns {MultiProviderApiClient}
495
+ */
496
+ export function createMultiProviderApiClient(options = {}) {
497
+ return new MultiProviderApiClient(options);
498
+ }
499
+
500
+ /**
501
+ * List provider identifiers currently supported by the client.
502
+ *
503
+ * @returns {string[]}
504
+ */
505
+ export function listSupportedProviders() {
506
+ return [...SUPPORTED_PROVIDERS];
507
+ }
508
+