@artenx/dshb 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2241 @@
1
+ import { sharedSessionInstructionSnapshotStore, sharedWorkspaceInstructionStore } from "./core/workspace-instructions.js";
2
+ import { createRequire } from "node:module";
3
+ import { Service } from "@deepseek-ai/cordis";
4
+ //#region ../../node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
5
+ /** The one Remote failure class shared by owners, the Gateway, and consumers. */
6
+ /**
7
+ * One Remote call failure: a real Error carrying its stable code and typed
8
+ * details. Owners throw it at the failure point; the Host Gateway encodes it
9
+ * onto the wire unchanged; the Client face rebuilds an instance for the
10
+ * `RemoteResult` error branch, so `throw result.error` keeps throw semantics.
11
+ * Discrimination is always by `code`, never by instanceof.
12
+ */
13
+ var RemoteError = class extends Error {
14
+ code;
15
+ details;
16
+ /** Structural marker: cross-realm/bundle identification never uses instanceof. */
17
+ isDSHRemoteError = true;
18
+ /**
19
+ * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}.
20
+ * @param message - human diagnostic carried across the wire.
21
+ * @param details - structured payload typed by the code.
22
+ * @param options - standard Error options (`cause` survives in-process only).
23
+ */
24
+ constructor(code, message, details, options) {
25
+ super(message, options);
26
+ this.code = code;
27
+ this.details = details;
28
+ this.name = "RemoteError";
29
+ }
30
+ };
31
+ /**
32
+ * Remote decorators and explicit Gateway bindings backed by versioned
33
+ * descriptors carried on decorated class prototypes. Strict reflection
34
+ * remains a Typert compiler responsibility.
35
+ * @module @deepseek-ai/dsh-typert-protocol
36
+ */
37
+ const TYPERT_REMOTE_SEGMENT_PATTERN = /^[A-Za-z0-9_$.-]+$/;
38
+ /**
39
+ * Test one generated Remote name against the Connection endpoint grammar.
40
+ * @param value - namespace, method, lookup, or Context segment.
41
+ * @returns whether the value can cross the shared RPC carrier unchanged.
42
+ */
43
+ function isTypertRemoteSegment(value) {
44
+ return value !== "." && value !== ".." && TYPERT_REMOTE_SEGMENT_PATTERN.test(value);
45
+ }
46
+ const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-methods";
47
+ /**
48
+ * Bind one visible Service field to a Cordis key and Remote namespace.
49
+ * @param service - owning Service instance, normally `this`.
50
+ * @param serviceKey - exact Cordis service key.
51
+ * @param options - optional distinct wire namespace.
52
+ * @returns a frozen, inspectable binding with no compiler-injected metadata.
53
+ */
54
+ function bindTypertRemote(service, serviceKey, options = {}) {
55
+ validateName("service key", serviceKey);
56
+ const namespace = options.namespace ?? serviceKey;
57
+ validateName("namespace", namespace);
58
+ return Object.freeze({
59
+ service,
60
+ serviceKey,
61
+ namespace
62
+ });
63
+ }
64
+ /** Cordis Service base that exposes its registered name through Typert Gateway. */
65
+ var TypertRemoteService = class extends Service {
66
+ /** Visible binding consumed by the Gateway's source-mode discovery. */
67
+ typertRemote;
68
+ /**
69
+ * Register the Service and bind the same key to Typert Gateway.
70
+ * @param ctx - owning Cordis Context.
71
+ * @param serviceKey - exact Cordis service key and default wire namespace.
72
+ * @param options - optional distinct wire namespace.
73
+ */
74
+ constructor(ctx, serviceKey, options = {}) {
75
+ super(ctx, serviceKey);
76
+ this.typertRemote = bindTypertRemote(this, this.name, options);
77
+ }
78
+ };
79
+ function Remote(methodExportOrOptions, context) {
80
+ if (typeof methodExportOrOptions === "string") {
81
+ validateName("Remote export name", methodExportOrOptions);
82
+ return remoteDecorator({ kind: "direct" }, void 0, methodExportOrOptions);
83
+ }
84
+ if (typeof methodExportOrOptions === "object") {
85
+ if (remoteOptionMode(methodExportOrOptions) !== "stream" || Reflect.ownKeys(methodExportOrOptions).length !== 1) throw new TypeError("typert-protocol: Remote options must contain exactly mode: \"stream\"");
86
+ return remoteDecorator({ kind: "direct" }, "stream");
87
+ }
88
+ if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
89
+ addMarkerInitializer(context, { kind: "direct" });
90
+ }
91
+ function remoteOptionMode(options) {
92
+ return Reflect.get(options, "mode");
93
+ }
94
+ function remoteDecorator(invocation, mode, exportName) {
95
+ return function(_method, context) {
96
+ addMarkerInitializer(context, invocation, mode, exportName);
97
+ };
98
+ }
99
+ function readRemoteMethodDescriptor(prototype) {
100
+ const property = Object.getOwnPropertyDescriptor(prototype, REMOTE_METHOD_DESCRIPTOR);
101
+ if (property === void 0) return void 0;
102
+ const descriptor = property.value;
103
+ if (descriptor === null || typeof descriptor !== "object") throw new TypeError("typert-protocol: Remote method descriptor must be an object");
104
+ const version = Reflect.get(descriptor, "version");
105
+ if (version !== 1) throw new TypeError(`typert-protocol: unsupported Remote method descriptor version ${String(version)}`);
106
+ const methods = Reflect.get(descriptor, "methods");
107
+ if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
108
+ return descriptor;
109
+ }
110
+ function addMarkerInitializer(context, invocation, mode, exportName) {
111
+ if (context.private || context.static || typeof context.name !== "string") throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");
112
+ const method = context.name;
113
+ context.addInitializer(function() {
114
+ const prototype = Object.getPrototypeOf(this);
115
+ if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
116
+ mark(prototype, method, invocation, mode, exportName);
117
+ });
118
+ }
119
+ function mark(prototype, method, invocation, mode, exportName) {
120
+ const descriptor = readRemoteMethodDescriptor(prototype);
121
+ const marker = Object.freeze({
122
+ method,
123
+ ...exportName === void 0 || exportName === method ? {} : { exportName },
124
+ ...mode === void 0 ? {} : { mode },
125
+ invocation: Object.freeze(invocation)
126
+ });
127
+ const current = descriptor?.methods.find((candidate) => candidate.method === method);
128
+ if (current !== void 0) {
129
+ if (current.exportName === marker.exportName && current.mode === marker.mode && sameInvocation(current.invocation, invocation)) return;
130
+ throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
131
+ }
132
+ Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
133
+ configurable: true,
134
+ value: Object.freeze({
135
+ version: 1,
136
+ methods: Object.freeze([...descriptor?.methods ?? [], marker])
137
+ })
138
+ });
139
+ }
140
+ function sameInvocation(left, right) {
141
+ if (left.kind === "direct") return right.kind === "direct";
142
+ if (right.kind === "direct") return false;
143
+ return left.context === right.context;
144
+ }
145
+ function validateName(subject, value) {
146
+ if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
147
+ }
148
+ //#endregion
149
+ //#region ../../node_modules/@deepseek-ai/dsh-util-values/lib/index.js
150
+ /**
151
+ * Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
152
+ * @param value - value to freeze.
153
+ * @returns the same value after every reachable enumerable child is frozen.
154
+ */
155
+ function deepFreeze(value) {
156
+ const seen = /* @__PURE__ */ new WeakSet();
157
+ const pending = [{
158
+ kind: "visit",
159
+ node: value
160
+ }];
161
+ while (pending.length > 0) {
162
+ const task = pending.pop();
163
+ /* v8 ignore next -- the loop condition guarantees one pending task. */
164
+ if (task === void 0) continue;
165
+ if (task.kind === "property") {
166
+ pending.push({
167
+ kind: "visit",
168
+ node: task.source[task.key]
169
+ });
170
+ continue;
171
+ }
172
+ const node = task.node;
173
+ if (node === null || typeof node !== "object") continue;
174
+ if (node instanceof AbortSignal) continue;
175
+ if (seen.has(node)) continue;
176
+ seen.add(node);
177
+ Object.freeze(node);
178
+ const keys = Object.keys(node);
179
+ for (let index = keys.length - 1; index >= 0; index--) {
180
+ const key = keys[index];
181
+ /* v8 ignore next -- the loop is bounded by the captured key count. */
182
+ if (key === void 0) continue;
183
+ pending.push({
184
+ kind: "property",
185
+ source: node,
186
+ key
187
+ });
188
+ }
189
+ }
190
+ return value;
191
+ }
192
+ //#endregion
193
+ //#region ../../node_modules/@deepseek-ai/dsh-util-crypto/lib/index.js
194
+ /**
195
+ * Random v4 UUID, minted from `crypto.getRandomValues`.
196
+ * @returns the UUID string.
197
+ */
198
+ function randomUUID() {
199
+ const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
200
+ const hex = Array.from(bytes, (byte, index) => {
201
+ return (index === 6 ? byte & 15 | 64 : index === 8 ? byte & 63 | 128 : byte).toString(16).padStart(2, "0");
202
+ }).join("");
203
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
204
+ }
205
+ //#endregion
206
+ //#region ../../node_modules/@deepseek-ai/dsh-brand/lib/index.js
207
+ /**
208
+ * Duplicate-install-safe nominal primitive helpers.
209
+ *
210
+ * A brand makes structurally identical strings or numbers non-interchangeable
211
+ * at the type level: a `SessionId` cannot be passed where a `ToolCallId` is
212
+ * expected, and an event sequence cannot be passed as a log offset. Comparison,
213
+ * logging, and serialization retain the underlying primitive behavior.
214
+ *
215
+ * This package owns no concrete domain value and keeps no runtime identity or mutable
216
+ * state, so independently installed copies produce interchangeable values.
217
+ *
218
+ * @module @deepseek-ai/dsh-brand
219
+ */
220
+ /**
221
+ * Apply a compile-time string brand without changing the value.
222
+ * @param value - string admitted by the domain that owns the target brand.
223
+ * @returns the same string with the requested compile-time brand.
224
+ */
225
+ function brandString(value) {
226
+ return value;
227
+ }
228
+ //#endregion
229
+ //#region ../../node_modules/@deepseek-ai/cosmokit/lib/index.js
230
+ /** Return true when a value is `null` or `undefined`. */
231
+ function isNullable(value) {
232
+ return value === null || value === void 0;
233
+ }
234
+ /** Return true for non-array object values. */
235
+ function isPlainObject(data) {
236
+ return data && typeof data === "object" && !Array.isArray(data);
237
+ }
238
+ /** Filter object entries and return a new object. */
239
+ function filterKeys(object, filter) {
240
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
241
+ }
242
+ /** Map object values while preserving the original key set. */
243
+ function mapValues(object, transform) {
244
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
245
+ }
246
+ /** Pick selected keys from an object, optionally including `undefined` values. */
247
+ function pick(source, keys, forced) {
248
+ if (!keys) return { ...source };
249
+ const result = {};
250
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
251
+ return result;
252
+ }
253
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
254
+ function is(type, value) {
255
+ if (arguments.length === 1) return (value) => is(type, value);
256
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
257
+ }
258
+ function isArrayBufferLike(value) {
259
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
260
+ }
261
+ function isArrayBufferSource(value) {
262
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
263
+ }
264
+ /** Binary source detection and base64/hex conversion helpers. */
265
+ var Binary;
266
+ (function(Binary) {
267
+ Binary.is = isArrayBufferLike;
268
+ Binary.isSource = isArrayBufferSource;
269
+ function fromSource(source) {
270
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
271
+ else return source;
272
+ }
273
+ Binary.fromSource = fromSource;
274
+ function toBase64(source) {
275
+ source = fromSource(source);
276
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
277
+ let binary = "";
278
+ const bytes = new Uint8Array(source);
279
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
280
+ return btoa(binary);
281
+ }
282
+ Binary.toBase64 = toBase64;
283
+ function fromBase64(source) {
284
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
285
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
286
+ }
287
+ Binary.fromBase64 = fromBase64;
288
+ function toHex(source) {
289
+ source = fromSource(source);
290
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
291
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
292
+ }
293
+ Binary.toHex = toHex;
294
+ function fromHex(source) {
295
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
296
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
297
+ const buffer = [];
298
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
299
+ return Uint8Array.from(buffer).buffer;
300
+ }
301
+ Binary.fromHex = fromHex;
302
+ })(Binary || (Binary = {}));
303
+ Binary.fromBase64;
304
+ Binary.toBase64;
305
+ Binary.fromHex;
306
+ Binary.toHex;
307
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
308
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
309
+ if (!source || typeof source !== "object") return source;
310
+ if (is("Date", source)) return new Date(source.valueOf());
311
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
312
+ if (isArrayBufferLike(source)) return source.slice(0);
313
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
314
+ const cached = refs.get(source);
315
+ if (cached) return cached;
316
+ if (Array.isArray(source)) {
317
+ const result = [];
318
+ refs.set(source, result);
319
+ source.forEach((value, index) => {
320
+ result[index] = Reflect.apply(clone, null, [value, refs]);
321
+ });
322
+ return result;
323
+ }
324
+ const result = Object.create(Object.getPrototypeOf(source));
325
+ refs.set(source, result);
326
+ for (const key of Reflect.ownKeys(source)) {
327
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
328
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
329
+ Reflect.defineProperty(result, key, descriptor);
330
+ }
331
+ return result;
332
+ }
333
+ /** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
334
+ function deepEqual(a, b, strict) {
335
+ if (a === b) return true;
336
+ if (!strict && isNullable(a) && isNullable(b)) return true;
337
+ if (typeof a !== typeof b) return false;
338
+ if (typeof a !== "object") return false;
339
+ if (!a || !b) return false;
340
+ function check(test, then) {
341
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
342
+ }
343
+ return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
344
+ if (a.byteLength !== b.byteLength) return false;
345
+ const viewA = new Uint8Array(a);
346
+ const viewB = new Uint8Array(b);
347
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
348
+ return true;
349
+ }) ?? Object.keys({
350
+ ...a,
351
+ ...b
352
+ }).every((key) => deepEqual(a[key], b[key], strict));
353
+ }
354
+ /** Time constants plus parsing and formatting helpers. */
355
+ var Time;
356
+ (function(Time) {
357
+ Time.millisecond = 1;
358
+ Time.second = 1e3;
359
+ Time.minute = Time.second * 60;
360
+ Time.hour = Time.minute * 60;
361
+ Time.day = Time.hour * 24;
362
+ Time.week = Time.day * 7;
363
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
364
+ function setTimezoneOffset(offset) {
365
+ timezoneOffset = offset;
366
+ }
367
+ Time.setTimezoneOffset = setTimezoneOffset;
368
+ function getTimezoneOffset() {
369
+ return timezoneOffset;
370
+ }
371
+ Time.getTimezoneOffset = getTimezoneOffset;
372
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
373
+ if (typeof date === "number") date = new Date(date);
374
+ if (offset === void 0) offset = timezoneOffset;
375
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
376
+ }
377
+ Time.getDateNumber = getDateNumber;
378
+ function fromDateNumber(value, offset) {
379
+ const date = new Date(value * Time.day);
380
+ if (offset === void 0) offset = timezoneOffset;
381
+ return new Date(+date + offset * Time.minute);
382
+ }
383
+ Time.fromDateNumber = fromDateNumber;
384
+ const numeric = /\d+(?:\.\d+)?/.source;
385
+ const timeRegExp = new RegExp(`^${[
386
+ "w(?:eek(?:s)?)?",
387
+ "d(?:ay(?:s)?)?",
388
+ "h(?:our(?:s)?)?",
389
+ "m(?:in(?:ute)?(?:s)?)?",
390
+ "s(?:ec(?:ond)?(?:s)?)?"
391
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
392
+ function parseTime(source) {
393
+ const capture = timeRegExp.exec(source);
394
+ if (!capture) return 0;
395
+ return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
396
+ }
397
+ Time.parseTime = parseTime;
398
+ function parseDate(date) {
399
+ const parsed = parseTime(date);
400
+ if (parsed) date = Date.now() + parsed;
401
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
402
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
403
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
404
+ }
405
+ Time.parseDate = parseDate;
406
+ function format(ms) {
407
+ const abs = Math.abs(ms);
408
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
409
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
410
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
411
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
412
+ return ms + "ms";
413
+ }
414
+ Time.format = format;
415
+ function toDigits(source, length = 2) {
416
+ return source.toString().padStart(length, "0");
417
+ }
418
+ Time.toDigits = toDigits;
419
+ function template(template, time = /* @__PURE__ */ new Date()) {
420
+ return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
421
+ }
422
+ Time.template = template;
423
+ })(Time || (Time = {}));
424
+ //#endregion
425
+ //#region ../../node_modules/@deepseek-ai/schemastery/lib/index.mjs
426
+ const kSchema = Symbol.for("schemastery");
427
+ const kValidationError = Symbol.for("ValidationError");
428
+ globalThis.__schemastery_index__ ??= 0;
429
+ globalThis.__schemastery_refs__ = void 0;
430
+ var ValidationError = class extends TypeError {
431
+ options;
432
+ name = "ValidationError";
433
+ constructor(message, options) {
434
+ let prefix = "$";
435
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
436
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
437
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
438
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
439
+ super((prefix === "$" ? "" : `${prefix} `) + message);
440
+ this.options = options;
441
+ }
442
+ static is(error) {
443
+ return !!error?.[kValidationError];
444
+ }
445
+ };
446
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
447
+ const Schema = function(options) {
448
+ const schema = function(data, options = {}) {
449
+ return Schema.resolve(data, schema, options)[0];
450
+ };
451
+ if (options.refs) {
452
+ const refs = mapValues(options.refs, (options) => new Schema(options));
453
+ const getRef = (uid) => refs[uid];
454
+ for (const key in refs) {
455
+ const options = refs[key];
456
+ options.sKey = getRef(options.sKey);
457
+ options.inner = getRef(options.inner);
458
+ options.list = options.list && options.list.map(getRef);
459
+ options.dict = options.dict && mapValues(options.dict, getRef);
460
+ }
461
+ return refs[options.uid];
462
+ }
463
+ Object.assign(schema, options);
464
+ if (typeof schema.callback === "string") try {
465
+ schema.callback = new Function("return " + schema.callback)();
466
+ } catch {}
467
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
468
+ Object.setPrototypeOf(schema, Schema.prototype);
469
+ schema.meta ||= {};
470
+ schema.toString = schema.toString.bind(schema);
471
+ return schema;
472
+ };
473
+ Schema.prototype = Object.create(Function.prototype);
474
+ Schema.prototype[kSchema] = true;
475
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
476
+ return {
477
+ version: 1,
478
+ vendor: "schemastery",
479
+ validate: (value) => {
480
+ try {
481
+ return { value: Schema.resolve(value, this, {})[0] };
482
+ } catch (error) {
483
+ if (ValidationError.is(error)) return { issues: [{
484
+ message: error.message,
485
+ path: error.options.path
486
+ }] };
487
+ throw error;
488
+ }
489
+ }
490
+ };
491
+ } });
492
+ Schema.ValidationError = ValidationError;
493
+ Schema.prototype.toJSON = function toJSON() {
494
+ if (globalThis.__schemastery_refs__) {
495
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
496
+ return this.uid;
497
+ }
498
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
499
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
500
+ const result = {
501
+ uid: this.uid,
502
+ refs: globalThis.__schemastery_refs__
503
+ };
504
+ globalThis.__schemastery_refs__ = void 0;
505
+ return result;
506
+ };
507
+ Schema.prototype.set = function set(key, value) {
508
+ this.dict[key] = value;
509
+ return this;
510
+ };
511
+ Schema.prototype.push = function push(value) {
512
+ this.list.push(value);
513
+ return this;
514
+ };
515
+ function mergeDesc(original, messages) {
516
+ const result = typeof original === "string" ? { "": original } : { ...original };
517
+ for (const locale in messages) {
518
+ const value = messages[locale];
519
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
520
+ else if (typeof value === "string") result[locale] = value;
521
+ }
522
+ return result;
523
+ }
524
+ function getInner(value) {
525
+ return value?.$value ?? value?.$inner;
526
+ }
527
+ function extractKeys(data) {
528
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
529
+ }
530
+ Schema.prototype.i18n = function i18n(messages) {
531
+ const schema = Schema(this);
532
+ const desc = mergeDesc(schema.meta.description, messages);
533
+ if (Object.keys(desc).length) schema.meta.description = desc;
534
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
535
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
536
+ });
537
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
538
+ return inner.i18n(mapValues(messages, (data = {}) => {
539
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
540
+ if (Array.isArray(data)) return data[index];
541
+ return extractKeys(data);
542
+ }));
543
+ });
544
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
545
+ if (getInner(data)) return getInner(data);
546
+ return extractKeys(data);
547
+ }));
548
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
549
+ return schema;
550
+ };
551
+ Schema.prototype.extra = function extra(key, value) {
552
+ const schema = Schema(this);
553
+ schema.meta = {
554
+ ...schema.meta,
555
+ [key]: value
556
+ };
557
+ return schema;
558
+ };
559
+ for (const key of [
560
+ "required",
561
+ "disabled",
562
+ "collapse",
563
+ "hidden",
564
+ "loose"
565
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
566
+ const schema = Schema(this);
567
+ schema.meta = {
568
+ ...schema.meta,
569
+ [key]: value
570
+ };
571
+ return schema;
572
+ } });
573
+ Schema.prototype.deprecated = function deprecated() {
574
+ const schema = Schema(this);
575
+ schema.meta.badges ||= [];
576
+ schema.meta.badges.push({
577
+ text: "deprecated",
578
+ type: "danger"
579
+ });
580
+ return schema;
581
+ };
582
+ Schema.prototype.experimental = function experimental() {
583
+ const schema = Schema(this);
584
+ schema.meta.badges ||= [];
585
+ schema.meta.badges.push({
586
+ text: "experimental",
587
+ type: "warning"
588
+ });
589
+ return schema;
590
+ };
591
+ Schema.prototype.pattern = function pattern(regexp) {
592
+ const schema = Schema(this);
593
+ const pattern = pick(regexp, ["source", "flags"]);
594
+ schema.meta = {
595
+ ...schema.meta,
596
+ pattern
597
+ };
598
+ return schema;
599
+ };
600
+ Schema.prototype.simplify = function simplify(value) {
601
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
602
+ if (isNullable(value)) return value;
603
+ if (this.type === "object" || this.type === "dict") {
604
+ const result = {};
605
+ for (const key in value) {
606
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
607
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
608
+ }
609
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
610
+ return result;
611
+ } else if (this.type === "array" || this.type === "tuple") {
612
+ const result = [];
613
+ value.forEach((value, index) => {
614
+ const schema = this.type === "array" ? this.inner : this.list[index];
615
+ const item = schema ? schema.simplify(value) : value;
616
+ result.push(item);
617
+ });
618
+ return result;
619
+ } else if (this.type === "intersect") {
620
+ const result = {};
621
+ for (const item of this.list) Object.assign(result, item.simplify(value));
622
+ return result;
623
+ } else if (this.type === "union") for (const schema of this.list) try {
624
+ Schema.resolve(value, schema, {});
625
+ return schema.simplify(value);
626
+ } catch {}
627
+ return value;
628
+ };
629
+ Schema.prototype.toString = function toString(inline) {
630
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
631
+ };
632
+ Schema.prototype.role = function role(role, extra) {
633
+ const schema = Schema(this);
634
+ schema.meta = {
635
+ ...schema.meta,
636
+ role,
637
+ extra
638
+ };
639
+ return schema;
640
+ };
641
+ for (const key of [
642
+ "default",
643
+ "link",
644
+ "comment",
645
+ "description",
646
+ "max",
647
+ "min",
648
+ "step"
649
+ ]) Object.assign(Schema.prototype, { [key](value) {
650
+ const schema = Schema(this);
651
+ schema.meta = {
652
+ ...schema.meta,
653
+ [key]: value
654
+ };
655
+ return schema;
656
+ } });
657
+ const resolvers = {};
658
+ Schema.extend = function extend(type, resolve) {
659
+ resolvers[type] = resolve;
660
+ };
661
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
662
+ if (!schema) return [data];
663
+ if (options.ignore?.(data, schema)) return [data];
664
+ if (isNullable(data) && schema.type !== "lazy") {
665
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
666
+ let current = schema;
667
+ let fallback = schema.meta.default;
668
+ while (current?.type === "intersect" && isNullable(fallback)) {
669
+ current = current.list[0];
670
+ fallback = current?.meta.default;
671
+ }
672
+ if (isNullable(fallback)) return [data];
673
+ data = clone(fallback);
674
+ }
675
+ const callback = resolvers[schema.type];
676
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
677
+ try {
678
+ return callback(data, schema, options, strict);
679
+ } catch (error) {
680
+ if (!schema.meta.loose) throw error;
681
+ return [schema.meta.default];
682
+ }
683
+ };
684
+ Schema.from = function from(source) {
685
+ if (isNullable(source)) return Schema.any();
686
+ else if ([
687
+ "string",
688
+ "number",
689
+ "boolean"
690
+ ].includes(typeof source)) return Schema.const(source).required();
691
+ else if (source[kSchema]) return source;
692
+ else if (typeof source === "function") switch (source) {
693
+ case String: return Schema.string().required();
694
+ case Number: return Schema.number().required();
695
+ case Boolean: return Schema.boolean().required();
696
+ case Function: return Schema.function().required();
697
+ default: return Schema.is(source).required();
698
+ }
699
+ else throw new TypeError(`cannot infer schema from ${source}`);
700
+ };
701
+ Schema.lazy = function lazy(builder) {
702
+ const toJSON = () => {
703
+ if (!schema.inner[kSchema]) {
704
+ schema.inner = schema.builder();
705
+ schema.inner.meta = {
706
+ ...schema.meta,
707
+ ...schema.inner.meta
708
+ };
709
+ }
710
+ return schema.inner.toJSON();
711
+ };
712
+ const schema = new Schema({
713
+ type: "lazy",
714
+ builder,
715
+ inner: { toJSON }
716
+ });
717
+ return schema;
718
+ };
719
+ Schema.natural = function natural() {
720
+ return Schema.number().step(1).min(0);
721
+ };
722
+ Schema.percent = function percent() {
723
+ return Schema.number().step(.01).min(0).max(1).role("slider");
724
+ };
725
+ Schema.date = function date() {
726
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
727
+ const date = new Date(value);
728
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
729
+ return date;
730
+ }, true)]);
731
+ };
732
+ Schema.regExp = function regExp(flag = "") {
733
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
734
+ try {
735
+ return new RegExp(value, flag);
736
+ } catch (e) {
737
+ throw new ValidationError(e.message, options);
738
+ }
739
+ }, true)]);
740
+ };
741
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
742
+ return Schema.union([
743
+ Schema.is(ArrayBuffer),
744
+ Schema.is(SharedArrayBuffer),
745
+ Schema.transform(Schema.any(), (value, options) => {
746
+ if (Binary.isSource(value)) return Binary.fromSource(value);
747
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
748
+ }, true),
749
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
750
+ try {
751
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
752
+ } catch (e) {
753
+ throw new ValidationError(e.message, options);
754
+ }
755
+ }, true)] : []
756
+ ]);
757
+ };
758
+ Schema.extend("lazy", (data, schema, options, strict) => {
759
+ if (!schema.inner[kSchema]) {
760
+ schema.inner = schema.builder();
761
+ schema.inner.meta = {
762
+ ...schema.meta,
763
+ ...schema.inner.meta
764
+ };
765
+ }
766
+ return Schema.resolve(data, schema.inner, options, strict);
767
+ });
768
+ Schema.extend("any", (data) => {
769
+ return [data];
770
+ });
771
+ Schema.extend("never", (data, _, options) => {
772
+ throw new ValidationError(`expected nullable but got ${data}`, options);
773
+ });
774
+ Schema.extend("const", (data, { value }, options) => {
775
+ if (deepEqual(data, value)) return [value];
776
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
777
+ });
778
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
779
+ const { max = Infinity, min = -Infinity } = meta;
780
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
781
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
782
+ }
783
+ Schema.extend("string", (data, { meta }, options) => {
784
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
785
+ if (meta.pattern) {
786
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
787
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
788
+ }
789
+ checkWithinRange(data.length, meta, "string length", options);
790
+ return [data];
791
+ });
792
+ function decimalShift(data, digits) {
793
+ const str = data.toString();
794
+ if (str.includes("e")) return data * Math.pow(10, digits);
795
+ const index = str.indexOf(".");
796
+ if (index === -1) return data * Math.pow(10, digits);
797
+ const frac = str.slice(index + 1);
798
+ const integer = str.slice(0, index);
799
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
800
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
801
+ }
802
+ function isMultipleOf(data, min, step) {
803
+ step = Math.abs(step);
804
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
805
+ const index = step.toString().indexOf(".");
806
+ const digits = step.toString().slice(index + 1).length;
807
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
808
+ }
809
+ Schema.extend("number", (data, { meta }, options) => {
810
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
811
+ checkWithinRange(data, meta, "number", options);
812
+ const { step } = meta;
813
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
814
+ return [data];
815
+ });
816
+ Schema.extend("boolean", (data, _, options) => {
817
+ if (typeof data === "boolean") return [data];
818
+ throw new ValidationError(`expected boolean but got ${data}`, options);
819
+ });
820
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
821
+ let value = 0, keys = [];
822
+ if (typeof data === "number") {
823
+ value = data;
824
+ for (const key in bits) if (data & bits[key]) keys.push(key);
825
+ } else if (Array.isArray(data)) {
826
+ keys = data;
827
+ for (const key of keys) {
828
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
829
+ if (key in bits) value |= bits[key];
830
+ }
831
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
832
+ if (value === meta.default) return [value];
833
+ return [value, keys];
834
+ });
835
+ Schema.extend("function", (data, _, options) => {
836
+ if (typeof data === "function") return [data];
837
+ throw new ValidationError(`expected function but got ${data}`, options);
838
+ });
839
+ Schema.extend("is", (data, { constructor }, options) => {
840
+ if (typeof constructor === "function") {
841
+ if (data instanceof constructor) return [data];
842
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
843
+ } else {
844
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
845
+ let prototype = Object.getPrototypeOf(data);
846
+ while (prototype) {
847
+ if (prototype.constructor?.name === constructor) return [data];
848
+ prototype = Object.getPrototypeOf(prototype);
849
+ }
850
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
851
+ }
852
+ });
853
+ function property(data, key, schema, options) {
854
+ try {
855
+ const [value, adapted] = Schema.resolve(data[key], schema, {
856
+ ...options,
857
+ path: [...options.path || [], key]
858
+ });
859
+ if (adapted !== void 0) data[key] = adapted;
860
+ return value;
861
+ } catch (e) {
862
+ if (!options?.autofix) throw e;
863
+ delete data[key];
864
+ return schema.meta.default;
865
+ }
866
+ }
867
+ Schema.extend("array", (data, { inner, meta }, options) => {
868
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
869
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
870
+ return [data.map((_, index) => property(data, index, inner, options))];
871
+ });
872
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
873
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
874
+ const result = {};
875
+ for (const key in data) {
876
+ let rKey;
877
+ try {
878
+ rKey = Schema.resolve(key, sKey, options)[0];
879
+ } catch (error) {
880
+ if (strict) continue;
881
+ throw error;
882
+ }
883
+ result[rKey] = property(data, key, inner, options);
884
+ data[rKey] = data[key];
885
+ if (key !== rKey) delete data[key];
886
+ }
887
+ return [result];
888
+ });
889
+ Schema.extend("tuple", (data, { list }, options, strict) => {
890
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
891
+ const result = list.map((inner, index) => property(data, index, inner, options));
892
+ if (strict) return [result];
893
+ result.push(...data.slice(list.length));
894
+ return [result];
895
+ });
896
+ function merge(result, data) {
897
+ for (const key in data) {
898
+ if (key in result) continue;
899
+ result[key] = data[key];
900
+ }
901
+ }
902
+ Schema.extend("object", (data, { dict }, options, strict) => {
903
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
904
+ const result = {};
905
+ for (const key in dict) {
906
+ const value = property(data, key, dict[key], options);
907
+ if (!isNullable(value) || key in data) result[key] = value;
908
+ }
909
+ if (!strict) merge(result, data);
910
+ return [result];
911
+ });
912
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
913
+ const messages = [];
914
+ for (const inner of list) try {
915
+ return Schema.resolve(data, inner, options, strict);
916
+ } catch (error) {
917
+ messages.push(error);
918
+ }
919
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
920
+ });
921
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
922
+ if (!list.length) return [data];
923
+ let result;
924
+ for (const inner of list) {
925
+ const value = Schema.resolve(data, inner, options, true)[0];
926
+ if (isNullable(value)) continue;
927
+ if (isNullable(result)) result = value;
928
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
929
+ else if (typeof value === "object") merge(result ??= {}, value);
930
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
931
+ }
932
+ if (!strict && isPlainObject(data)) merge(result, data);
933
+ return [result];
934
+ });
935
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
936
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
937
+ if (preserve) return [callback(result)];
938
+ else return [callback(result), callback(adapted)];
939
+ });
940
+ const formatters = {};
941
+ function defineMethod(name, keys, format) {
942
+ formatters[name] = format;
943
+ Object.assign(Schema, { [name](...args) {
944
+ const schema = new Schema({ type: name });
945
+ keys.forEach((key, index) => {
946
+ switch (key) {
947
+ case "sKey":
948
+ schema.sKey = args[index] ?? Schema.string();
949
+ break;
950
+ case "inner":
951
+ schema.inner = Schema.from(args[index]);
952
+ break;
953
+ case "list":
954
+ schema.list = args[index].map(Schema.from);
955
+ break;
956
+ case "dict":
957
+ schema.dict = mapValues(args[index], Schema.from);
958
+ break;
959
+ case "bits":
960
+ schema.bits = {};
961
+ for (const key in args[index]) {
962
+ if (typeof args[index][key] !== "number") continue;
963
+ schema.bits[key] = args[index][key];
964
+ }
965
+ break;
966
+ case "callback": {
967
+ const callback = schema.callback = args[index];
968
+ callback["toJSON"] ||= () => callback.toString();
969
+ break;
970
+ }
971
+ case "constructor": {
972
+ const constructor = schema.constructor = args[index];
973
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
974
+ break;
975
+ }
976
+ default: schema[key] = args[index];
977
+ }
978
+ });
979
+ if (name === "object" || name === "dict") schema.meta.default = {};
980
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
981
+ else if (name === "bitset") schema.meta.default = 0;
982
+ return schema;
983
+ } });
984
+ }
985
+ defineMethod("is", ["constructor"], ({ constructor }) => {
986
+ if (typeof constructor === "function") return constructor.name;
987
+ else return constructor;
988
+ });
989
+ defineMethod("any", [], () => "any");
990
+ defineMethod("never", [], () => "never");
991
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
992
+ defineMethod("string", [], () => "string");
993
+ defineMethod("number", [], () => "number");
994
+ defineMethod("boolean", [], () => "boolean");
995
+ defineMethod("bitset", ["bits"], () => "bitset");
996
+ defineMethod("function", [], () => "function");
997
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
998
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
999
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
1000
+ defineMethod("object", ["dict"], ({ dict }) => {
1001
+ if (Object.keys(dict).length === 0) return "{}";
1002
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
1003
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
1004
+ }).join(", ")} }`;
1005
+ });
1006
+ defineMethod("union", ["list"], ({ list }, inline) => {
1007
+ const result = list.map(({ toString: format }) => format()).join(" | ");
1008
+ return inline ? `(${result})` : result;
1009
+ });
1010
+ defineMethod("intersect", ["list"], ({ list }) => {
1011
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
1012
+ });
1013
+ defineMethod("transform", [
1014
+ "inner",
1015
+ "callback",
1016
+ "preserve"
1017
+ ], ({ inner }, isInner) => inner.toString(isInner));
1018
+ //#endregion
1019
+ //#region ../../node_modules/@deepseek-ai/dsh-timeout/lib/index.js
1020
+ /** Largest delay Node schedules without clamping it to one millisecond. */
1021
+ const MAX_TIMER_DELAY_MS = 2147483647;
1022
+ //#endregion
1023
+ //#region ../../node_modules/@deepseek-ai/dsh-llm/lib/index.js
1024
+ /**
1025
+ * Detach and deep-freeze a message whose identity already exists.
1026
+ * @param message - complete message, including its stable identity.
1027
+ * @returns an immutable snapshot that preserves the identity.
1028
+ */
1029
+ function freezeMessage(message) {
1030
+ return deepFreeze(structuredClone(message));
1031
+ }
1032
+ /**
1033
+ * Create one identified message and freeze it before publication.
1034
+ * @param input - complete role, content, and source for a new message.
1035
+ * @returns an immutable message with a fresh stable identity.
1036
+ */
1037
+ function createMessage(input) {
1038
+ return freezeMessage({
1039
+ ...input,
1040
+ id: brandString(randomUUID())
1041
+ });
1042
+ }
1043
+ /**
1044
+ * Create one identified user-role message and freeze it before publication.
1045
+ * @param input - complete content and source for a new user message.
1046
+ * @returns an immutable user message with a fresh stable identity.
1047
+ */
1048
+ function createUserMessage(input) {
1049
+ return createMessage({
1050
+ ...input,
1051
+ role: "user"
1052
+ });
1053
+ }
1054
+ /**
1055
+ * Harness error base with a stable machine-routable code and chained cause.
1056
+ * Package errors extend it so tool results and replay can retain failure class.
1057
+ * @module @deepseek-ai/dsh-llm/error
1058
+ */
1059
+ /**
1060
+ * Base class for all harness errors. Carries a `code` (stable, programmatic —
1061
+ * e.g. `NO_ADAPTER`, `INVALID_ARGS`, `INVARIANT`) distinct from the
1062
+ * human-readable `message`, and supports `cause` chaining via the standard
1063
+ * `ErrorOptions`. `name` defaults to the subclass constructor name.
1064
+ */
1065
+ var HarnessError = class extends Error {
1066
+ /** Stable machine-routable failure class (e.g. `RATE_LIMIT`); route on this, never by parsing `message`. */
1067
+ code;
1068
+ constructor(message, code, options) {
1069
+ super(message, options);
1070
+ this.code = code;
1071
+ this.name = new.target.name;
1072
+ }
1073
+ };
1074
+ /**
1075
+ * Canonical provider-neutral code for a response that completed normally but
1076
+ * carried no content blocks at all. Providers occasionally emit a degenerate
1077
+ * completion (a terminal stop with zero output); adapters classify it as this
1078
+ * failure instead of yielding an empty assistant message, because an empty
1079
+ * message silently ends the turn with nothing for the user or the loop to act
1080
+ * on. The attempt produced nothing durable, so retry policy treats it as safe
1081
+ * to repeat.
1082
+ */
1083
+ const EMPTY_RESPONSE_CODE = "EMPTY_RESPONSE";
1084
+ 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");
1085
+ 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");
1086
+ 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");
1087
+ /**
1088
+ * Provider-owned request-retry policy configuration and resolution.
1089
+ *
1090
+ * Adapters expose one resolved policy per registered provider route; the
1091
+ * optional dsh-llm-retry plugin executes it on the agent's failed-step extension point.
1092
+ *
1093
+ * @module @deepseek-ai/dsh-llm/retry-policy
1094
+ */
1095
+ const DEFAULT_MAX_RETRIES = 5;
1096
+ const DEFAULT_INITIAL_DELAY_MS = 500;
1097
+ const DEFAULT_MAX_DELAY_MS = 1e4;
1098
+ const DEFAULT_JITTER_RATIO = .1;
1099
+ const DEFAULT_RETRYABLE_CODES = Object.freeze([
1100
+ EMPTY_RESPONSE_CODE,
1101
+ "RATE_LIMIT",
1102
+ "SERVER",
1103
+ "TIMEOUT",
1104
+ "TRANSPORT"
1105
+ ]);
1106
+ const backoffSchema = Schema.object({
1107
+ initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
1108
+ maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
1109
+ jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
1110
+ });
1111
+ const normalPolicySchema = Schema.object({
1112
+ mode: Schema.const("normal").required(),
1113
+ maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
1114
+ retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
1115
+ backoff: backoffSchema
1116
+ });
1117
+ const alwaysPolicySchema = Schema.object({
1118
+ mode: Schema.const("always").required(),
1119
+ backoff: backoffSchema
1120
+ });
1121
+ Schema.union([normalPolicySchema, alwaysPolicySchema]);
1122
+ const NORMAL_POLICY_KEYS = /* @__PURE__ */ new Set([
1123
+ "mode",
1124
+ "maxRetries",
1125
+ "retryableCodes",
1126
+ "backoff"
1127
+ ]);
1128
+ const ALWAYS_POLICY_KEYS = /* @__PURE__ */ new Set([
1129
+ "mode",
1130
+ "maxRetries",
1131
+ "retryableCodes",
1132
+ "backoff"
1133
+ ]);
1134
+ const BACKOFF_KEYS = /* @__PURE__ */ new Set([
1135
+ "initialDelayMs",
1136
+ "maxDelayMs",
1137
+ "jitterRatio"
1138
+ ]);
1139
+ function validateKeys(value, allowed, path) {
1140
+ for (const key of Object.keys(value)) if (!allowed.has(key)) throw new Error(`${path}: unknown key "${key}"`);
1141
+ }
1142
+ function resolveBackoff(config, path) {
1143
+ if (config !== void 0) validateKeys(config, BACKOFF_KEYS, path);
1144
+ const initialDelayMs = config?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
1145
+ const maxDelayMs = config?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
1146
+ const jitterRatio = config?.jitterRatio ?? DEFAULT_JITTER_RATIO;
1147
+ if (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > 2147483647) throw new Error(`${path}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
1148
+ if (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > 2147483647) throw new Error(`${path}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
1149
+ if (initialDelayMs > maxDelayMs) throw new Error(`${path}.initialDelayMs must be less than or equal to maxDelayMs`);
1150
+ if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) throw new Error(`${path}.jitterRatio must be between 0 and 1`);
1151
+ return Object.freeze({
1152
+ initialDelayMs,
1153
+ maxDelayMs,
1154
+ jitterRatio
1155
+ });
1156
+ }
1157
+ /**
1158
+ * Validate, default, and detach one provider-owned retry policy.
1159
+ * @param config - optional provider configuration; omission selects normal defaults.
1160
+ * @param path - diagnostic path naming the provider config that owns the value.
1161
+ * @returns an immutable policy safe to capture in provider registration state.
1162
+ */
1163
+ function resolveRetryPolicy(config, path) {
1164
+ if (config === void 0) return Object.freeze({
1165
+ mode: "normal",
1166
+ maxRetries: DEFAULT_MAX_RETRIES,
1167
+ retryableCodes: DEFAULT_RETRYABLE_CODES,
1168
+ ...resolveBackoff(void 0, `${path}.backoff`)
1169
+ });
1170
+ switch (config.mode) {
1171
+ case "normal": {
1172
+ validateKeys(config, NORMAL_POLICY_KEYS, path);
1173
+ const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
1174
+ const retryableCodes = config.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];
1175
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) throw new Error(`${path}.maxRetries must be a non-negative safe integer`);
1176
+ if (retryableCodes.length === 0) throw new Error(`${path}.retryableCodes must not be empty`);
1177
+ if (retryableCodes.some((code) => typeof code !== "string" || code.length === 0)) throw new Error(`${path}.retryableCodes must contain only non-empty strings`);
1178
+ if (new Set(retryableCodes).size !== retryableCodes.length) throw new Error(`${path}.retryableCodes must not contain duplicates`);
1179
+ return Object.freeze({
1180
+ mode: "normal",
1181
+ maxRetries,
1182
+ retryableCodes: Object.freeze([...retryableCodes]),
1183
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
1184
+ });
1185
+ }
1186
+ case "always":
1187
+ validateKeys(config, ALWAYS_POLICY_KEYS, path);
1188
+ return Object.freeze({
1189
+ mode: "always",
1190
+ ...resolveBackoff(config.backoff, `${path}.backoff`)
1191
+ });
1192
+ default: throw new Error(`${path}.mode must be "normal" or "always"`);
1193
+ }
1194
+ }
1195
+ /**
1196
+ * Field-wise equality over {@link LlmCallConfig} — the comparison a caller
1197
+ * runs to decide whether a proposed configuration is a real change (worth a
1198
+ * logged header snapshot) or the held one restated.
1199
+ * @param a - one configuration.
1200
+ * @param b - the other.
1201
+ * @returns whether every field (including the `stop` list, element-wise) matches.
1202
+ */
1203
+ function callConfigEquals(a, b) {
1204
+ if (a.provider !== b.provider || a.model !== b.model || a.reasoningEffort !== b.reasoningEffort || a.temperature !== b.temperature || a.maxTokens !== b.maxTokens) return false;
1205
+ if (a.stop === void 0 || b.stop === void 0) return a.stop === b.stop;
1206
+ return a.stop.length === b.stop.length && a.stop.every((s, i) => s === b.stop?.[i]);
1207
+ }
1208
+ /**
1209
+ * Normalization for values thrown by a final LLM adapter boundary.
1210
+ *
1211
+ * @module @deepseek-ai/dsh-llm/adapter-failure
1212
+ */
1213
+ /**
1214
+ * Detach serializable provider facts from a value thrown by an adapter.
1215
+ * @param value - arbitrary value thrown during adapter dispatch or iteration.
1216
+ * @returns immutable provider-neutral facts suitable for a terminal finish chunk.
1217
+ * @internal
1218
+ */
1219
+ function normalizeLlmFailure(value) {
1220
+ const error = value instanceof Error ? value : new HarnessError(thrownMessage(value), "UNKNOWN", { cause: value });
1221
+ const carried = ownFailureSnapshot(error);
1222
+ if (carried !== void 0 && carried.code === ownErrorCode(error)) return carried;
1223
+ return Object.freeze({
1224
+ message: errorMessage(error),
1225
+ code: harnessErrorCode(error)
1226
+ });
1227
+ }
1228
+ /** Render a non-Error throw without letting hostile coercion escape normalization. */
1229
+ function thrownMessage(value) {
1230
+ try {
1231
+ const message = String(value);
1232
+ return message.length > 0 ? message : "LLM adapter failed";
1233
+ } catch (_hostileThrownValue) {
1234
+ return "LLM adapter failed";
1235
+ }
1236
+ }
1237
+ /** Read a foreign error's own data-backed `code` without invoking accessors. */
1238
+ function ownErrorCode(error) {
1239
+ try {
1240
+ const descriptor = Object.getOwnPropertyDescriptor(error, "code");
1241
+ return descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0;
1242
+ } catch (_sdkPropertyTrap) {
1243
+ return;
1244
+ }
1245
+ }
1246
+ /** Snapshot an own data property without invoking an SDK-defined accessor. */
1247
+ function ownFailureSnapshot(error) {
1248
+ try {
1249
+ const descriptor = Object.getOwnPropertyDescriptor(error, "failure");
1250
+ return descriptor !== void 0 && "value" in descriptor ? failureSnapshot(descriptor.value) : void 0;
1251
+ } catch (_sdkPropertyTrap) {
1252
+ return;
1253
+ }
1254
+ }
1255
+ /** Validate and detach an arbitrary serializable failure payload. */
1256
+ function failureSnapshot(value) {
1257
+ if (typeof value !== "object" || value === null) return void 0;
1258
+ try {
1259
+ const candidate = value;
1260
+ const message = candidate.message;
1261
+ const code = candidate.code;
1262
+ const status = candidate.status;
1263
+ const providerRetryAfterMs = candidate.providerRetryAfterMs;
1264
+ const requestId = candidate.requestId;
1265
+ 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;
1266
+ return Object.freeze({
1267
+ message,
1268
+ code,
1269
+ ...status === void 0 ? {} : { status },
1270
+ ...providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs },
1271
+ ...requestId === void 0 ? {} : { requestId }
1272
+ });
1273
+ } catch (_sdkFailureGetter) {
1274
+ return;
1275
+ }
1276
+ }
1277
+ /** Read an SDK error message without letting an accessor replace the primary failure. */
1278
+ function errorMessage(error) {
1279
+ try {
1280
+ const message = error.message;
1281
+ if (typeof message === "string" && message.length > 0) return message;
1282
+ } catch (_sdkMessageGetter) {}
1283
+ return "LLM adapter failed";
1284
+ }
1285
+ /** Trust only Harness-owned codes; third-party SDK codes are not our taxonomy. */
1286
+ function harnessErrorCode(error) {
1287
+ return error instanceof HarnessError ? error.code : "UNKNOWN";
1288
+ }
1289
+ function quoted(value) {
1290
+ return JSON.stringify(value);
1291
+ }
1292
+ /**
1293
+ * Stable text shown to a model that cannot accept one durable image reference.
1294
+ * @param ref - durable normalized attachment omitted from the request.
1295
+ * @returns deterministic text-only placeholder.
1296
+ */
1297
+ function textOnlyImageText(ref) {
1298
+ return `[image omitted because this model accepts text only; attachment sha256:${String(ref.attachmentId).slice(7, 15)}]`;
1299
+ }
1300
+ /**
1301
+ * True when typed model content contains an image block, walking nested
1302
+ * tool-result content. This is the one recursive image walk shared by every
1303
+ * image policy (capability gating, text-only serialization, compaction
1304
+ * survey), so a consumer cannot silently diverge on nesting depth.
1305
+ * @param content - typed model content blocks.
1306
+ * @returns whether any nested block is an image.
1307
+ */
1308
+ function contentHasImage(content) {
1309
+ return content.some((block) => block.type === "image" || block.type === "tool-result" && contentHasImage(block.content));
1310
+ }
1311
+ /**
1312
+ * True when typed model content contains a file block, walking nested
1313
+ * tool-result content on the same recursion every file policy shares.
1314
+ * Reads current content on every call without retaining scan results.
1315
+ * @param content - typed model content blocks.
1316
+ * @returns whether any nested block is a file.
1317
+ */
1318
+ function contentHasFile(content) {
1319
+ for (const block of content) if (block.type === "file" || block.type === "tool-result" && contentHasFile(block.content)) return true;
1320
+ return false;
1321
+ }
1322
+ /**
1323
+ * Stable model-facing handle for one durable file reference: the address of
1324
+ * the verbatim stored copy and the instruction to read it on demand. This is
1325
+ * the only representation a provider ever receives for a file.
1326
+ * @param ref - durable verbatim file reference.
1327
+ * @param readonlyPath - execution-world path of the stored copy, when resolvable.
1328
+ * @returns deterministic handle text naming the file, its size, and its address.
1329
+ */
1330
+ function fileHandleText(ref, readonlyPath) {
1331
+ const digest = String(ref.attachmentId).slice(7, 15);
1332
+ const identity = `File ${quoted(ref.name)} (${ref.bytes} bytes, sha256:${digest})`;
1333
+ if (readonlyPath === void 0) return `[${identity} was uploaded, but the current execution environment cannot access a readable path. Report that limitation if its contents are needed; do not claim to have read it.]`;
1334
+ return `[${identity}: verbatim read-only copy saved at ${quoted(readonlyPath)}. Read that path with your file tools when its contents are needed; copy it to a writable location before modifying it. When delegating file work, include this saved path in the delegation prompt; only subagents sharing this execution environment can read it.]`;
1335
+ }
1336
+ /** Replace every file occurrence, including nested tool results, with handle text. */
1337
+ function replaceFilesWithHandles(blocks, resolvePath) {
1338
+ let next;
1339
+ for (const [index, block] of blocks.entries()) {
1340
+ if (block.type === "file") {
1341
+ next ??= blocks.slice(0, index);
1342
+ next.push({
1343
+ type: "text",
1344
+ text: fileHandleText(block.attachment, resolvePath(block.attachment))
1345
+ });
1346
+ continue;
1347
+ }
1348
+ if (block.type === "tool-result") {
1349
+ const content = replaceFilesWithHandles(block.content, resolvePath);
1350
+ if (content !== block.content) {
1351
+ next ??= blocks.slice(0, index);
1352
+ next.push({
1353
+ ...block,
1354
+ content
1355
+ });
1356
+ continue;
1357
+ }
1358
+ }
1359
+ next?.push(block);
1360
+ }
1361
+ return next ?? blocks;
1362
+ }
1363
+ /**
1364
+ * Project durable file history into deterministic handle text for every model
1365
+ * route. Unlike images, no provider receives file blocks natively, so this
1366
+ * projection is unconditional in request assembly.
1367
+ * @param messages - complete request history.
1368
+ * @param resolvePath - resolve one reference's current execution-world read path.
1369
+ * @returns the original list without files, otherwise shallow message copies with handle text.
1370
+ */
1371
+ function projectFilesToText(messages, resolvePath) {
1372
+ if (!messages.some((message) => contentHasFile(message.content))) return messages;
1373
+ return messages.map((message) => {
1374
+ const content = replaceFilesWithHandles(message.content, resolvePath);
1375
+ return content === message.content ? message : {
1376
+ ...message,
1377
+ content
1378
+ };
1379
+ });
1380
+ }
1381
+ /** Replace every image occurrence, including nested tool results, for a text-only model. */
1382
+ function replaceImagesForTextModel(blocks) {
1383
+ let next;
1384
+ for (const [index, block] of blocks.entries()) {
1385
+ if (block.type === "image") {
1386
+ next ??= blocks.slice(0, index);
1387
+ next.push({
1388
+ type: "text",
1389
+ text: textOnlyImageText(block.attachment)
1390
+ });
1391
+ continue;
1392
+ }
1393
+ if (block.type === "tool-result") {
1394
+ const content = replaceImagesForTextModel(block.content);
1395
+ if (content !== block.content) {
1396
+ next ??= blocks.slice(0, index);
1397
+ next.push({
1398
+ ...block,
1399
+ content
1400
+ });
1401
+ continue;
1402
+ }
1403
+ }
1404
+ next?.push(block);
1405
+ }
1406
+ return next ?? blocks;
1407
+ }
1408
+ /**
1409
+ * Project durable image history into deterministic text for an exact text-only model.
1410
+ * @param messages - complete request history.
1411
+ * @returns the original list without images, otherwise shallow message copies with stable placeholders.
1412
+ */
1413
+ function projectImagesForTextModel(messages) {
1414
+ if (!messages.some((message) => contentHasImage(message.content))) return messages;
1415
+ return messages.map((message) => {
1416
+ const content = replaceImagesForTextModel(message.content);
1417
+ return content === message.content ? message : {
1418
+ ...message,
1419
+ content
1420
+ };
1421
+ });
1422
+ }
1423
+ /**
1424
+ * Centralize the non-secret product identity every provider request sends as `User-Agent`, keeping
1425
+ * adapters from drifting. See
1426
+ * `.agents/notes/implemented/architecture/2026-06-21-mandatory-app-attribution-headers.md`.
1427
+ *
1428
+ * App-attribution vocabulary for provider requests.
1429
+ * @module @deepseek-ai/dsh-llm/attribution
1430
+ */
1431
+ const { version } = createRequire(import.meta.url)("../package.json");
1432
+ /**
1433
+ * LLM service: adapter registry with a waterfall-interceptable streaming call
1434
+ * API. Exports the `LlmRuntime` default, the abstract `LlmAdapter` for
1435
+ * provider backends, and `BlockAssembler` for chunk assembly.
1436
+ *
1437
+ * @module @deepseek-ai/dsh-llm
1438
+ */
1439
+ var __runInitializers = function(thisArg, initializers, value) {
1440
+ var useValue = arguments.length > 2;
1441
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
1442
+ return useValue ? value : void 0;
1443
+ };
1444
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
1445
+ function accept(f) {
1446
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
1447
+ return f;
1448
+ }
1449
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
1450
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
1451
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
1452
+ var _, done = false;
1453
+ for (var i = decorators.length - 1; i >= 0; i--) {
1454
+ var context = {};
1455
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
1456
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
1457
+ context.addInitializer = function(f) {
1458
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
1459
+ extraInitializers.push(accept(f || null));
1460
+ };
1461
+ var result = (0, decorators[i])(kind === "accessor" ? {
1462
+ get: descriptor.get,
1463
+ set: descriptor.set
1464
+ } : descriptor[key], context);
1465
+ if (kind === "accessor") {
1466
+ if (result === void 0) continue;
1467
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
1468
+ if (_ = accept(result.get)) descriptor.get = _;
1469
+ if (_ = accept(result.set)) descriptor.set = _;
1470
+ if (_ = accept(result.init)) initializers.unshift(_);
1471
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
1472
+ else descriptor[key] = _;
1473
+ }
1474
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
1475
+ done = true;
1476
+ };
1477
+ /**
1478
+ * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
1479
+ * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
1480
+ */
1481
+ var LlmError = class extends HarnessError {
1482
+ /** Serializable facts retained beside this live Error. */
1483
+ failure;
1484
+ /**
1485
+ * @param message - non-empty human-readable failure summary.
1486
+ * @param code - non-empty stable provider-neutral machine code.
1487
+ * @param options - optional cause and validated serializable provider facts.
1488
+ */
1489
+ constructor(message, code, options) {
1490
+ if (typeof message !== "string" || message.length === 0) throw new Error("LlmError message must be a non-empty string");
1491
+ if (typeof code !== "string" || code.length === 0) throw new Error("LlmError code must be a non-empty string");
1492
+ 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");
1493
+ if (options?.providerRetryAfterMs !== void 0 && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) throw new Error("LlmError providerRetryAfterMs must be a positive finite number");
1494
+ if (options?.requestId !== void 0 && (typeof options.requestId !== "string" || options.requestId.length === 0)) throw new Error("LlmError requestId must be a non-empty string");
1495
+ super(message, code, options);
1496
+ this.name = "LlmError";
1497
+ this.failure = Object.freeze({
1498
+ message,
1499
+ code,
1500
+ ...options?.status === void 0 ? {} : { status: options.status },
1501
+ ...options?.providerRetryAfterMs === void 0 ? {} : { providerRetryAfterMs: options.providerRetryAfterMs },
1502
+ ...options?.requestId === void 0 ? {} : { requestId: options.requestId }
1503
+ });
1504
+ }
1505
+ };
1506
+ (() => {
1507
+ let _classSuper = TypertRemoteService;
1508
+ let _instanceExtraInitializers = [];
1509
+ let _listProviders_decorators;
1510
+ let _listConfigurableProviders_decorators;
1511
+ let _remoteDiscoverModels_decorators;
1512
+ return class LlmRuntime extends _classSuper {
1513
+ static {
1514
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
1515
+ _listProviders_decorators = [Remote];
1516
+ _listConfigurableProviders_decorators = [Remote];
1517
+ _remoteDiscoverModels_decorators = [Remote("discoverModels")];
1518
+ __esDecorate(this, null, _listProviders_decorators, {
1519
+ kind: "method",
1520
+ name: "listProviders",
1521
+ static: false,
1522
+ private: false,
1523
+ access: {
1524
+ has: (obj) => "listProviders" in obj,
1525
+ get: (obj) => obj.listProviders
1526
+ },
1527
+ metadata: _metadata
1528
+ }, null, _instanceExtraInitializers);
1529
+ __esDecorate(this, null, _listConfigurableProviders_decorators, {
1530
+ kind: "method",
1531
+ name: "listConfigurableProviders",
1532
+ static: false,
1533
+ private: false,
1534
+ access: {
1535
+ has: (obj) => "listConfigurableProviders" in obj,
1536
+ get: (obj) => obj.listConfigurableProviders
1537
+ },
1538
+ metadata: _metadata
1539
+ }, null, _instanceExtraInitializers);
1540
+ __esDecorate(this, null, _remoteDiscoverModels_decorators, {
1541
+ kind: "method",
1542
+ name: "remoteDiscoverModels",
1543
+ static: false,
1544
+ private: false,
1545
+ access: {
1546
+ has: (obj) => "remoteDiscoverModels" in obj,
1547
+ get: (obj) => obj.remoteDiscoverModels
1548
+ },
1549
+ metadata: _metadata
1550
+ }, null, _instanceExtraInitializers);
1551
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
1552
+ enumerable: true,
1553
+ configurable: true,
1554
+ writable: true,
1555
+ value: _metadata
1556
+ });
1557
+ }
1558
+ adapters = (__runInitializers(this, _instanceExtraInitializers), /* @__PURE__ */ new Map());
1559
+ directory = /* @__PURE__ */ new Map();
1560
+ discoveries = /* @__PURE__ */ new Map();
1561
+ constructor(ctx) {
1562
+ super(ctx, "llm");
1563
+ }
1564
+ /** Notify topology observers without letting one broken listener veto the commit. */
1565
+ emitAdaptersUpdated() {
1566
+ let invariantFailure;
1567
+ for (const listener of this.ctx.events.dispatch("emit", ["llm/adapters-updated"])) try {
1568
+ const returned = listener();
1569
+ if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
1570
+ this.warnAdaptersListenerFailure(error);
1571
+ });
1572
+ } catch (error) {
1573
+ if (error?.code === "INVARIANT") {
1574
+ invariantFailure ??= error;
1575
+ continue;
1576
+ }
1577
+ this.warnAdaptersListenerFailure(error);
1578
+ }
1579
+ if (invariantFailure !== void 0) throw invariantFailure;
1580
+ }
1581
+ /** Contained-listener diagnostic shared by the sync and async failure paths. */
1582
+ warnAdaptersListenerFailure(error) {
1583
+ this.ctx.logger.warn("llm: an llm/adapters-updated listener failed");
1584
+ this.ctx.logger.warn(error);
1585
+ }
1586
+ /**
1587
+ * Register an adapter for the given provider routes. Throws `LlmError` with code
1588
+ * `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).
1589
+ * Disposed with the fiber.
1590
+ * @param providers - every provider route this adapter should serve.
1591
+ * @param adapter - the adapter that streams calls for those providers.
1592
+ * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.
1593
+ */
1594
+ registerAdapter(providers, adapter) {
1595
+ const owned = /* @__PURE__ */ new Set();
1596
+ let released = false;
1597
+ const dispose = this.ctx.effect(function* () {
1598
+ if (providers.length === 0) throw new LlmError("an adapter must register at least one provider", "INVALID_ADAPTER");
1599
+ this.commitRoutes(owned, this.prepareRoutes(providers, adapter, owned));
1600
+ yield () => {
1601
+ released = true;
1602
+ for (const provider of owned) this.adapters.delete(provider);
1603
+ owned.clear();
1604
+ this.emitAdaptersUpdated();
1605
+ };
1606
+ }.bind(this), "llm.registerAdapter()");
1607
+ const handle = (() => void dispose());
1608
+ handle.replace = (next) => {
1609
+ if (released) throw new LlmError("a disposed adapter registration cannot replace its routes", "REGISTRATION_DISPOSED");
1610
+ this.commitRoutes(owned, this.prepareRoutes(next, adapter, owned));
1611
+ };
1612
+ return handle;
1613
+ }
1614
+ /**
1615
+ * Validate one candidate route set for `adapter`, treating routes this
1616
+ * registration already holds as available. Nothing is mutated: a rejected
1617
+ * candidate leaves the registry exactly as it was.
1618
+ */
1619
+ prepareRoutes(providers, adapter, owned) {
1620
+ const unique = /* @__PURE__ */ new Set();
1621
+ const registrations = [];
1622
+ for (const provider of providers) {
1623
+ if (provider.length === 0) throw new LlmError("adapter provider names must be non-empty", "INVALID_ADAPTER");
1624
+ if (unique.has(provider) || this.adapters.has(provider) && !owned.has(provider)) throw new LlmError(`an adapter for provider "${provider}" is already registered`, "DUPLICATE_ADAPTER");
1625
+ const info = adapter.providerInfo(provider);
1626
+ 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");
1627
+ unique.add(provider);
1628
+ const retryPolicy = adapter.providerRetryPolicy(provider) ?? resolveRetryPolicy(void 0, `llm: provider "${provider}" retryPolicy`);
1629
+ registrations.push({
1630
+ adapter,
1631
+ provider: {
1632
+ id: info.id,
1633
+ name: info.name
1634
+ },
1635
+ retryPolicy
1636
+ });
1637
+ }
1638
+ return registrations;
1639
+ }
1640
+ /**
1641
+ * Swap this registration's routes for the prepared ones in one synchronous
1642
+ * section, so no observer can see the registry between the release and the
1643
+ * re-registration. The route set's one mutation point is also where
1644
+ * `llm/adapters-updated` is published, so a `replace` announces itself
1645
+ * exactly like a first registration.
1646
+ */
1647
+ commitRoutes(owned, registrations) {
1648
+ for (const provider of owned) this.adapters.delete(provider);
1649
+ owned.clear();
1650
+ for (const registration of registrations) {
1651
+ this.adapters.set(registration.provider.id, registration);
1652
+ owned.add(registration.provider.id);
1653
+ }
1654
+ this.emitAdaptersUpdated();
1655
+ }
1656
+ /**
1657
+ * Describe provider routes with a registered adapter.
1658
+ * @returns detached provider metadata in registration order.
1659
+ */
1660
+ listProviders() {
1661
+ return [...this.adapters.values()].map(({ provider }) => ({ ...provider }));
1662
+ }
1663
+ /**
1664
+ * Declare provider routes an adapter plugin can activate through
1665
+ * configuration. Registration is all-or-nothing: an empty list, invalid
1666
+ * entry, or a provider already declared by any registration throws
1667
+ * `LlmError` without registering the rest. Disposed with the fiber.
1668
+ * @param entries - every configurable provider this plugin owns.
1669
+ * @returns a handle that withdraws all of them, and can atomically replace them.
1670
+ */
1671
+ registerConfigurableProviders(entries) {
1672
+ let held = [];
1673
+ let disposed = false;
1674
+ /**
1675
+ * Validate a candidate set in full against everything this registration
1676
+ * does not already hold, then publish it. Nothing is written until the
1677
+ * whole set passes, so a refused candidate leaves the current entries in
1678
+ * place — the property that makes `replace` a swap rather than a
1679
+ * delete-then-add that can strand the directory empty.
1680
+ */
1681
+ const commit = (candidates) => {
1682
+ const detached = [];
1683
+ const own = new Set(held.map((entry) => entry.provider));
1684
+ for (const entry of candidates) {
1685
+ 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");
1686
+ if (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider "${entry.provider}" has an empty settingsPath segment`, "INVALID_DIRECTORY");
1687
+ 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");
1688
+ detached.push({
1689
+ ...entry,
1690
+ settingsPath: [...entry.settingsPath]
1691
+ });
1692
+ }
1693
+ for (const entry of held) this.directory.delete(entry.provider);
1694
+ for (const entry of detached) this.directory.set(entry.provider, entry);
1695
+ held = detached;
1696
+ this.emitAdaptersUpdated();
1697
+ };
1698
+ const dispose = this.ctx.effect(function* () {
1699
+ if (entries.length === 0) throw new LlmError("a configurable-provider registration must declare at least one provider", "INVALID_DIRECTORY");
1700
+ commit(entries);
1701
+ yield () => {
1702
+ disposed = true;
1703
+ for (const entry of held) this.directory.delete(entry.provider);
1704
+ held = [];
1705
+ this.emitAdaptersUpdated();
1706
+ };
1707
+ }.bind(this), "llm.registerConfigurableProviders()");
1708
+ const handle = (() => void dispose());
1709
+ handle.replace = (next) => {
1710
+ if (disposed) throw new LlmError("this configurable-provider registration was disposed", "REGISTRATION_DISPOSED");
1711
+ commit(next);
1712
+ };
1713
+ return handle;
1714
+ }
1715
+ /**
1716
+ * List every declared configurable provider, registered or dormant.
1717
+ * @returns detached directory entries in declaration order.
1718
+ */
1719
+ listConfigurableProviders() {
1720
+ return [...this.directory.values()].map((entry) => ({
1721
+ ...entry,
1722
+ settingsPath: [...entry.settingsPath]
1723
+ }));
1724
+ }
1725
+ /**
1726
+ * Offer to interrogate provider endpoints on behalf of the settings
1727
+ * namespace this plugin owns. The namespace is the key because that is what
1728
+ * a configuration surface already holds from the configurable-provider
1729
+ * directory, and because a provider being *added* has no route to name yet.
1730
+ * Disposed with the fiber.
1731
+ * @param settingsNs - the namespace whose profiles this discovery serves.
1732
+ * @param discover - interrogates one endpoint and must honor the supplied signal.
1733
+ * @returns the disposer that withdraws the offer.
1734
+ */
1735
+ registerModelDiscovery(settingsNs, discover) {
1736
+ const dispose = this.ctx.effect(function* () {
1737
+ if (settingsNs.length === 0) throw new LlmError("model discovery needs a non-empty settings namespace", "INVALID_DISCOVERY");
1738
+ if (this.discoveries.has(settingsNs)) throw new LlmError(`model discovery for "${settingsNs}" is already registered`, "DUPLICATE_DISCOVERY");
1739
+ this.discoveries.set(settingsNs, discover);
1740
+ yield () => {
1741
+ this.discoveries.delete(settingsNs);
1742
+ };
1743
+ }.bind(this), "llm.registerModelDiscovery()");
1744
+ return () => void dispose();
1745
+ }
1746
+ /**
1747
+ * Interrogate one provider endpoint for the models it advertises. The
1748
+ * request describes a draft, not a stored route, so nothing here reads or
1749
+ * writes settings or credentials — the caller owns both, and the reply is
1750
+ * candidate metadata a surface may offer for adoption.
1751
+ * @param settingsNs - namespace whose registered discovery serves this draft.
1752
+ * @param request - the endpoint, protocol, and one-shot credential to use.
1753
+ * @param signal - caller cancellation.
1754
+ * @returns the advertised models, deduplicated in endpoint order.
1755
+ */
1756
+ async discoverModels(settingsNs, request, signal) {
1757
+ const discover = this.discoveries.get(settingsNs);
1758
+ if (discover === void 0) throw new LlmError(`no model discovery is registered for "${settingsNs}"`, "NO_DISCOVERY");
1759
+ if ((request.provider ?? "").length === 0 && (request.baseURL ?? "").length === 0) throw new LlmError("model discovery needs a provider route or a baseURL", "INVALID_DISCOVERY");
1760
+ const discovered = signal === void 0 ? await discover(request) : await discover(request, signal);
1761
+ const seen = /* @__PURE__ */ new Set();
1762
+ const models = [];
1763
+ for (const model of discovered) {
1764
+ if (typeof model.id !== "string" || model.id.length === 0 || seen.has(model.id)) continue;
1765
+ seen.add(model.id);
1766
+ models.push({
1767
+ id: model.id,
1768
+ ...model.name === void 0 ? {} : { name: model.name },
1769
+ ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
1770
+ ...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens }
1771
+ });
1772
+ }
1773
+ return models;
1774
+ }
1775
+ /**
1776
+ * Remote adapter for one draft provider interrogation.
1777
+ * @param settingsNs - namespace whose registered discovery serves this draft.
1778
+ * @param request - endpoint, protocol, and one-shot credential to use.
1779
+ * @param signal - caller cancellation supplied by the Remote carrier.
1780
+ * @returns advertised models in endpoint order.
1781
+ * @throws RemoteError with `llm/model-discovery-rejected` when discovery refuses or fails.
1782
+ */
1783
+ async remoteDiscoverModels(settingsNs, request, signal) {
1784
+ try {
1785
+ return await this.discoverModels(settingsNs, request, signal);
1786
+ } catch (error) {
1787
+ throw new RemoteError("llm/model-discovery-rejected", error instanceof Error ? error.message : String(error), {
1788
+ settingsNs,
1789
+ ...request.baseURL === void 0 ? {} : { baseURL: request.baseURL }
1790
+ }, { cause: error });
1791
+ }
1792
+ }
1793
+ /**
1794
+ * Resolve the retry policy captured when one provider route was registered.
1795
+ * @param provider - registered provider route to inspect.
1796
+ * @returns the provider-owned policy, with normal defaults already resolved.
1797
+ */
1798
+ providerRetryPolicy(provider) {
1799
+ return this.registration(provider).retryPolicy;
1800
+ }
1801
+ /**
1802
+ * Resolve provider-side request-image pricing for one exact route, or
1803
+ * `undefined` when the provider is unregistered or declares none. Unknown
1804
+ * providers degrade to `undefined` rather than throwing because callers
1805
+ * price durable history whose route may no longer be mounted.
1806
+ * @param provider - provider route named by a request header.
1807
+ * @param model - exact model id named by the same header.
1808
+ * @returns the owning adapter's image pricing for the route, when declared.
1809
+ */
1810
+ imageRequestPricing(provider, model) {
1811
+ return this.adapters.get(provider)?.adapter.imageRequestPricing(provider, model);
1812
+ }
1813
+ /**
1814
+ * Resolve the exact text one durable file occurrence contributes to every
1815
+ * provider request in the current execution environment.
1816
+ * @param ref - durable verbatim file reference from model history.
1817
+ * @returns the same deterministic handle text used at adapter dispatch.
1818
+ */
1819
+ fileRequestText(ref) {
1820
+ return fileHandleText(ref, this.fileReadPath(ref));
1821
+ }
1822
+ /** Detach typed adapter-owned modality metadata. */
1823
+ detachedModalities(modalities) {
1824
+ return modalities === void 0 ? void 0 : [...modalities];
1825
+ }
1826
+ /**
1827
+ * Discover models advertised by one registered provider. Catalog membership
1828
+ * is advisory and never changes routing or request validation.
1829
+ * @param provider - registered provider route to inspect.
1830
+ * @returns detached model metadata in adapter-preferred order.
1831
+ */
1832
+ async listModels(provider) {
1833
+ const models = await this.registration(provider).adapter.listModels(provider);
1834
+ const seen = /* @__PURE__ */ new Set();
1835
+ return models.map((model) => {
1836
+ 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");
1837
+ seen.add(model.id);
1838
+ const inputModalities = this.detachedModalities(model.inputModalities);
1839
+ return {
1840
+ provider: model.provider,
1841
+ id: model.id,
1842
+ name: model.name,
1843
+ ...model.description === void 0 ? {} : { description: model.description },
1844
+ ...inputModalities === void 0 ? {} : { inputModalities }
1845
+ };
1846
+ });
1847
+ }
1848
+ /**
1849
+ * Resolve and validate all metadata from the adapter that owns one exact
1850
+ * route. The result is detached from adapter-owned objects; catalog
1851
+ * membership remains advisory and does not control request routing.
1852
+ * @param provider - registered provider route to inspect.
1853
+ * @param model - exact model id passed to the adapter.
1854
+ * @param signal - optional cancellation for adapter-owned asynchronous lookup.
1855
+ * @returns exact model identity plus available context and reasoning metadata.
1856
+ */
1857
+ async resolveModelInfo(provider, model, signal) {
1858
+ return this.resolveModelInfoFor(this.registration(provider), model, signal);
1859
+ }
1860
+ async resolveModelInfoFor(registration, model, signal) {
1861
+ const resolved = await registration.adapter.resolveModel(registration.provider.id, model, signal);
1862
+ return this.normalizeModelInfo(registration, model, resolved);
1863
+ }
1864
+ /** Validate and detach one adapter-returned exact model result. */
1865
+ normalizeModelInfo(registration, model, resolved) {
1866
+ const provider = registration.provider.id;
1867
+ 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");
1868
+ const context = resolved.context;
1869
+ 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");
1870
+ const inputModalities = this.detachedModalities(resolved.inputModalities);
1871
+ const systemPromptUpdate = resolved.systemPromptUpdate;
1872
+ if (systemPromptUpdate !== void 0 && systemPromptUpdate !== "in-history") throw new LlmError(`adapter returned invalid system prompt update mode for provider "${provider}" model "${model}"`, "INVALID_MODEL_INFO");
1873
+ const defaultMaxTokens = resolved.defaultMaxTokens;
1874
+ 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");
1875
+ const info = {
1876
+ provider,
1877
+ id: model,
1878
+ name: resolved.name,
1879
+ ...resolved.description === void 0 ? {} : { description: resolved.description },
1880
+ ...inputModalities === void 0 ? {} : { inputModalities },
1881
+ ...context === void 0 ? {} : { context: { contextWindow: context.contextWindow } },
1882
+ ...defaultMaxTokens === void 0 ? {} : { defaultMaxTokens },
1883
+ ...resolved.systemPromptUpdate === void 0 ? {} : { systemPromptUpdate: resolved.systemPromptUpdate }
1884
+ };
1885
+ const reasoning = resolved.reasoning;
1886
+ if (reasoning === void 0) return info;
1887
+ if (reasoning.efforts.length === 0) throw new LlmError(`adapter returned invalid reasoning metadata for provider "${provider}" model "${model}"`, "INVALID_MODEL_REASONING");
1888
+ const seen = /* @__PURE__ */ new Set();
1889
+ const efforts = reasoning.efforts.map((effort) => {
1890
+ 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");
1891
+ seen.add(effort.id);
1892
+ return {
1893
+ id: effort.id,
1894
+ name: effort.name,
1895
+ ...effort.description === void 0 ? {} : { description: effort.description }
1896
+ };
1897
+ });
1898
+ 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");
1899
+ return {
1900
+ ...info,
1901
+ reasoning: {
1902
+ efforts,
1903
+ ...reasoning.defaultEffort === void 0 ? {} : { defaultEffort: reasoning.defaultEffort }
1904
+ }
1905
+ };
1906
+ }
1907
+ /**
1908
+ * Validate a conversation call config against its exact model capability and
1909
+ * materialize adapter-configured defaults. Unsupported explicit efforts
1910
+ * reject before provider I/O; no clamping or aliasing is performed. This
1911
+ * standalone query does not bind a later dispatch; use {@link prepareCall}
1912
+ * when logging and streaming must share one adapter registration.
1913
+ * @param config - provider/model route and optional request controls.
1914
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1915
+ * @returns a detached config only when a default must be materialized.
1916
+ */
1917
+ async resolveCallConfig(config, signal) {
1918
+ return (await this.resolveCallFor(this.registration(config.provider), config, signal)).config;
1919
+ }
1920
+ async resolveCallFor(registration, config, signal) {
1921
+ const info = await this.resolveModelInfoFor(registration, config.model, signal);
1922
+ return this.resolveCallWithInfo(config, info);
1923
+ }
1924
+ /** Validate request controls against one already-bound exact model result. */
1925
+ resolveCallWithInfo(config, info) {
1926
+ const defaulted = config.maxTokens === void 0 && info.defaultMaxTokens !== void 0 ? {
1927
+ ...config,
1928
+ maxTokens: info.defaultMaxTokens
1929
+ } : config;
1930
+ const reasoning = info.reasoning;
1931
+ const requested = defaulted.reasoningEffort;
1932
+ let resolvedConfig = defaulted;
1933
+ if (reasoning === void 0) {
1934
+ if (requested !== void 0) throw new LlmError(`provider "${config.provider}" model "${config.model}" does not support reasoning effort "${requested}"`, "UNSUPPORTED_REASONING_EFFORT");
1935
+ } else {
1936
+ const effective = requested ?? reasoning.defaultEffort;
1937
+ if (effective !== void 0) {
1938
+ 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");
1939
+ if (requested !== effective) resolvedConfig = {
1940
+ ...defaulted,
1941
+ reasoningEffort: effective
1942
+ };
1943
+ }
1944
+ }
1945
+ return {
1946
+ config: resolvedConfig,
1947
+ ...info.context === void 0 ? {} : { context: info.context },
1948
+ modelInfo: info
1949
+ };
1950
+ }
1951
+ /**
1952
+ * Resolve one call under its current adapter registration. The returned
1953
+ * one-shot handle keeps that registration across header logging and dispatch,
1954
+ * so HMR cannot combine one adapter's capability result with another adapter.
1955
+ * @param config - provider/model route and optional request controls.
1956
+ * @param signal - optional cancellation for adapter-owned capability lookup.
1957
+ * @returns a prepared config and its registration-bound stream entry point.
1958
+ */
1959
+ async prepareCall(config, signal) {
1960
+ const registration = this.registration(config.provider);
1961
+ const adapterCall = await registration.adapter.prepareCall(config.provider, config.model, signal);
1962
+ const modelInfo = this.normalizeModelInfo(registration, config.model, adapterCall.model);
1963
+ const resolved = this.resolveCallWithInfo(config, modelInfo);
1964
+ const resolvedConfig = deepFreeze(structuredClone(resolved.config));
1965
+ const context = resolved.context === void 0 ? void 0 : deepFreeze(structuredClone(resolved.context));
1966
+ const adapterDefaults = deepFreeze({
1967
+ ...config.reasoningEffort === void 0 && resolvedConfig.reasoningEffort !== void 0 ? { reasoningEffort: true } : {},
1968
+ ...config.maxTokens === void 0 && resolvedConfig.maxTokens !== void 0 ? { maxTokens: true } : {}
1969
+ });
1970
+ let dispatched = false;
1971
+ return Object.freeze({
1972
+ config: resolvedConfig,
1973
+ retryPolicy: registration.retryPolicy,
1974
+ adapterDefaults,
1975
+ ...context === void 0 ? {} : { context },
1976
+ ...modelInfo.inputModalities === void 0 ? {} : { inputModalities: Object.freeze([...modelInfo.inputModalities]) },
1977
+ ...modelInfo.systemPromptUpdate === void 0 ? {} : { systemPromptUpdate: modelInfo.systemPromptUpdate },
1978
+ stream: (options) => {
1979
+ if (dispatched) throw new LlmError("a prepared LLM call can only be dispatched once", "INVALID_PREPARED_CALL");
1980
+ if (!callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
1981
+ dispatched = true;
1982
+ return this.streamWithRegistration(options, {
1983
+ registration,
1984
+ config: resolvedConfig,
1985
+ modelInfo,
1986
+ dispatch: (options) => adapterCall.stream(options)
1987
+ });
1988
+ }
1989
+ });
1990
+ }
1991
+ registration(provider) {
1992
+ const registration = this.adapters.get(provider);
1993
+ if (!registration) throw new LlmError(`no adapter registered for provider "${provider}"`, "NO_ADAPTER");
1994
+ return registration;
1995
+ }
1996
+ /** Remove replay state whose historical route is owned by another adapter. */
1997
+ forAdapter(options, adapter) {
1998
+ const messages = options.messages.map((message) => {
1999
+ const source = message.source;
2000
+ if (message.role !== "assistant" || source.kind !== "model" || source.replayState === void 0) return message;
2001
+ if (this.adapters.get(source.provider)?.adapter === adapter) return message;
2002
+ return freezeMessage({
2003
+ ...message,
2004
+ source: {
2005
+ kind: "model",
2006
+ provider: source.provider,
2007
+ model: source.model
2008
+ }
2009
+ });
2010
+ });
2011
+ if (messages.every((message, index) => message === options.messages[index])) return options;
2012
+ const filtered = {
2013
+ ...options,
2014
+ messages
2015
+ };
2016
+ return Object.isFrozen(options) ? deepFreeze(filtered) : filtered;
2017
+ }
2018
+ /**
2019
+ * Resolve the current execution-world read path of one durable file
2020
+ * reference through the mounted attachment and filesystem providers.
2021
+ */
2022
+ fileReadPath(ref) {
2023
+ let hostPath;
2024
+ try {
2025
+ hostPath = this.ctx.get("attachments")?.fileHostPath(ref);
2026
+ } catch {
2027
+ return;
2028
+ }
2029
+ if (hostPath === void 0) return void 0;
2030
+ return this.ctx.get("fs")?.processPathFromHostPath(hostPath);
2031
+ }
2032
+ /**
2033
+ * Final adapter boundary. Adapter selection, dispatch, iterator construction,
2034
+ * and iteration failures become one terminal failure chunk. Middleware and
2035
+ * downstream consumer failures remain thrown plugin or consumer errors.
2036
+ */
2037
+ async *adapterStream(options, prepared) {
2038
+ let iterator;
2039
+ try {
2040
+ const registration = prepared?.registration ?? this.registration(options.provider);
2041
+ const adapter = registration.adapter;
2042
+ let modelInfo;
2043
+ let resolvedConfig;
2044
+ let dispatch;
2045
+ if (prepared === void 0) {
2046
+ const adapterCall = await adapter.prepareCall(options.provider, options.model, options.signal);
2047
+ modelInfo = this.normalizeModelInfo(registration, options.model, adapterCall.model);
2048
+ resolvedConfig = this.resolveCallWithInfo(options, modelInfo).config;
2049
+ dispatch = (options) => adapterCall.stream(options);
2050
+ } else {
2051
+ modelInfo = prepared.modelInfo;
2052
+ resolvedConfig = prepared.config;
2053
+ dispatch = prepared.dispatch;
2054
+ }
2055
+ if (prepared !== void 0 && !callConfigEquals(options, resolvedConfig)) throw new LlmError("prepared LLM call config changed before adapter dispatch", "INVALID_PREPARED_CALL");
2056
+ const resolvedOptions = callConfigEquals(options, resolvedConfig) ? options : Object.isFrozen(options) ? deepFreeze({
2057
+ ...options,
2058
+ ...resolvedConfig
2059
+ }) : {
2060
+ ...options,
2061
+ ...resolvedConfig
2062
+ };
2063
+ let projectedMessages = resolvedOptions.messages;
2064
+ if (projectedMessages.some((message) => contentHasFile(message.content))) projectedMessages = projectFilesToText(projectedMessages, (ref) => this.fileReadPath(ref));
2065
+ if (modelInfo.inputModalities !== void 0 && !modelInfo.inputModalities.includes("image") && projectedMessages.some((message) => contentHasImage(message.content))) projectedMessages = projectImagesForTextModel(projectedMessages);
2066
+ const projectedOptions = projectedMessages === resolvedOptions.messages ? resolvedOptions : Object.isFrozen(resolvedOptions) ? deepFreeze({
2067
+ ...resolvedOptions,
2068
+ messages: projectedMessages
2069
+ }) : {
2070
+ ...resolvedOptions,
2071
+ messages: projectedMessages
2072
+ };
2073
+ iterator = dispatch(this.forAdapter(projectedOptions, adapter))[Symbol.asyncIterator]();
2074
+ } catch (error) {
2075
+ yield adapterFailureChunk(error, options.signal);
2076
+ return;
2077
+ }
2078
+ let completed = false;
2079
+ try {
2080
+ while (true) {
2081
+ let item;
2082
+ try {
2083
+ const next = await iterator.next();
2084
+ item = next.done ? { done: true } : {
2085
+ done: false,
2086
+ value: next.value
2087
+ };
2088
+ } catch (error) {
2089
+ completed = true;
2090
+ yield adapterFailureChunk(error, options.signal);
2091
+ return;
2092
+ }
2093
+ if (item.done) {
2094
+ completed = true;
2095
+ return;
2096
+ }
2097
+ yield item.value;
2098
+ }
2099
+ } finally {
2100
+ if (!completed) {
2101
+ const close = iterator.return?.bind(iterator);
2102
+ if (close) await close();
2103
+ }
2104
+ }
2105
+ }
2106
+ /**
2107
+ * Stream one model call as raw chunks (token-level deltas). Replay state is
2108
+ * retained only when the same adapter instance owns its historical provider
2109
+ * and the target provider. Final adapter selection remains fixed through
2110
+ * asynchronous exact-model resolution and dispatch. Adapter selection,
2111
+ * dispatch, and iteration failures become terminal `error` or `aborted`
2112
+ * finish chunks; middleware, nested-call, cleanup, and consumer failures
2113
+ * remain thrown.
2114
+ * @param options - the full request; `options.provider` selects the adapter.
2115
+ * @returns the chunk stream, possibly wrapped by `llm/stream` listeners.
2116
+ */
2117
+ stream(options) {
2118
+ return this.streamWithRegistration(options);
2119
+ }
2120
+ streamWithRegistration(options, prepared) {
2121
+ return this.ctx.waterfall(this, "llm/stream", options, () => this.adapterStream(options, prepared));
2122
+ }
2123
+ };
2124
+ })();
2125
+ /** Convert one adapter throw into the stream protocol's terminal outcome. */
2126
+ function adapterFailureChunk(error, signal) {
2127
+ const failure = normalizeLlmFailure(error);
2128
+ return {
2129
+ type: "finish",
2130
+ reason: signal?.aborted || failure.code === "ABORTED" ? {
2131
+ kind: "aborted",
2132
+ failure
2133
+ } : {
2134
+ kind: "error",
2135
+ failure
2136
+ }
2137
+ };
2138
+ }
2139
+ //#endregion
2140
+ //#region src/core/workspace-instruction-context.ts
2141
+ const SYSTEM_REMINDER_OPEN = "<system-reminder>";
2142
+ const SYSTEM_REMINDER_CLOSE = "</system-reminder>";
2143
+ const INSTRUCTION_INTRO = "The following project instructions are managed by the user for this DSH workspace. Follow them as persistent workspace guidance. They take precedence over repository-provided workspace guidance. System, developer, and direct user instructions take precedence over these project instructions.";
2144
+ function escapeInstructionFrameBody(body) {
2145
+ return body.replaceAll(SYSTEM_REMINDER_CLOSE, "<\\/system-reminder>");
2146
+ }
2147
+ function renderInstructionMessageText(workspaceTitle, text) {
2148
+ const escaped = escapeInstructionFrameBody(text);
2149
+ return `${SYSTEM_REMINDER_OPEN}\n${INSTRUCTION_INTRO}\n\nInstructions for workspace: ${workspaceTitle}\n\n${escaped}\n${SYSTEM_REMINDER_CLOSE}`;
2150
+ }
2151
+ function createInstructionMessage(workspaceId, workspaceTitle, snapshot) {
2152
+ return createUserMessage({
2153
+ content: [{
2154
+ type: "text",
2155
+ text: renderInstructionMessageText(workspaceTitle, snapshot.text)
2156
+ }],
2157
+ source: {
2158
+ kind: "dshb-workspace-instructions",
2159
+ form: "instructions",
2160
+ workspaceId,
2161
+ revision: snapshot.workspaceRevision,
2162
+ digest: snapshot.digest,
2163
+ snapshot: true
2164
+ }
2165
+ });
2166
+ }
2167
+ function hasDirectUserMessage(messages) {
2168
+ return messages.some((m) => m.role === "user" && m.source.kind === "user");
2169
+ }
2170
+ function hasOwnInstructionMessage(agent) {
2171
+ const nodes = agent.session.surface?.nodes;
2172
+ if (!nodes) return false;
2173
+ for (const seq of nodes) {
2174
+ const event = agent.session.eventAt?.(seq);
2175
+ if (event?.type === "user/message" && event.data.source.kind === "dshb-workspace-instructions") return true;
2176
+ }
2177
+ return false;
2178
+ }
2179
+ async function resolveSnapshotForSession(agent, messages, workspaceStore = sharedWorkspaceInstructionStore(), snapshotStore = sharedSessionInstructionSnapshotStore(), registry) {
2180
+ const sessionId = agent.session.id;
2181
+ const existing = snapshotStore.get(sessionId);
2182
+ if (existing) return existing;
2183
+ if (!(hasDirectUserMessage(messages) && !hasOwnInstructionMessage(agent))) return void 0;
2184
+ let workspaceId;
2185
+ const cwd = agent.session.header.cwd;
2186
+ if (registry && cwd) try {
2187
+ const ws = await registry.resolveByPath(cwd);
2188
+ if (ws) {
2189
+ workspaceId = ws.id;
2190
+ ws.title;
2191
+ }
2192
+ } catch {}
2193
+ const record = workspaceId ? workspaceStore.get(workspaceId) : void 0;
2194
+ if (!record || record.text.length === 0) return snapshotStore.createIfAbsent(sessionId, {
2195
+ kind: "empty",
2196
+ workspaceId
2197
+ });
2198
+ return snapshotStore.createIfAbsent(sessionId, {
2199
+ kind: "workspace",
2200
+ record,
2201
+ workspaceId
2202
+ });
2203
+ }
2204
+ function registerWorkspaceInstructionInjector(ctx) {
2205
+ if (typeof ctx.on !== "function") return;
2206
+ const workspaceStore = sharedWorkspaceInstructionStore();
2207
+ const snapshotStore = sharedSessionInstructionSnapshotStore();
2208
+ ctx.on("agent/pre-step", async ({ agent, messages, signal }, next) => {
2209
+ const decision = await next();
2210
+ if (decision.kind === "reject") return decision;
2211
+ signal.throwIfAborted();
2212
+ const agentLike = agent;
2213
+ const messagesLike = messages;
2214
+ const registry = ctx.get("workspaceRegistry");
2215
+ let snapshot = snapshotStore.get(agentLike.session.id);
2216
+ if (!snapshot) snapshot = await resolveSnapshotForSession(agentLike, messagesLike, workspaceStore, snapshotStore, registry);
2217
+ signal.throwIfAborted();
2218
+ if (!snapshot || snapshot.text.length === 0) return decision;
2219
+ if (hasOwnInstructionMessage(agentLike)) return decision;
2220
+ const workspaceId = snapshot.workspaceId;
2221
+ if (!workspaceId) return decision;
2222
+ const message = createInstructionMessage(workspaceId, (registry?.get(workspaceId))?.title ?? "Unknown", snapshot);
2223
+ const lastClaimedIndex = decision.messages.findLastIndex((m) => messages.includes(m));
2224
+ const entered = decision.messages.toSpliced(lastClaimedIndex + 1, 0, message);
2225
+ return {
2226
+ ...decision,
2227
+ messages: entered
2228
+ };
2229
+ });
2230
+ try {
2231
+ ctx.on?.("session/deleted", (sessionId) => {
2232
+ snapshotStore.remove(sessionId);
2233
+ });
2234
+ } catch {}
2235
+ }
2236
+ const name = "dshb-workspace-instruction-injector";
2237
+ const inject = ["workspaceRegistry"];
2238
+ //#endregion
2239
+ export { registerWorkspaceInstructionInjector as a, name as i, escapeInstructionFrameBody as n, renderInstructionMessageText as o, inject as r, resolveSnapshotForSession as s, createInstructionMessage as t };
2240
+
2241
+ //# sourceMappingURL=workspace-instruction-context-CxUldQkP.js.map