@jxburros/ai-nugget 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +132 -385
  2. package/UPGRADING.md +158 -0
  3. package/dist/adapters/engines/anthropic.d.ts +7 -1
  4. package/dist/adapters/engines/anthropic.js +64 -37
  5. package/dist/adapters/engines/base.d.ts +29 -2
  6. package/dist/adapters/engines/base.js +52 -8
  7. package/dist/adapters/engines/google.d.ts +7 -1
  8. package/dist/adapters/engines/google.js +73 -29
  9. package/dist/adapters/engines/ollama.d.ts +2 -1
  10. package/dist/adapters/engines/ollama.js +51 -15
  11. package/dist/adapters/engines/openaiChat.d.ts +2 -1
  12. package/dist/adapters/engines/openaiChat.js +60 -30
  13. package/dist/adapters/profiles.d.ts +21 -1
  14. package/dist/adapters/profiles.js +12 -2
  15. package/dist/agent/loop.d.ts +43 -1
  16. package/dist/agent/loop.js +116 -12
  17. package/dist/cjs/adapters/engines/anthropic.js +308 -0
  18. package/dist/cjs/adapters/engines/base.js +147 -0
  19. package/dist/cjs/adapters/engines/google.js +284 -0
  20. package/dist/cjs/adapters/engines/ollama.js +199 -0
  21. package/dist/cjs/adapters/engines/openaiChat.js +261 -0
  22. package/dist/cjs/adapters/index.js +22 -0
  23. package/dist/cjs/adapters/profiles.js +125 -0
  24. package/dist/cjs/agent/index.js +18 -0
  25. package/dist/cjs/agent/loop.js +372 -0
  26. package/dist/cjs/agent/tools.js +51 -0
  27. package/dist/cjs/connect.js +27 -0
  28. package/dist/cjs/errors.js +110 -0
  29. package/dist/cjs/handler.js +561 -0
  30. package/dist/cjs/index.js +27 -0
  31. package/dist/cjs/json.js +121 -0
  32. package/dist/cjs/keys.js +81 -0
  33. package/dist/cjs/package.json +3 -0
  34. package/dist/cjs/policy.js +42 -0
  35. package/dist/cjs/redact.js +78 -0
  36. package/dist/cjs/tokens.js +22 -0
  37. package/dist/cjs/transport.js +172 -0
  38. package/dist/cjs/types.js +6 -0
  39. package/dist/cjs/util.js +112 -0
  40. package/dist/errors.js +25 -1
  41. package/dist/handler.d.ts +61 -1
  42. package/dist/handler.js +239 -59
  43. package/dist/redact.d.ts +18 -0
  44. package/dist/redact.js +29 -1
  45. package/dist/transport.d.ts +3 -1
  46. package/dist/transport.js +21 -1
  47. package/dist/types.d.ts +96 -2
  48. package/dist/util.d.ts +15 -0
  49. package/dist/util.js +46 -0
  50. package/nugget/VERSION.txt +2 -2
  51. package/nugget/dist/adapters/engines/anthropic.d.ts +14 -0
  52. package/nugget/dist/adapters/engines/anthropic.d.ts.map +1 -0
  53. package/nugget/dist/adapters/engines/anthropic.js +305 -0
  54. package/nugget/dist/adapters/engines/anthropic.js.map +1 -0
  55. package/nugget/dist/adapters/engines/base.d.ts +50 -0
  56. package/nugget/dist/adapters/engines/base.d.ts.map +1 -0
  57. package/nugget/dist/adapters/engines/base.js +137 -0
  58. package/nugget/dist/adapters/engines/base.js.map +1 -0
  59. package/nugget/dist/adapters/engines/google.d.ts +24 -0
  60. package/nugget/dist/adapters/engines/google.d.ts.map +1 -0
  61. package/nugget/dist/adapters/engines/google.js +281 -0
  62. package/nugget/dist/adapters/engines/google.js.map +1 -0
  63. package/nugget/dist/adapters/engines/ollama.d.ts +11 -0
  64. package/nugget/dist/adapters/engines/ollama.d.ts.map +1 -0
  65. package/nugget/dist/adapters/engines/ollama.js +196 -0
  66. package/nugget/dist/adapters/engines/ollama.js.map +1 -0
  67. package/nugget/dist/adapters/engines/openaiChat.d.ts +16 -0
  68. package/nugget/dist/adapters/engines/openaiChat.d.ts.map +1 -0
  69. package/nugget/dist/adapters/engines/openaiChat.js +258 -0
  70. package/nugget/dist/adapters/engines/openaiChat.js.map +1 -0
  71. package/nugget/dist/adapters/index.d.ts +5 -0
  72. package/nugget/dist/adapters/index.d.ts.map +1 -0
  73. package/nugget/dist/adapters/index.js +17 -0
  74. package/nugget/dist/adapters/index.js.map +1 -0
  75. package/nugget/dist/adapters/profiles.d.ts +62 -0
  76. package/nugget/dist/adapters/profiles.d.ts.map +1 -0
  77. package/nugget/dist/adapters/profiles.js +121 -0
  78. package/nugget/dist/adapters/profiles.js.map +1 -0
  79. package/nugget/dist/agent/index.d.ts +3 -0
  80. package/nugget/dist/agent/index.d.ts.map +1 -0
  81. package/nugget/dist/agent/index.js +3 -0
  82. package/nugget/dist/agent/index.js.map +1 -0
  83. package/nugget/dist/agent/loop.d.ts +112 -0
  84. package/nugget/dist/agent/loop.d.ts.map +1 -0
  85. package/nugget/dist/agent/loop.js +370 -0
  86. package/nugget/dist/agent/loop.js.map +1 -0
  87. package/nugget/dist/agent/tools.d.ts +29 -0
  88. package/nugget/dist/agent/tools.d.ts.map +1 -0
  89. package/nugget/dist/agent/tools.js +48 -0
  90. package/nugget/dist/agent/tools.js.map +1 -0
  91. package/nugget/dist/cjs/adapters/engines/anthropic.js +308 -0
  92. package/nugget/dist/cjs/adapters/engines/base.js +147 -0
  93. package/nugget/dist/cjs/adapters/engines/google.js +284 -0
  94. package/nugget/dist/cjs/adapters/engines/ollama.js +199 -0
  95. package/nugget/dist/cjs/adapters/engines/openaiChat.js +261 -0
  96. package/nugget/dist/cjs/adapters/index.js +22 -0
  97. package/nugget/dist/cjs/adapters/profiles.js +125 -0
  98. package/nugget/dist/cjs/agent/index.js +18 -0
  99. package/nugget/dist/cjs/agent/loop.js +372 -0
  100. package/nugget/dist/cjs/agent/tools.js +51 -0
  101. package/nugget/dist/cjs/connect.js +27 -0
  102. package/nugget/dist/cjs/errors.js +110 -0
  103. package/nugget/dist/cjs/handler.js +561 -0
  104. package/nugget/dist/cjs/index.js +27 -0
  105. package/nugget/dist/cjs/json.js +121 -0
  106. package/nugget/dist/cjs/keys.js +81 -0
  107. package/nugget/dist/cjs/package.json +3 -0
  108. package/nugget/dist/cjs/policy.js +42 -0
  109. package/nugget/dist/cjs/redact.js +78 -0
  110. package/nugget/dist/cjs/tokens.js +22 -0
  111. package/nugget/dist/cjs/transport.js +172 -0
  112. package/nugget/dist/cjs/types.js +6 -0
  113. package/nugget/dist/cjs/util.js +112 -0
  114. package/nugget/dist/connect.d.ts +31 -0
  115. package/nugget/dist/connect.d.ts.map +1 -0
  116. package/nugget/dist/connect.js +25 -0
  117. package/nugget/dist/connect.js.map +1 -0
  118. package/nugget/dist/errors.d.ts +22 -0
  119. package/nugget/dist/errors.d.ts.map +1 -0
  120. package/nugget/dist/errors.js +104 -0
  121. package/nugget/dist/errors.js.map +1 -0
  122. package/nugget/dist/handler.d.ts +108 -0
  123. package/nugget/dist/handler.d.ts.map +1 -0
  124. package/nugget/dist/handler.js +557 -0
  125. package/nugget/dist/handler.js.map +1 -0
  126. package/nugget/dist/index.d.ts +12 -0
  127. package/nugget/dist/index.d.ts.map +1 -0
  128. package/nugget/dist/index.js +12 -0
  129. package/nugget/dist/index.js.map +1 -0
  130. package/nugget/dist/json.d.ts +7 -0
  131. package/nugget/dist/json.d.ts.map +1 -0
  132. package/nugget/dist/json.js +114 -0
  133. package/nugget/dist/json.js.map +1 -0
  134. package/nugget/dist/keys.d.ts +7 -0
  135. package/nugget/dist/keys.d.ts.map +1 -0
  136. package/nugget/dist/keys.js +75 -0
  137. package/nugget/dist/keys.js.map +1 -0
  138. package/nugget/dist/policy.d.ts +6 -0
  139. package/nugget/dist/policy.d.ts.map +1 -0
  140. package/nugget/dist/policy.js +37 -0
  141. package/nugget/dist/policy.js.map +1 -0
  142. package/nugget/dist/redact.d.ts +26 -0
  143. package/nugget/dist/redact.d.ts.map +1 -0
  144. package/nugget/dist/redact.js +74 -0
  145. package/nugget/dist/redact.js.map +1 -0
  146. package/nugget/dist/tokens.d.ts +5 -0
  147. package/nugget/dist/tokens.d.ts.map +1 -0
  148. package/nugget/dist/tokens.js +18 -0
  149. package/nugget/dist/tokens.js.map +1 -0
  150. package/nugget/dist/transport.d.ts +30 -0
  151. package/nugget/dist/transport.d.ts.map +1 -0
  152. package/nugget/dist/transport.js +165 -0
  153. package/nugget/dist/transport.js.map +1 -0
  154. package/nugget/dist/types.d.ts +285 -0
  155. package/nugget/dist/types.d.ts.map +1 -0
  156. package/nugget/dist/types.js +4 -0
  157. package/nugget/dist/types.js.map +1 -0
  158. package/nugget/dist/util.d.ts +24 -0
  159. package/nugget/dist/util.d.ts.map +1 -0
  160. package/nugget/dist/util.js +101 -0
  161. package/nugget/dist/util.js.map +1 -0
  162. package/nugget/src/adapters/engines/anthropic.ts +62 -37
  163. package/nugget/src/adapters/engines/base.ts +50 -7
  164. package/nugget/src/adapters/engines/google.ts +72 -29
  165. package/nugget/src/adapters/engines/ollama.ts +51 -17
  166. package/nugget/src/adapters/engines/openaiChat.ts +61 -32
  167. package/nugget/src/adapters/profiles.ts +53 -3
  168. package/nugget/src/agent/loop.ts +153 -13
  169. package/nugget/src/errors.ts +25 -1
  170. package/nugget/src/handler.ts +279 -57
  171. package/nugget/src/redact.ts +32 -1
  172. package/nugget/src/transport.ts +20 -1
  173. package/nugget/src/types.ts +96 -1
  174. package/nugget/src/util.ts +50 -0
  175. package/package.json +18 -5
