@x1a0f3n9/dsh-llm 0.1.2-alpha.6

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.
package/lib/index.js ADDED
@@ -0,0 +1,1758 @@
1
+ import { createRequire } from "node:module";
2
+ import { Remote, RemoteError, TypertRemoteService } from "@x1a0f3n9/dsh-typert-protocol";
3
+ import { assertNever, deepFreeze } from "@x1a0f3n9/dsh-util-values";
4
+ import { randomUUID } from "@x1a0f3n9/dsh-util-crypto";
5
+ import { brandString } from "@x1a0f3n9/dsh-brand";
6
+ import z from "@deepseek-ai/schemastery";
7
+ import { MAX_TIMER_DELAY_MS } from "@x1a0f3n9/dsh-timeout";
8
+ //#region lib/types/message.js
9
+ /** Message value types, identity, and immutable construction helpers. */
10
+ /**
11
+ * Bound for a `notice` summary. The account rides a collapsed transcript row
12
+ * and is committed to the durable log, while its inputs — task labels, goal
13
+ * objectives, tool arguments — are caller text with no length of their own.
14
+ */
15
+ const CONTEXT_SUMMARY_MAX_CHARS = 120;
16
+ /**
17
+ * Bound one `notice` summary to {@link CONTEXT_SUMMARY_MAX_CHARS}.
18
+ * @param summary - the producer's one-line account, of any length.
19
+ * @returns the account, ellipsized when it exceeds the bound.
20
+ */
21
+ function boundContextSummary(summary) {
22
+ return summary.length <= 120 ? summary : `${summary.slice(0, 119)}…`;
23
+ }
24
+ /**
25
+ * Detach and deep-freeze a message whose identity already exists.
26
+ * @param message - complete message, including its stable identity.
27
+ * @returns an immutable snapshot that preserves the identity.
28
+ */
29
+ function freezeMessage(message) {
30
+ return deepFreeze(structuredClone(message));
31
+ }
32
+ /**
33
+ * Create one identified message and freeze it before publication.
34
+ * @param input - complete role, content, and source for a new message.
35
+ * @returns an immutable message with a fresh stable identity.
36
+ */
37
+ function createMessage(input) {
38
+ return freezeMessage({
39
+ ...input,
40
+ id: brandString(randomUUID())
41
+ });
42
+ }
43
+ /**
44
+ * Create one identified user-role message and freeze it before publication.
45
+ * @param input - complete content and source for a new user message.
46
+ * @returns an immutable user message with a fresh stable identity.
47
+ */
48
+ function createUserMessage(input) {
49
+ return createMessage({
50
+ ...input,
51
+ role: "user"
52
+ });
53
+ }
54
+ /**
55
+ * Create one identified model-produced assistant message and freeze it before publication.
56
+ * @param input - complete content plus the provider, model, and optional replay state for a new assistant message.
57
+ * @returns an immutable assistant message with fixed role/source tags and a fresh stable identity.
58
+ */
59
+ function createAssistantMessage(input) {
60
+ return createMessage({
61
+ role: "assistant",
62
+ content: input.content,
63
+ source: {
64
+ kind: "model",
65
+ ...input.source
66
+ }
67
+ });
68
+ }
69
+ /**
70
+ * Create and freeze one identified tool-result message.
71
+ * @param input - call identity, raw result blocks, and outcome.
72
+ * @returns an immutable user-role tool-result message.
73
+ */
74
+ function createToolResultMessage(input) {
75
+ return createUserMessage({
76
+ source: {
77
+ kind: "tool",
78
+ callId: input.callId
79
+ },
80
+ content: [{
81
+ type: "tool-result",
82
+ toolCallId: input.callId,
83
+ content: input.content,
84
+ isError: input.isError
85
+ }]
86
+ });
87
+ }
88
+ //#endregion
89
+ //#region lib/types/error.js
90
+ /**
91
+ * Harness error base with a stable machine-routable code and chained cause.
92
+ * Package errors extend it so tool results and replay can retain failure class.
93
+ * @module @x1a0f3n9/dsh-llm/error
94
+ */
95
+ /**
96
+ * Base class for all harness errors. Carries a `code` (stable, programmatic —
97
+ * e.g. `NO_ADAPTER`, `INVALID_ARGS`, `INVARIANT`) distinct from the
98
+ * human-readable `message`, and supports `cause` chaining via the standard
99
+ * `ErrorOptions`. `name` defaults to the subclass constructor name.
100
+ */
101
+ var HarnessError = class extends Error {
102
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
103
+ code;
104
+ constructor(message, code, options) {
105
+ super(message, options);
106
+ this.code = code;
107
+ this.name = new.target.name;
108
+ }
109
+ };
110
+ /** Canonical provider-neutral code for a model request rejected because its context window was exceeded. */
111
+ const CONTEXT_WINDOW_EXCEEDED_CODE = "CONTEXT_WINDOW_EXCEEDED";
112
+ /** Canonical provider-neutral code for an exhausted account quota or balance. */
113
+ const QUOTA_EXCEEDED_CODE = "QUOTA";
114
+ /**
115
+ * Canonical provider-neutral code for a response that completed normally but
116
+ * carried no content blocks at all. Providers occasionally emit a degenerate
117
+ * completion (a terminal stop with zero output); adapters classify it as this
118
+ * failure instead of yielding an empty assistant message, because an empty
119
+ * message silently ends the turn with nothing for the user or the loop to act
120
+ * on. The attempt produced nothing durable, so retry policy treats it as safe
121
+ * to repeat.
122
+ */
123
+ const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
124
+ /**
125
+ * Canonical provider-neutral code for a credential that was supplied but
126
+ * cannot be used — malformed rather than absent. Distinct from
127
+ * `MISSING_CREDENTIAL` because the fix differs: correct the stored value
128
+ * rather than supply one. Deliberately outside the default retryable set —
129
+ * a malformed credential fails identically on every attempt.
130
+ */
131
+ const INVALID_CREDENTIAL_CODE = "INVALID_CREDENTIAL";
132
+ /** Structured codes and plain phrases that explicitly name a context bound being exceeded. */
133
+ const STRUCTURED_CONTEXT_OVERFLOW = new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` + String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`, "i");
134
+ /** Request-size wording that ties "too large" directly to model context capacity. */
135
+ const TOO_LARGE_FOR_CONTEXT = new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?` + String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?` + String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`, "i");
136
+ /** "Exceeds" wording is safe only when its object is explicitly the model context. */
137
+ const EXCEEDS_MODEL_CONTEXT = new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}` + String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}` + String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`, "i");
138
+ /**
139
+ * Recognize the context-overflow wording used by OpenAI-compatible providers
140
+ * and library adapters. Adapters pass all available provider code, type, and
141
+ * message text so both thrown and in-band delivery styles share one classifier.
142
+ * @param detail - provider error code/type/message text joined into one string.
143
+ * @returns true when the detail identifies a request exceeding the model context window.
144
+ */
145
+ function isContextWindowExceededError(detail) {
146
+ return STRUCTURED_CONTEXT_OVERFLOW.test(detail) || /\b(?:maximum|max)(?:\s+(?:allowed|supported))?\s+context\s+(?:length|window)\b/i.test(detail) || TOO_LARGE_FOR_CONTEXT.test(detail) || /\b(?:input|prompt|request)\s+(?:is\s+)?too\s+(?:long|large)\s+for\s+(?:this|the)\s+model\b/i.test(detail) || EXCEEDS_MODEL_CONTEXT.test(detail);
147
+ }
148
+ /**
149
+ * Recognize provider wording that identifies an exhausted account quota rather
150
+ * than a transient request-rate limit.
151
+ * @param detail - provider error code/type/message text joined into one string.
152
+ * @returns true only for terminal quota, balance, credit, budget, or usage-limit wording.
153
+ */
154
+ function isQuotaExceededError(detail) {
155
+ return /\binsufficient[\s_-]+(?:quota|balance|credits?)\b/i.test(detail) || /\b(?:quota|usage[\s_-]+limit)[\s_-]+(?:exceeded|exhausted|reached)\b/i.test(detail) || /\bexceed(?:ed|s)?[\s_-]+(?:(?:your|the)[\s_-]+)?(?:current[\s_-]+)?quota\b/i.test(detail) || /\b(?:balance|credits?)[\s_-]+(?:exhausted|depleted)\b/i.test(detail) || /\bout[\s_-]+of[\s_-]+(?:credits?|budget)\b/i.test(detail);
156
+ }
157
+ /**
158
+ * Render a thrown value with its full `cause` chain and AggregateError
159
+ * members, so transport wrappers like undici's `TypeError: fetch failed`
160
+ * surface the underlying failure instead of masking it. Plain structured
161
+ * failures render their own data-backed `message`. Diagnostic-surface
162
+ * rendering only (messages, notices, logs) — never parse the result; route on
163
+ * {@link HarnessError.code}.
164
+ * @param value - the caught value (`unknown` in catch clauses).
165
+ * @returns the outermost message first, each cause appended with `: ` (skipped
166
+ * when it repeats the wrapper message verbatim), and AggregateError members
167
+ * bracketed and `; `-joined.
168
+ */
169
+ function errorChain(value) {
170
+ const path = /* @__PURE__ */ new Set();
171
+ const render = (current) => {
172
+ if (path.has(current)) return "<circular cause>";
173
+ path.add(current);
174
+ try {
175
+ if (!(current instanceof Error)) {
176
+ if (typeof current === "object" && current !== null) {
177
+ const descriptor = Object.getOwnPropertyDescriptor(current, "message");
178
+ if (descriptor !== void 0 && "value" in descriptor && typeof descriptor.value === "string") return descriptor.value;
179
+ }
180
+ return String(current);
181
+ }
182
+ const message = current.message === "" ? current.name : current.message;
183
+ const members = current instanceof AggregateError && current.errors.length > 0 ? ` [${current.errors.map(render).join("; ")}]` : "";
184
+ const causeText = current.cause === void 0 || current.cause === null ? "" : render(current.cause);
185
+ return `${message}${members}${causeText === "" || causeText === message ? "" : `: ${causeText}`}`;
186
+ } catch {
187
+ return "<unrenderable value>";
188
+ } finally {
189
+ path.delete(current);
190
+ }
191
+ };
192
+ return render(value);
193
+ }
194
+ /**
195
+ * Narrow an arbitrary thrown value to a HarnessError (for `instanceof` at runtime boundaries).
196
+ * @param value - the caught value (`unknown` in catch clauses).
197
+ * @returns true only for real instances; duck-typed or cross-realm errors do not narrow.
198
+ */
199
+ function isHarnessError(value) {
200
+ return value instanceof HarnessError;
201
+ }
202
+ //#endregion
203
+ //#region lib/types/retry-policy.js
204
+ /**
205
+ * Provider-owned request-retry policy configuration and resolution.
206
+ *
207
+ * Adapters expose one resolved policy per registered provider route; the
208
+ * optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
209
+ *
210
+ * @module @x1a0f3n9/dsh-llm/retry-policy
211
+ */
212
+ const DEFAULT_MAX_RETRIES = 5;
213
+ const DEFAULT_INITIAL_DELAY_MS = 500;
214
+ const DEFAULT_MAX_DELAY_MS = 1e4;
215
+ const DEFAULT_JITTER_RATIO = .1;
216
+ const DEFAULT_RETRYABLE_CODES = Object.freeze([
217
+ EMPTY_RESPONSE_CODE,
218
+ "RATE_LIMIT",
219
+ "SERVER",
220
+ "TIMEOUT",
221
+ "TRANSPORT"
222
+ ]);
223
+ const backoffSchema = z.object({
224
+ initialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
225
+ maxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
226
+ jitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
227
+ });
228
+ const normalPolicySchema = z.object({
229
+ mode: z.const("normal").required(),
230
+ maxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
231
+ retryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),
232
+ backoff: backoffSchema
233
+ });
234
+ const alwaysPolicySchema = z.object({
235
+ mode: z.const("always").required(),
236
+ backoff: backoffSchema
237
+ });
238
+ /** Cordis schema embedded by each concrete provider configuration. */
239
+ const RetryPolicySchema = z.union([normalPolicySchema, alwaysPolicySchema]);
240
+ const NORMAL_POLICY_KEYS = new Set([
241
+ "mode",
242
+ "maxRetries",
243
+ "retryableCodes",
244
+ "backoff"
245
+ ]);
246
+ const ALWAYS_POLICY_KEYS = new Set([
247
+ "mode",
248
+ "maxRetries",
249
+ "retryableCodes",
250
+ "backoff"
251
+ ]);
252
+ const BACKOFF_KEYS = new Set([
253
+ "initialDelayMs",
254
+ "maxDelayMs",
255
+ "jitterRatio"
256
+ ]);
257
+ function validateKeys(value, allowed, path) {
258
+ for (const key of Object.keys(value)) if (!allowed.has(key)) throw new Error(`${path}: unknown key "${key}"`);
259
+ }
260
+ function resolveBackoff(config, path) {
261
+ if (config !== void 0) validateKeys(config, BACKOFF_KEYS, path);
262
+ const initialDelayMs = config?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
263
+ const maxDelayMs = config?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
264
+ const jitterRatio = config?.jitterRatio ?? DEFAULT_JITTER_RATIO;
265
+ if (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
266
+ if (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > MAX_TIMER_DELAY_MS) throw new Error(`${path}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
267
+ if (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
268
+ if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) throw new Error(`${path}.jitterRatio must be between 0 and 1`);
269
+ return Object.freeze({
270
+ initialDelayMs,
271
+ maxDelayMs,
272
+ jitterRatio
273
+ });
274
+ }
275
+ /**
276
+ * Validate, default, and detach one provider-owned retry policy.
277
+ * @param config - optional provider configuration; omission selects normal defaults.
278
+ * @param path - diagnostic path naming the provider config that owns the value.
279
+ * @returns an immutable policy safe to capture in provider registration state.
280
+ */
281
+ function resolveRetryPolicy(config, path) {
282
+ if (config === void 0) return Object.freeze({
283
+ mode: "normal",
284
+ maxRetries: DEFAULT_MAX_RETRIES,
285
+ retryableCodes: DEFAULT_RETRYABLE_CODES,
286
+ ...resolveBackoff(void 0, `${path}.backoff`)
287
+ });
288
+ switch (config.mode) {
289
+ case "normal": {
290
+ validateKeys(config, NORMAL_POLICY_KEYS, path);
291
+ const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
292
+ const retryableCodes = config.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];
293
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) throw new Error(`${path}.maxRetries must be a non-negative safe integer`);
294
+ if (retryableCodes.length === 0) throw new Error(`${path}.retryableCodes must not be empty`);
295
+ if (retryableCodes.some((code) => typeof code !== "string" || code.length === 0)) throw new Error(`${path}.retryableCodes must contain only non-empty strings`);
296
+ if (new Set(retryableCodes).size !== retryableCodes.length) throw new Error(`${path}.retryableCodes must not contain duplicates`);
297
+ return Object.freeze({
298
+ mode: "normal",
299
+ maxRetries,
300
+ retryableCodes: Object.freeze([...retryableCodes]),
301
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
302
+ });
303
+ }
304
+ case "always":
305
+ validateKeys(config, ALWAYS_POLICY_KEYS, path);
306
+ return Object.freeze({
307
+ mode: "always",
308
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
309
+ });
310
+ default: throw new Error(`${path}.mode must be "normal" or "always"`);
311
+ }
312
+ }
313
+ //#endregion
314
+ //#region lib/types/call-config.js
315
+ /**
316
+ * Conversation call configuration and freeze utilities. Provider routing,
317
+ * model, reasoning effort, and sampling values are request-header state that
318
+ * can affect cache reuse; request waterfalls replace them and the loop logs
319
+ * changed snapshots instead of allowing silent per-call drift.
320
+ * @module dsh-llm/call-config
321
+ */
322
+ /** Process-local identities of request objects assembled by dsh-agent-loop. */
323
+ const AGENT_LOOP_REQUESTS = /* @__PURE__ */ new WeakSet();
324
+ /**
325
+ * Field-wise equality over {@link LlmCallConfig} — the comparison a caller
326
+ * runs to decide whether a proposed configuration is a real change (worth a
327
+ * logged header snapshot) or the held one restated.
328
+ * @param a - one configuration.
329
+ * @param b - the other.
330
+ * @returns whether every field (including the `stop` list, element-wise) matches.
331
+ */
332
+ function callConfigEquals(a, b) {
333
+ if (a.provider !== b.provider || a.model !== b.model || a.reasoningEffort !== b.reasoningEffort || a.temperature !== b.temperature || a.maxTokens !== b.maxTokens) return false;
334
+ if (a.stop === void 0 || b.stop === void 0) return a.stop === b.stop;
335
+ return a.stop.length === b.stop.length && a.stop.every((s, i) => s === b.stop?.[i]);
336
+ }
337
+ /**
338
+ * Mark one exact request object as assembled by dsh-agent-loop.
339
+ * @param request - loop-owned request envelope before LLM dispatch.
340
+ * @returns the same request object marked as created by the process-local agent loop.
341
+ */
342
+ function markAgentLoopRequest(request) {
343
+ AGENT_LOOP_REQUESTS.add(request);
344
+ return request;
345
+ }
346
+ /**
347
+ * Test whether the exact request object was assembled by dsh-agent-loop.
348
+ * @param request - request envelope observed at the LLM waterfall.
349
+ * @returns whether {@link markAgentLoopRequest} recorded this object.
350
+ */
351
+ function isAgentLoopRequest(request) {
352
+ return AGENT_LOOP_REQUESTS.has(request);
353
+ }
354
+ //#endregion
355
+ //#region lib/types/adapter-failure.js
356
+ /**
357
+ * Normalization for values thrown by a final LLM adapter boundary.
358
+ *
359
+ * @module @x1a0f3n9/dsh-llm/adapter-failure
360
+ */
361
+ /**
362
+ * Detach serializable provider facts from a value thrown by an adapter.
363
+ * @param value - arbitrary value thrown during adapter dispatch or iteration.
364
+ * @returns immutable provider-neutral facts suitable for a terminal finish chunk.
365
+ * @internal
366
+ */
367
+ function normalizeLlmFailure(value) {
368
+ const error = value instanceof Error ? value : new HarnessError(thrownMessage(value), "UNKNOWN", { cause: value });
369
+ const carried = ownFailureSnapshot(error);
370
+ if (carried !== void 0 && carried.code === ownErrorCode(error)) return carried;
371
+ return Object.freeze({
372
+ message: errorMessage(error),
373
+ code: harnessErrorCode(error)
374
+ });
375
+ }
376
+ /** Render a non-Error throw without letting hostile coercion escape normalization. */
377
+ function thrownMessage(value) {
378
+ try {
379
+ const message = String(value);
380
+ return message.length > 0 ? message : "LLM adapter failed";
381
+ } catch (_hostileThrownValue) {
382
+ return "LLM adapter failed";
383
+ }
384
+ }
385
+ /** Read a foreign error's own data-backed `code` without invoking accessors. */
386
+ function ownErrorCode(error) {
387
+ try {
388
+ const descriptor = Object.getOwnPropertyDescriptor(error, "code");
389
+ return descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0;
390
+ } catch (_sdkPropertyTrap) {
391
+ return;
392
+ }
393
+ }
394
+ /** Snapshot an own data property without invoking an SDK-defined accessor. */
395
+ function ownFailureSnapshot(error) {
396
+ try {
397
+ const descriptor = Object.getOwnPropertyDescriptor(error, "failure");
398
+ return descriptor !== void 0 && "value" in descriptor ? failureSnapshot(descriptor.value) : void 0;
399
+ } catch (_sdkPropertyTrap) {
400
+ return;
401
+ }
402
+ }
403
+ /** Validate and detach an arbitrary serializable failure payload. */
404
+ function failureSnapshot(value) {
405
+ if (typeof value !== "object" || value === null) return void 0;
406
+ try {
407
+ const candidate = value;
408
+ const message = candidate.message;
409
+ const code = candidate.code;
410
+ const status = candidate.status;
411
+ const providerRetryAfterMs = candidate.providerRetryAfterMs;
412
+ const requestId = candidate.requestId;
413
+ if (typeof message !== "string" || message.length === 0 || typeof code !== "string" || code.length === 0 || status !== void 0 && (!Number.isInteger(status) || status < 100 || status > 599) || providerRetryAfterMs !== void 0 && (!Number.isFinite(providerRetryAfterMs) || providerRetryAfterMs <= 0) || requestId !== void 0 && (typeof requestId !== "string" || requestId.length === 0)) return void 0;
414
+ return Object.freeze({
415
+ message,
416
+ code,
417
+ ...status === void 0 ? {} : { status },
418
+ ...providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs },
419
+ ...requestId === void 0 ? {} : { requestId }
420
+ });
421
+ } catch (_sdkFailureGetter) {
422
+ return;
423
+ }
424
+ }
425
+ /** Read an SDK error message without letting an accessor replace the primary failure. */
426
+ function errorMessage(error) {
427
+ try {
428
+ const message = error.message;
429
+ if (typeof message === "string" && message.length > 0) return message;
430
+ } catch (_sdkMessageGetter) {}
431
+ return "LLM adapter failed";
432
+ }
433
+ /** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */
434
+ function harnessErrorCode(error) {
435
+ return error instanceof HarnessError ? error.code : "UNKNOWN";
436
+ }
437
+ //#endregion
438
+ //#region lib/types/api-key.js
439
+ /**
440
+ * The one definition of a well-formed provider API key, shared by every
441
+ * adapter that puts one in an HTTP header.
442
+ * @module @x1a0f3n9/dsh-llm/api-key
443
+ */
444
+ /**
445
+ * Characters an HTTP header value carries verbatim and every known provider
446
+ * key uses: printable ASCII, space excluded. A key outside this set cannot
447
+ * reach any provider — `fetch` refuses to build the header — so this is a
448
+ * transport invariant rather than one provider's policy. Latin-1 is excluded
449
+ * deliberately: a header could carry it, but no provider issues it, and
450
+ * admitting it trades a local explained refusal for an opaque 401.
451
+ */
452
+ const LEGAL_API_KEY = /^[\x21-\x7E]+$/;
453
+ /**
454
+ * Judge one *supplied* API key, trimming surrounding whitespace first.
455
+ *
456
+ * Trimming is silent because a padded key has one unambiguous reading; every
457
+ * other defect is reported. Absence is a configuration state this function
458
+ * never sees — a profile naming no credential authenticates through the
459
+ * provider's own ambient discovery or OAuth — so callers decide whether a
460
+ * value was supplied before asking.
461
+ * @param raw - the key exactly as configured, stored, or typed.
462
+ * @returns the trimmed key, or why it cannot be used.
463
+ */
464
+ function normalizeApiKey(raw) {
465
+ const value = raw.trim();
466
+ if (value.length === 0) return {
467
+ ok: false,
468
+ reason: "empty"
469
+ };
470
+ if (!LEGAL_API_KEY.test(value)) return {
471
+ ok: false,
472
+ reason: "illegalCharacters"
473
+ };
474
+ return {
475
+ ok: true,
476
+ value
477
+ };
478
+ }
479
+ //#endregion
480
+ //#region lib/types/content.js
481
+ /** Content-block structure helpers. @module @x1a0f3n9/dsh-llm/content */
482
+ /**
483
+ * Bridge one attachment provider's host object location into the mounted
484
+ * tool execution world. The consumer supplies the current filesystem
485
+ * provider's mapping without making attachment or LLM definitions depend on it.
486
+ * @param attachments - provider that owns the normalized attachment object.
487
+ * @param mapHostPath - map one absolute host path into the current tool execution world.
488
+ * @param ref - durable normalized attachment reference.
489
+ * @returns a read-only execution-world path, or undefined when either provider exposes no mapping.
490
+ * @throws an attachment error when the durable reference is invalid.
491
+ */
492
+ function resolveImageAttachmentAccess(attachments, mapHostPath, ref) {
493
+ const hostPath = attachments.imageHostPath(ref);
494
+ if (hostPath === void 0) return void 0;
495
+ const readonlyPath = mapHostPath(hostPath);
496
+ return readonlyPath === void 0 ? void 0 : { readonlyPath };
497
+ }
498
+ function quoted(value) {
499
+ return JSON.stringify(value);
500
+ }
501
+ function imageIdentity(ref) {
502
+ return ref.name === void 0 ? String(ref.attachmentId) : `${quoted(ref.name)} (${ref.attachmentId})`;
503
+ }
504
+ function extension(mediaType) {
505
+ switch (mediaType) {
506
+ case "image/png": return ".png";
507
+ case "image/jpeg": return ".jpg";
508
+ case "image/webp": return ".webp";
509
+ case "image/gif": return ".gif";
510
+ default: return assertNever(mediaType, "image extension");
511
+ }
512
+ }
513
+ function normalizedAccessText(ref, access) {
514
+ return ` Normalized copy (read-only; may be resized or re-encoded): ${quoted(access.readonlyPath)} (${ref.width}x${ref.height}px, ${ref.mediaType}). Source dimensions, format, and byte size may differ. Copy to a writable path ending in ${extension(ref.mediaType)} before editing.`;
515
+ }
516
+ /**
517
+ * Stable text shown to a model that cannot accept one durable image reference.
518
+ * @param ref - durable normalized attachment omitted from the request.
519
+ * @returns deterministic text-only placeholder.
520
+ */
521
+ function textOnlyImageText(ref) {
522
+ return `[image omitted because this model accepts text only; attachment sha256:${String(ref.attachmentId).slice(7, 15)}]`;
523
+ }
524
+ /**
525
+ * Stable model-facing handle for one exact request image. Identity comes from
526
+ * the occurrence's own durable reference: request versions are prepared per
527
+ * attachment id, so one shared version may serve occurrences whose display
528
+ * names differ.
529
+ * @param ref - the occurrence's durable normalized attachment.
530
+ * @param version - exact request-image dimensions shown beside the text.
531
+ * @param access - optional path resolved for the current tool execution world.
532
+ * @returns attachment handle and request-image dimensions.
533
+ */
534
+ function requestImageHandleText(ref, version, access) {
535
+ const preview = `Image ${imageIdentity(ref)}; request preview ${version.width}x${version.height}px.`;
536
+ return access === void 0 ? `${preview} It may be resized or re-encoded; source dimensions, format, and byte size may differ.` : preview + normalizedAccessText(ref, access);
537
+ }
538
+ /**
539
+ * Stable per-image placeholder for a request-limit omission.
540
+ * @param ref - durable normalized attachment omitted from this request.
541
+ * @param access - optional provider-resolved path for model tools.
542
+ * @returns identity, normalized metadata, and the available recovery path.
543
+ */
544
+ function offloadedImageText(ref, access) {
545
+ const identity = `image omitted to fit request image limits; ${imageIdentity(ref)}.`;
546
+ if (access === void 0) return `[${identity} No local normalized image path is available; ask the user to attach it again if needed.]`;
547
+ return `[${identity}${normalizedAccessText(ref, access)}]`;
548
+ }
549
+ /**
550
+ * True when typed model content contains an image block, walking nested
551
+ * tool-result content. This is the one recursive image walk shared by every
552
+ * image policy (capability gating, text-only serialization, compaction
553
+ * survey), so a consumer cannot silently diverge on nesting depth.
554
+ * @param content - typed model content blocks.
555
+ * @returns whether any nested block is an image.
556
+ */
557
+ function contentHasImage(content) {
558
+ return content.some((block) => block.type === "image" || block.type === "tool-result" && contentHasImage(block.content));
559
+ }
560
+ /** Base64 length of raw image bytes, including padding. */
561
+ function base64Length(bytes) {
562
+ return Math.ceil(bytes / 3) * 4;
563
+ }
564
+ /** Collect represented image lengths in request and nested-block order. */
565
+ function collectImageLengths(blocks, lengths, policy) {
566
+ for (const block of blocks) if (block.type === "image") {
567
+ const bytes = policy.byteLength === void 0 ? block.attachment.bytes : policy.byteLength(block.attachment);
568
+ lengths.push(policy.representation === "base64" ? base64Length(bytes) : bytes);
569
+ } else if (block.type === "tool-result") collectImageLengths(block.content, lengths, policy);
570
+ }
571
+ /** Replace the first `remaining.count` image occurrences without mutating durable messages. */
572
+ function replaceOldestImages(blocks, remaining, placeholder) {
573
+ let next;
574
+ for (const [index, block] of blocks.entries()) {
575
+ if (block.type === "image" && remaining.count > 0) {
576
+ remaining.count -= 1;
577
+ next ??= blocks.slice(0, index);
578
+ next.push({
579
+ type: "text",
580
+ text: placeholder(block.attachment)
581
+ });
582
+ continue;
583
+ }
584
+ if (block.type === "tool-result") {
585
+ const content = replaceOldestImages(block.content, remaining, placeholder);
586
+ if (content !== block.content) {
587
+ next ??= blocks.slice(0, index);
588
+ next.push({
589
+ ...block,
590
+ content
591
+ });
592
+ continue;
593
+ }
594
+ }
595
+ next?.push(block);
596
+ }
597
+ return next ?? blocks;
598
+ }
599
+ /** Replace every image occurrence, including nested tool results, for a text-only model. */
600
+ function replaceImagesForTextModel(blocks) {
601
+ let next;
602
+ for (const [index, block] of blocks.entries()) {
603
+ if (block.type === "image") {
604
+ next ??= blocks.slice(0, index);
605
+ next.push({
606
+ type: "text",
607
+ text: textOnlyImageText(block.attachment)
608
+ });
609
+ continue;
610
+ }
611
+ if (block.type === "tool-result") {
612
+ const content = replaceImagesForTextModel(block.content);
613
+ if (content !== block.content) {
614
+ next ??= blocks.slice(0, index);
615
+ next.push({
616
+ ...block,
617
+ content
618
+ });
619
+ continue;
620
+ }
621
+ }
622
+ next?.push(block);
623
+ }
624
+ return next ?? blocks;
625
+ }
626
+ /**
627
+ * Project durable image history into deterministic text for an exact text-only model.
628
+ * @param messages - complete request history.
629
+ * @returns the original list without images, otherwise shallow message copies with stable placeholders.
630
+ */
631
+ function projectImagesForTextModel(messages) {
632
+ if (!messages.some((message) => contentHasImage(message.content))) return messages;
633
+ return messages.map((message) => {
634
+ const content = replaceImagesForTextModel(message.content);
635
+ return content === message.content ? message : {
636
+ ...message,
637
+ content
638
+ };
639
+ });
640
+ }
641
+ /**
642
+ * Number of oldest image occurrences one request projection removes, in whole
643
+ * count and byte quanta, once a route budget is exceeded. The result depends
644
+ * only on the represented lengths, so provider request pricing reproduces the
645
+ * exact serialization decision without building the projected messages.
646
+ * @param lengths - represented byte length of every occurrence, in request order.
647
+ * @param policy - count/byte budgets and removal quanta; unbounded when absent.
648
+ * @returns how many leading occurrences the projection replaces with placeholders.
649
+ */
650
+ function offloadedImagePrefixCount(lengths, policy) {
651
+ const total = lengths.reduce((sum, bytes) => sum + bytes, 0);
652
+ const excessCount = policy.maxImages === void 0 ? 0 : Math.max(0, lengths.length - policy.maxImages);
653
+ const excessBytes = policy.maxBytes === void 0 ? 0 : Math.max(0, total - policy.maxBytes);
654
+ if (excessCount === 0 && excessBytes === 0) return 0;
655
+ const countQuantum = policy.countQuantum ?? 1;
656
+ const byteQuantum = policy.byteQuantum ?? 1;
657
+ const removeCount = excessCount === 0 ? 0 : Math.ceil(excessCount / countQuantum) * countQuantum;
658
+ const removeBytes = excessBytes === 0 ? 0 : Math.ceil(excessBytes / byteQuantum) * byteQuantum;
659
+ let count = 0;
660
+ let removedBytes = 0;
661
+ for (const imageBytes of lengths) {
662
+ if (count >= removeCount && (removeBytes === 0 || (byteQuantum === 1 ? removedBytes >= removeBytes : removedBytes > removeBytes))) break;
663
+ removedBytes += imageBytes;
664
+ count += 1;
665
+ }
666
+ return count;
667
+ }
668
+ /**
669
+ * Return a deterministic transient projection whose oldest images are replaced
670
+ * in whole count and byte quanta after a route budget is exceeded. The target
671
+ * depends only on complete durable history: at 129 one-megabyte images under
672
+ * a 128 MiB bound with a 64 MiB quantum, the oldest 65 images are removed so
673
+ * 64 MiB remain; that removed prefix stays fixed until total history exceeds
674
+ * 192 MiB.
675
+ * @param messages - complete request history, oldest first.
676
+ * @param policy - route representation, budgets, and removal quanta.
677
+ * @returns original messages below both bounds, otherwise shallow copies with deterministic placeholders.
678
+ */
679
+ function offloadRequestImagesWithPolicy(messages, policy) {
680
+ const lengths = [];
681
+ for (const message of messages) collectImageLengths(message.content, lengths, policy);
682
+ const count = offloadedImagePrefixCount(lengths, policy);
683
+ if (count === 0) return messages;
684
+ const remaining = { count };
685
+ return messages.map((message) => {
686
+ const content = replaceOldestImages(message.content, remaining, policy.placeholder);
687
+ return content === message.content ? message : {
688
+ ...message,
689
+ content
690
+ };
691
+ });
692
+ }
693
+ //#endregion
694
+ //#region lib/types/attribution.js
695
+ /**
696
+ * Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping
697
+ * adapters from drifting. See
698
+ * `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.
699
+ *
700
+ * App-attribution vocabulary for provider requests.
701
+ * @module @x1a0f3n9/dsh-llm/attribution
702
+ */
703
+ const { version } = createRequire(import.meta.url)("../package.json");
704
+ /**
705
+ * The harness's own identity: the default every adapter sends. Deployments
706
+ * that need a white-label identity pass their own {@link AppIdentity} to
707
+ * {@link attributionHeaders} — omission falls back to this default; nothing
708
+ * can suppress attribution entirely.
709
+ */
710
+ const APP_IDENTITY = {
711
+ product: "deepseek-harness",
712
+ version,
713
+ url: "https://github.com/deepseek-ai/deepseek-harness"
714
+ };
715
+ /**
716
+ * The standard `User-Agent` value: `product/version (+url)`. The
717
+ * parenthesized `+url` comment is the conventional self-identification form
718
+ * (RFC 9110 §10.1.5 product + comment syntax).
719
+ * @param identity - the identity to render; defaults to {@link APP_IDENTITY}.
720
+ * @returns the ready-to-send header value.
721
+ */
722
+ function userAgent(identity = APP_IDENTITY) {
723
+ return `${identity.product}/${identity.version} (+${identity.url})`;
724
+ }
725
+ /**
726
+ * Build the attribution headers an adapter must send on every provider
727
+ * request. Header names are lowercase (HTTP field names are case-insensitive
728
+ * on the wire).
729
+ * @param identity - the identity to send; defaults to {@link APP_IDENTITY} — omission cannot suppress attribution.
730
+ * @returns headers to merge into the provider request (currently just `user-agent`).
731
+ */
732
+ function attributionHeaders(identity = APP_IDENTITY) {
733
+ return { "user-agent": userAgent(identity) };
734
+ }
735
+ //#endregion
736
+ //#region lib/types/brand.js
737
+ /**
738
+ * dsh-llm's owned branded ids: tool-call correlation and provider request
739
+ * diagnostics.
740
+ *
741
+ * The `Branded<B>` primitive and stateless constructor live in
742
+ * `@x1a0f3n9/dsh-brand` so every owner of a cross-boundary id can brand it
743
+ * without depending on dsh-llm; see that package's README for the
744
+ * nominal-typing policy.
745
+ *
746
+ * @module @x1a0f3n9/dsh-llm/brand
747
+ */
748
+ /**
749
+ * Brand a message identifier.
750
+ * @param id - the opaque message identifier.
751
+ * @returns the same string with the message-id brand.
752
+ */
753
+ function MessageId(id) {
754
+ return brandString(id);
755
+ }
756
+ /**
757
+ * Brand a string as a {@link ToolCallId}.
758
+ * @param id - the provider-issued or synthesized call id.
759
+ * @returns the same string with the tool-call-id brand.
760
+ */
761
+ function ToolCallId(id) {
762
+ return brandString(id);
763
+ }
764
+ /**
765
+ * Brand a provider-issued request identifier.
766
+ * @param id - the opaque provider-issued string.
767
+ * @returns the same string, branded; no validation is performed.
768
+ */
769
+ function ProviderRequestId(id) {
770
+ return brandString(id);
771
+ }
772
+ /**
773
+ * Brand an adapter-owned reasoning-effort identifier.
774
+ * @param id - the opaque identifier exposed by one model capability.
775
+ * @returns the same string, branded; no validation is performed.
776
+ */
777
+ function ReasoningEffortId(id) {
778
+ return brandString(id);
779
+ }
780
+ //#endregion
781
+ //#region lib/types/assembler.js
782
+ /**
783
+ * Incremental chunk-to-message assembler. This is the single canonical assembly
784
+ * algorithm used by the agent loop to build an assistant message from a chunk
785
+ * stream while logging the raw chunks for replay fidelity.
786
+ *
787
+ * @module @x1a0f3n9/dsh-llm/assembler
788
+ */
789
+ /**
790
+ * Incrementally assembles raw {@link StreamChunk}s into complete
791
+ * {@link ContentBlock}s and a final assistant {@link Message}.
792
+ *
793
+ * The agent loop feeds it while logging raw chunks for replay fidelity, then
794
+ * reads `blocks()` / `message()` / `usage` / `finish` once the stream ends,
795
+ * or `interruptedBlocks()` when cancellation cut the stream short.
796
+ *
797
+ * Tolerant of delta-only protocols (no block-start/end); deltas arriving for
798
+ * an index already closed by `block-end` are ignored (malformed stream) so a
799
+ * misbehaving adapter cannot grow memory or corrupt a completed block.
800
+ */
801
+ var BlockAssembler = class {
802
+ partials = /* @__PURE__ */ new Map();
803
+ order = [];
804
+ _usage;
805
+ _finish;
806
+ _replayState;
807
+ /**
808
+ * Feed one chunk into the assembly state.
809
+ * @param chunk - the next raw chunk, in stream order.
810
+ */
811
+ push(chunk) {
812
+ switch (chunk.type) {
813
+ case "block-start":
814
+ if (!this.partials.has(chunk.index)) {
815
+ this.order.push(chunk.index);
816
+ this.partials.set(chunk.index, {
817
+ blockType: chunk.blockType,
818
+ text: "",
819
+ toolCallArguments: ""
820
+ });
821
+ }
822
+ return;
823
+ case "text-delta":
824
+ case "reasoning-delta": {
825
+ const partial = this.ensure(chunk.index, chunk.type === "text-delta" ? "text" : "reasoning");
826
+ if (partial.block) return;
827
+ partial.text += chunk.text;
828
+ return;
829
+ }
830
+ case "tool-call-delta": {
831
+ const partial = this.ensure(chunk.index, "tool-call");
832
+ if (partial.block) return;
833
+ partial.toolCallId = chunk.id;
834
+ if (chunk.name) partial.toolCallName = chunk.name;
835
+ partial.toolCallArguments += chunk.argumentsDelta;
836
+ return;
837
+ }
838
+ case "block-end": {
839
+ const partial = this.ensure(chunk.index, chunk.block.type);
840
+ if (partial.block) return;
841
+ partial.block = chunk.block;
842
+ return;
843
+ }
844
+ case "usage":
845
+ this._usage = chunk.usage;
846
+ return;
847
+ case "finish":
848
+ this._finish = chunk.reason;
849
+ this._replayState = chunk.replayState;
850
+ return;
851
+ default: return assertNever(chunk, "BlockAssembler.push");
852
+ }
853
+ }
854
+ ensure(index, blockType) {
855
+ let partial = this.partials.get(index);
856
+ if (!partial) {
857
+ partial = {
858
+ blockType,
859
+ text: "",
860
+ toolCallArguments: ""
861
+ };
862
+ this.partials.set(index, partial);
863
+ this.order.push(index);
864
+ }
865
+ return partial;
866
+ }
867
+ assemble(partial, index) {
868
+ if (partial.block) return partial.block;
869
+ switch (partial.blockType) {
870
+ case "text": return {
871
+ type: "text",
872
+ text: partial.text
873
+ };
874
+ case "reasoning": return {
875
+ type: "reasoning",
876
+ text: partial.text
877
+ };
878
+ case "tool-call": return {
879
+ type: "tool-call",
880
+ id: partial.toolCallId ?? brandString(`call-${index}`),
881
+ name: partial.toolCallName ?? "",
882
+ arguments: partial.toolCallArguments
883
+ };
884
+ default: throw new Error(`cannot assemble incomplete block of type "${partial.blockType}"`);
885
+ }
886
+ }
887
+ /** Invariant accessor: every index in `order` has a partial. */
888
+ mustGet(index) {
889
+ const partial = this.partials.get(index);
890
+ if (!partial) throw new Error(`BlockAssembler invariant violated: no partial for index ${index}`);
891
+ return partial;
892
+ }
893
+ /**
894
+ * The one shared keep/drop decision over all seen blocks: max-token
895
+ * truncation drops tool calls that cannot be executed safely. Emitted blocks
896
+ * and replay metadata both derive from this result, so they cannot disagree.
897
+ */
898
+ assembled() {
899
+ const all = this.order.map((index) => this.assemble(this.mustGet(index), index));
900
+ const kept = this.finish.kind === "max-tokens" ? all.map((block) => block.type !== "tool-call") : void 0;
901
+ const blocks = kept === void 0 ? all : all.filter((_, position) => kept[position]);
902
+ const envelope = this._replayState;
903
+ if (envelope?.blocks === void 0) return {
904
+ blocks,
905
+ replay: envelope
906
+ };
907
+ if (envelope.blocks.length !== all.length) return {
908
+ blocks,
909
+ replay: void 0
910
+ };
911
+ return {
912
+ blocks,
913
+ replay: kept === void 0 || blocks.length === all.length ? envelope : {
914
+ response: envelope.response,
915
+ blocks: envelope.blocks.filter((_, position) => kept[position])
916
+ }
917
+ };
918
+ }
919
+ /**
920
+ * Assemble all blocks seen so far, in stream order.
921
+ * @returns one block per seen index, except that max-token truncation drops
922
+ * tool calls that cannot be executed safely; an open block assembles from
923
+ * its accumulated deltas (an unknown block type never closed by `block-end` throws).
924
+ */
925
+ blocks() {
926
+ return this.assembled().blocks;
927
+ }
928
+ /**
929
+ * Assemble the prefix an interrupted stream can safely finalize: closed and
930
+ * open text/reasoning blocks with non-whitespace content, in stream order.
931
+ * Tool calls are omitted because interruption precedes dispatch; retaining
932
+ * one would require a fabricated result. Open unknown blocks are also omitted.
933
+ * @returns the kept blocks; empty when nothing streamed before the interruption.
934
+ */
935
+ interruptedBlocks() {
936
+ return this.order.map((index) => {
937
+ const partial = this.mustGet(index);
938
+ const type = partial.block?.type ?? partial.blockType;
939
+ if (type !== "text" && type !== "reasoning") return void 0;
940
+ return this.assemble(partial, index);
941
+ }).filter((block) => (block?.type === "text" || block?.type === "reasoning") && block.text.trim() !== "");
942
+ }
943
+ /** Usage from the `usage` chunk; undefined until one arrives. */
944
+ get usage() {
945
+ return this._usage;
946
+ }
947
+ /** Finish reason from the `finish` chunk; `{kind: 'stop'}` when the stream ended without one. */
948
+ get finish() {
949
+ return this._finish ?? { kind: "stop" };
950
+ }
951
+ /**
952
+ * Replay metadata from the terminal finish chunk, if any, with per-block
953
+ * entries pruned in step with {@link blocks}. Undefined when the envelope's
954
+ * entries do not align with the emitted blocks.
955
+ */
956
+ get replayState() {
957
+ return this.assembled().replay;
958
+ }
959
+ /**
960
+ * The assembled assistant message.
961
+ * @param source - producer attribution for the assembled message.
962
+ * @returns a frozen assistant-role message over `blocks()` (same open-block assembly rules).
963
+ */
964
+ message(source = {
965
+ kind: "plugin",
966
+ plugin: "dsh-llm/assembler"
967
+ }) {
968
+ return createMessage({
969
+ role: "assistant",
970
+ content: this.blocks(),
971
+ source
972
+ });
973
+ }
974
+ };
975
+ //#endregion
976
+ //#region lib/types/index.js
977
+ /**
978
+ * LLM service: adapter registry with a waterfall-interceptable streaming call
979
+ * API. Exports the `LlmRuntime` default, the abstract `LlmAdapter` for
980
+ * provider backends, and `BlockAssembler` for chunk assembly.
981
+ *
982
+ * @module @x1a0f3n9/dsh-llm
983
+ */
984
+ var __runInitializers = function(thisArg, initializers, value) {
985
+ var useValue = arguments.length > 2;
986
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
987
+ return useValue ? value : void 0;
988
+ };
989
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
990
+ function accept(f) {
991
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
992
+ return f;
993
+ }
994
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
995
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
996
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
997
+ var _, done = false;
998
+ for (var i = decorators.length - 1; i >= 0; i--) {
999
+ var context = {};
1000
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
1001
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
1002
+ context.addInitializer = function(f) {
1003
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
1004
+ extraInitializers.push(accept(f || null));
1005
+ };
1006
+ var result = (0, decorators[i])(kind === "accessor" ? {
1007
+ get: descriptor.get,
1008
+ set: descriptor.set
1009
+ } : descriptor[key], context);
1010
+ if (kind === "accessor") {
1011
+ if (result === void 0) continue;
1012
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
1013
+ if (_ = accept(result.get)) descriptor.get = _;
1014
+ if (_ = accept(result.set)) descriptor.set = _;
1015
+ if (_ = accept(result.init)) initializers.unshift(_);
1016
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
1017
+ else descriptor[key] = _;
1018
+ }
1019
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
1020
+ done = true;
1021
+ };
1022
+ /**
1023
+ * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
1024
+ * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
1025
+ */
1026
+ var LlmError = class extends HarnessError {
1027
+ /** Serializable facts retained beside this live Error. */
1028
+ failure;
1029
+ /**
1030
+ * @param message - non-empty human-readable failure summary.
1031
+ * @param code - non-empty stable provider-neutral machine code.
1032
+ * @param options - optional cause and validated serializable provider facts.
1033
+ */
1034
+ constructor(message, code, options) {
1035
+ if (typeof message !== "string" || message.length === 0) throw new Error("LlmError message must be a non-empty string");
1036
+ if (typeof code !== "string" || code.length === 0) throw new Error("LlmError code must be a non-empty string");
1037
+ if (options?.status !== void 0 && (!Number.isInteger(options.status) || options.status < 100 || options.status > 599)) throw new Error("LlmError status must be an integer from 100 through 599");
1038
+ if (options?.providerRetryAfterMs !== void 0 && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) throw new Error("LlmError providerRetryAfterMs must be a positive finite number");
1039
+ if (options?.requestId !== void 0 && (typeof options.requestId !== "string" || options.requestId.length === 0)) throw new Error("LlmError requestId must be a non-empty string");
1040
+ super(message, code, options);
1041
+ this.name = "LlmError";
1042
+ this.failure = Object.freeze({
1043
+ message,
1044
+ code,
1045
+ ...options?.status === void 0 ? {} : { status: options.status },
1046
+ ...options?.providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs: options.providerRetryAfterMs },
1047
+ ...options?.requestId === void 0 ? {} : { requestId: options.requestId }
1048
+ });
1049
+ }
1050
+ };
1051
+ /**
1052
+ * Accept one supplied credential, or refuse it as unusable.
1053
+ *
1054
+ * A stored key arrives from the credentials seam, a `.env` line, or a shell
1055
+ * export, all of which pick up surrounding whitespace, so trimming is silent.
1056
+ * Anything else fails here rather than inside `fetch`, whose ByteString
1057
+ * refusal names a UTF-16 code point instead of the setting to change. The key
1058
+ * never enters the message: `ref` names where to fix it, and echoing any part
1059
+ * of a secret into a log or a UI is the failure this diagnosis avoids.
1060
+ *
1061
+ * Lives beside {@link LlmError} rather than in `./api-key.ts` so the predicate
1062
+ * module stays dependency-free; both adapters share this one diagnosis instead
1063
+ * of keeping near-identical local copies.
1064
+ * @param raw - the credential exactly as supplied.
1065
+ * @param pkg - the refusing package name, prefixed to the diagnostic.
1066
+ * @param ref - the credential reference the value resolved through.
1067
+ * @returns the trimmed, usable key.
1068
+ */
1069
+ function assertUsableApiKey(raw, pkg, ref) {
1070
+ const checked = normalizeApiKey(raw);
1071
+ if (checked.ok) return checked.value;
1072
+ throw new LlmError(checked.reason === "empty" ? `${pkg}: the API key resolved from ${ref} is blank; set ${ref} to the raw key (the web Models page writes it) or export it in the launching environment` : `${pkg}: the API key resolved from ${ref} contains characters no HTTP header can carry; set ${ref} to the raw key alone (the web Models page writes it)`, INVALID_CREDENTIAL_CODE);
1073
+ }
1074
+ /**
1075
+ * Provider-wire adapter for the harness message and stream vocabulary. Register implementations
1076
+ * with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include
1077
+ * `attributionHeaders()`; prove the headers are added in the wire request or library header hook. The direct-fetch
1078
+ * DeepSeek and library-backed pi-ai adapters meet this contract through different internals.
1079
+ */
1080
+ var LlmAdapter = class {
1081
+ /**
1082
+ * Describe one provider route owned by this adapter.
1083
+ * @param provider - a route passed to `registerAdapter()` for this instance.
1084
+ * @returns detached display metadata whose id must equal `provider`.
1085
+ */
1086
+ providerInfo(provider) {
1087
+ return {
1088
+ id: provider,
1089
+ name: provider
1090
+ };
1091
+ }
1092
+ /**
1093
+ * Return the provider-owned retry policy captured with this route.
1094
+ * @param _provider - a route passed to `registerAdapter()` for this instance.
1095
+ * @returns a resolved policy, or `undefined` to use the normal defaults.
1096
+ */
1097
+ providerRetryPolicy(_provider) {}
1098
+ /**
1099
+ * Resolve provider-side request-image pricing for one exact model route.
1100
+ * The default declares none, so consumers fall back to their own neutral
1101
+ * estimate. Implementations must answer synchronously without I/O; the
1102
+ * token meter resolves this per measurement.
1103
+ * @param _provider - a route passed to `registerAdapter()` for this instance.
1104
+ * @param _model - exact model id passed to {@link GenerateOptions.model}.
1105
+ * @returns route-owned image pricing, or `undefined` when the route declares none.
1106
+ */
1107
+ imageRequestPricing(_provider, _model) {}
1108
+ /**
1109
+ * List models this adapter can currently advertise for one owned provider.
1110
+ * The result is advisory: an adapter may accept unlisted model ids, and
1111
+ * consumers must not turn absence into request rejection.
1112
+ * @param _provider - one provider route owned by this adapter.
1113
+ * @returns discoverable models in adapter-preferred order.
1114
+ */
1115
+ listModels(_provider) {
1116
+ return Promise.resolve([]);
1117
+ }
1118
+ /**
1119
+ * Resolve all metadata available for one exact model. This query is
1120
+ * independent of the advisory catalog and does not validate request routing.
1121
+ * @param provider - one provider route owned by this adapter.
1122
+ * @param model - exact model id passed to {@link GenerateOptions.model}.
1123
+ * @param _signal - cancellation for this exact-model lookup; asynchronous
1124
+ * implementations must settle promptly after it aborts.
1125
+ * @returns provider/model identity plus any context, call-default, and reasoning metadata.
1126
+ */
1127
+ resolveModel(provider, model, _signal) {
1128
+ return Promise.resolve({
1129
+ provider,
1130
+ id: model,
1131
+ name: model
1132
+ });
1133
+ }
1134
+ /**
1135
+ * Bind exact model metadata and the eventual request dispatch to one adapter generation.
1136
+ * Dynamic adapters override this so settings changes between preparation and
1137
+ * dispatch cannot combine one generation's capabilities with another's endpoint.
1138
+ * @param provider - registered provider route.
1139
+ * @param model - exact model id.
1140
+ * @param signal - cancellation for model resolution.
1141
+ * @returns model metadata and a one-generation stream entry point.
1142
+ */
1143
+ async prepareCall(provider, model, signal) {
1144
+ return {
1145
+ model: await this.resolveModel(provider, model, signal),
1146
+ stream: (options) => this.stream(options)
1147
+ };
1148
+ }
1149
+ };
1150
+ /**
1151
+ * The abstract `llm` service: an adapter registry plus a streaming model-call
1152
+ * API, interceptable via the `llm/stream` waterfall.
1153
+ */
1154
+ let LlmRuntime = (() => {
1155
+ let _classSuper = TypertRemoteService;
1156
+ let _instanceExtraInitializers = [];
1157
+ let _listProviders_decorators;
1158
+ let _listConfigurableProviders_decorators;
1159
+ let _remoteDiscoverModels_decorators;
1160
+ return class LlmRuntime extends _classSuper {
1161
+ static {
1162
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
1163
+ _listProviders_decorators = [Remote];
1164
+ _listConfigurableProviders_decorators = [Remote];
1165
+ _remoteDiscoverModels_decorators = [Remote("discoverModels")];
1166
+ __esDecorate(this, null, _listProviders_decorators, {
1167
+ kind: "method",
1168
+ name: "listProviders",
1169
+ static: false,
1170
+ private: false,
1171
+ access: {
1172
+ has: (obj) => "listProviders" in obj,
1173
+ get: (obj) => obj.listProviders
1174
+ },
1175
+ metadata: _metadata
1176
+ }, null, _instanceExtraInitializers);
1177
+ __esDecorate(this, null, _listConfigurableProviders_decorators, {
1178
+ kind: "method",
1179
+ name: "listConfigurableProviders",
1180
+ static: false,
1181
+ private: false,
1182
+ access: {
1183
+ has: (obj) => "listConfigurableProviders" in obj,
1184
+ get: (obj) => obj.listConfigurableProviders
1185
+ },
1186
+ metadata: _metadata
1187
+ }, null, _instanceExtraInitializers);
1188
+ __esDecorate(this, null, _remoteDiscoverModels_decorators, {
1189
+ kind: "method",
1190
+ name: "remoteDiscoverModels",
1191
+ static: false,
1192
+ private: false,
1193
+ access: {
1194
+ has: (obj) => "remoteDiscoverModels" in obj,
1195
+ get: (obj) => obj.remoteDiscoverModels
1196
+ },
1197
+ metadata: _metadata
1198
+ }, null, _instanceExtraInitializers);
1199
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
1200
+ enumerable: true,
1201
+ configurable: true,
1202
+ writable: true,
1203
+ value: _metadata
1204
+ });
1205
+ }
1206
+ adapters = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map());
1207
+ directory = /* @__PURE__ */ new Map();
1208
+ discoveries = /* @__PURE__ */ new Map();
1209
+ constructor(ctx) {
1210
+ super(ctx, "llm");
1211
+ }
1212
+ /** Notify topology observers without letting one broken listener veto the commit. */
1213
+ emitAdaptersUpdated() {
1214
+ let invariantFailure;
1215
+ for (const listener of this.ctx.events.dispatch("emit", ["llm/adapters-updated"])) try {
1216
+ const returned = listener();
1217
+ if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
1218
+ this.warnAdaptersListenerFailure(error);
1219
+ });
1220
+ } catch (error) {
1221
+ if (error?.code === "INVARIANT") {
1222
+ invariantFailure ??= error;
1223
+ continue;
1224
+ }
1225
+ this.warnAdaptersListenerFailure(error);
1226
+ }
1227
+ if (invariantFailure !== void 0) throw invariantFailure;
1228
+ }
1229
+ /** Contained-listener diagnostic shared by the sync and async failure paths. */
1230
+ warnAdaptersListenerFailure(error) {
1231
+ this.ctx.logger.warn("llm: an llm/adapters-updated listener failed");
1232
+ this.ctx.logger.warn(error);
1233
+ }
1234
+ /**
1235
+ * Register an adapter for the given provider routes. Throws `LlmError` with code
1236
+ * `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).
1237
+ * Disposed with the fiber.
1238
+ * @param providers - every provider route this adapter should serve.
1239
+ * @param adapter - the adapter that streams calls for those providers.
1240
+ * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.
1241
+ */
1242
+ registerAdapter(providers, adapter) {
1243
+ const owned = /* @__PURE__ */ new Set();
1244
+ let released = false;
1245
+ const dispose = this.ctx.effect(function* () {
1246
+ if (providers.length === 0) throw new LlmError("an adapter must register at least one provider", "INVALID_ADAPTER");
1247
+ this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned));
1248
+ yield () => {
1249
+ released = true;
1250
+ for (const provider of owned) this.adapters.delete(provider);
1251
+ owned.clear();
1252
+ this.emitAdaptersUpdated();
1253
+ };
1254
+ }.bind(this), "llm.registerAdapter()");
1255
+ const handle = (() => void dispose());
1256
+ handle.replace = (next) => {
1257
+ if (released) throw new LlmError("a disposed adapter registration cannot replace its routes", "REGISTRATION_DISPOSED");
1258
+ this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned));
1259
+ };
1260
+ return handle;
1261
+ }
1262
+ /**
1263
+ * Validate one candidate route set for `adapter`, treating routes this
1264
+ * registration already holds as available. Nothing is mutated: a rejected
1265
+ * candidate leaves the registry exactly as it was.
1266
+ */
1267
+ prepareRoutes(providers, adapter, owned) {
1268
+ const unique = /* @__PURE__ */ new Set();
1269
+ const registrations = [];
1270
+ for (const provider of providers) {
1271
+ if (provider.length === 0) throw new LlmError("adapter provider names must be non-empty", "INVALID_ADAPTER");
1272
+ if (unique.has(provider) || this.adapters.has(provider) && !owned.has(provider)) throw new LlmError(`an adapter for provider "${provider}" is already registered`, "DUPLICATE_ADAPTER");
1273
+ const info = adapter.providerInfo(provider);
1274
+ if (typeof info.id !== "string" || info.id !== provider || typeof info.name !== "string" || info.name.length === 0) throw new LlmError(`adapter metadata for provider "${provider}" must preserve its id and have a non-empty name`, "INVALID_ADAPTER");
1275
+ unique.add(provider);
1276
+ const retryPolicy = adapter.providerRetryPolicy(provider) ?? resolveRetryPolicy(void 0, `llm: provider "${provider}" retryPolicy`);
1277
+ registrations.push({
1278
+ adapter,
1279
+ provider: {
1280
+ id: info.id,
1281
+ name: info.name
1282
+ },
1283
+ retryPolicy
1284
+ });
1285
+ }
1286
+ return registrations;
1287
+ }
1288
+ /**
1289
+ * Swap this registration's routes for the prepared ones in one synchronous
1290
+ * section, so no observer can see the registry between the release and the
1291
+ * re-registration. The route set's one mutation point is also where
1292
+ * `llm/adapters-updated` is published, so a `replace` announces itself
1293
+ * exactly like a first registration.
1294
+ */
1295
+ commitRoutes(owned, registrations) {
1296
+ for (const provider of owned) this.adapters.delete(provider);
1297
+ owned.clear();
1298
+ for (const registration of registrations) {
1299
+ this.adapters.set(registration.provider.id, registration);
1300
+ owned.add(registration.provider.id);
1301
+ }
1302
+ this.emitAdaptersUpdated();
1303
+ }
1304
+ /**
1305
+ * Describe provider routes with a registered adapter.
1306
+ * @returns detached provider metadata in registration order.
1307
+ */
1308
+ listProviders() {
1309
+ return [...this.adapters.values()].map(({ provider }) => ({ ...provider }));
1310
+ }
1311
+ /**
1312
+ * Declare provider routes an adapter plugin can activate through
1313
+ * configuration. Registration is all-or-nothing: an empty list, invalid
1314
+ * entry, or a provider already declared by any registration throws
1315
+ * `LlmError` without registering the rest. Disposed with the fiber.
1316
+ * @param entries - every configurable provider this plugin owns.
1317
+ * @returns a handle that withdraws all of them, and can atomically replace them.
1318
+ */
1319
+ registerConfigurableProviders(entries) {
1320
+ let held = [];
1321
+ let disposed = false;
1322
+ /**
1323
+ * Validate a candidate set in full against everything this registration
1324
+ * does not already hold, then publish it. Nothing is written until the
1325
+ * whole set passes, so a refused candidate leaves the current entries in
1326
+ * place — the property that makes `replace` a swap rather than a
1327
+ * delete-then-add that can strand the directory empty.
1328
+ */
1329
+ const commit = (candidates) => {
1330
+ const detached = [];
1331
+ const own = new Set(held.map((entry) => entry.provider));
1332
+ for (const entry of candidates) {
1333
+ if (entry.provider.length === 0 || entry.displayName.length === 0 || entry.settingsNs.length === 0) throw new LlmError("configurable providers need a non-empty provider, displayName, and settingsNs", "INVALID_DIRECTORY");
1334
+ if (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider "${entry.provider}" has an empty settingsPath segment`, "INVALID_DIRECTORY");
1335
+ if (this.directory.has(entry.provider) && !own.has(entry.provider) || detached.some((seen) => seen.provider === entry.provider)) throw new LlmError(`configurable provider "${entry.provider}" is already declared`, "DUPLICATE_DIRECTORY");
1336
+ detached.push({
1337
+ ...entry,
1338
+ settingsPath: [...entry.settingsPath]
1339
+ });
1340
+ }
1341
+ for (const entry of held) this.directory.delete(entry.provider);
1342
+ for (const entry of detached) this.directory.set(entry.provider, entry);
1343
+ held = detached;
1344
+ this.emitAdaptersUpdated();
1345
+ };
1346
+ const dispose = this.ctx.effect(function* () {
1347
+ if (entries.length === 0) throw new LlmError("a configurable-provider registration must declare at least one provider", "INVALID_DIRECTORY");
1348
+ commit(entries);
1349
+ yield () => {
1350
+ disposed = true;
1351
+ for (const entry of held) this.directory.delete(entry.provider);
1352
+ held = [];
1353
+ this.emitAdaptersUpdated();
1354
+ };
1355
+ }.bind(this), "llm.registerConfigurableProviders()");
1356
+ const handle = (() => void dispose());
1357
+ handle.replace = (next) => {
1358
+ if (disposed) throw new LlmError("this configurable-provider registration was disposed", "REGISTRATION_DISPOSED");
1359
+ commit(next);
1360
+ };
1361
+ return handle;
1362
+ }
1363
+ /**
1364
+ * List every declared configurable provider, registered or dormant.
1365
+ * @returns detached directory entries in declaration order.
1366
+ */
1367
+ listConfigurableProviders() {
1368
+ return [...this.directory.values()].map((entry) => ({
1369
+ ...entry,
1370
+ settingsPath: [...entry.settingsPath]
1371
+ }));
1372
+ }
1373
+ /**
1374
+ * Offer to interrogate provider endpoints on behalf of the settings
1375
+ * namespace this plugin owns. The namespace is the key because that is what
1376
+ * a configuration surface already holds from the configurable-provider
1377
+ * directory, and because a provider being *added* has no route to name yet.
1378
+ * Disposed with the fiber.
1379
+ * @param settingsNs - the namespace whose profiles this discovery serves.
1380
+ * @param discover - interrogates one endpoint and must honor the supplied signal.
1381
+ * @returns the disposer that withdraws the offer.
1382
+ */
1383
+ registerModelDiscovery(settingsNs, discover) {
1384
+ const dispose = this.ctx.effect(function* () {
1385
+ if (settingsNs.length === 0) throw new LlmError("model discovery needs a non-empty settings namespace", "INVALID_DISCOVERY");
1386
+ if (this.discoveries.has(settingsNs)) throw new LlmError(`model discovery for "${settingsNs}" is already registered`, "DUPLICATE_DISCOVERY");
1387
+ this.discoveries.set(settingsNs, discover);
1388
+ yield () => {
1389
+ this.discoveries.delete(settingsNs);
1390
+ };
1391
+ }.bind(this), "llm.registerModelDiscovery()");
1392
+ return () => void dispose();
1393
+ }
1394
+ /**
1395
+ * Interrogate one provider endpoint for the models it advertises. The
1396
+ * request describes a draft, not a stored route, so nothing here reads or
1397
+ * writes settings or credentials — the caller owns both, and the reply is
1398
+ * candidate metadata a surface may offer for adoption.
1399
+ * @param settingsNs - namespace whose registered discovery serves this draft.
1400
+ * @param request - the endpoint, protocol, and one-shot credential to use.
1401
+ * @param signal - caller cancellation.
1402
+ * @returns the advertised models, deduplicated in endpoint order.
1403
+ */
1404
+ async discoverModels(settingsNs, request, signal) {
1405
+ const discover = this.discoveries.get(settingsNs);
1406
+ if (discover === void 0) throw new LlmError(`no model discovery is registered for "${settingsNs}"`, "NO_DISCOVERY");
1407
+ if ((request.provider ?? "").length === 0 && (request.baseURL ?? "").length === 0) throw new LlmError("model discovery needs a provider route or a baseURL", "INVALID_DISCOVERY");
1408
+ const discovered = signal === void 0 ? await discover(request) : await discover(request, signal);
1409
+ const seen = /* @__PURE__ */ new Set();
1410
+ const models = [];
1411
+ for (const model of discovered) {
1412
+ if (typeof model.id !== "string" || model.id.length === 0 || seen.has(model.id)) continue;
1413
+ seen.add(model.id);
1414
+ models.push({
1415
+ id: model.id,
1416
+ ...model.name === void 0 ? {} : { name: model.name },
1417
+ ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
1418
+ ...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens }
1419
+ });
1420
+ }
1421
+ return models;
1422
+ }
1423
+ /**
1424
+ * Remote adapter for one draft provider interrogation.
1425
+ * @param settingsNs - namespace whose registered discovery serves this draft.
1426
+ * @param request - endpoint, protocol, and one-shot credential to use.
1427
+ * @param signal - caller cancellation supplied by the Remote carrier.
1428
+ * @returns advertised models in endpoint order.
1429
+ * @throws RemoteError with `llm/model-discovery-rejected` when discovery refuses or fails.
1430
+ */
1431
+ async remoteDiscoverModels(settingsNs, request, signal) {
1432
+ try {
1433
+ return await this.discoverModels(settingsNs, request, signal);
1434
+ } catch (error) {
1435
+ throw new RemoteError("llm/model-discovery-rejected", error instanceof Error ? error.message : String(error), {
1436
+ settingsNs,
1437
+ ...request.baseURL === void 0 ? {} : { baseURL: request.baseURL }
1438
+ }, { cause: error });
1439
+ }
1440
+ }
1441
+ /**
1442
+ * Resolve the retry policy captured when one provider route was registered.
1443
+ * @param provider - registered provider route to inspect.
1444
+ * @returns the provider-owned policy, with normal defaults already resolved.
1445
+ */
1446
+ providerRetryPolicy(provider) {
1447
+ return this.registration(provider).retryPolicy;
1448
+ }
1449
+ /**
1450
+ * Resolve provider-side request-image pricing for one exact route, or
1451
+ * `undefined` when the provider is unregistered or declares none. Unknown
1452
+ * providers degrade to `undefined` rather than throwing because callers
1453
+ * price durable history whose route may no longer be mounted.
1454
+ * @param provider - provider route named by a request header.
1455
+ * @param model - exact model id named by the same header.
1456
+ * @returns the owning adapter's image pricing for the route, when declared.
1457
+ */
1458
+ imageRequestPricing(provider, model) {
1459
+ return this.adapters.get(provider)?.adapter.imageRequestPricing(provider, model);
1460
+ }
1461
+ /** Detach typed adapter-owned modality metadata. */
1462
+ detachedModalities(modalities) {
1463
+ return modalities === void 0 ? void 0 : [...modalities];
1464
+ }
1465
+ /**
1466
+ * Discover models advertised by one registered provider. Catalog membership
1467
+ * is advisory and never changes routing or request validation.
1468
+ * @param provider - registered provider route to inspect.
1469
+ * @returns detached model metadata in adapter-preferred order.
1470
+ */
1471
+ async listModels(provider) {
1472
+ const models = await this.registration(provider).adapter.listModels(provider);
1473
+ const seen = /* @__PURE__ */ new Set();
1474
+ return models.map((model) => {
1475
+ if (typeof model.provider !== "string" || model.provider !== provider || typeof model.id !== "string" || model.id.length === 0 || typeof model.name !== "string" || model.name.length === 0 || model.description !== void 0 && typeof model.description !== "string" || seen.has(model.id)) throw new LlmError(`adapter returned invalid or duplicate model metadata for provider "${provider}"`, "INVALID_CATALOG");
1476
+ seen.add(model.id);
1477
+ const inputModalities = this.detachedModalities(model.inputModalities);
1478
+ return {
1479
+ provider: model.provider,
1480
+ id: model.id,
1481
+ name: model.name,
1482
+ ...model.description === void 0 ? {} : { description: model.description },
1483
+ ...inputModalities === void 0 ? {} : { inputModalities }
1484
+ };
1485
+ });
1486
+ }
1487
+ /**
1488
+ * Resolve and validate all metadata from the adapter that owns one exact
1489
+ * route. The result is detached from adapter-owned objects; catalog
1490
+ * membership remains advisory and does not control request routing.
1491
+ * @param provider - registered provider route to inspect.
1492
+ * @param model - exact model id passed to the adapter.
1493
+ * @param signal - optional cancellation for adapter-owned asynchronous lookup.
1494
+ * @returns exact model identity plus available context and reasoning metadata.
1495
+ */
1496
+ async resolveModelInfo(provider, model, signal) {
1497
+ return this.resolveModelInfoFor(this.registration(provider), model, signal);
1498
+ }
1499
+ async resolveModelInfoFor(registration, model, signal) {
1500
+ const resolved = await registration.adapter.resolveModel(registration.provider.id, model, signal);
1501
+ return this.normalizeModelInfo(registration, model, resolved);
1502
+ }
1503
+ /** Validate and detach one adapter-returned exact model result. */
1504
+ normalizeModelInfo(registration, model, resolved) {
1505
+ const provider = registration.provider.id;
1506
+ if (typeof resolved.provider !== "string" || resolved.provider !== provider || typeof resolved.id !== "string" || resolved.id !== model || typeof resolved.name !== "string" || resolved.name.length === 0 || resolved.description !== void 0 && typeof resolved.description !== "string") throw new LlmError(`adapter returned invalid exact model metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_INFO");
1507
+ const context = resolved.context;
1508
+ if (context !== void 0 && (!Number.isInteger(context.contextWindow) || context.contextWindow <= 0)) throw new LlmError(`adapter returned invalid context metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_CONTEXT");
1509
+ const inputModalities = this.detachedModalities(resolved.inputModalities);
1510
+ const defaultMaxTokens = resolved.defaultMaxTokens;
1511
+ if (defaultMaxTokens !== void 0 && (!Number.isSafeInteger(defaultMaxTokens) || defaultMaxTokens <= 0)) throw new LlmError(`adapter returned invalid default maxTokens for provider "${provider}" model "${model}"`, "INVALID_MODEL_MAX_TOKENS");
1512
+ const info = {
1513
+ provider,
1514
+ id: model,
1515
+ name: resolved.name,
1516
+ ...resolved.description === void 0 ? {} : { description: resolved.description },
1517
+ ...inputModalities === void 0 ? {} : { inputModalities },
1518
+ ...context === void 0 ? {} : { context: { contextWindow: context.contextWindow } },
1519
+ ...defaultMaxTokens === void 0 ? {} : { defaultMaxTokens }
1520
+ };
1521
+ const reasoning = resolved.reasoning;
1522
+ if (reasoning === void 0) return info;
1523
+ if (reasoning.efforts.length === 0) throw new LlmError(`adapter returned invalid reasoning metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
1524
+ const seen = /* @__PURE__ */ new Set();
1525
+ const efforts = reasoning.efforts.map((effort) => {
1526
+ if (typeof effort.id !== "string" || effort.id.length === 0 || typeof effort.name !== "string" || effort.name.length === 0 || effort.description !== void 0 && typeof effort.description !== "string" || seen.has(effort.id)) throw new LlmError(`adapter returned invalid or duplicate reasoning effort metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
1527
+ seen.add(effort.id);
1528
+ return {
1529
+ id: effort.id,
1530
+ name: effort.name,
1531
+ ...effort.description === void 0 ? {} : { description: effort.description }
1532
+ };
1533
+ });
1534
+ if (reasoning.defaultEffort !== void 0 && !seen.has(reasoning.defaultEffort)) throw new LlmError(`adapter returned an unknown default reasoning effort for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
1535
+ return {
1536
+ ...info,
1537
+ reasoning: {
1538
+ efforts,
1539
+ ...reasoning.defaultEffort === void 0 ? {} : { defaultEffort: reasoning.defaultEffort }
1540
+ }
1541
+ };
1542
+ }
1543
+ /**
1544
+ * Validate a conversation call config against its exact model capability and
1545
+ * materialize adapter-configured defaults. Unsupported explicit efforts
1546
+ * reject before provider I/O; no clamping or aliasing is performed. This
1547
+ * standalone query does not bind a later dispatch; use {@link prepareCall}
1548
+ * when logging and streaming must share one adapter registration.
1549
+ * @param config - provider/model route and optional request controls.
1550
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1551
+ * @returns a detached config only when a default must be materialized.
1552
+ */
1553
+ async resolveCallConfig(config, signal) {
1554
+ return (await this.resolveCallFor(this.registration(config.provider), config, signal)).config;
1555
+ }
1556
+ async resolveCallFor(registration, config, signal) {
1557
+ const info = await this.resolveModelInfoFor(registration, config.model, signal);
1558
+ return this.resolveCallWithInfo(config, info);
1559
+ }
1560
+ /** Validate request controls against one already-bound exact model result. */
1561
+ resolveCallWithInfo(config, info) {
1562
+ const defaulted = config.maxTokens === void 0 && info.defaultMaxTokens !== void 0 ? {
1563
+ ...config,
1564
+ maxTokens: info.defaultMaxTokens
1565
+ } : config;
1566
+ const reasoning = info.reasoning;
1567
+ const requested = defaulted.reasoningEffort;
1568
+ let resolvedConfig = defaulted;
1569
+ if (reasoning === void 0) {
1570
+ if (requested !== void 0) throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${requested}"`, "UNSUPPORTED_REASONING_EFFORT");
1571
+ } else {
1572
+ const effective = requested ?? reasoning.defaultEffort;
1573
+ if (effective !== void 0) {
1574
+ if (!reasoning.efforts.some((effort) => effort.id === effective)) throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${effective}"`, "UNSUPPORTED_REASONING_EFFORT");
1575
+ if (requested !== effective) resolvedConfig = {
1576
+ ...defaulted,
1577
+ reasoningEffort: effective
1578
+ };
1579
+ }
1580
+ }
1581
+ return {
1582
+ config: resolvedConfig,
1583
+ ...info.context === void 0 ? {} : { context: info.context },
1584
+ modelInfo: info
1585
+ };
1586
+ }
1587
+ /**
1588
+ * Resolve one call under its current adapter registration. The returned
1589
+ * one-shot handle keeps that registration across header logging and dispatch,
1590
+ * so HMR cannot combine one adapter's capability result with another adapter.
1591
+ * @param config - provider/model route and optional request controls.
1592
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1593
+ * @returns a prepared config and its registration-bound stream entry point.
1594
+ */
1595
+ async prepareCall(config, signal) {
1596
+ const registration = this.registration(config.provider);
1597
+ const adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal);
1598
+ const modelInfo = this.normalizeModelInfo(registration, config.model, adapterCall.model);
1599
+ const resolved = this.resolveCallWithInfo(config, modelInfo);
1600
+ const resolvedConfig = deepFreeze(structuredClone(resolved.config));
1601
+ const context = resolved.context === void 0 ? void 0 : deepFreeze(structuredClone(resolved.context));
1602
+ const adapterDefaults = deepFreeze({
1603
+ ...config.reasoningEffort === void 0 && resolvedConfig.reasoningEffort !== void 0 ? { reasoningEffort: true } : {},
1604
+ ...config.maxTokens === void 0 && resolvedConfig.maxTokens !== void 0 ? { maxTokens: true } : {}
1605
+ });
1606
+ let dispatched = false;
1607
+ return Object.freeze({
1608
+ config: resolvedConfig,
1609
+ retryPolicy: registration.retryPolicy,
1610
+ adapterDefaults,
1611
+ ...context === void 0 ? {} : { context },
1612
+ ...modelInfo.inputModalities === void 0 ? {} : { inputModalities: Object.freeze([...modelInfo.inputModalities]) },
1613
+ stream: (options) => {
1614
+ if (dispatched) throw new LlmError("a prepared LLM call can only be dispatched once", "INVALID_PREPARED_CALL");
1615
+ if (!callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
1616
+ dispatched = true;
1617
+ return this.streamWithRegistration(options, {
1618
+ registration,
1619
+ config: resolvedConfig,
1620
+ modelInfo,
1621
+ dispatch: (options) => adapterCall.stream(options)
1622
+ });
1623
+ }
1624
+ });
1625
+ }
1626
+ registration(provider) {
1627
+ const registration = this.adapters.get(provider);
1628
+ if (!registration) throw new LlmError(`no adapter registered for provider "${provider}"`, "NO_ADAPTER");
1629
+ return registration;
1630
+ }
1631
+ /** Remove replay state whose historical route is owned by another adapter. */
1632
+ forAdapter(options, adapter) {
1633
+ const messages = options.messages.map((message) => {
1634
+ const source = message.source;
1635
+ if (message.role !== "assistant" || source.kind !== "model" || source.replayState === void 0) return message;
1636
+ if (this.adapters.get(source.provider)?.adapter === adapter) return message;
1637
+ return freezeMessage({
1638
+ ...message,
1639
+ source: {
1640
+ kind: "model",
1641
+ provider: source.provider,
1642
+ model: source.model
1643
+ }
1644
+ });
1645
+ });
1646
+ if (messages.every((message, index) => message === options.messages[index])) return options;
1647
+ const filtered = {
1648
+ ...options,
1649
+ messages
1650
+ };
1651
+ return Object.isFrozen(options) ? deepFreeze(filtered) : filtered;
1652
+ }
1653
+ /**
1654
+ * Final adapter boundary. Adapter selection, dispatch, iterator construction,
1655
+ * and iteration failures become one terminal failure chunk. Middleware and
1656
+ * downstream consumer failures remain thrown plugin or consumer errors.
1657
+ */
1658
+ async *adapterStream(options, prepared) {
1659
+ let iterator;
1660
+ try {
1661
+ const registration = prepared?.registration ?? this.registration(options.provider);
1662
+ const adapter = registration.adapter;
1663
+ let modelInfo;
1664
+ let resolvedConfig;
1665
+ let dispatch;
1666
+ if (prepared === void 0) {
1667
+ const adapterCall = await adapter.prepareCall(options.provider, options.model, options.signal);
1668
+ modelInfo = this.normalizeModelInfo(registration, options.model, adapterCall.model);
1669
+ resolvedConfig = this.resolveCallWithInfo(options, modelInfo).config;
1670
+ dispatch = (options) => adapterCall.stream(options);
1671
+ } else {
1672
+ modelInfo = prepared.modelInfo;
1673
+ resolvedConfig = prepared.config;
1674
+ dispatch = prepared.dispatch;
1675
+ }
1676
+ if (prepared !== void 0 && !callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
1677
+ const resolvedOptions = callConfigEquals(options, resolvedConfig) ? options : Object.isFrozen(options) ? deepFreeze({
1678
+ ...options,
1679
+ ...resolvedConfig
1680
+ }) : {
1681
+ ...options,
1682
+ ...resolvedConfig
1683
+ };
1684
+ const projectedOptions = modelInfo.inputModalities !== void 0 && !modelInfo.inputModalities.includes("image") && resolvedOptions.messages.some((message) => contentHasImage(message.content)) ? Object.isFrozen(resolvedOptions) ? deepFreeze({
1685
+ ...resolvedOptions,
1686
+ messages: projectImagesForTextModel(resolvedOptions.messages)
1687
+ }) : {
1688
+ ...resolvedOptions,
1689
+ messages: projectImagesForTextModel(resolvedOptions.messages)
1690
+ } : resolvedOptions;
1691
+ iterator = dispatch(this.forAdapter(projectedOptions, adapter))[Symbol.asyncIterator]();
1692
+ } catch (error) {
1693
+ yield adapterFailureChunk(error, options.signal);
1694
+ return;
1695
+ }
1696
+ let completed = false;
1697
+ try {
1698
+ while (true) {
1699
+ let item;
1700
+ try {
1701
+ const next = await iterator.next();
1702
+ item = next.done ? { done: true } : {
1703
+ done: false,
1704
+ value: next.value
1705
+ };
1706
+ } catch (error) {
1707
+ completed = true;
1708
+ yield adapterFailureChunk(error, options.signal);
1709
+ return;
1710
+ }
1711
+ if (item.done) {
1712
+ completed = true;
1713
+ return;
1714
+ }
1715
+ yield item.value;
1716
+ }
1717
+ } finally {
1718
+ if (!completed) {
1719
+ const close = iterator.return?.bind(iterator);
1720
+ if (close) await close();
1721
+ }
1722
+ }
1723
+ }
1724
+ /**
1725
+ * Stream one model call as raw chunks (token-level deltas). Replay state is
1726
+ * retained only when the same adapter instance owns its historical provider
1727
+ * and the target provider. Final adapter selection remains fixed through
1728
+ * asynchronous exact-model resolution and dispatch. Adapter selection,
1729
+ * dispatch, and iteration failures become terminal `error` or `aborted`
1730
+ * finish chunks; middleware, nested-call, cleanup, and consumer failures
1731
+ * remain thrown.
1732
+ * @param options - the full request; `options.provider` selects the adapter.
1733
+ * @returns the chunk stream, possibly wrapped by `llm/stream` listeners.
1734
+ */
1735
+ stream(options) {
1736
+ return this.streamWithRegistration(options);
1737
+ }
1738
+ streamWithRegistration(options, prepared) {
1739
+ return this.ctx.waterfall(this, "llm/stream", options, () => this.adapterStream(options, prepared));
1740
+ }
1741
+ };
1742
+ })();
1743
+ /** Convert one adapter throw into the stream protocol's terminal outcome. */
1744
+ function adapterFailureChunk(error, signal) {
1745
+ const failure = normalizeLlmFailure(error);
1746
+ return {
1747
+ type: "finish",
1748
+ reason: signal?.aborted || failure.code === "ABORTED" ? {
1749
+ kind: "aborted",
1750
+ failure
1751
+ } : {
1752
+ kind: "error",
1753
+ failure
1754
+ }
1755
+ };
1756
+ }
1757
+ //#endregion
1758
+ export { APP_IDENTITY, BlockAssembler, CONTEXT_SUMMARY_MAX_CHARS, CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, HarnessError, INVALID_CREDENTIAL_CODE, LlmAdapter, LlmError, LlmRuntime, LlmRuntime as default, MessageId, ProviderRequestId, QUOTA_EXCEEDED_CODE, ReasoningEffortId, RetryPolicySchema, ToolCallId, assertUsableApiKey, attributionHeaders, boundContextSummary, callConfigEquals, contentHasImage, createAssistantMessage, createMessage, createToolResultMessage, createUserMessage, errorChain, freezeMessage, isAgentLoopRequest, isContextWindowExceededError, isHarnessError, isQuotaExceededError, markAgentLoopRequest, normalizeApiKey, offloadRequestImagesWithPolicy, offloadedImagePrefixCount, offloadedImageText, projectImagesForTextModel, requestImageHandleText, resolveImageAttachmentAccess, resolveRetryPolicy, textOnlyImageText, userAgent };