@deepseek-ai/dsh-llm 0.0.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1391 @@
1
+ import { createRequire } from "node:module";
2
+ import { Service } from "@deepseek-ai/cordis";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-timeout";
5
+ //#region lib/types/brand.js
6
+ /**
7
+ * dsh-llm's owned branded ids: tool-call correlation and provider request
8
+ * diagnostics.
9
+ *
10
+ * The `Branded<B>` primitive itself lives in `@deepseek-ai/dsh-brand` (a
11
+ * zero-dependency type-only package) so every owner of a cross-boundary id can
12
+ * brand it without depending on dsh-llm; see that package's README for the
13
+ * nominal-typing policy.
14
+ *
15
+ * @module @deepseek-ai/dsh-llm/brand
16
+ */
17
+ /**
18
+ * Brand a message identifier.
19
+ * @param id - the opaque message identifier.
20
+ * @returns the same string, branded; no validation is performed.
21
+ */
22
+ function MessageId(id) {
23
+ return id;
24
+ }
25
+ /**
26
+ * Brand a string as a {@link CallId}.
27
+ * @param id - the provider-issued (or synthesized) call id.
28
+ * @returns the same string, branded; no validation is performed.
29
+ */
30
+ function CallId(id) {
31
+ return id;
32
+ }
33
+ /**
34
+ * Brand a provider-issued request identifier.
35
+ * @param id - the opaque provider-issued string.
36
+ * @returns the same string, branded; no validation is performed.
37
+ */
38
+ function ProviderRequestId(id) {
39
+ return id;
40
+ }
41
+ /**
42
+ * Brand an adapter-owned reasoning-effort identifier.
43
+ * @param id - the opaque identifier exposed by one model capability.
44
+ * @returns the same string, branded; no validation is performed.
45
+ */
46
+ function ReasoningEffortId(id) {
47
+ return id;
48
+ }
49
+ //#endregion
50
+ //#region lib/types/call-config.js
51
+ /**
52
+ * Conversation call configuration and freeze utilities. Provider routing,
53
+ * model, reasoning effort, and sampling values are request-header state that
54
+ * can affect cache reuse; request waterfalls replace them and the loop logs
55
+ * changed snapshots instead of allowing silent per-call drift.
56
+ * @module dsh-llm/call-config
57
+ */
58
+ /** Process-local identities of request objects assembled by dsh-agent-loop. */
59
+ const AGENT_LOOP_REQUESTS = /* @__PURE__ */ new WeakSet();
60
+ /**
61
+ * Field-wise equality over {@link LlmCallConfig} — the comparison a caller
62
+ * runs to decide whether a proposed configuration is a real change (worth a
63
+ * logged header snapshot) or the held one restated.
64
+ * @param a - one configuration.
65
+ * @param b - the other.
66
+ * @returns whether every field (including the `stop` list, element-wise) matches.
67
+ */
68
+ function callConfigEquals(a, b) {
69
+ if (a.provider !== b.provider || a.model !== b.model || a.reasoningEffort !== b.reasoningEffort || a.temperature !== b.temperature || a.maxTokens !== b.maxTokens) return false;
70
+ if (a.stop === void 0 || b.stop === void 0) return a.stop === b.stop;
71
+ return a.stop.length === b.stop.length && a.stop.every((s, i) => s === b.stop?.[i]);
72
+ }
73
+ /**
74
+ * Mark one exact request object as assembled by dsh-agent-loop.
75
+ * @param request - loop-owned request envelope before LLM dispatch.
76
+ * @returns the same request object marked as created by the process-local agent loop.
77
+ */
78
+ function markAgentLoopRequest(request) {
79
+ AGENT_LOOP_REQUESTS.add(request);
80
+ return request;
81
+ }
82
+ /**
83
+ * Test whether the exact request object was assembled by dsh-agent-loop.
84
+ * @param request - request envelope observed at the LLM waterfall.
85
+ * @returns whether {@link markAgentLoopRequest} recorded this object.
86
+ */
87
+ function isAgentLoopRequest(request) {
88
+ return AGENT_LOOP_REQUESTS.has(request);
89
+ }
90
+ /**
91
+ * Deep-freeze a value in place with an iterative traversal, guarding cycles,
92
+ * so later mutation throws without imposing a JavaScript call-stack depth cap.
93
+ * {@link AbortSignal} objects are deliberately skipped because they are the
94
+ * request's live cancellation channel and freezing them breaks abort.
95
+ * @param value - the value to freeze in place.
96
+ * @returns the same value, frozen.
97
+ */
98
+ function deepFreeze(value) {
99
+ const seen = /* @__PURE__ */ new WeakSet();
100
+ const pending = [{
101
+ kind: "visit",
102
+ node: value
103
+ }];
104
+ while (pending.length > 0) {
105
+ const task = pending.pop();
106
+ /* v8 ignore next -- the loop condition guarantees one pending task. */
107
+ if (task === void 0) continue;
108
+ if (task.kind === "property") {
109
+ pending.push({
110
+ kind: "visit",
111
+ node: task.source[task.key]
112
+ });
113
+ continue;
114
+ }
115
+ const node = task.node;
116
+ if (node === null || typeof node !== "object") continue;
117
+ if (node instanceof AbortSignal) continue;
118
+ if (seen.has(node)) continue;
119
+ seen.add(node);
120
+ Object.freeze(node);
121
+ const keys = Object.keys(node);
122
+ for (let index = keys.length - 1; index >= 0; index--) {
123
+ const key = keys[index];
124
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
125
+ if (key === void 0) continue;
126
+ pending.push({
127
+ kind: "property",
128
+ source: node,
129
+ key
130
+ });
131
+ }
132
+ }
133
+ return value;
134
+ }
135
+ //#endregion
136
+ //#region lib/types/message.js
137
+ /** Message value types, identity, and immutable construction helpers. */
138
+ /**
139
+ * Bound for a `notice` summary. The account rides a collapsed transcript row
140
+ * and is committed to the durable log, while its inputs — task labels, goal
141
+ * objectives, tool arguments — are caller text with no length of their own.
142
+ */
143
+ const CONTEXT_SUMMARY_MAX_CHARS = 120;
144
+ /**
145
+ * Bound one `notice` summary to {@link CONTEXT_SUMMARY_MAX_CHARS}.
146
+ * @param summary - the producer's one-line account, of any length.
147
+ * @returns the account, ellipsized when it exceeds the bound.
148
+ */
149
+ function boundContextSummary(summary) {
150
+ return summary.length <= 120 ? summary : `${summary.slice(0, 119)}…`;
151
+ }
152
+ /**
153
+ * Detach and deep-freeze a message whose identity already exists.
154
+ * @param message - complete message, including its stable identity.
155
+ * @returns an immutable snapshot that preserves the identity.
156
+ */
157
+ function freezeMessage(message) {
158
+ return deepFreeze(structuredClone(message));
159
+ }
160
+ /**
161
+ * Create one identified message and freeze it before publication.
162
+ * @param input - complete role, content, and source for a new message.
163
+ * @returns an immutable message with a fresh stable identity.
164
+ */
165
+ function createMessage(input) {
166
+ return freezeMessage({
167
+ ...input,
168
+ id: MessageId(crypto.randomUUID())
169
+ });
170
+ }
171
+ /**
172
+ * Create one identified user-role message and freeze it before publication.
173
+ * @param input - complete content and source for a new user message.
174
+ * @returns an immutable user message with a fresh stable identity.
175
+ */
176
+ function createUserMessage(input) {
177
+ return createMessage({
178
+ ...input,
179
+ role: "user"
180
+ });
181
+ }
182
+ /**
183
+ * Create one identified model-produced assistant message and freeze it before publication.
184
+ * @param input - complete content plus the provider, model, and optional replay state for a new assistant message.
185
+ * @returns an immutable assistant message with fixed role/source tags and a fresh stable identity.
186
+ */
187
+ function createAssistantMessage(input) {
188
+ return createMessage({
189
+ role: "assistant",
190
+ content: input.content,
191
+ source: {
192
+ kind: "model",
193
+ ...input.source
194
+ }
195
+ });
196
+ }
197
+ /**
198
+ * Create and freeze one identified tool-result message.
199
+ * @param input - call identity, raw result blocks, and outcome.
200
+ * @returns an immutable user-role tool-result message.
201
+ */
202
+ function createToolResultMessage(input) {
203
+ return createUserMessage({
204
+ source: {
205
+ kind: "tool",
206
+ callId: input.callId
207
+ },
208
+ content: [{
209
+ type: "tool-result",
210
+ toolCallId: input.callId,
211
+ content: input.content,
212
+ isError: input.isError
213
+ }]
214
+ });
215
+ }
216
+ //#endregion
217
+ //#region lib/types/error.js
218
+ /**
219
+ * Harness error base with a stable machine-routable code and chained cause.
220
+ * Package errors extend it so tool results and replay can retain failure class.
221
+ * @module @deepseek-ai/dsh-llm/error
222
+ */
223
+ /**
224
+ * Base class for all harness errors. Carries a `code` (stable, programmatic —
225
+ * e.g. `NO_ADAPTER`, `INVALID_ARGS`, `INVARIANT`) distinct from the
226
+ * human-readable `message`, and supports `cause` chaining via the standard
227
+ * `ErrorOptions`. `name` defaults to the subclass constructor name.
228
+ */
229
+ var HarnessError = class extends Error {
230
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
231
+ code;
232
+ constructor(message, code, options) {
233
+ super(message, options);
234
+ this.code = code;
235
+ this.name = new.target.name;
236
+ }
237
+ };
238
+ /** Canonical provider-neutral code for a model request rejected because its context window was exceeded. */
239
+ const CONTEXT_WINDOW_EXCEEDED_CODE = "CONTEXT_WINDOW_EXCEEDED";
240
+ /** Canonical provider-neutral code for an exhausted account quota or balance. */
241
+ const QUOTA_EXCEEDED_CODE = "QUOTA";
242
+ /**
243
+ * Canonical provider-neutral code for a response that completed normally but
244
+ * carried no content blocks at all. Providers occasionally emit a degenerate
245
+ * completion (a terminal stop with zero output); adapters classify it as this
246
+ * failure instead of yielding an empty assistant message, because an empty
247
+ * message silently ends the turn with nothing for the user or the loop to act
248
+ * on. The attempt produced nothing durable, so retry policy treats it as safe
249
+ * to repeat.
250
+ */
251
+ const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
252
+ /**
253
+ * Canonical provider-neutral code for a credential that was supplied but
254
+ * cannot be used — malformed rather than absent. Distinct from
255
+ * `MISSING_CREDENTIAL` because the fix differs: correct the stored value
256
+ * rather than supply one. Deliberately outside the default retryable set —
257
+ * a malformed credential fails identically on every attempt.
258
+ */
259
+ const INVALID_CREDENTIAL_CODE = "INVALID_CREDENTIAL";
260
+ /** Structured codes and plain phrases that explicitly name a context bound being exceeded. */
261
+ 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");
262
+ /** Request-size wording that ties "too large" directly to model context capacity. */
263
+ 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");
264
+ /** "Exceeds" wording is safe only when its object is explicitly the model context. */
265
+ 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");
266
+ /**
267
+ * Recognize the context-overflow wording used by OpenAI-compatible providers
268
+ * and library adapters. Adapters pass all available provider code, type, and
269
+ * message text so both thrown and in-band delivery styles share one classifier.
270
+ * @param detail - provider error code/type/message text joined into one string.
271
+ * @returns true when the detail identifies a request exceeding the model context window.
272
+ */
273
+ function isContextWindowExceededError(detail) {
274
+ 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);
275
+ }
276
+ /**
277
+ * Recognize provider wording that identifies an exhausted account quota rather
278
+ * than a transient request-rate limit.
279
+ * @param detail - provider error code/type/message text joined into one string.
280
+ * @returns true only for terminal quota, balance, credit, budget, or usage-limit wording.
281
+ */
282
+ function isQuotaExceededError(detail) {
283
+ 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);
284
+ }
285
+ /**
286
+ * Render a thrown value with its full `cause` chain and AggregateError
287
+ * members, so transport wrappers like undici's `TypeError: fetch failed`
288
+ * surface the underlying failure instead of masking it. Plain structured
289
+ * failures render their own data-backed `message`. Diagnostic-surface
290
+ * rendering only (messages, notices, logs) — never parse the result; route on
291
+ * {@link HarnessError.code}.
292
+ * @param value - the caught value (`unknown` in catch clauses).
293
+ * @returns the outermost message first, each cause appended with `: ` (skipped
294
+ * when it repeats the wrapper message verbatim), and AggregateError members
295
+ * bracketed and `; `-joined.
296
+ */
297
+ function errorChain(value) {
298
+ const path = /* @__PURE__ */ new Set();
299
+ const render = (current) => {
300
+ if (path.has(current)) return "<circular cause>";
301
+ path.add(current);
302
+ try {
303
+ if (!(current instanceof Error)) {
304
+ if (typeof current === "object" && current !== null) {
305
+ const descriptor = Object.getOwnPropertyDescriptor(current, "message");
306
+ if (descriptor !== void 0 && "value" in descriptor && typeof descriptor.value === "string") return descriptor.value;
307
+ }
308
+ return String(current);
309
+ }
310
+ const message = current.message === "" ? current.name : current.message;
311
+ const members = current instanceof AggregateError && current.errors.length > 0 ? ` [${current.errors.map(render).join("; ")}]` : "";
312
+ const causeText = current.cause === void 0 || current.cause === null ? "" : render(current.cause);
313
+ return `${message}${members}${causeText === "" || causeText === message ? "" : `: ${causeText}`}`;
314
+ } catch {
315
+ return "<unrenderable value>";
316
+ } finally {
317
+ path.delete(current);
318
+ }
319
+ };
320
+ return render(value);
321
+ }
322
+ /**
323
+ * Narrow an arbitrary thrown value to a HarnessError (for `instanceof` at runtime boundaries).
324
+ * @param value - the caught value (`unknown` in catch clauses).
325
+ * @returns true only for real instances; duck-typed or cross-realm errors do not narrow.
326
+ */
327
+ function isHarnessError(value) {
328
+ return value instanceof HarnessError;
329
+ }
330
+ //#endregion
331
+ //#region lib/types/retry-policy.js
332
+ /**
333
+ * Provider-owned request-retry policy configuration and resolution.
334
+ *
335
+ * Adapters expose one resolved policy per registered provider route; the
336
+ * optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
337
+ *
338
+ * @module @deepseek-ai/dsh-llm/retry-policy
339
+ */
340
+ const DEFAULT_MAX_RETRIES = 2;
341
+ const DEFAULT_INITIAL_DELAY_MS = 500;
342
+ const DEFAULT_MAX_DELAY_MS = 1e4;
343
+ const DEFAULT_JITTER_RATIO = .1;
344
+ const DEFAULT_RETRYABLE_CODES = Object.freeze([
345
+ EMPTY_RESPONSE_CODE,
346
+ "RATE_LIMIT",
347
+ "SERVER",
348
+ "TIMEOUT",
349
+ "TRANSPORT"
350
+ ]);
351
+ const backoffSchema = z.object({
352
+ initialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
353
+ maxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
354
+ jitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
355
+ });
356
+ const normalPolicySchema = z.object({
357
+ mode: z.const("normal").required(),
358
+ maxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
359
+ retryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),
360
+ backoff: backoffSchema
361
+ });
362
+ const alwaysPolicySchema = z.object({
363
+ mode: z.const("always").required(),
364
+ backoff: backoffSchema
365
+ });
366
+ /** Cordis schema embedded by each concrete provider configuration. */
367
+ const RetryPolicySchema = z.union([normalPolicySchema, alwaysPolicySchema]);
368
+ const NORMAL_POLICY_KEYS = new Set([
369
+ "mode",
370
+ "maxRetries",
371
+ "retryableCodes",
372
+ "backoff"
373
+ ]);
374
+ const ALWAYS_POLICY_KEYS = new Set(["mode", "backoff"]);
375
+ const BACKOFF_KEYS = new Set([
376
+ "initialDelayMs",
377
+ "maxDelayMs",
378
+ "jitterRatio"
379
+ ]);
380
+ function validateKeys(value, allowed, path) {
381
+ for (const key of Object.keys(value)) if (!allowed.has(key)) throw new Error(`${path}: unknown key "${key}"`);
382
+ }
383
+ function resolveBackoff(config, path) {
384
+ if (config !== void 0) validateKeys(config, BACKOFF_KEYS, path);
385
+ const initialDelayMs = config?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
386
+ const maxDelayMs = config?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
387
+ const jitterRatio = config?.jitterRatio ?? DEFAULT_JITTER_RATIO;
388
+ 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}`);
389
+ 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}`);
390
+ if (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
391
+ if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) throw new Error(`${path}.jitterRatio must be between 0 and 1`);
392
+ return Object.freeze({
393
+ initialDelayMs,
394
+ maxDelayMs,
395
+ jitterRatio
396
+ });
397
+ }
398
+ /**
399
+ * Validate, default, and detach one provider-owned retry policy.
400
+ * @param config - optional provider configuration; omission selects normal defaults.
401
+ * @param path - diagnostic path naming the provider config that owns the value.
402
+ * @returns an immutable policy safe to capture in provider registration state.
403
+ */
404
+ function resolveRetryPolicy(config, path) {
405
+ if (config === void 0) return Object.freeze({
406
+ mode: "normal",
407
+ maxRetries: DEFAULT_MAX_RETRIES,
408
+ retryableCodes: DEFAULT_RETRYABLE_CODES,
409
+ ...resolveBackoff(void 0, `${path}.backoff`)
410
+ });
411
+ switch (config.mode) {
412
+ case "normal": {
413
+ validateKeys(config, NORMAL_POLICY_KEYS, path);
414
+ const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
415
+ const retryableCodes = config.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];
416
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) throw new Error(`${path}.maxRetries must be a non-negative safe integer`);
417
+ if (retryableCodes.length === 0) throw new Error(`${path}.retryableCodes must not be empty`);
418
+ if (retryableCodes.some((code) => typeof code !== "string" || code.length === 0)) throw new Error(`${path}.retryableCodes must contain only non-empty strings`);
419
+ if (new Set(retryableCodes).size !== retryableCodes.length) throw new Error(`${path}.retryableCodes must not contain duplicates`);
420
+ return Object.freeze({
421
+ mode: "normal",
422
+ maxRetries,
423
+ retryableCodes: Object.freeze([...retryableCodes]),
424
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
425
+ });
426
+ }
427
+ case "always":
428
+ validateKeys(config, ALWAYS_POLICY_KEYS, path);
429
+ return Object.freeze({
430
+ mode: "always",
431
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
432
+ });
433
+ default: throw new Error(`${path}.mode must be "normal" or "always"`);
434
+ }
435
+ }
436
+ //#endregion
437
+ //#region lib/types/adapter-failure.js
438
+ /**
439
+ * Normalization for values thrown by a final LLM adapter boundary.
440
+ *
441
+ * @module @deepseek-ai/dsh-llm/adapter-failure
442
+ */
443
+ /**
444
+ * Detach serializable provider facts from a value thrown by an adapter.
445
+ * @param value - arbitrary value thrown during adapter dispatch or iteration.
446
+ * @returns immutable provider-neutral facts suitable for a terminal finish chunk.
447
+ * @internal
448
+ */
449
+ function normalizeLlmFailure(value) {
450
+ const error = value instanceof Error ? value : new HarnessError(thrownMessage(value), "UNKNOWN", { cause: value });
451
+ const carried = ownFailureSnapshot(error);
452
+ if (carried !== void 0 && carried.code === ownErrorCode(error)) return carried;
453
+ return Object.freeze({
454
+ message: errorMessage(error),
455
+ code: harnessErrorCode(error)
456
+ });
457
+ }
458
+ /** Render a non-Error throw without letting hostile coercion escape normalization. */
459
+ function thrownMessage(value) {
460
+ try {
461
+ const message = String(value);
462
+ return message.length > 0 ? message : "LLM adapter failed";
463
+ } catch (_hostileThrownValue) {
464
+ return "LLM adapter failed";
465
+ }
466
+ }
467
+ /** Read a foreign error's own data-backed `code` without invoking accessors. */
468
+ function ownErrorCode(error) {
469
+ try {
470
+ const descriptor = Object.getOwnPropertyDescriptor(error, "code");
471
+ return descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0;
472
+ } catch (_sdkPropertyTrap) {
473
+ return;
474
+ }
475
+ }
476
+ /** Snapshot an own data property without invoking an SDK-defined accessor. */
477
+ function ownFailureSnapshot(error) {
478
+ try {
479
+ const descriptor = Object.getOwnPropertyDescriptor(error, "failure");
480
+ return descriptor !== void 0 && "value" in descriptor ? failureSnapshot(descriptor.value) : void 0;
481
+ } catch (_sdkPropertyTrap) {
482
+ return;
483
+ }
484
+ }
485
+ /** Validate and detach an arbitrary serializable failure payload. */
486
+ function failureSnapshot(value) {
487
+ if (typeof value !== "object" || value === null) return void 0;
488
+ try {
489
+ const candidate = value;
490
+ const message = candidate.message;
491
+ const code = candidate.code;
492
+ const status = candidate.status;
493
+ const providerRetryAfterMs = candidate.providerRetryAfterMs;
494
+ const requestId = candidate.requestId;
495
+ 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;
496
+ return Object.freeze({
497
+ message,
498
+ code,
499
+ ...status === void 0 ? {} : { status },
500
+ ...providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs },
501
+ ...requestId === void 0 ? {} : { requestId }
502
+ });
503
+ } catch (_sdkFailureGetter) {
504
+ return;
505
+ }
506
+ }
507
+ /** Read an SDK error message without letting an accessor replace the primary failure. */
508
+ function errorMessage(error) {
509
+ try {
510
+ const message = error.message;
511
+ if (typeof message === "string" && message.length > 0) return message;
512
+ } catch (_sdkMessageGetter) {}
513
+ return "LLM adapter failed";
514
+ }
515
+ /** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */
516
+ function harnessErrorCode(error) {
517
+ return error instanceof HarnessError ? error.code : "UNKNOWN";
518
+ }
519
+ //#endregion
520
+ //#region lib/types/api-key.js
521
+ /**
522
+ * The one definition of a well-formed provider API key, shared by every
523
+ * adapter that puts one in an HTTP header.
524
+ * @module @deepseek-ai/dsh-llm/api-key
525
+ */
526
+ /**
527
+ * Characters an HTTP header value carries verbatim and every known provider
528
+ * key uses: printable ASCII, space excluded. A key outside this set cannot
529
+ * reach any provider — `fetch` refuses to build the header — so this is a
530
+ * transport invariant rather than one provider's policy. Latin-1 is excluded
531
+ * deliberately: a header could carry it, but no provider issues it, and
532
+ * admitting it trades a local explained refusal for an opaque 401.
533
+ */
534
+ const LEGAL_API_KEY = /^[\x21-\x7E]+$/;
535
+ /**
536
+ * Judge one *supplied* API key, trimming surrounding whitespace first.
537
+ *
538
+ * Trimming is silent because a padded key has one unambiguous reading; every
539
+ * other defect is reported. Absence is a configuration state this function
540
+ * never sees — a profile naming no credential authenticates through the
541
+ * provider's own ambient discovery or OAuth — so callers decide whether a
542
+ * value was supplied before asking.
543
+ * @param raw - the key exactly as configured, stored, or typed.
544
+ * @returns the trimmed key, or why it cannot be used.
545
+ */
546
+ function normalizeApiKey(raw) {
547
+ const value = raw.trim();
548
+ if (value.length === 0) return {
549
+ ok: false,
550
+ reason: "empty"
551
+ };
552
+ if (!LEGAL_API_KEY.test(value)) return {
553
+ ok: false,
554
+ reason: "illegalCharacters"
555
+ };
556
+ return {
557
+ ok: true,
558
+ value
559
+ };
560
+ }
561
+ //#endregion
562
+ //#region lib/types/attribution.js
563
+ /**
564
+ * Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping
565
+ * adapters from drifting. See
566
+ * `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.
567
+ *
568
+ * App-attribution vocabulary for provider requests.
569
+ * @module @deepseek-ai/dsh-llm/attribution
570
+ */
571
+ const { version } = createRequire(import.meta.url)("../package.json");
572
+ /**
573
+ * The harness's own identity: the default every adapter sends. Deployments
574
+ * that need a white-label identity pass their own {@link AppIdentity} to
575
+ * {@link attributionHeaders} — omission falls back to this default; nothing
576
+ * can suppress attribution entirely.
577
+ */
578
+ const APP_IDENTITY = {
579
+ product: "deepseek-harness",
580
+ version,
581
+ url: "https://github.com/deepseek-ai/deepseek-harness-sdk"
582
+ };
583
+ /**
584
+ * The standard `User-Agent` value: `product/version (+url)`. The
585
+ * parenthesized `+url` comment is the conventional self-identification form
586
+ * (RFC 9110 §10.1.5 product + comment syntax).
587
+ * @param identity - the identity to render; defaults to {@link APP_IDENTITY}.
588
+ * @returns the ready-to-send header value.
589
+ */
590
+ function userAgent(identity = APP_IDENTITY) {
591
+ return `${identity.product}/${identity.version} (+${identity.url})`;
592
+ }
593
+ /**
594
+ * Build the attribution headers an adapter must send on every provider
595
+ * request. Header names are lowercase (HTTP field names are case-insensitive
596
+ * on the wire).
597
+ * @param identity - the identity to send; defaults to {@link APP_IDENTITY} — omission cannot suppress attribution.
598
+ * @returns headers to merge into the provider request (currently just `user-agent`).
599
+ */
600
+ function attributionHeaders(identity = APP_IDENTITY) {
601
+ return { "user-agent": userAgent(identity) };
602
+ }
603
+ //#endregion
604
+ //#region lib/types/never.js
605
+ /**
606
+ * Exhaustiveness helper for closed core unions. Use {@link assertNever} at the default branch so a
607
+ * new variant fails compilation at every required handler. Do not use it for declaration-merged
608
+ * unions such as session events or content blocks: handle known variants and explicitly fall
609
+ * through because plugins may add valid unknown cases.
610
+ * @module @deepseek-ai/dsh-llm/never
611
+ */
612
+ /**
613
+ * Mark an unreachable closed-union branch. A newly unhandled typed variant fails at the call site;
614
+ * a value that escaped its type throws with diagnostics at runtime.
615
+ * @param value - the impossible value; typed `never` so an unhandled variant fails compilation at the call site.
616
+ * @param context - optional label (e.g. the switch site) prefixed into the throw message.
617
+ * @returns never — it always throws, with the offending value JSON-rendered in the message.
618
+ */
619
+ function assertNever(value, context) {
620
+ const rendered = JSON.stringify(value) ?? String(value);
621
+ throw new Error(`unreachable variant${context ? ` in ${context}` : ""}: ${rendered}`);
622
+ }
623
+ //#endregion
624
+ //#region lib/types/content.js
625
+ /** Content-block structure helpers. @module @deepseek-ai/dsh-llm/content */
626
+ /**
627
+ * True when typed model content contains an image block, walking nested
628
+ * tool-result content. This is the one recursive image walk shared by every
629
+ * image policy (capability gating, text-only serialization, compaction
630
+ * survey), so a consumer cannot silently diverge on nesting depth.
631
+ * @param content - typed model content blocks.
632
+ * @returns whether any nested block is an image.
633
+ */
634
+ function contentHasImage(content) {
635
+ return content.some((block) => block.type === "image" || block.type === "tool-result" && contentHasImage(block.content));
636
+ }
637
+ //#endregion
638
+ //#region lib/types/assembler.js
639
+ /**
640
+ * Incremental chunk-to-message assembler. This is the single canonical assembly
641
+ * algorithm used by the agent loop to build an assistant message from a chunk
642
+ * stream while logging the raw chunks for replay fidelity.
643
+ *
644
+ * @module @deepseek-ai/dsh-llm/assembler
645
+ */
646
+ /**
647
+ * Incrementally assembles raw {@link StreamChunk}s into complete
648
+ * {@link ContentBlock}s and a final assistant {@link Message}.
649
+ *
650
+ * The agent loop feeds it while logging raw chunks for replay fidelity, then
651
+ * reads `blocks()` / `message()` / `usage` / `finish` once the stream ends.
652
+ *
653
+ * Tolerant of delta-only protocols (no block-start/end); deltas arriving for
654
+ * an index already closed by `block-end` are ignored (malformed stream) so a
655
+ * misbehaving adapter cannot grow memory or corrupt a completed block.
656
+ */
657
+ var BlockAssembler = class {
658
+ partials = /* @__PURE__ */ new Map();
659
+ order = [];
660
+ _usage;
661
+ _finish;
662
+ _replayState = void 0;
663
+ /**
664
+ * Feed one chunk into the assembly state.
665
+ * @param chunk - the next raw chunk, in stream order.
666
+ */
667
+ push(chunk) {
668
+ switch (chunk.type) {
669
+ case "block-start":
670
+ if (!this.partials.has(chunk.index)) {
671
+ this.order.push(chunk.index);
672
+ this.partials.set(chunk.index, {
673
+ blockType: chunk.blockType,
674
+ text: "",
675
+ toolCallArguments: ""
676
+ });
677
+ }
678
+ return;
679
+ case "text-delta":
680
+ case "reasoning-delta": {
681
+ const partial = this.ensure(chunk.index, chunk.type === "text-delta" ? "text" : "reasoning");
682
+ if (partial.block) return;
683
+ partial.text += chunk.text;
684
+ return;
685
+ }
686
+ case "tool-call-delta": {
687
+ const partial = this.ensure(chunk.index, "tool-call");
688
+ if (partial.block) return;
689
+ partial.toolCallId = chunk.id;
690
+ if (chunk.name) partial.toolCallName = chunk.name;
691
+ partial.toolCallArguments += chunk.argumentsDelta;
692
+ return;
693
+ }
694
+ case "block-end": {
695
+ const partial = this.ensure(chunk.index, chunk.block.type);
696
+ if (partial.block) return;
697
+ partial.block = chunk.block;
698
+ return;
699
+ }
700
+ case "usage":
701
+ this._usage = chunk.usage;
702
+ return;
703
+ case "finish":
704
+ this._finish = chunk.reason;
705
+ this._replayState = chunk.replayState;
706
+ return;
707
+ default: return assertNever(chunk, "BlockAssembler.push");
708
+ }
709
+ }
710
+ ensure(index, blockType) {
711
+ let partial = this.partials.get(index);
712
+ if (!partial) {
713
+ partial = {
714
+ blockType,
715
+ text: "",
716
+ toolCallArguments: ""
717
+ };
718
+ this.partials.set(index, partial);
719
+ this.order.push(index);
720
+ }
721
+ return partial;
722
+ }
723
+ assemble(partial, index) {
724
+ if (partial.block) return partial.block;
725
+ switch (partial.blockType) {
726
+ case "text": return {
727
+ type: "text",
728
+ text: partial.text
729
+ };
730
+ case "reasoning": return {
731
+ type: "reasoning",
732
+ text: partial.text
733
+ };
734
+ case "tool-call": return {
735
+ type: "tool-call",
736
+ id: partial.toolCallId ?? CallId(`call-${index}`),
737
+ name: partial.toolCallName ?? "",
738
+ arguments: partial.toolCallArguments
739
+ };
740
+ default: throw new Error(`cannot assemble incomplete block of type "${partial.blockType}"`);
741
+ }
742
+ }
743
+ /** Invariant accessor: every index in `order` has a partial. */
744
+ mustGet(index) {
745
+ const partial = this.partials.get(index);
746
+ if (!partial) throw new Error(`BlockAssembler invariant violated: no partial for index ${index}`);
747
+ return partial;
748
+ }
749
+ /**
750
+ * Assemble all blocks seen so far, in stream order.
751
+ * @returns one block per seen index, except that max-token truncation drops
752
+ * tool calls that cannot be executed safely; an open block assembles from
753
+ * its accumulated deltas (an unknown block type never closed by `block-end` throws).
754
+ */
755
+ blocks() {
756
+ const blocks = this.order.map((index) => this.assemble(this.mustGet(index), index));
757
+ return this.finish.kind === "max-tokens" ? blocks.filter((block) => block.type !== "tool-call") : blocks;
758
+ }
759
+ /** Usage from the `usage` chunk; undefined until one arrives. */
760
+ get usage() {
761
+ return this._usage;
762
+ }
763
+ /** Finish reason from the `finish` chunk; `{kind: 'stop'}` when the stream ended without one. */
764
+ get finish() {
765
+ return this._finish ?? { kind: "stop" };
766
+ }
767
+ /** Adapter-private replay state from the terminal finish chunk, if any. */
768
+ get replayState() {
769
+ return this._replayState;
770
+ }
771
+ /**
772
+ * The assembled assistant message.
773
+ * @param source - producer attribution for the assembled message.
774
+ * @returns a frozen assistant-role message over `blocks()` (same open-block assembly rules).
775
+ */
776
+ message(source = {
777
+ kind: "plugin",
778
+ plugin: "dsh-llm/assembler"
779
+ }) {
780
+ return createMessage({
781
+ role: "assistant",
782
+ content: this.blocks(),
783
+ source
784
+ });
785
+ }
786
+ };
787
+ //#endregion
788
+ //#region lib/types/index.js
789
+ /**
790
+ * LLM service: adapter registry with a waterfall-interceptable streaming call
791
+ * surface. Exports the `LlmService` default, the abstract `LlmAdapter` for
792
+ * provider backends, and `BlockAssembler` for chunk assembly.
793
+ *
794
+ * @module @deepseek-ai/dsh-llm
795
+ */
796
+ /**
797
+ * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
798
+ * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
799
+ */
800
+ var LlmError = class extends HarnessError {
801
+ /** Serializable facts retained beside this live Error. */
802
+ failure;
803
+ /**
804
+ * @param message - non-empty human-readable failure summary.
805
+ * @param code - non-empty stable provider-neutral machine code.
806
+ * @param options - optional cause and validated serializable provider facts.
807
+ */
808
+ constructor(message, code, options) {
809
+ if (typeof message !== "string" || message.length === 0) throw new Error("LlmError message must be a non-empty string");
810
+ if (typeof code !== "string" || code.length === 0) throw new Error("LlmError code must be a non-empty string");
811
+ 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");
812
+ if (options?.providerRetryAfterMs !== void 0 && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) throw new Error("LlmError providerRetryAfterMs must be a positive finite number");
813
+ if (options?.requestId !== void 0 && (typeof options.requestId !== "string" || options.requestId.length === 0)) throw new Error("LlmError requestId must be a non-empty string");
814
+ super(message, code, options);
815
+ this.name = "LlmError";
816
+ this.failure = Object.freeze({
817
+ message,
818
+ code,
819
+ ...options?.status === void 0 ? {} : { status: options.status },
820
+ ...options?.providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs: options.providerRetryAfterMs },
821
+ ...options?.requestId === void 0 ? {} : { requestId: options.requestId }
822
+ });
823
+ }
824
+ };
825
+ /**
826
+ * Accept one supplied credential, or refuse it as unusable.
827
+ *
828
+ * A stored key arrives from the credentials seam, a `.env` line, or a shell
829
+ * export, all of which pick up surrounding whitespace, so trimming is silent.
830
+ * Anything else fails here rather than inside `fetch`, whose ByteString
831
+ * refusal names a UTF-16 code point instead of the setting to change. The key
832
+ * never enters the message: `ref` names where to fix it, and echoing any part
833
+ * of a secret into a log or a UI is the failure this diagnosis avoids.
834
+ *
835
+ * Lives beside {@link LlmError} rather than in `./api-key.ts` so the predicate
836
+ * module stays dependency-free; both adapters share this one diagnosis instead
837
+ * of keeping near-identical local copies.
838
+ * @param raw - the credential exactly as supplied.
839
+ * @param pkg - the refusing package name, prefixed to the diagnostic.
840
+ * @param ref - the credential reference the value resolved through.
841
+ * @returns the trimmed, usable key.
842
+ */
843
+ function assertUsableApiKey(raw, pkg, ref) {
844
+ const checked = normalizeApiKey(raw);
845
+ if (checked.ok) return checked.value;
846
+ 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);
847
+ }
848
+ /**
849
+ * Provider-wire adapter for the harness message and stream vocabulary. Register implementations
850
+ * with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include
851
+ * `attributionHeaders()`; prove the headers are added in the wire request or library header hook. The direct-fetch
852
+ * DeepSeek and library-backed pi-ai adapters meet this contract through different internals.
853
+ */
854
+ var LlmAdapter = class {
855
+ /**
856
+ * Describe one provider route owned by this adapter.
857
+ * @param provider - a route passed to `registerAdapter()` for this instance.
858
+ * @returns detached display metadata whose id must equal `provider`.
859
+ */
860
+ providerInfo(provider) {
861
+ return {
862
+ id: provider,
863
+ name: provider
864
+ };
865
+ }
866
+ /**
867
+ * Return the provider-owned retry policy captured with this route.
868
+ * @param _provider - a route passed to `registerAdapter()` for this instance.
869
+ * @returns a resolved policy, or `undefined` to use the normal defaults.
870
+ */
871
+ providerRetryPolicy(_provider) {}
872
+ /**
873
+ * List models this adapter can currently advertise for one owned provider.
874
+ * The result is advisory: an adapter may accept unlisted model ids, and
875
+ * consumers must not turn absence into request rejection.
876
+ * @param _provider - one provider route owned by this adapter.
877
+ * @returns discoverable models in adapter-preferred order.
878
+ */
879
+ listModels(_provider) {
880
+ return Promise.resolve([]);
881
+ }
882
+ /**
883
+ * Resolve all metadata available for one exact model. This query is
884
+ * independent of the advisory catalog and does not validate request routing.
885
+ * @param provider - one provider route owned by this adapter.
886
+ * @param model - exact model id passed to {@link GenerateOptions.model}.
887
+ * @param _signal - cancellation for this exact-model lookup; asynchronous
888
+ * implementations must settle promptly after it aborts.
889
+ * @returns provider/model identity plus any context, call-default, and reasoning metadata.
890
+ */
891
+ resolveModel(provider, model, _signal) {
892
+ return Promise.resolve({
893
+ provider,
894
+ id: model,
895
+ name: model
896
+ });
897
+ }
898
+ };
899
+ /**
900
+ * The abstract `llm` service: an adapter registry plus a streaming model-call
901
+ * surface, interceptable via the `llm/stream` waterfall.
902
+ */
903
+ var LlmService = class extends Service {
904
+ adapters = /* @__PURE__ */ new Map();
905
+ directory = /* @__PURE__ */ new Map();
906
+ discoveries = /* @__PURE__ */ new Map();
907
+ constructor(ctx) {
908
+ super(ctx, "llm");
909
+ }
910
+ /** Notify topology observers without letting one broken listener veto the commit. */
911
+ emitAdaptersUpdated() {
912
+ let invariantFailure;
913
+ for (const listener of this.ctx.events.dispatch("emit", ["llm/adapters-updated"])) try {
914
+ const returned = listener();
915
+ if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
916
+ this.warnAdaptersListenerFailure(error);
917
+ });
918
+ } catch (error) {
919
+ if (error?.code === "INVARIANT") {
920
+ invariantFailure ??= error;
921
+ continue;
922
+ }
923
+ this.warnAdaptersListenerFailure(error);
924
+ }
925
+ if (invariantFailure !== void 0) throw invariantFailure;
926
+ }
927
+ /** Contained-listener diagnostic shared by the sync and async failure paths. */
928
+ warnAdaptersListenerFailure(error) {
929
+ this.ctx.logger.warn("llm: an llm/adapters-updated listener failed");
930
+ this.ctx.logger.warn(error);
931
+ }
932
+ /**
933
+ * Register an adapter for the given provider routes. Throws `LlmError` with code
934
+ * `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).
935
+ * Disposed with the fiber.
936
+ * @param providers - every provider route this adapter should serve.
937
+ * @param adapter - the adapter that streams calls for those providers.
938
+ * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.
939
+ */
940
+ registerAdapter(providers, adapter) {
941
+ const owned = /* @__PURE__ */ new Set();
942
+ let released = false;
943
+ const dispose = this.ctx.effect(function* () {
944
+ if (providers.length === 0) throw new LlmError("an adapter must register at least one provider", "INVALID_ADAPTER");
945
+ this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned));
946
+ yield () => {
947
+ released = true;
948
+ for (const provider of owned) this.adapters.delete(provider);
949
+ owned.clear();
950
+ this.emitAdaptersUpdated();
951
+ };
952
+ }.bind(this), "llm.registerAdapter()");
953
+ const handle = (() => void dispose());
954
+ handle.replace = (next) => {
955
+ if (released) throw new LlmError("a disposed adapter registration cannot replace its routes", "REGISTRATION_DISPOSED");
956
+ this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned));
957
+ };
958
+ return handle;
959
+ }
960
+ /**
961
+ * Validate one candidate route set for `adapter`, treating routes this
962
+ * registration already holds as available. Nothing is mutated: a rejected
963
+ * candidate leaves the registry exactly as it was.
964
+ */
965
+ prepareRoutes(providers, adapter, owned) {
966
+ const unique = /* @__PURE__ */ new Set();
967
+ const registrations = [];
968
+ for (const provider of providers) {
969
+ if (provider.length === 0) throw new LlmError("adapter provider names must be non-empty", "INVALID_ADAPTER");
970
+ if (unique.has(provider) || this.adapters.has(provider) && !owned.has(provider)) throw new LlmError(`an adapter for provider "${provider}" is already registered`, "DUPLICATE_ADAPTER");
971
+ const info = adapter.providerInfo(provider);
972
+ 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");
973
+ unique.add(provider);
974
+ const retryPolicy = adapter.providerRetryPolicy(provider) ?? resolveRetryPolicy(void 0, `llm: provider "${provider}" retryPolicy`);
975
+ registrations.push({
976
+ adapter,
977
+ provider: {
978
+ id: info.id,
979
+ name: info.name
980
+ },
981
+ retryPolicy
982
+ });
983
+ }
984
+ return registrations;
985
+ }
986
+ /**
987
+ * Swap this registration's routes for the prepared ones in one synchronous
988
+ * section, so no observer can see the registry between the release and the
989
+ * re-registration. The route set's one mutation point is also where
990
+ * `llm/adapters-updated` is published, so a `replace` announces itself
991
+ * exactly like a first registration.
992
+ */
993
+ commitRoutes(owned, registrations) {
994
+ for (const provider of owned) this.adapters.delete(provider);
995
+ owned.clear();
996
+ for (const registration of registrations) {
997
+ this.adapters.set(registration.provider.id, registration);
998
+ owned.add(registration.provider.id);
999
+ }
1000
+ this.emitAdaptersUpdated();
1001
+ }
1002
+ /**
1003
+ * Describe provider routes with a registered adapter.
1004
+ * @returns detached provider metadata in registration order.
1005
+ */
1006
+ listProviders() {
1007
+ return [...this.adapters.values()].map(({ provider }) => ({ ...provider }));
1008
+ }
1009
+ /**
1010
+ * Declare provider routes an adapter plugin can activate through
1011
+ * configuration. Registration is all-or-nothing: an empty list, invalid
1012
+ * entry, or a provider already declared by any registration throws
1013
+ * `LlmError` without registering the rest. Disposed with the fiber.
1014
+ * @param entries - every configurable provider this plugin owns.
1015
+ * @returns a handle that withdraws all of them, and can atomically replace them.
1016
+ */
1017
+ registerConfigurableProviders(entries) {
1018
+ let held = [];
1019
+ let disposed = false;
1020
+ /**
1021
+ * Validate a candidate set in full against everything this registration
1022
+ * does not already hold, then publish it. Nothing is written until the
1023
+ * whole set passes, so a refused candidate leaves the current entries in
1024
+ * place — the property that makes `replace` a swap rather than a
1025
+ * delete-then-add that can strand the directory empty.
1026
+ */
1027
+ const commit = (candidates) => {
1028
+ const detached = [];
1029
+ const own = new Set(held.map((entry) => entry.provider));
1030
+ for (const entry of candidates) {
1031
+ 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");
1032
+ if (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider "${entry.provider}" has an empty settingsPath segment`, "INVALID_DIRECTORY");
1033
+ 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");
1034
+ detached.push({
1035
+ ...entry,
1036
+ settingsPath: [...entry.settingsPath]
1037
+ });
1038
+ }
1039
+ for (const entry of held) this.directory.delete(entry.provider);
1040
+ for (const entry of detached) this.directory.set(entry.provider, entry);
1041
+ held = detached;
1042
+ this.emitAdaptersUpdated();
1043
+ };
1044
+ const dispose = this.ctx.effect(function* () {
1045
+ if (entries.length === 0) throw new LlmError("a configurable-provider registration must declare at least one provider", "INVALID_DIRECTORY");
1046
+ commit(entries);
1047
+ yield () => {
1048
+ disposed = true;
1049
+ for (const entry of held) this.directory.delete(entry.provider);
1050
+ held = [];
1051
+ this.emitAdaptersUpdated();
1052
+ };
1053
+ }.bind(this), "llm.registerConfigurableProviders()");
1054
+ const handle = (() => void dispose());
1055
+ handle.replace = (next) => {
1056
+ if (disposed) throw new LlmError("this configurable-provider registration was disposed", "REGISTRATION_DISPOSED");
1057
+ commit(next);
1058
+ };
1059
+ return handle;
1060
+ }
1061
+ /**
1062
+ * List every declared configurable provider, registered or dormant.
1063
+ * @returns detached directory entries in declaration order.
1064
+ */
1065
+ listConfigurableProviders() {
1066
+ return [...this.directory.values()].map((entry) => ({
1067
+ ...entry,
1068
+ settingsPath: [...entry.settingsPath]
1069
+ }));
1070
+ }
1071
+ /**
1072
+ * Offer to interrogate provider endpoints on behalf of the settings
1073
+ * namespace this plugin owns. The namespace is the key because that is what
1074
+ * a configuration surface already holds from the configurable-provider
1075
+ * directory, and because a provider being *added* has no route to name yet.
1076
+ * Disposed with the fiber.
1077
+ * @param settingsNs - the namespace whose profiles this discovery serves.
1078
+ * @param discover - interrogates one endpoint; must honor `request.signal`.
1079
+ * @returns the disposer that withdraws the offer.
1080
+ */
1081
+ registerModelDiscovery(settingsNs, discover) {
1082
+ const dispose = this.ctx.effect(function* () {
1083
+ if (settingsNs.length === 0) throw new LlmError("model discovery needs a non-empty settings namespace", "INVALID_DISCOVERY");
1084
+ if (this.discoveries.has(settingsNs)) throw new LlmError(`model discovery for "${settingsNs}" is already registered`, "DUPLICATE_DISCOVERY");
1085
+ this.discoveries.set(settingsNs, discover);
1086
+ yield () => {
1087
+ this.discoveries.delete(settingsNs);
1088
+ };
1089
+ }.bind(this), "llm.registerModelDiscovery()");
1090
+ return () => void dispose();
1091
+ }
1092
+ /**
1093
+ * Interrogate one provider endpoint for the models it advertises. The
1094
+ * request describes a draft, not a stored route, so nothing here reads or
1095
+ * writes settings or credentials — the caller owns both, and the reply is
1096
+ * candidate metadata a surface may offer for adoption.
1097
+ * @param settingsNs - namespace whose registered discovery serves this draft.
1098
+ * @param request - the endpoint, protocol, and one-shot credential to use.
1099
+ * @returns the advertised models, deduplicated in endpoint order.
1100
+ */
1101
+ async discoverModels(settingsNs, request) {
1102
+ const discover = this.discoveries.get(settingsNs);
1103
+ if (discover === void 0) throw new LlmError(`no model discovery is registered for "${settingsNs}"`, "NO_DISCOVERY");
1104
+ if ((request.provider ?? "").length === 0 && (request.baseURL ?? "").length === 0) throw new LlmError("model discovery needs a provider route or a baseURL", "INVALID_DISCOVERY");
1105
+ const discovered = await discover(request);
1106
+ const seen = /* @__PURE__ */ new Set();
1107
+ const models = [];
1108
+ for (const model of discovered) {
1109
+ if (typeof model.id !== "string" || model.id.length === 0 || seen.has(model.id)) continue;
1110
+ seen.add(model.id);
1111
+ models.push({
1112
+ id: model.id,
1113
+ ...model.name === void 0 ? {} : { name: model.name },
1114
+ ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
1115
+ ...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens }
1116
+ });
1117
+ }
1118
+ return models;
1119
+ }
1120
+ /**
1121
+ * Resolve the retry policy captured when one provider route was registered.
1122
+ * @param provider - registered provider route to inspect.
1123
+ * @returns the provider-owned policy, with normal defaults already resolved.
1124
+ */
1125
+ providerRetryPolicy(provider) {
1126
+ return this.registration(provider).retryPolicy;
1127
+ }
1128
+ /** Detach typed adapter-owned modality metadata. */
1129
+ detachedModalities(modalities) {
1130
+ return modalities === void 0 ? void 0 : [...modalities];
1131
+ }
1132
+ /**
1133
+ * Discover models advertised by one registered provider. Catalog membership
1134
+ * is advisory and never changes routing or request validation.
1135
+ * @param provider - registered provider route to inspect.
1136
+ * @returns detached model metadata in adapter-preferred order.
1137
+ */
1138
+ async listModels(provider) {
1139
+ const models = await this.registration(provider).adapter.listModels(provider);
1140
+ const seen = /* @__PURE__ */ new Set();
1141
+ return models.map((model) => {
1142
+ 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");
1143
+ seen.add(model.id);
1144
+ const inputModalities = this.detachedModalities(model.inputModalities);
1145
+ return {
1146
+ provider: model.provider,
1147
+ id: model.id,
1148
+ name: model.name,
1149
+ ...model.description === void 0 ? {} : { description: model.description },
1150
+ ...inputModalities === void 0 ? {} : { inputModalities }
1151
+ };
1152
+ });
1153
+ }
1154
+ /**
1155
+ * Resolve and validate all metadata from the adapter that owns one exact
1156
+ * route. The result is detached from adapter-owned objects; catalog
1157
+ * membership remains advisory and does not control request routing.
1158
+ * @param provider - registered provider route to inspect.
1159
+ * @param model - exact model id passed to the adapter.
1160
+ * @param signal - optional cancellation for adapter-owned asynchronous lookup.
1161
+ * @returns exact model identity plus available context and reasoning metadata.
1162
+ */
1163
+ async resolveModelInfo(provider, model, signal) {
1164
+ return this.resolveModelInfoFor(this.registration(provider), model, signal);
1165
+ }
1166
+ async resolveModelInfoFor(registration, model, signal) {
1167
+ const provider = registration.provider.id;
1168
+ const resolved = await registration.adapter.resolveModel(provider, model, signal);
1169
+ 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");
1170
+ const context = resolved.context;
1171
+ 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");
1172
+ const inputModalities = this.detachedModalities(resolved.inputModalities);
1173
+ const defaultMaxTokens = resolved.defaultMaxTokens;
1174
+ 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");
1175
+ const info = {
1176
+ provider,
1177
+ id: model,
1178
+ name: resolved.name,
1179
+ ...resolved.description === void 0 ? {} : { description: resolved.description },
1180
+ ...inputModalities === void 0 ? {} : { inputModalities },
1181
+ ...context === void 0 ? {} : { context: { contextWindow: context.contextWindow } },
1182
+ ...defaultMaxTokens === void 0 ? {} : { defaultMaxTokens }
1183
+ };
1184
+ const reasoning = resolved.reasoning;
1185
+ if (reasoning === void 0) return info;
1186
+ if (reasoning.efforts.length === 0) throw new LlmError(`adapter returned invalid reasoning metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
1187
+ const seen = /* @__PURE__ */ new Set();
1188
+ const efforts = reasoning.efforts.map((effort) => {
1189
+ 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");
1190
+ seen.add(effort.id);
1191
+ return {
1192
+ id: effort.id,
1193
+ name: effort.name,
1194
+ ...effort.description === void 0 ? {} : { description: effort.description }
1195
+ };
1196
+ });
1197
+ 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");
1198
+ return {
1199
+ ...info,
1200
+ reasoning: {
1201
+ efforts,
1202
+ ...reasoning.defaultEffort === void 0 ? {} : { defaultEffort: reasoning.defaultEffort }
1203
+ }
1204
+ };
1205
+ }
1206
+ /**
1207
+ * Validate a conversation call config against its exact model capability and
1208
+ * materialize adapter-configured defaults. Unsupported explicit efforts
1209
+ * reject before provider I/O; no clamping or aliasing is performed. This
1210
+ * standalone query does not bind a later dispatch; use {@link prepareCall}
1211
+ * when logging and streaming must share one adapter registration.
1212
+ * @param config - provider/model route and optional request controls.
1213
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1214
+ * @returns a detached config only when a default must be materialized.
1215
+ */
1216
+ async resolveCallConfig(config, signal) {
1217
+ return (await this.resolveCallFor(this.registration(config.provider), config, signal)).config;
1218
+ }
1219
+ async resolveCallFor(registration, config, signal) {
1220
+ const info = await this.resolveModelInfoFor(registration, config.model, signal);
1221
+ const defaulted = config.maxTokens === void 0 && info.defaultMaxTokens !== void 0 ? {
1222
+ ...config,
1223
+ maxTokens: info.defaultMaxTokens
1224
+ } : config;
1225
+ const reasoning = info.reasoning;
1226
+ const requested = defaulted.reasoningEffort;
1227
+ let resolvedConfig = defaulted;
1228
+ if (reasoning === void 0) {
1229
+ if (requested !== void 0) throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${requested}"`, "UNSUPPORTED_REASONING_EFFORT");
1230
+ } else {
1231
+ const effective = requested ?? reasoning.defaultEffort;
1232
+ if (effective !== void 0) {
1233
+ 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");
1234
+ if (requested !== effective) resolvedConfig = {
1235
+ ...defaulted,
1236
+ reasoningEffort: effective
1237
+ };
1238
+ }
1239
+ }
1240
+ return {
1241
+ config: resolvedConfig,
1242
+ ...info.context === void 0 ? {} : { context: info.context }
1243
+ };
1244
+ }
1245
+ /**
1246
+ * Resolve one call under its current adapter registration. The returned
1247
+ * one-shot handle keeps that registration across header logging and dispatch,
1248
+ * so HMR cannot combine one adapter's capability result with another adapter.
1249
+ * @param config - provider/model route and optional request controls.
1250
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1251
+ * @returns a prepared config and its registration-bound stream entry point.
1252
+ */
1253
+ async prepareCall(config, signal) {
1254
+ const registration = this.registration(config.provider);
1255
+ const resolved = await this.resolveCallFor(registration, config, signal);
1256
+ const resolvedConfig = deepFreeze(structuredClone(resolved.config));
1257
+ const context = resolved.context === void 0 ? void 0 : deepFreeze(structuredClone(resolved.context));
1258
+ const adapterDefaults = deepFreeze({
1259
+ ...config.reasoningEffort === void 0 && resolvedConfig.reasoningEffort !== void 0 ? { reasoningEffort: true } : {},
1260
+ ...config.maxTokens === void 0 && resolvedConfig.maxTokens !== void 0 ? { maxTokens: true } : {}
1261
+ });
1262
+ let dispatched = false;
1263
+ return Object.freeze({
1264
+ config: resolvedConfig,
1265
+ retryPolicy: registration.retryPolicy,
1266
+ adapterDefaults,
1267
+ ...context === void 0 ? {} : { context },
1268
+ stream: (options) => {
1269
+ if (dispatched) throw new LlmError("a prepared LLM call can only be dispatched once", "INVALID_PREPARED_CALL");
1270
+ if (!callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
1271
+ dispatched = true;
1272
+ return this.streamWithRegistration(options, {
1273
+ registration,
1274
+ config: resolvedConfig
1275
+ });
1276
+ }
1277
+ });
1278
+ }
1279
+ registration(provider) {
1280
+ const registration = this.adapters.get(provider);
1281
+ if (!registration) throw new LlmError(`no adapter registered for provider "${provider}"`, "NO_ADAPTER");
1282
+ return registration;
1283
+ }
1284
+ /** Remove replay state whose historical route is owned by another adapter. */
1285
+ forAdapter(options, adapter) {
1286
+ const messages = options.messages.map((message) => {
1287
+ const source = message.source;
1288
+ if (message.role !== "assistant" || source.kind !== "model" || source.replayState === void 0) return message;
1289
+ if (this.adapters.get(source.provider)?.adapter === adapter) return message;
1290
+ return freezeMessage({
1291
+ ...message,
1292
+ source: {
1293
+ kind: "model",
1294
+ provider: source.provider,
1295
+ model: source.model
1296
+ }
1297
+ });
1298
+ });
1299
+ if (messages.every((message, index) => message === options.messages[index])) return options;
1300
+ const filtered = {
1301
+ ...options,
1302
+ messages
1303
+ };
1304
+ return Object.isFrozen(options) ? deepFreeze(filtered) : filtered;
1305
+ }
1306
+ /**
1307
+ * Final adapter boundary. Adapter selection, dispatch, iterator construction,
1308
+ * and iteration failures become one terminal failure chunk. Middleware and
1309
+ * downstream consumer failures remain thrown plugin or consumer errors.
1310
+ */
1311
+ async *adapterStream(options, prepared) {
1312
+ let iterator;
1313
+ try {
1314
+ const registration = prepared?.registration ?? this.registration(options.provider);
1315
+ const resolvedConfig = prepared === void 0 ? (await this.resolveCallFor(registration, options, options.signal)).config : prepared.config;
1316
+ if (prepared !== void 0 && !callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
1317
+ const resolvedOptions = callConfigEquals(options, resolvedConfig) ? options : Object.isFrozen(options) ? deepFreeze({
1318
+ ...options,
1319
+ ...resolvedConfig
1320
+ }) : {
1321
+ ...options,
1322
+ ...resolvedConfig
1323
+ };
1324
+ const adapter = registration.adapter;
1325
+ iterator = adapter.stream(this.forAdapter(resolvedOptions, adapter))[Symbol.asyncIterator]();
1326
+ } catch (error) {
1327
+ yield adapterFailureChunk(error, options.signal);
1328
+ return;
1329
+ }
1330
+ let completed = false;
1331
+ try {
1332
+ while (true) {
1333
+ let item;
1334
+ try {
1335
+ const next = await iterator.next();
1336
+ item = next.done ? { done: true } : {
1337
+ done: false,
1338
+ value: next.value
1339
+ };
1340
+ } catch (error) {
1341
+ completed = true;
1342
+ yield adapterFailureChunk(error, options.signal);
1343
+ return;
1344
+ }
1345
+ if (item.done) {
1346
+ completed = true;
1347
+ return;
1348
+ }
1349
+ yield item.value;
1350
+ }
1351
+ } finally {
1352
+ if (!completed) {
1353
+ const close = iterator.return?.bind(iterator);
1354
+ if (close) await close();
1355
+ }
1356
+ }
1357
+ }
1358
+ /**
1359
+ * Stream one model call as raw chunks (token-level deltas). Replay state is
1360
+ * retained only when the same adapter instance owns its historical provider
1361
+ * and the target provider. Final adapter selection remains fixed through
1362
+ * asynchronous exact-model resolution and dispatch. Adapter selection,
1363
+ * dispatch, and iteration failures become terminal `error` or `aborted`
1364
+ * finish chunks; middleware, nested-call, cleanup, and consumer failures
1365
+ * remain thrown.
1366
+ * @param options - the full request; `options.provider` selects the adapter.
1367
+ * @returns the chunk stream, possibly wrapped by `llm/stream` listeners.
1368
+ */
1369
+ stream(options) {
1370
+ return this.streamWithRegistration(options);
1371
+ }
1372
+ streamWithRegistration(options, prepared) {
1373
+ return this.ctx.waterfall(this, "llm/stream", options, () => this.adapterStream(options, prepared));
1374
+ }
1375
+ };
1376
+ /** Convert one adapter throw into the stream protocol's terminal outcome. */
1377
+ function adapterFailureChunk(error, signal) {
1378
+ const failure = normalizeLlmFailure(error);
1379
+ return {
1380
+ type: "finish",
1381
+ reason: signal?.aborted || failure.code === "ABORTED" ? {
1382
+ kind: "aborted",
1383
+ failure
1384
+ } : {
1385
+ kind: "error",
1386
+ failure
1387
+ }
1388
+ };
1389
+ }
1390
+ //#endregion
1391
+ export { APP_IDENTITY, BlockAssembler, CONTEXT_SUMMARY_MAX_CHARS, CONTEXT_WINDOW_EXCEEDED_CODE, CallId, EMPTY_RESPONSE_CODE, HarnessError, INVALID_CREDENTIAL_CODE, LlmAdapter, LlmError, LlmService, LlmService as default, MessageId, ProviderRequestId, QUOTA_EXCEEDED_CODE, ReasoningEffortId, RetryPolicySchema, assertNever, assertUsableApiKey, attributionHeaders, boundContextSummary, callConfigEquals, contentHasImage, createAssistantMessage, createMessage, createToolResultMessage, createUserMessage, deepFreeze, errorChain, freezeMessage, isAgentLoopRequest, isContextWindowExceededError, isHarnessError, isQuotaExceededError, markAgentLoopRequest, normalizeApiKey, resolveRetryPolicy, userAgent };