@@ -0,0 +1,557 @@
1
+ import { adapterFor } from './adapters/index.js';
2
+ import { applyAuth, profileFor } from './adapters/profiles.js';
3
+ import { AIError, fromUnknown } from './errors.js';
4
+ import { extractJson } from './json.js';
5
+ import { allowAllPolicy } from './policy.js';
6
+ import { SessionRedactor } from './redact.js';
7
+ import { promptChars, sleep } from './util.js';
8
+ /**
9
+ * A *startup* notice, so it fires once per process rather than once per handler
10
+ * — an app that builds a handler per request would otherwise flood its logs
11
+ * with a message that says the same thing every time.
12
+ */
13
+ let warnedNoPolicy = false;
14
+ /** Test seam: reset the once-per-process startup notice. */
15
+ export function resetPolicyWarningForTests() {
16
+ warnedNoPolicy = false;
17
+ }
18
+ export class AIHandler {
19
+ opts;
20
+ active = 0;
21
+ queue = [];
22
+ lastStarted = 0;
23
+ sessionRedactor = new SessionRedactor();
24
+ policy;
25
+ constructor(opts) {
26
+ this.opts = opts;
27
+ this.policy = opts.policy ?? allowAllPolicy();
28
+ // `allowAllPolicy()` stays the default — a library must not decide an app's
29
+ // governance — but "no policy configured" should be visible at runtime, not
30
+ // only in a README paragraph. Passing an explicit policy (including
31
+ // `allowAllPolicy()`) is the opt-out.
32
+ if (!opts.policy && !opts.silencePolicyWarning && !warnedNoPolicy) {
33
+ warnedNoPolicy = true;
34
+ globalThis.console?.warn?.('[ai-nugget] No GovernancePolicy configured — every provider/model is allowed. ' +
35
+ 'Pass `policy` (e.g. allowlistPolicy(...)), or `policy: allowAllPolicy()` / `silencePolicyWarning: true` to accept this deliberately.');
36
+ }
37
+ }
38
+ async chat(conn, req) {
39
+ let result;
40
+ for await (const event of this.stream(conn, req)) {
41
+ if (event.type === 'done')
42
+ result = event.result;
43
+ if (event.type === 'error')
44
+ throw event.error;
45
+ }
46
+ if (!result)
47
+ throw new AIError('Call ended without a result', { kind: 'invalid_response', provider: conn.provider });
48
+ return result;
49
+ }
50
+ async *stream(conn, req) {
51
+ const callId = createCallId();
52
+ const startedAt = Date.now();
53
+ const adapter = adapterFor(conn.provider, conn.baseUrl);
54
+ const preflight = await this.preflight(callId, conn, req.model, req.metadata);
55
+ if (!preflight.ok)
56
+ return yield* this.failStream(callId, conn, req, startedAt, 1, preflight.error);
57
+ // One idempotency key per logical call, reused across every retry attempt,
58
+ // so a provider that supports it collapses a re-sent generation instead of
59
+ // billing it twice (see `supportsIdempotencyKey` in the profile table).
60
+ const resolved = withIdempotencyKey(preflight.resolved, callId);
61
+ let acquired = false;
62
+ let recorded = false;
63
+ let attempt = 0;
64
+ try {
65
+ await this.acquire(req.signal);
66
+ acquired = true;
67
+ const maxAttempts = this.opts.retry?.maxAttempts ?? 3;
68
+ let emittedStart = false;
69
+ let emittedOutput = false;
70
+ for (;;) {
71
+ attempt += 1;
72
+ try {
73
+ for await (const event of adapter.stream(resolved, req)) {
74
+ if (event.type === 'start') {
75
+ if (!emittedStart) {
76
+ emittedStart = true;
77
+ yield { ...event, callId };
78
+ }
79
+ continue;
80
+ }
81
+ if (event.type === 'delta' || event.type === 'tool_call')
82
+ emittedOutput = true;
83
+ if (event.type === 'done') {
84
+ await this.recordSuccess(callId, conn, req, startedAt, attempt, event.result);
85
+ recorded = true;
86
+ yield event;
87
+ return;
88
+ }
89
+ yield event;
90
+ }
91
+ throw new AIError('Provider did not emit a done event', { kind: 'invalid_response', provider: conn.provider });
92
+ }
93
+ catch (errorValue) {
94
+ const error = fromUnknown(errorValue, conn.provider);
95
+ // `emittedOutput` stops retries once any byte has reached the caller:
96
+ // never silently re-run a partially delivered answer.
97
+ if (!error.retryable || attempt >= maxAttempts || req.signal?.aborted || emittedOutput) {
98
+ recorded = true;
99
+ return yield* this.failStream(callId, conn, req, startedAt, attempt, error);
100
+ }
101
+ const delayMs = this.retryDelay(error, attempt);
102
+ yield { type: 'retry', attempt, reason: error.kind, delayMs };
103
+ try {
104
+ await sleep(delayMs, req.signal);
105
+ }
106
+ catch (sleepError) {
107
+ recorded = true;
108
+ return yield* this.failStream(callId, conn, req, startedAt, attempt, fromUnknown(sleepError, conn.provider));
109
+ }
110
+ }
111
+ }
112
+ }
113
+ catch (errorValue) {
114
+ recorded = true;
115
+ return yield* this.failStream(callId, conn, req, startedAt, Math.max(1, attempt), fromUnknown(errorValue, conn.provider));
116
+ }
117
+ finally {
118
+ if (acquired)
119
+ this.release();
120
+ if (acquired && !recorded) {
121
+ await this.recordFailure(callId, conn, req, startedAt, Math.max(1, attempt), new AIError('Call canceled before completion', { kind: 'canceled', retryable: false, provider: conn.provider }));
122
+ }
123
+ }
124
+ }
125
+ /**
126
+ * The shared pre-call preamble: policy check → key resolution → `beforeCall`
127
+ * hook. Every entry point (`stream`, `embed`, `listModels`/`testConnection`)
128
+ * runs exactly this sequence, so it lives once. Failures are *returned*, not
129
+ * recorded — each caller owns its own telemetry shape (`recordFailure` for
130
+ * chat/probe, `recordEmbed` for embeddings) and records the returned error.
131
+ */
132
+ async preflight(callId, conn, model, metadata) {
133
+ const policyResult = this.policy.checkModel(conn.provider, model);
134
+ if (!policyResult.allowed) {
135
+ return { ok: false, error: new AIError(policyResult.reason, { kind: 'policy_blocked', retryable: false, provider: conn.provider }) };
136
+ }
137
+ let resolved;
138
+ try {
139
+ resolved = await this.resolveConnection(conn);
140
+ }
141
+ catch (errorValue) {
142
+ // Key resolution failures (missing/locked/denied) are a recorded outcome,
143
+ // not an uncaught throw — the traceability contract covers them too.
144
+ return { ok: false, error: fromUnknown(errorValue, conn.provider) };
145
+ }
146
+ try {
147
+ const info = {
148
+ callId,
149
+ connection: safeConnection(conn),
150
+ provider: conn.provider,
151
+ model,
152
+ metadata,
153
+ resolved: safeResolved(resolved),
154
+ };
155
+ if (await this.opts.hooks?.beforeCall?.(info) === 'deny') {
156
+ return { ok: false, error: new AIError('Call denied by beforeCall hook', { kind: 'policy_blocked', retryable: false, provider: conn.provider }) };
157
+ }
158
+ }
159
+ catch (errorValue) {
160
+ // A throwing beforeCall hook is a recorded, redacted outcome too — not
161
+ // an uncaught throw that skips telemetry and the redaction guarantee.
162
+ return { ok: false, error: fromUnknown(errorValue, conn.provider) };
163
+ }
164
+ return { ok: true, resolved };
165
+ }
166
+ /** Record a failed call and emit the single redacted `error` event for it. */
167
+ async *failStream(callId, conn, req, startedAt, attempts, error) {
168
+ await this.recordFailure(callId, conn, req, startedAt, attempts, error);
169
+ yield { type: 'error', error: this.redactedError(error) };
170
+ }
171
+ async listModels(conn) {
172
+ return this.runProbe(conn, '__listModels__', async (resolved) => {
173
+ const adapter = adapterFor(conn.provider, conn.baseUrl);
174
+ return adapter.listModels?.(resolved) ?? [];
175
+ });
176
+ }
177
+ async testConnection(conn) {
178
+ try {
179
+ return await this.runProbe(conn, '__testConnection__', async (resolved) => {
180
+ const adapter = adapterFor(conn.provider, conn.baseUrl);
181
+ const health = await adapter.health?.(resolved);
182
+ if (health) {
183
+ if (!health.ok)
184
+ throw new AIError(health.detail ?? 'Connection failed', { kind: 'network', retryable: false, provider: conn.provider });
185
+ return { ok: true, message: health.detail ?? 'Connection healthy' };
186
+ }
187
+ await adapter.listModels?.(resolved);
188
+ return { ok: true, message: 'Connection healthy' };
189
+ });
190
+ }
191
+ catch (error) {
192
+ return { ok: false, message: error instanceof Error ? this.redact(error.message) : 'Connection failed' };
193
+ }
194
+ }
195
+ /**
196
+ * Warm a connection so the first real call doesn't pay cold DNS/TLS and
197
+ * (for a local daemon) process spin-up on the hot path. Runs a lightweight
198
+ * health probe and never throws — call it once at boot. Combined with a CJS
199
+ * `require` path it removes the cold-start "offline" false negative.
200
+ */
201
+ async prewarm(conn) {
202
+ try {
203
+ await this.testConnection(conn);
204
+ }
205
+ catch {
206
+ // Warm-up only: a failure here just means the first real call pays the cost.
207
+ }
208
+ }
209
+ /**
210
+ * Chat that returns typed, validated output. Requests JSON mode, extracts the
211
+ * JSON from the reply, and validates it against any Standard Schema validator
212
+ * (Zod / Valibot / ArkType). On a validation miss it performs exactly one
213
+ * corrective retry that shows the model its error, then throws
214
+ * `invalid_response` if still invalid. No schema library is bundled — the
215
+ * caller supplies the schema.
216
+ */
217
+ async chatParsed(conn, req, schema) {
218
+ const base = { ...req, responseFormat: req.responseFormat ?? { type: 'json' } };
219
+ let result = await this.chat(conn, base);
220
+ let validated = await validateWithSchema(schema, result.text);
221
+ if (validated.ok)
222
+ return { data: validated.value, result };
223
+ const retry = {
224
+ ...base,
225
+ messages: [
226
+ ...base.messages,
227
+ { role: 'assistant', content: result.text },
228
+ { role: 'user', content: `That response did not match the required schema (${validated.message}). Reply again with ONLY a valid JSON value that matches it.` },
229
+ ],
230
+ };
231
+ result = await this.chat(conn, retry);
232
+ validated = await validateWithSchema(schema, result.text);
233
+ if (validated.ok)
234
+ return { data: validated.value, result };
235
+ throw new AIError(`Model output failed schema validation: ${validated.message}`, { kind: 'invalid_response', provider: conn.provider });
236
+ }
237
+ /**
238
+ * Produce embeddings through the same governed pipeline as chat: policy check,
239
+ * key resolution, `beforeCall` hook, concurrency, and exactly one redacted
240
+ * telemetry record. Throws a typed `invalid_request` error for providers whose
241
+ * adapter has no `embed` (Anthropic, Google) rather than failing silently.
242
+ */
243
+ async embed(conn, req) {
244
+ const callId = createCallId();
245
+ const startedAt = Date.now();
246
+ const inputChars = (Array.isArray(req.input) ? req.input : [req.input]).reduce((sum, text) => sum + text.length, 0);
247
+ const fail = async (error) => {
248
+ await this.recordEmbed(callId, conn, req, startedAt, { estimated: true }, inputChars, error);
249
+ throw this.redactedError(error);
250
+ };
251
+ const preflight = await this.preflight(callId, conn, req.model, req.metadata);
252
+ if (!preflight.ok)
253
+ return fail(preflight.error);
254
+ const resolved = preflight.resolved;
255
+ const adapter = adapterFor(conn.provider, conn.baseUrl);
256
+ if (!adapter.embed) {
257
+ return fail(new AIError(`Provider ${conn.provider} does not support embeddings`, { kind: 'invalid_request', retryable: false, provider: conn.provider }));
258
+ }
259
+ await this.acquire(req.signal);
260
+ try {
261
+ const result = await adapter.embed(resolved, req);
262
+ await this.recordEmbed(callId, conn, req, startedAt, result.usage, inputChars);
263
+ return result;
264
+ }
265
+ catch (errorValue) {
266
+ return fail(fromUnknown(errorValue, conn.provider));
267
+ }
268
+ finally {
269
+ this.release();
270
+ }
271
+ }
272
+ async recordEmbed(callId, conn, req, startedAt, usage, inputChars, error) {
273
+ const costUsd = error ? undefined : this.opts.pricing?.({ provider: conn.provider, model: req.model, usage });
274
+ await this.record({
275
+ callId,
276
+ connectionId: conn.id,
277
+ provider: conn.provider,
278
+ model: req.model,
279
+ startedAt,
280
+ timing: { firstTokenMs: null, totalMs: Date.now() - startedAt },
281
+ usage,
282
+ finishReason: error ? (error.kind === 'canceled' ? 'canceled' : 'error') : 'stop',
283
+ ...(error ? { error: { kind: error.kind, status: error.status, message: error.message } } : {}),
284
+ attempts: 1,
285
+ metadata: { ...req.metadata, operation: '__embed__' },
286
+ promptChars: inputChars,
287
+ responseChars: 0,
288
+ ...(costUsd !== undefined ? { costUsd } : {}),
289
+ });
290
+ }
291
+ async runProbe(conn, operation, action) {
292
+ const callId = createCallId();
293
+ const startedAt = Date.now();
294
+ const req = { model: operation, messages: [], metadata: { operation } };
295
+ try {
296
+ const preflight = await this.preflight(callId, conn, operation, req.metadata);
297
+ if (!preflight.ok)
298
+ throw preflight.error;
299
+ const resolved = preflight.resolved;
300
+ await this.acquire(undefined);
301
+ try {
302
+ const value = await action(resolved);
303
+ await this.recordSuccess(callId, conn, req, startedAt, 1, {
304
+ text: '',
305
+ finishReason: 'stop',
306
+ usage: { estimated: true },
307
+ timing: { firstTokenMs: null, totalMs: Date.now() - startedAt },
308
+ model: operation,
309
+ source: { provider: conn.provider, connectionId: conn.id, baseUrl: resolved.baseUrl },
310
+ });
311
+ return value;
312
+ }
313
+ finally {
314
+ this.release();
315
+ }
316
+ }
317
+ catch (errorValue) {
318
+ const error = fromUnknown(errorValue, conn.provider);
319
+ await this.recordFailure(callId, conn, req, startedAt, 1, error);
320
+ throw this.redactedError(error);
321
+ }
322
+ }
323
+ async resolveConnection(conn) {
324
+ const profile = profileFor(conn.provider, conn.baseUrl);
325
+ const baseUrl = conn.baseUrl ?? profile.defaultBaseUrl;
326
+ if (!baseUrl)
327
+ throw new AIError(`Provider ${conn.provider} requires baseUrl`, { kind: 'invalid_request', retryable: false, provider: conn.provider });
328
+ const keyRef = conn.keyRef ?? { kind: 'none' };
329
+ const key = await this.opts.keySource.resolve(keyRef);
330
+ if (!key.ok) {
331
+ throw new AIError(`API key unavailable: ${key.reason}`, { kind: 'key_unavailable', retryable: false, provider: conn.provider });
332
+ }
333
+ this.sessionRedactor.addSecret(key.apiKey);
334
+ return {
335
+ ...conn,
336
+ baseUrl: trimSlash(baseUrl),
337
+ apiKey: key.apiKey,
338
+ headers: applyAuth(profile, key.apiKey, conn.headers ?? {}),
339
+ };
340
+ }
341
+ async acquire(signal) {
342
+ const max = this.opts.limits?.maxConcurrent ?? Number.POSITIVE_INFINITY;
343
+ while (this.active >= max) {
344
+ await new Promise((resolve, reject) => {
345
+ let waiter;
346
+ const onAbort = () => {
347
+ const index = this.queue.indexOf(waiter);
348
+ if (index >= 0)
349
+ this.queue.splice(index, 1);
350
+ reject(new AIError('Call canceled while waiting for concurrency slot', { kind: 'canceled', retryable: false }));
351
+ };
352
+ if (signal?.aborted) {
353
+ reject(new AIError('Call canceled while waiting for concurrency slot', { kind: 'canceled', retryable: false }));
354
+ return;
355
+ }
356
+ signal?.addEventListener('abort', onAbort, { once: true });
357
+ waiter = { resolve, reject, signal, onAbort };
358
+ this.queue.push(waiter);
359
+ });
360
+ }
361
+ this.active += 1;
362
+ const minInterval = this.opts.limits?.minIntervalMs ?? 0;
363
+ const previousLastStarted = this.lastStarted;
364
+ const wait = Math.max(0, previousLastStarted + minInterval - Date.now());
365
+ const reserved = Date.now() + wait;
366
+ this.lastStarted = reserved;
367
+ try {
368
+ if (wait)
369
+ await sleep(wait, signal);
370
+ }
371
+ catch (error) {
372
+ this.release();
373
+ // Only undo our own reservation — a later caller may have already
374
+ // paced itself off `reserved` and must keep that spacing.
375
+ if (this.lastStarted === reserved)
376
+ this.lastStarted = previousLastStarted;
377
+ throw error;
378
+ }
379
+ }
380
+ release() {
381
+ this.active = Math.max(0, this.active - 1);
382
+ while (this.queue.length) {
383
+ const waiter = this.queue.shift();
384
+ waiter.signal?.removeEventListener('abort', waiter.onAbort);
385
+ if (waiter.signal?.aborted)
386
+ continue;
387
+ waiter.resolve();
388
+ break;
389
+ }
390
+ }
391
+ retryDelay(error, attempt) {
392
+ const base = this.opts.retry?.baseDelayMs ?? 250;
393
+ const max = this.opts.retry?.maxDelayMs ?? 30_000;
394
+ if (error.retryAfterMs !== undefined)
395
+ return Math.min(error.retryAfterMs, max);
396
+ const exponential = Math.min(max, base * 2 ** Math.max(0, attempt - 1));
397
+ return Math.round(exponential * (0.75 + Math.random() * 0.5));
398
+ }
399
+ async recordSuccess(callId, conn, req, startedAt, attempts, result) {
400
+ const costUsd = this.opts.pricing?.({ provider: conn.provider, model: req.model, usage: result.usage });
401
+ await this.record({
402
+ callId,
403
+ connectionId: conn.id,
404
+ provider: conn.provider,
405
+ model: req.model,
406
+ startedAt,
407
+ timing: result.timing,
408
+ usage: result.usage,
409
+ finishReason: result.finishReason,
410
+ attempts,
411
+ metadata: req.metadata,
412
+ promptChars: promptChars(req.messages),
413
+ responseChars: result.text.length,
414
+ ...(costUsd !== undefined ? { costUsd } : {}),
415
+ });
416
+ }
417
+ async recordFailure(callId, conn, req, startedAt, attempts, error) {
418
+ await this.record({
419
+ callId,
420
+ connectionId: conn.id,
421
+ provider: conn.provider,
422
+ model: req.model,
423
+ startedAt,
424
+ timing: { firstTokenMs: null, totalMs: Date.now() - startedAt },
425
+ usage: { estimated: true },
426
+ finishReason: error.kind === 'canceled' ? 'canceled' : 'error',
427
+ error: { kind: error.kind, status: error.status, message: error.message },
428
+ attempts,
429
+ metadata: req.metadata,
430
+ promptChars: promptChars(req.messages),
431
+ responseChars: 0,
432
+ });
433
+ }
434
+ async record(record) {
435
+ const redacted = redactRecord(record, (text) => this.redact(text));
436
+ try {
437
+ await this.opts.telemetry?.record(redacted);
438
+ await this.opts.hooks?.afterCall?.(redacted);
439
+ }
440
+ catch {
441
+ // Telemetry and afterCall hooks must not re-drive provider calls or turn
442
+ // an already-completed model response into a retry.
443
+ }
444
+ }
445
+ redact(text) {
446
+ return (this.opts.redactor ?? this.sessionRedactor).redact(this.sessionRedactor.redact(text));
447
+ }
448
+ redactedError(error) {
449
+ return new AIError(this.redact(error.message), {
450
+ kind: error.kind,
451
+ status: error.status,
452
+ retryable: error.retryable,
453
+ provider: error.provider,
454
+ raw: error.raw === undefined ? undefined : this.redact(error.raw),
455
+ retryAfterMs: error.retryAfterMs,
456
+ cause: this.redactedCause(error.cause),
457
+ });
458
+ }
459
+ redactedCause(cause) {
460
+ if (cause instanceof Error) {
461
+ const redacted = new Error(this.redact(cause.message));
462
+ redacted.name = cause.name;
463
+ redacted.stack = undefined;
464
+ return redacted;
465
+ }
466
+ return cause;
467
+ }
468
+ }
469
+ function redactRecord(record, redact) {
470
+ return {
471
+ ...record,
472
+ error: record.error ? { ...record.error, message: redact(record.error.message) } : undefined,
473
+ metadata: redactMetadata(record.metadata, redact),
474
+ };
475
+ }
476
+ /**
477
+ * Redacts metadata by round-tripping through JSON. Metadata is an app-supplied
478
+ * passthrough and may contain values JSON cannot represent (BigInt, circular
479
+ * references, functions); redaction must never throw, so a non-serializable
480
+ * payload is replaced with a sentinel rather than crashing the telemetry path.
481
+ */
482
+ function redactMetadata(metadata, redact) {
483
+ if (!metadata)
484
+ return undefined;
485
+ try {
486
+ return JSON.parse(redact(JSON.stringify(metadata)));
487
+ }
488
+ catch {
489
+ return { redacted: true, note: 'metadata was not JSON-serializable' };
490
+ }
491
+ }
492
+ function trimSlash(value) {
493
+ return value.replace(/\/+$/, '');
494
+ }
495
+ /**
496
+ * Drops the resolved API key *and* neutralizes the auth headers built from it,
497
+ * so a `beforeCall` hook can inspect the endpoint but never the secret.
498
+ * `keyRef` is scrubbed too — a `{ kind: 'literal' }` ref carries the plaintext
499
+ * key, and hooks routinely log the whole object.
500
+ */
501
+ function safeResolved(resolved) {
502
+ const { apiKey: _apiKey, headers, ...rest } = resolved;
503
+ return { ...rest, ...safeKeyRef(resolved), headers: maskAuthHeaders(headers) };
504
+ }
505
+ /**
506
+ * The caller's own `Connection`, with any plaintext `keyRef` masked. Hooks get
507
+ * the connection so they can key off `id`/`provider`/`baseUrl`; they must never
508
+ * be handed the secret, since logging `info.connection` for audit is the
509
+ * obvious thing to do and would otherwise ship the key in clear text.
510
+ */
511
+ function safeConnection(conn) {
512
+ return { ...conn, ...safeKeyRef(conn) };
513
+ }
514
+ function safeKeyRef(conn) {
515
+ if (conn.keyRef?.kind !== 'literal')
516
+ return conn.keyRef === undefined ? {} : { keyRef: conn.keyRef };
517
+ return { keyRef: { kind: 'literal', value: REDACTED } };
518
+ }
519
+ const REDACTED = '[REDACTED]';
520
+ /** Header names whose value is derived from the API key by {@link applyAuth}. */
521
+ const AUTH_HEADERS = new Set(['authorization', 'x-api-key', 'x-goog-api-key', 'api-key']);
522
+ function maskAuthHeaders(headers) {
523
+ const masked = {};
524
+ for (const [name, value] of Object.entries(headers)) {
525
+ masked[name] = AUTH_HEADERS.has(name.toLowerCase()) ? REDACTED : value;
526
+ }
527
+ return masked;
528
+ }
529
+ /**
530
+ * Attach a per-call `Idempotency-Key` for providers that honor one, so a retry
531
+ * after a dropped connection can't be billed as a second generation. Only set
532
+ * where the profile declares support, and never overrides a caller-supplied
533
+ * header.
534
+ */
535
+ function withIdempotencyKey(resolved, callId) {
536
+ const profile = profileFor(resolved.provider, resolved.baseUrl);
537
+ if (!profile.quirks?.supportsIdempotencyKey)
538
+ return resolved;
539
+ if (Object.keys(resolved.headers).some((name) => name.toLowerCase() === 'idempotency-key'))
540
+ return resolved;
541
+ return { ...resolved, headers: { ...resolved.headers, 'idempotency-key': callId } };
542
+ }
543
+ async function validateWithSchema(schema, text) {
544
+ const value = extractJson(text);
545
+ if (value === null)
546
+ return { ok: false, message: 'no JSON found in model output' };
547
+ const result = await schema['~standard'].validate(value);
548
+ if (result.issues) {
549
+ const message = result.issues.map((issue) => issue.message).join('; ');
550
+ return { ok: false, message: message || 'validation failed' };
551
+ }
552
+ return { ok: true, value: result.value };
553
+ }
554
+ function createCallId() {
555
+ return globalThis.crypto?.randomUUID?.() ?? `call_${Date.now()}_${Math.random().toString(36).slice(2)}`;
556
+ }
557
+ //# sourceMappingURL=handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.js","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,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OAAO,EAAE,+BAA+B,EAAE,CAAC;IACnF,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzD,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAClB,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,CAAC;IAChE,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;AAC3C,CAAC;AAED,SAAS,YAAY;IACnB,OAAO,UAAU,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,IAAI,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1G,CAAC"}
@@ -0,0 +1,12 @@
1
+ export * from './types.js';
2
+ export * from './errors.js';
3
+ export * from './transport.js';
4
+ export * from './json.js';
5
+ export * from './tokens.js';
6
+ export * from './keys.js';
7
+ export * from './connect.js';
8
+ export * from './redact.js';
9
+ export * from './policy.js';
10
+ export * from './handler.js';
11
+ export * from './adapters/index.js';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC"}
@@ -0,0 +1,12 @@
1
+ export * from './types.js';
2
+ export * from './errors.js';
3
+ export * from './transport.js';
4
+ export * from './json.js';
5
+ export * from './tokens.js';
6
+ export * from './keys.js';
7
+ export * from './connect.js';
8
+ export * from './redact.js';
9
+ export * from './policy.js';
10
+ export * from './handler.js';
11
+ export * from './adapters/index.js';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC"}
@@ -0,0 +1,7 @@
1
+ export declare function extractJson(text: string): unknown | null;
2
+ export declare function extractJsonWithSchema<T>(text: string, parse: (value: unknown) => T): T;
3
+ export declare function requireString(record: Record<string, unknown>, key: string): string;
4
+ export declare function requireNumber(record: Record<string, unknown>, key: string): number;
5
+ export declare function requireStringArray(record: Record<string, unknown>, key: string): string[];
6
+ export declare function requireOptionalString(record: Record<string, unknown>, key: string): string | undefined;
7
+ //# sourceMappingURL=json.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAEA,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAmBxD;AA0CD,wBAAgB,qBAAqB,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,CAAC,GAAG,CAAC,CAStF;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAIlF;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAIlF;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAMzF;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAKtG"}