dsh-llm-fallbacks 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1853 @@
1
+ import { installSettingsSection, settingsNamespace } from "@deepseek-ai/dsh-settings";
2
+ import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
3
+ //#region \0rolldown/runtime.js
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
13
+ key = keys[i];
14
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
22
+ value: mod,
23
+ enumerable: true
24
+ }) : target, mod));
25
+ //#endregion
26
+ //#region node_modules/cosmokit/lib/index.cjs
27
+ var require_lib$1 = __commonJSMin(((exports, module) => {
28
+ var __defProp = Object.defineProperty;
29
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
30
+ var __getOwnPropNames = Object.getOwnPropertyNames;
31
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
32
+ var __export = (target, all) => {
33
+ for (var name in all) __defProp(target, name, {
34
+ get: all[name],
35
+ enumerable: true
36
+ });
37
+ };
38
+ var __copyProps = (to, from, except, desc) => {
39
+ if (from && typeof from === "object" || typeof from === "function") {
40
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
41
+ get: () => from[key],
42
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
43
+ });
44
+ }
45
+ return to;
46
+ };
47
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
48
+ var index_exports = {};
49
+ __export(index_exports, {
50
+ Binary: () => Binary,
51
+ Time: () => Time,
52
+ arrayBufferToBase64: () => arrayBufferToBase64,
53
+ arrayBufferToHex: () => arrayBufferToHex,
54
+ base64ToArrayBuffer: () => base64ToArrayBuffer,
55
+ camelCase: () => camelCase,
56
+ camelize: () => camelize,
57
+ capitalize: () => capitalize,
58
+ clone: () => clone,
59
+ contain: () => contain,
60
+ deduplicate: () => deduplicate,
61
+ deepEqual: () => deepEqual,
62
+ defineProperty: () => defineProperty,
63
+ difference: () => difference,
64
+ filterKeys: () => filterKeys,
65
+ formatProperty: () => formatProperty,
66
+ hexToArrayBuffer: () => hexToArrayBuffer,
67
+ hyphenate: () => hyphenate,
68
+ intersection: () => intersection,
69
+ is: () => is,
70
+ isNonNullable: () => isNonNullable,
71
+ isNullable: () => isNullable,
72
+ isPlainObject: () => isPlainObject,
73
+ makeArray: () => makeArray,
74
+ mapValues: () => mapValues,
75
+ noop: () => noop,
76
+ omit: () => omit,
77
+ paramCase: () => paramCase,
78
+ pick: () => pick,
79
+ remove: () => remove,
80
+ sanitize: () => sanitize,
81
+ snakeCase: () => snakeCase,
82
+ trimSlash: () => trimSlash,
83
+ uncapitalize: () => uncapitalize,
84
+ union: () => union,
85
+ valueMap: () => mapValues
86
+ });
87
+ module.exports = __toCommonJS(index_exports);
88
+ function noop() {}
89
+ function isNullable(value) {
90
+ return value === null || value === void 0;
91
+ }
92
+ function isNonNullable(value) {
93
+ return !isNullable(value);
94
+ }
95
+ function isPlainObject(data) {
96
+ return data && typeof data === "object" && !Array.isArray(data);
97
+ }
98
+ function filterKeys(object, filter) {
99
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
100
+ }
101
+ function mapValues(object, transform) {
102
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
103
+ }
104
+ function pick(source, keys, forced) {
105
+ if (!keys) return { ...source };
106
+ const result = {};
107
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
108
+ return result;
109
+ }
110
+ function omit(source, keys) {
111
+ if (!keys) return { ...source };
112
+ const result = { ...source };
113
+ for (const key of keys) Reflect.deleteProperty(result, key);
114
+ return result;
115
+ }
116
+ function defineProperty(object, key, value) {
117
+ return Object.defineProperty(object, key, {
118
+ writable: true,
119
+ value,
120
+ enumerable: false
121
+ });
122
+ }
123
+ function contain(array1, array2) {
124
+ return array2.every((item) => array1.includes(item));
125
+ }
126
+ function intersection(array1, array2) {
127
+ return array1.filter((item) => array2.includes(item));
128
+ }
129
+ function difference(array1, array2) {
130
+ return array1.filter((item) => !array2.includes(item));
131
+ }
132
+ function union(array1, array2) {
133
+ return Array.from(new Set([...array1, ...array2]));
134
+ }
135
+ function deduplicate(array) {
136
+ return [...new Set(array)];
137
+ }
138
+ function remove(list, item) {
139
+ const index = list?.indexOf(item);
140
+ if (index >= 0) {
141
+ list.splice(index, 1);
142
+ return true;
143
+ } else return false;
144
+ }
145
+ function makeArray(source) {
146
+ return Array.isArray(source) ? source : isNullable(source) ? [] : [source];
147
+ }
148
+ function is(type, value) {
149
+ if (arguments.length === 1) return (value2) => is(type, value2);
150
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
151
+ }
152
+ function isArrayBufferLike(value) {
153
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
154
+ }
155
+ function isArrayBufferSource(value) {
156
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
157
+ }
158
+ var Binary;
159
+ ((Binary2) => {
160
+ Binary2.is = isArrayBufferLike;
161
+ Binary2.isSource = isArrayBufferSource;
162
+ function fromSource(source) {
163
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
164
+ else return source;
165
+ }
166
+ Binary2.fromSource = fromSource;
167
+ function toBase64(source) {
168
+ source = fromSource(source);
169
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
170
+ let binary = "";
171
+ const bytes = new Uint8Array(source);
172
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
173
+ return btoa(binary);
174
+ }
175
+ Binary2.toBase64 = toBase64;
176
+ function fromBase64(source) {
177
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
178
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
179
+ }
180
+ Binary2.fromBase64 = fromBase64;
181
+ function toHex(source) {
182
+ source = fromSource(source);
183
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
184
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
185
+ }
186
+ Binary2.toHex = toHex;
187
+ function fromHex(source) {
188
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
189
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
190
+ const buffer = [];
191
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
192
+ return Uint8Array.from(buffer).buffer;
193
+ }
194
+ Binary2.fromHex = fromHex;
195
+ })(Binary || (Binary = {}));
196
+ var base64ToArrayBuffer = Binary.fromBase64;
197
+ var arrayBufferToBase64 = Binary.toBase64;
198
+ var hexToArrayBuffer = Binary.fromHex;
199
+ var arrayBufferToHex = Binary.toHex;
200
+ function clone(source, refs = new Map()) {
201
+ if (!source || typeof source !== "object") return source;
202
+ if (is("Date", source)) return new Date(source.valueOf());
203
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
204
+ if (isArrayBufferLike(source)) return source.slice(0);
205
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
206
+ const cached = refs.get(source);
207
+ if (cached) return cached;
208
+ if (Array.isArray(source)) {
209
+ const result2 = [];
210
+ refs.set(source, result2);
211
+ source.forEach((value, index) => {
212
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
213
+ });
214
+ return result2;
215
+ }
216
+ const result = Object.create(Object.getPrototypeOf(source));
217
+ refs.set(source, result);
218
+ for (const key of Reflect.ownKeys(source)) {
219
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
220
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
221
+ Reflect.defineProperty(result, key, descriptor);
222
+ }
223
+ return result;
224
+ }
225
+ function deepEqual(a, b, strict) {
226
+ if (a === b) return true;
227
+ if (!strict && isNullable(a) && isNullable(b)) return true;
228
+ if (typeof a !== typeof b) return false;
229
+ if (typeof a !== "object") return false;
230
+ if (!a || !b) return false;
231
+ function check(test, then) {
232
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
233
+ }
234
+ return check(Array.isArray, (a2, b2) => a2.length === b2.length && a2.every((item, index) => deepEqual(item, b2[index]))) ?? check(is("Date"), (a2, b2) => a2.valueOf() === b2.valueOf()) ?? check(is("RegExp"), (a2, b2) => a2.source === b2.source && a2.flags === b2.flags) ?? check(isArrayBufferLike, (a2, b2) => {
235
+ if (a2.byteLength !== b2.byteLength) return false;
236
+ const viewA = new Uint8Array(a2);
237
+ const viewB = new Uint8Array(b2);
238
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
239
+ return true;
240
+ }) ?? Object.keys({
241
+ ...a,
242
+ ...b
243
+ }).every((key) => deepEqual(a[key], b[key], strict));
244
+ }
245
+ function capitalize(source) {
246
+ return source.charAt(0).toUpperCase() + source.slice(1);
247
+ }
248
+ function uncapitalize(source) {
249
+ return source.charAt(0).toLowerCase() + source.slice(1);
250
+ }
251
+ function camelCase(source) {
252
+ return source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());
253
+ }
254
+ function tokenize(source, delimiters, delimiter) {
255
+ const output = [];
256
+ let state = 0;
257
+ for (let i = 0; i < source.length; i++) {
258
+ const code = source.charCodeAt(i);
259
+ if (code >= 65 && code <= 90) {
260
+ if (state === 1) {
261
+ const next = source.charCodeAt(i + 1);
262
+ if (next >= 97 && next <= 122) output.push(delimiter);
263
+ output.push(code + 32);
264
+ } else {
265
+ if (state !== 0) output.push(delimiter);
266
+ output.push(code + 32);
267
+ }
268
+ state = 1;
269
+ } else if (code >= 97 && code <= 122) {
270
+ output.push(code);
271
+ state = 2;
272
+ } else if (delimiters.includes(code)) {
273
+ if (state !== 0) output.push(delimiter);
274
+ state = 0;
275
+ } else output.push(code);
276
+ }
277
+ return String.fromCharCode(...output);
278
+ }
279
+ function paramCase(source) {
280
+ return tokenize(source, [45, 95], 45);
281
+ }
282
+ function snakeCase(source) {
283
+ return tokenize(source, [45, 95], 95);
284
+ }
285
+ var camelize = camelCase;
286
+ var hyphenate = paramCase;
287
+ function formatProperty(key) {
288
+ if (typeof key !== "string") return `[${key.toString()}]`;
289
+ return /^[a-z_$][\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
290
+ }
291
+ function trimSlash(source) {
292
+ return source.replace(/\/$/, "");
293
+ }
294
+ function sanitize(source) {
295
+ if (!source.startsWith("/")) source = "/" + source;
296
+ return trimSlash(source);
297
+ }
298
+ var Time;
299
+ ((Time2) => {
300
+ Time2.millisecond = 1;
301
+ Time2.second = 1e3;
302
+ Time2.minute = Time2.second * 60;
303
+ Time2.hour = Time2.minute * 60;
304
+ Time2.day = Time2.hour * 24;
305
+ Time2.week = Time2.day * 7;
306
+ let timezoneOffset = new Date().getTimezoneOffset();
307
+ function setTimezoneOffset(offset) {
308
+ timezoneOffset = offset;
309
+ }
310
+ Time2.setTimezoneOffset = setTimezoneOffset;
311
+ function getTimezoneOffset() {
312
+ return timezoneOffset;
313
+ }
314
+ Time2.getTimezoneOffset = getTimezoneOffset;
315
+ function getDateNumber(date = new Date(), offset) {
316
+ if (typeof date === "number") date = new Date(date);
317
+ if (offset === void 0) offset = timezoneOffset;
318
+ return Math.floor((date.valueOf() / Time2.minute - offset) / 1440);
319
+ }
320
+ Time2.getDateNumber = getDateNumber;
321
+ function fromDateNumber(value, offset) {
322
+ const date = new Date(value * Time2.day);
323
+ if (offset === void 0) offset = timezoneOffset;
324
+ return new Date(+date + offset * Time2.minute);
325
+ }
326
+ Time2.fromDateNumber = fromDateNumber;
327
+ const numeric = /\d+(?:\.\d+)?/.source;
328
+ const timeRegExp = new RegExp(`^${[
329
+ "w(?:eek(?:s)?)?",
330
+ "d(?:ay(?:s)?)?",
331
+ "h(?:our(?:s)?)?",
332
+ "m(?:in(?:ute)?(?:s)?)?",
333
+ "s(?:ec(?:ond)?(?:s)?)?"
334
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
335
+ function parseTime(source) {
336
+ const capture = timeRegExp.exec(source);
337
+ if (!capture) return 0;
338
+ return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0);
339
+ }
340
+ Time2.parseTime = parseTime;
341
+ function parseDate(date) {
342
+ const parsed = parseTime(date);
343
+ if (parsed) date = Date.now() + parsed;
344
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${new Date().toLocaleDateString()}-${date}`;
345
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${new Date().getFullYear()}-${date}`;
346
+ return date ? new Date(date) : new Date();
347
+ }
348
+ Time2.parseDate = parseDate;
349
+ function format(ms) {
350
+ const abs = Math.abs(ms);
351
+ if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
352
+ else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
353
+ else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
354
+ else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
355
+ return ms + "ms";
356
+ }
357
+ Time2.format = format;
358
+ function toDigits(source, length = 2) {
359
+ return source.toString().padStart(length, "0");
360
+ }
361
+ Time2.toDigits = toDigits;
362
+ function template(template2, time = new Date()) {
363
+ return template2.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));
364
+ }
365
+ Time2.template = template;
366
+ })(Time || (Time = {}));
367
+ 0 && (module.exports = {
368
+ Binary,
369
+ Time,
370
+ arrayBufferToBase64,
371
+ arrayBufferToHex,
372
+ base64ToArrayBuffer,
373
+ camelCase,
374
+ camelize,
375
+ capitalize,
376
+ clone,
377
+ contain,
378
+ deduplicate,
379
+ deepEqual,
380
+ defineProperty,
381
+ difference,
382
+ filterKeys,
383
+ formatProperty,
384
+ hexToArrayBuffer,
385
+ hyphenate,
386
+ intersection,
387
+ is,
388
+ isNonNullable,
389
+ isNullable,
390
+ isPlainObject,
391
+ makeArray,
392
+ mapValues,
393
+ noop,
394
+ omit,
395
+ paramCase,
396
+ pick,
397
+ remove,
398
+ sanitize,
399
+ snakeCase,
400
+ trimSlash,
401
+ uncapitalize,
402
+ union,
403
+ valueMap
404
+ });
405
+ }));
406
+ //#endregion
407
+ //#region .build/host/selectors.js
408
+ var import_lib = __toESM(__commonJSMin(((exports, module) => {
409
+ var __defProp = Object.defineProperty;
410
+ var __name = (target, value) => __defProp(target, "name", {
411
+ value,
412
+ configurable: true
413
+ });
414
+ var import_cosmokit = require_lib$1();
415
+ var kSchema = Symbol.for("schemastery");
416
+ var kValidationError = Symbol.for("ValidationError");
417
+ globalThis.__schemastery_index__ ??= 0;
418
+ globalThis.__schemastery_refs__ = void 0;
419
+ var ValidationError = class extends TypeError {
420
+ constructor(message, options) {
421
+ let prefix = "$";
422
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
423
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
424
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
425
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
426
+ super((prefix === "$" ? "" : `${prefix} `) + message);
427
+ this.options = options;
428
+ }
429
+ static {
430
+ __name(this, "ValidationError");
431
+ }
432
+ name = "ValidationError";
433
+ static is(error) {
434
+ return !!error?.[kValidationError];
435
+ }
436
+ };
437
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
438
+ var Schema = __name(function(options) {
439
+ const schema = __name(function(data, options2 = {}) {
440
+ return Schema.resolve(data, schema, options2)[0];
441
+ }, "schema");
442
+ if (options.refs) {
443
+ const refs = (0, import_cosmokit.valueMap)(options.refs, (options2) => new Schema(options2));
444
+ const getRef = __name((uid) => refs[uid], "getRef");
445
+ for (const key in refs) {
446
+ const options2 = refs[key];
447
+ options2.sKey = getRef(options2.sKey);
448
+ options2.inner = getRef(options2.inner);
449
+ options2.list = options2.list && options2.list.map(getRef);
450
+ options2.dict = options2.dict && (0, import_cosmokit.valueMap)(options2.dict, getRef);
451
+ }
452
+ return refs[options.uid];
453
+ }
454
+ Object.assign(schema, options);
455
+ if (typeof schema.callback === "string") try {
456
+ schema.callback = new Function("return " + schema.callback)();
457
+ } catch {}
458
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
459
+ Object.setPrototypeOf(schema, Schema.prototype);
460
+ schema.meta ||= {};
461
+ schema.toString = schema.toString.bind(schema);
462
+ return schema;
463
+ }, "Schema");
464
+ Schema.prototype = Object.create(Function.prototype);
465
+ Schema.prototype[kSchema] = true;
466
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
467
+ return {
468
+ version: 1,
469
+ vendor: "schemastery",
470
+ validate: __name((value) => {
471
+ try {
472
+ return { value: Schema.resolve(value, this, {})[0] };
473
+ } catch (error) {
474
+ if (ValidationError.is(error)) return { issues: [{
475
+ message: error.message,
476
+ path: error.options.path
477
+ }] };
478
+ throw error;
479
+ }
480
+ }, "validate")
481
+ };
482
+ } });
483
+ Schema.ValidationError = ValidationError;
484
+ Schema.prototype.toJSON = __name(function toJSON() {
485
+ if (globalThis.__schemastery_refs__) {
486
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
487
+ return this.uid;
488
+ }
489
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
490
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
491
+ const result = {
492
+ uid: this.uid,
493
+ refs: globalThis.__schemastery_refs__
494
+ };
495
+ globalThis.__schemastery_refs__ = void 0;
496
+ return result;
497
+ }, "toJSON");
498
+ Schema.prototype.set = __name(function set(key, value) {
499
+ this.dict[key] = value;
500
+ return this;
501
+ }, "set");
502
+ Schema.prototype.push = __name(function push(value) {
503
+ this.list.push(value);
504
+ return this;
505
+ }, "push");
506
+ function mergeDesc(original, messages) {
507
+ const result = typeof original === "string" ? { "": original } : { ...original };
508
+ for (const locale in messages) {
509
+ const value = messages[locale];
510
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
511
+ else if (typeof value === "string") result[locale] = value;
512
+ }
513
+ return result;
514
+ }
515
+ __name(mergeDesc, "mergeDesc");
516
+ function getInner(value) {
517
+ return value?.$value ?? value?.$inner;
518
+ }
519
+ __name(getInner, "getInner");
520
+ function extractKeys(data) {
521
+ return (0, import_cosmokit.filterKeys)(data ?? {}, (key) => !key.startsWith("$"));
522
+ }
523
+ __name(extractKeys, "extractKeys");
524
+ Schema.prototype.i18n = __name(function i18n(messages) {
525
+ const schema = Schema(this);
526
+ const desc = mergeDesc(schema.meta.description, messages);
527
+ if (Object.keys(desc).length) schema.meta.description = desc;
528
+ if (schema.dict) schema.dict = (0, import_cosmokit.valueMap)(schema.dict, (inner, key) => {
529
+ return inner.i18n((0, import_cosmokit.valueMap)(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
530
+ });
531
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
532
+ return inner.i18n((0, import_cosmokit.valueMap)(messages, (data = {}) => {
533
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
534
+ if (Array.isArray(data)) return data[index];
535
+ return extractKeys(data);
536
+ }));
537
+ });
538
+ if (schema.inner) schema.inner = schema.inner.i18n((0, import_cosmokit.valueMap)(messages, (data) => {
539
+ if (getInner(data)) return getInner(data);
540
+ return extractKeys(data);
541
+ }));
542
+ if (schema.sKey) schema.sKey = schema.sKey.i18n((0, import_cosmokit.valueMap)(messages, (data) => data?.$key));
543
+ return schema;
544
+ }, "i18n");
545
+ Schema.prototype.extra = __name(function extra(key, value) {
546
+ const schema = Schema(this);
547
+ schema.meta = {
548
+ ...schema.meta,
549
+ [key]: value
550
+ };
551
+ return schema;
552
+ }, "extra");
553
+ for (const key of [
554
+ "required",
555
+ "disabled",
556
+ "collapse",
557
+ "hidden",
558
+ "loose"
559
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
560
+ const schema = Schema(this);
561
+ schema.meta = {
562
+ ...schema.meta,
563
+ [key]: value
564
+ };
565
+ return schema;
566
+ } });
567
+ Schema.prototype.deprecated = __name(function deprecated() {
568
+ const schema = Schema(this);
569
+ schema.meta.badges ||= [];
570
+ schema.meta.badges.push({
571
+ text: "deprecated",
572
+ type: "danger"
573
+ });
574
+ return schema;
575
+ }, "deprecated");
576
+ Schema.prototype.experimental = __name(function experimental() {
577
+ const schema = Schema(this);
578
+ schema.meta.badges ||= [];
579
+ schema.meta.badges.push({
580
+ text: "experimental",
581
+ type: "warning"
582
+ });
583
+ return schema;
584
+ }, "experimental");
585
+ Schema.prototype.pattern = __name(function pattern(regexp) {
586
+ const schema = Schema(this);
587
+ const pattern2 = (0, import_cosmokit.pick)(regexp, ["source", "flags"]);
588
+ schema.meta = {
589
+ ...schema.meta,
590
+ pattern: pattern2
591
+ };
592
+ return schema;
593
+ }, "pattern");
594
+ Schema.prototype.simplify = __name(function simplify(value) {
595
+ if ((0, import_cosmokit.deepEqual)(value, this.meta.default, this.type === "dict")) return null;
596
+ if ((0, import_cosmokit.isNullable)(value)) return value;
597
+ if (this.type === "object" || this.type === "dict") {
598
+ const result = {};
599
+ for (const key in value) {
600
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
601
+ if (this.type === "dict" || !(0, import_cosmokit.isNullable)(item)) result[key] = item;
602
+ }
603
+ if ((0, import_cosmokit.deepEqual)(result, this.meta.default, this.type === "dict")) return null;
604
+ return result;
605
+ } else if (this.type === "array" || this.type === "tuple") {
606
+ const result = [];
607
+ value.forEach((value2, index) => {
608
+ const schema = this.type === "array" ? this.inner : this.list[index];
609
+ const item = schema ? schema.simplify(value2) : value2;
610
+ result.push(item);
611
+ });
612
+ return result;
613
+ } else if (this.type === "intersect") {
614
+ const result = {};
615
+ for (const item of this.list) Object.assign(result, item.simplify(value));
616
+ return result;
617
+ } else if (this.type === "union") for (const schema of this.list) try {
618
+ Schema.resolve(value, schema, {});
619
+ return schema.simplify(value);
620
+ } catch {}
621
+ return value;
622
+ }, "simplify");
623
+ Schema.prototype.toString = __name(function toString(inline) {
624
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
625
+ }, "toString");
626
+ Schema.prototype.role = __name(function role(role, extra2) {
627
+ const schema = Schema(this);
628
+ schema.meta = {
629
+ ...schema.meta,
630
+ role,
631
+ extra: extra2
632
+ };
633
+ return schema;
634
+ }, "role");
635
+ for (const key of [
636
+ "default",
637
+ "link",
638
+ "comment",
639
+ "description",
640
+ "max",
641
+ "min",
642
+ "step"
643
+ ]) Object.assign(Schema.prototype, { [key](value) {
644
+ const schema = Schema(this);
645
+ schema.meta = {
646
+ ...schema.meta,
647
+ [key]: value
648
+ };
649
+ return schema;
650
+ } });
651
+ var resolvers = {};
652
+ Schema.extend = __name(function extend(type, resolve2) {
653
+ resolvers[type] = resolve2;
654
+ }, "extend");
655
+ Schema.resolve = __name(function resolve(data, schema, options = {}, strict = false) {
656
+ if (!schema) return [data];
657
+ if (options.ignore?.(data, schema)) return [data];
658
+ if ((0, import_cosmokit.isNullable)(data) && schema.type !== "lazy") {
659
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
660
+ let current = schema;
661
+ let fallback = schema.meta.default;
662
+ while (current?.type === "intersect" && (0, import_cosmokit.isNullable)(fallback)) {
663
+ current = current.list[0];
664
+ fallback = current?.meta.default;
665
+ }
666
+ if ((0, import_cosmokit.isNullable)(fallback)) return [data];
667
+ data = (0, import_cosmokit.clone)(fallback);
668
+ }
669
+ const callback = resolvers[schema.type];
670
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
671
+ try {
672
+ return callback(data, schema, options, strict);
673
+ } catch (error) {
674
+ if (!schema.meta.loose) throw error;
675
+ return [schema.meta.default];
676
+ }
677
+ }, "resolve");
678
+ Schema.from = __name(function from(source) {
679
+ if ((0, import_cosmokit.isNullable)(source)) return Schema.any();
680
+ else if ([
681
+ "string",
682
+ "number",
683
+ "boolean"
684
+ ].includes(typeof source)) return Schema.const(source).required();
685
+ else if (source[kSchema]) return source;
686
+ else if (typeof source === "function") switch (source) {
687
+ case String: return Schema.string().required();
688
+ case Number: return Schema.number().required();
689
+ case Boolean: return Schema.boolean().required();
690
+ case Function: return Schema.function().required();
691
+ default: return Schema.is(source).required();
692
+ }
693
+ else throw new TypeError(`cannot infer schema from ${source}`);
694
+ }, "from");
695
+ Schema.lazy = __name(function lazy(builder) {
696
+ const schema = new Schema({
697
+ type: "lazy",
698
+ builder,
699
+ inner: { toJSON: __name(() => {
700
+ if (!schema.inner[kSchema]) {
701
+ schema.inner = schema.builder();
702
+ schema.inner.meta = {
703
+ ...schema.meta,
704
+ ...schema.inner.meta
705
+ };
706
+ }
707
+ return schema.inner.toJSON();
708
+ }, "toJSON") }
709
+ });
710
+ return schema;
711
+ }, "lazy");
712
+ Schema.natural = __name(function natural() {
713
+ return Schema.number().step(1).min(0);
714
+ }, "natural");
715
+ Schema.percent = __name(function percent() {
716
+ return Schema.number().step(.01).min(0).max(1).role("slider");
717
+ }, "percent");
718
+ Schema.date = __name(function date() {
719
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
720
+ const date2 = new Date(value);
721
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
722
+ return date2;
723
+ }, true)]);
724
+ }, "date");
725
+ Schema.regExp = __name(function regExp(flag = "") {
726
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
727
+ try {
728
+ return new RegExp(value, flag);
729
+ } catch (e) {
730
+ throw new ValidationError(e.message, options);
731
+ }
732
+ }, true)]);
733
+ }, "regExp");
734
+ Schema.arrayBuffer = __name(function arrayBuffer(encoding) {
735
+ return Schema.union([
736
+ Schema.is(ArrayBuffer),
737
+ Schema.is(SharedArrayBuffer),
738
+ Schema.transform(Schema.any(), (value, options) => {
739
+ if (import_cosmokit.Binary.isSource(value)) return import_cosmokit.Binary.fromSource(value);
740
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
741
+ }, true),
742
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
743
+ try {
744
+ return encoding === "base64" ? import_cosmokit.Binary.fromBase64(value) : import_cosmokit.Binary.fromHex(value);
745
+ } catch (e) {
746
+ throw new ValidationError(e.message, options);
747
+ }
748
+ }, true)] : []
749
+ ]);
750
+ }, "arrayBuffer");
751
+ Schema.extend("lazy", (data, schema, options, strict) => {
752
+ if (!schema.inner[kSchema]) {
753
+ schema.inner = schema.builder();
754
+ schema.inner.meta = {
755
+ ...schema.meta,
756
+ ...schema.inner.meta
757
+ };
758
+ }
759
+ return Schema.resolve(data, schema.inner, options, strict);
760
+ });
761
+ Schema.extend("any", (data) => {
762
+ return [data];
763
+ });
764
+ Schema.extend("never", (data, _, options) => {
765
+ throw new ValidationError(`expected nullable but got ${data}`, options);
766
+ });
767
+ Schema.extend("const", (data, { value }, options) => {
768
+ if ((0, import_cosmokit.deepEqual)(data, value)) return [value];
769
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
770
+ });
771
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
772
+ const { max = Infinity, min = -Infinity } = meta;
773
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
774
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
775
+ }
776
+ __name(checkWithinRange, "checkWithinRange");
777
+ Schema.extend("string", (data, { meta }, options) => {
778
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
779
+ if (meta.pattern) {
780
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
781
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
782
+ }
783
+ checkWithinRange(data.length, meta, "string length", options);
784
+ return [data];
785
+ });
786
+ function decimalShift(data, digits) {
787
+ const str = data.toString();
788
+ if (str.includes("e")) return data * Math.pow(10, digits);
789
+ const index = str.indexOf(".");
790
+ if (index === -1) return data * Math.pow(10, digits);
791
+ const frac = str.slice(index + 1);
792
+ const integer = str.slice(0, index);
793
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
794
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
795
+ }
796
+ __name(decimalShift, "decimalShift");
797
+ function isMultipleOf(data, min, step) {
798
+ step = Math.abs(step);
799
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
800
+ const index = step.toString().indexOf(".");
801
+ const digits = step.toString().slice(index + 1).length;
802
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
803
+ }
804
+ __name(isMultipleOf, "isMultipleOf");
805
+ Schema.extend("number", (data, { meta }, options) => {
806
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
807
+ checkWithinRange(data, meta, "number", options);
808
+ const { step } = meta;
809
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
810
+ return [data];
811
+ });
812
+ Schema.extend("boolean", (data, _, options) => {
813
+ if (typeof data === "boolean") return [data];
814
+ throw new ValidationError(`expected boolean but got ${data}`, options);
815
+ });
816
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
817
+ let value = 0, keys = [];
818
+ if (typeof data === "number") {
819
+ value = data;
820
+ for (const key in bits) if (data & bits[key]) keys.push(key);
821
+ } else if (Array.isArray(data)) {
822
+ keys = data;
823
+ for (const key of keys) {
824
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
825
+ if (key in bits) value |= bits[key];
826
+ }
827
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
828
+ if (value === meta.default) return [value];
829
+ return [value, keys];
830
+ });
831
+ Schema.extend("function", (data, _, options) => {
832
+ if (typeof data === "function") return [data];
833
+ throw new ValidationError(`expected function but got ${data}`, options);
834
+ });
835
+ Schema.extend("is", (data, { constructor }, options) => {
836
+ if (typeof constructor === "function") {
837
+ if (data instanceof constructor) return [data];
838
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
839
+ } else {
840
+ if ((0, import_cosmokit.isNullable)(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
841
+ let prototype = Object.getPrototypeOf(data);
842
+ while (prototype) {
843
+ if (prototype.constructor?.name === constructor) return [data];
844
+ prototype = Object.getPrototypeOf(prototype);
845
+ }
846
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
847
+ }
848
+ });
849
+ function property(data, key, schema, options) {
850
+ try {
851
+ const [value, adapted] = Schema.resolve(data[key], schema, {
852
+ ...options,
853
+ path: [...options.path || [], key]
854
+ });
855
+ if (adapted !== void 0) data[key] = adapted;
856
+ return value;
857
+ } catch (e) {
858
+ if (!options?.autofix) throw e;
859
+ delete data[key];
860
+ return schema.meta.default;
861
+ }
862
+ }
863
+ __name(property, "property");
864
+ Schema.extend("array", (data, { inner, meta }, options) => {
865
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
866
+ checkWithinRange(data.length, meta, "array length", options, !(0, import_cosmokit.isNullable)(inner.meta.default));
867
+ return [data.map((_, index) => property(data, index, inner, options))];
868
+ });
869
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
870
+ if (!(0, import_cosmokit.isPlainObject)(data)) throw new ValidationError(`expected object but got ${data}`, options);
871
+ const result = {};
872
+ for (const key in data) {
873
+ let rKey;
874
+ try {
875
+ rKey = Schema.resolve(key, sKey, options)[0];
876
+ } catch (error) {
877
+ if (strict) continue;
878
+ throw error;
879
+ }
880
+ result[rKey] = property(data, key, inner, options);
881
+ data[rKey] = data[key];
882
+ if (key !== rKey) delete data[key];
883
+ }
884
+ return [result];
885
+ });
886
+ Schema.extend("tuple", (data, { list }, options, strict) => {
887
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
888
+ const result = list.map((inner, index) => property(data, index, inner, options));
889
+ if (strict) return [result];
890
+ result.push(...data.slice(list.length));
891
+ return [result];
892
+ });
893
+ function merge(result, data) {
894
+ for (const key in data) {
895
+ if (key in result) continue;
896
+ result[key] = data[key];
897
+ }
898
+ }
899
+ __name(merge, "merge");
900
+ Schema.extend("object", (data, { dict }, options, strict) => {
901
+ if (!(0, import_cosmokit.isPlainObject)(data)) throw new ValidationError(`expected object but got ${data}`, options);
902
+ const result = {};
903
+ for (const key in dict) {
904
+ const value = property(data, key, dict[key], options);
905
+ if (!(0, import_cosmokit.isNullable)(value) || key in data) result[key] = value;
906
+ }
907
+ if (!strict) merge(result, data);
908
+ return [result];
909
+ });
910
+ Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
911
+ const messages = [];
912
+ for (const inner of list) try {
913
+ return Schema.resolve(data, inner, options, strict);
914
+ } catch (error) {
915
+ messages.push(error);
916
+ }
917
+ throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
918
+ });
919
+ Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
920
+ if (!list.length) return [data];
921
+ let result;
922
+ for (const inner of list) {
923
+ const value = Schema.resolve(data, inner, options, true)[0];
924
+ if ((0, import_cosmokit.isNullable)(value)) continue;
925
+ if ((0, import_cosmokit.isNullable)(result)) result = value;
926
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
927
+ else if (typeof value === "object") merge(result ??= {}, value);
928
+ else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
929
+ }
930
+ if (!strict && (0, import_cosmokit.isPlainObject)(data)) merge(result, data);
931
+ return [result];
932
+ });
933
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
934
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
935
+ if (preserve) return [callback(result)];
936
+ else return [callback(result), callback(adapted)];
937
+ });
938
+ var formatters = {};
939
+ function defineMethod(name, keys, format) {
940
+ formatters[name] = format;
941
+ Object.assign(Schema, { [name](...args) {
942
+ const schema = new Schema({ type: name });
943
+ keys.forEach((key, index) => {
944
+ switch (key) {
945
+ case "sKey":
946
+ schema.sKey = args[index] ?? Schema.string();
947
+ break;
948
+ case "inner":
949
+ schema.inner = Schema.from(args[index]);
950
+ break;
951
+ case "list":
952
+ schema.list = args[index].map(Schema.from);
953
+ break;
954
+ case "dict":
955
+ schema.dict = (0, import_cosmokit.valueMap)(args[index], Schema.from);
956
+ break;
957
+ case "bits":
958
+ schema.bits = {};
959
+ for (const key2 in args[index]) {
960
+ if (typeof args[index][key2] !== "number") continue;
961
+ schema.bits[key2] = args[index][key2];
962
+ }
963
+ break;
964
+ case "callback": {
965
+ const callback = schema.callback = args[index];
966
+ callback["toJSON"] ||= () => callback.toString();
967
+ break;
968
+ }
969
+ case "constructor": {
970
+ const constructor = schema.constructor = args[index];
971
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
972
+ break;
973
+ }
974
+ default: schema[key] = args[index];
975
+ }
976
+ });
977
+ if (name === "object" || name === "dict") schema.meta.default = {};
978
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
979
+ else if (name === "bitset") schema.meta.default = 0;
980
+ return schema;
981
+ } });
982
+ }
983
+ __name(defineMethod, "defineMethod");
984
+ defineMethod("is", ["constructor"], ({ constructor }) => {
985
+ if (typeof constructor === "function") return constructor.name;
986
+ else return constructor;
987
+ });
988
+ defineMethod("any", [], () => "any");
989
+ defineMethod("never", [], () => "never");
990
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
991
+ defineMethod("string", [], () => "string");
992
+ defineMethod("number", [], () => "number");
993
+ defineMethod("boolean", [], () => "boolean");
994
+ defineMethod("bitset", ["bits"], () => "bitset");
995
+ defineMethod("function", [], () => "function");
996
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
997
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
998
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
999
+ defineMethod("object", ["dict"], ({ dict }) => {
1000
+ if (Object.keys(dict).length === 0) return "{}";
1001
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
1002
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
1003
+ }).join(", ")} }`;
1004
+ });
1005
+ defineMethod("union", ["list"], ({ list }, inline) => {
1006
+ const result = list.map(({ toString: format }) => format()).join(" | ");
1007
+ return inline ? `(${result})` : result;
1008
+ });
1009
+ defineMethod("intersect", ["list"], ({ list }) => {
1010
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
1011
+ });
1012
+ defineMethod("transform", [
1013
+ "inner",
1014
+ "callback",
1015
+ "preserve"
1016
+ ], ({ inner }, isInner) => inner.toString(isInner));
1017
+ module.exports = Schema;
1018
+ }))(), 1);
1019
+ var SelectorError = class extends Error {
1020
+ constructor(message) {
1021
+ super(message);
1022
+ this.name = "SelectorError";
1023
+ }
1024
+ };
1025
+ function selectorKey(provider, model) {
1026
+ return model === void 0 ? `${provider}/*` : `${provider}/${model}`;
1027
+ }
1028
+ function parseSelector(input) {
1029
+ if (typeof input !== "string") throw new SelectorError(`invalid selector ${String(input)}: expected "provider/model" or "provider/*"`);
1030
+ const trimmed = input.trim();
1031
+ const slash = trimmed.indexOf("/");
1032
+ if (slash <= 0 || slash === trimmed.length - 1) throw new SelectorError(`invalid selector "${input}": expected "provider/model" or "provider/*"`);
1033
+ const provider = trimmed.slice(0, slash).trim();
1034
+ const modelPart = trimmed.slice(slash + 1).trim();
1035
+ if (!provider || !modelPart) throw new SelectorError(`invalid selector "${input}": empty provider or model`);
1036
+ if (modelPart.includes("/")) throw new SelectorError(`invalid selector "${input}": unexpected extra separator`);
1037
+ return {
1038
+ provider,
1039
+ model: modelPart === "*" ? void 0 : modelPart,
1040
+ raw: trimmed
1041
+ };
1042
+ }
1043
+ function resolveWildcardEntry(failingModel, provider) {
1044
+ return {
1045
+ provider,
1046
+ model: failingModel,
1047
+ raw: `${provider}/${failingModel}`
1048
+ };
1049
+ }
1050
+ //#endregion
1051
+ //#region .build/host/config.js
1052
+ const defaultFallbacksConfig = {
1053
+ enabled: false,
1054
+ triggerCodes: [
1055
+ "AUTH",
1056
+ "QUOTA",
1057
+ "RATE_LIMIT"
1058
+ ],
1059
+ rootChain: [],
1060
+ roles: {
1061
+ list: [],
1062
+ rules: []
1063
+ },
1064
+ cooldownMs: 3e5,
1065
+ revertPolicy: "cooldown-expiry",
1066
+ maxSwitchesPerStep: 8,
1067
+ alwaysModeRetryCap: 5
1068
+ };
1069
+ const INHERIT_ROLE_ID = "inherit";
1070
+ const ROLE_ID_PATTERN = /^[a-z0-9-]{1,32}$/;
1071
+ function validateFallbacksConfig(config, logger) {
1072
+ const declaredIds = new Set();
1073
+ for (const role of config.roles.list) {
1074
+ const id = role.id.trim();
1075
+ if (!ROLE_ID_PATTERN.test(id)) logger.warn(`llm-fallbacks: invalid role id "${role.id}" — must match /^[a-z0-9-]{1,32}$/`);
1076
+ if (id === "inherit") logger.warn(`llm-fallbacks: role id "${role.id}" is reserved — "inherit" cannot be declared in roles.list`);
1077
+ if (declaredIds.has(id)) logger.warn(`llm-fallbacks: duplicate role id "${role.id}" — role ids must be unique`);
1078
+ declaredIds.add(id);
1079
+ for (const entry of role.chain ?? []) try {
1080
+ parseSelector(entry);
1081
+ } catch (error) {
1082
+ logger.warn(`llm-fallbacks: ignoring invalid chain entry "${entry}" in role "${role.id}": ${error.message}`);
1083
+ }
1084
+ if (role.fallback !== void 0 && role.fallback !== "inherit-root" && role.fallback !== "none") logger.warn(`llm-fallbacks: role "${role.id}" has invalid fallback "${String(role.fallback)}" — expected "inherit-root" or "none"`);
1085
+ }
1086
+ for (const entry of config.rootChain) try {
1087
+ parseSelector(entry);
1088
+ } catch (error) {
1089
+ logger.warn(`llm-fallbacks: ignoring invalid rootChain entry "${entry}": ${error.message}`);
1090
+ }
1091
+ const validTargets = new Set([...declaredIds, INHERIT_ROLE_ID]);
1092
+ for (const rule of config.roles.rules) if (!validTargets.has(rule.role.trim())) logger.warn(`llm-fallbacks: rule references undeclared role "${rule.role}" — expected one of roles.list ids or "inherit"`);
1093
+ }
1094
+ function detectLegacyKeys(source) {
1095
+ const keys = [];
1096
+ if (Object.hasOwn(source, "chains")) keys.push("chains");
1097
+ const roles = source.roles;
1098
+ if (isRecordLike(roles)) {
1099
+ if (Object.hasOwn(roles, "default")) keys.push("roles.default");
1100
+ const declared = new Set();
1101
+ if (Array.isArray(roles.list)) {
1102
+ for (const item of roles.list) if (isRecordLike(item) && typeof item.id === "string") declared.add(item.id);
1103
+ }
1104
+ if (Array.isArray(roles.rules)) {
1105
+ for (const rule of roles.rules) if (isRecordLike(rule) && typeof rule.role === "string" && rule.role !== "inherit" && !declared.has(rule.role)) keys.push(`roles.rules[].role: ${rule.role}`);
1106
+ }
1107
+ }
1108
+ return keys;
1109
+ }
1110
+ function isRecordLike(value) {
1111
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1112
+ }
1113
+ const Config = import_lib.default.object({
1114
+ enabled: import_lib.default.boolean().default(false),
1115
+ triggerCodes: import_lib.default.array(import_lib.default.string()).default([
1116
+ "AUTH",
1117
+ "QUOTA",
1118
+ "RATE_LIMIT"
1119
+ ]),
1120
+ rootChain: import_lib.default.array(import_lib.default.string()).default([]),
1121
+ roles: import_lib.default.object({
1122
+ list: import_lib.default.array(import_lib.default.object({
1123
+ id: import_lib.default.string().required(),
1124
+ label: import_lib.default.string().default(""),
1125
+ description: import_lib.default.string().default(""),
1126
+ prompt: import_lib.default.string(),
1127
+ permissions: import_lib.default.object({
1128
+ allow: import_lib.default.array(import_lib.default.string()),
1129
+ deny: import_lib.default.array(import_lib.default.string())
1130
+ }),
1131
+ chain: import_lib.default.array(import_lib.default.string()),
1132
+ fallback: import_lib.default.union([import_lib.default.const("inherit-root"), import_lib.default.const("none")]).default("inherit-root")
1133
+ })).default([]),
1134
+ rules: import_lib.default.array(import_lib.default.object({
1135
+ origin: import_lib.default.union([import_lib.default.const("root"), import_lib.default.const("subagent")]),
1136
+ provider: import_lib.default.string(),
1137
+ model: import_lib.default.string(),
1138
+ role: import_lib.default.string().required()
1139
+ })).default([])
1140
+ }).default({
1141
+ list: [],
1142
+ rules: []
1143
+ }),
1144
+ cooldownMs: import_lib.default.number().default(3e5),
1145
+ revertPolicy: import_lib.default.union([import_lib.default.const("cooldown-expiry"), import_lib.default.const("never")]).default("cooldown-expiry"),
1146
+ maxSwitchesPerStep: import_lib.default.number().default(8),
1147
+ alwaysModeRetryCap: import_lib.default.number().default(5)
1148
+ });
1149
+ //#endregion
1150
+ //#region .build/host/chains.js
1151
+ function resolveCandidate(entry, failing, modelExists) {
1152
+ let selector;
1153
+ try {
1154
+ selector = parseSelector(entry);
1155
+ } catch {
1156
+ return null;
1157
+ }
1158
+ if (selector.model === void 0) {
1159
+ const resolved = resolveWildcardEntry(failing.model, selector.provider);
1160
+ if (modelExists && !modelExists(resolved.provider, resolved.model)) return null;
1161
+ return resolved;
1162
+ }
1163
+ return selector;
1164
+ }
1165
+ function buildRoleEntries(roles, rootChain, role) {
1166
+ if (role.trim() === "inherit") return rootChain;
1167
+ const roleDef = roles.find((declared) => declared.id.trim() === role.trim());
1168
+ if (roleDef === void 0) return rootChain;
1169
+ return [...roleDef.chain ?? [], ...roleDef.fallback === "none" ? [] : rootChain];
1170
+ }
1171
+ function resolveChainViews(roles, rootChain, role, provider, model, warn = console.warn) {
1172
+ const failing = {
1173
+ provider,
1174
+ model
1175
+ };
1176
+ const entries = buildRoleEntries(roles, rootChain, role);
1177
+ if (role.trim() !== "inherit" && !roles.some((declared) => declared.id.trim() === role.trim())) warn(`llm-fallbacks: unknown role "${role}" — falling back to rootChain`);
1178
+ const all = [];
1179
+ const wildcard = [];
1180
+ for (const entry of entries) {
1181
+ let selector;
1182
+ try {
1183
+ selector = parseSelector(entry);
1184
+ } catch {
1185
+ continue;
1186
+ }
1187
+ const candidate = resolveCandidate(entry, failing);
1188
+ if (candidate === null) continue;
1189
+ all.push(candidate);
1190
+ wildcard.push(selector.model === void 0);
1191
+ }
1192
+ return {
1193
+ all,
1194
+ wildcard
1195
+ };
1196
+ }
1197
+ function selectCandidates(all, wildcard, filter, modelExists) {
1198
+ const surviving = [];
1199
+ for (let index = 0; index < all.length; index += 1) {
1200
+ const candidate = all[index];
1201
+ if (filter && !filter(candidate)) continue;
1202
+ if (modelExists && wildcard[index] && !modelExists(candidate.provider, candidate.model)) continue;
1203
+ surviving.push(candidate);
1204
+ }
1205
+ return surviving;
1206
+ }
1207
+ function hasWildcardEntry(roles, rootChain, role) {
1208
+ const entries = buildRoleEntries(roles, rootChain, role);
1209
+ for (const entry of entries) try {
1210
+ if (parseSelector(entry).model === void 0) return true;
1211
+ } catch {}
1212
+ return false;
1213
+ }
1214
+ function createCandidateFilter(options) {
1215
+ const { current, cooldown, failed, modelExists } = options;
1216
+ return (candidate) => {
1217
+ if (candidate.provider === current.provider && candidate.model === current.model) return false;
1218
+ if (cooldown.isSuppressed(selectorKey(candidate.provider, candidate.model))) return false;
1219
+ if (failed.has(selectorKey(candidate.provider, candidate.model))) return false;
1220
+ if (modelExists && candidate.model !== void 0 && !modelExists(candidate.provider, candidate.model)) return false;
1221
+ return true;
1222
+ };
1223
+ }
1224
+ function annotateCandidates(candidates, surviving, options) {
1225
+ const { current, cooldown, failed } = options;
1226
+ const usable = new Set(surviving.map((candidate) => selectorKey(candidate.provider, candidate.model)));
1227
+ return candidates.map((candidate) => {
1228
+ if (candidate.provider === current.provider && candidate.model === current.model) return {
1229
+ candidate,
1230
+ skip: "same-as-current"
1231
+ };
1232
+ const key = selectorKey(candidate.provider, candidate.model);
1233
+ if (usable.has(key)) return { candidate };
1234
+ if (cooldown.isSuppressed(key)) return {
1235
+ candidate,
1236
+ skip: "cooldown"
1237
+ };
1238
+ if (failed.has(key)) return {
1239
+ candidate,
1240
+ skip: "step-failed"
1241
+ };
1242
+ return {
1243
+ candidate,
1244
+ skip: "missing-id"
1245
+ };
1246
+ });
1247
+ }
1248
+ //#endregion
1249
+ //#region .build/host/roles.js
1250
+ function resolveRole(agent, rules, roleIds, warn = console.warn) {
1251
+ const origin = agent.session?.header?.origin ?? "root";
1252
+ for (const rule of rules) {
1253
+ if (rule.origin && rule.origin !== origin) continue;
1254
+ if (rule.provider && rule.provider !== agent.options?.provider) continue;
1255
+ if (rule.model && rule.model !== agent.options?.model) continue;
1256
+ const target = rule.role.trim();
1257
+ if (target === "inherit") return INHERIT_ROLE_ID;
1258
+ const declared = roleIds.get(target);
1259
+ if (declared === void 0) {
1260
+ warn(`llm-fallbacks: rule references undeclared role "${rule.role}" — falling back to "inherit"`);
1261
+ return INHERIT_ROLE_ID;
1262
+ }
1263
+ return declared;
1264
+ }
1265
+ return INHERIT_ROLE_ID;
1266
+ }
1267
+ //#endregion
1268
+ //#region .build/host/cooldown.js
1269
+ var CooldownStore = class {
1270
+ entries = new Map();
1271
+ get size() {
1272
+ return this.entries.size;
1273
+ }
1274
+ suppress(key, untilEpochMs) {
1275
+ this.entries.set(key, untilEpochMs);
1276
+ }
1277
+ isSuppressed(key, now = Date.now()) {
1278
+ const until = this.entries.get(key);
1279
+ if (until === void 0) return false;
1280
+ if (until <= now) {
1281
+ this.entries.delete(key);
1282
+ return false;
1283
+ }
1284
+ return true;
1285
+ }
1286
+ snapshot(now = Date.now()) {
1287
+ const active = [];
1288
+ for (const [key, until] of this.entries) {
1289
+ if (until <= now) continue;
1290
+ active.push({
1291
+ key,
1292
+ untilEpochMs: until
1293
+ });
1294
+ }
1295
+ return active;
1296
+ }
1297
+ };
1298
+ var StepFailureSet = class {
1299
+ keys = new Set();
1300
+ get size() {
1301
+ return this.keys.size;
1302
+ }
1303
+ add(key) {
1304
+ this.keys.add(key);
1305
+ }
1306
+ has(key) {
1307
+ return this.keys.has(key);
1308
+ }
1309
+ reset() {
1310
+ this.keys.clear();
1311
+ }
1312
+ };
1313
+ //#endregion
1314
+ //#region .build/host/state.js
1315
+ var FallbackStateStore = class {
1316
+ states = new Map();
1317
+ get size() {
1318
+ return this.states.size;
1319
+ }
1320
+ has(agentId) {
1321
+ return this.states.has(agentId);
1322
+ }
1323
+ peek(agentId) {
1324
+ return this.states.get(agentId);
1325
+ }
1326
+ get(agentId) {
1327
+ let state = this.states.get(agentId);
1328
+ if (state === void 0) {
1329
+ state = {
1330
+ stepFailures: {
1331
+ turn: 0,
1332
+ step: 0,
1333
+ failed: new StepFailureSet(),
1334
+ switchCount: 0
1335
+ },
1336
+ cooldown: new CooldownStore()
1337
+ };
1338
+ this.states.set(agentId, state);
1339
+ }
1340
+ return state;
1341
+ }
1342
+ delete(agentId) {
1343
+ this.states.delete(agentId);
1344
+ }
1345
+ clear() {
1346
+ this.states.clear();
1347
+ }
1348
+ syncStep(state, turn, step) {
1349
+ const { stepFailures } = state;
1350
+ if (stepFailures.turn === turn && stepFailures.step === step) return;
1351
+ stepFailures.turn = turn;
1352
+ stepFailures.step = step;
1353
+ stepFailures.failed.reset();
1354
+ stepFailures.switchCount = 0;
1355
+ }
1356
+ recordFailure(state, key) {
1357
+ state.stepFailures.failed.add(key);
1358
+ }
1359
+ recordSwitch(state) {
1360
+ state.stepFailures.switchCount += 1;
1361
+ }
1362
+ writePending(state, pending) {
1363
+ state.pendingSwitch = pending;
1364
+ state.appliedTurnStep = void 0;
1365
+ }
1366
+ applyPending(state, turn, step) {
1367
+ const pending = state.pendingSwitch;
1368
+ if (pending === void 0) return void 0;
1369
+ const applied = state.appliedTurnStep;
1370
+ if (applied !== void 0 && applied.turn === turn && applied.step === step) return void 0;
1371
+ state.appliedTurnStep = {
1372
+ turn,
1373
+ step
1374
+ };
1375
+ state.pendingSwitch = void 0;
1376
+ return pending;
1377
+ }
1378
+ clearStepState(state) {
1379
+ state.pendingSwitch = void 0;
1380
+ state.appliedTurnStep = void 0;
1381
+ state.stepFailures.failed.reset();
1382
+ state.stepFailures.switchCount = 0;
1383
+ }
1384
+ suppress(state, key, untilEpochMs) {
1385
+ state.cooldown.suppress(key, untilEpochMs);
1386
+ }
1387
+ isSuppressed(state, key, now = Date.now()) {
1388
+ return state.cooldown.isSuppressed(key, now);
1389
+ }
1390
+ };
1391
+ //#endregion
1392
+ //#region .build/host/gateway.js
1393
+ const FALLBACKS_SETTINGS_NAMESPACE = settingsNamespace("fallbacks");
1394
+ const CONFIG_KEYS = {
1395
+ enabled: true,
1396
+ triggerCodes: true,
1397
+ rootChain: true,
1398
+ roles: true,
1399
+ cooldownMs: true,
1400
+ revertPolicy: true,
1401
+ maxSwitchesPerStep: true,
1402
+ alwaysModeRetryCap: true
1403
+ };
1404
+ const ROLES_KEYS = {
1405
+ list: true,
1406
+ rules: true
1407
+ };
1408
+ var FallbacksConfigGateway = class extends TypertRemoteService {
1409
+ bridge;
1410
+ settings;
1411
+ constructor(ctx, bridge) {
1412
+ super(ctx, "fallbacks");
1413
+ this.bridge = bridge;
1414
+ ctx.inject(["settings"], (sctx) => {
1415
+ this.settings = sctx.settings;
1416
+ return () => {
1417
+ this.settings = void 0;
1418
+ };
1419
+ });
1420
+ }
1421
+ get() {
1422
+ return this.readResult();
1423
+ }
1424
+ async set(patch) {
1425
+ validateConfigPatch(patch);
1426
+ if (Object.keys(patch).length === 0) return this.readResult();
1427
+ const settings = this.settings;
1428
+ if (settings === void 0) throw new Error("fallbacks: settings service is unavailable — configuration cannot be written");
1429
+ const normalized = Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== null));
1430
+ if (Object.keys(normalized).length === 0) return this.readResult();
1431
+ await settings.update(FALLBACKS_SETTINGS_NAMESPACE, normalized);
1432
+ return this.readResult();
1433
+ }
1434
+ async reset() {
1435
+ const settings = this.settings;
1436
+ if (settings === void 0) throw new Error("fallbacks: settings service is unavailable — configuration cannot be written");
1437
+ await settings.replace(FALLBACKS_SETTINGS_NAMESPACE, {});
1438
+ return this.readResult();
1439
+ }
1440
+ readConfig(source = this.bridge.source()) {
1441
+ const wire = {};
1442
+ for (const key of Object.keys(CONFIG_KEYS)) {
1443
+ const value = source[key];
1444
+ if (value === void 0) continue;
1445
+ wire[key] = key === "roles" ? normalizeRoles(value) : value;
1446
+ }
1447
+ return wire;
1448
+ }
1449
+ readResult() {
1450
+ const source = this.bridge.source();
1451
+ return {
1452
+ config: this.readConfig(source),
1453
+ legacyKeys: detectLegacyKeys(source)
1454
+ };
1455
+ }
1456
+ };
1457
+ function normalizeRoles(value) {
1458
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
1459
+ const roles = {};
1460
+ for (const field of ["list", "rules"]) {
1461
+ const member = value[field];
1462
+ if (member !== void 0) roles[field] = member;
1463
+ }
1464
+ return roles;
1465
+ }
1466
+ function validateConfigPatch(patch) {
1467
+ if (patch === null || typeof patch !== "object" || Array.isArray(patch)) throw new TypeError("dsh-llm-fallbacks: configuration patch must be a plain object");
1468
+ for (const key of Object.keys(patch)) {
1469
+ if (!Object.hasOwn(CONFIG_KEYS, key)) throw new Error(`dsh-llm-fallbacks: unknown config key "${key}"`);
1470
+ if (key === "roles") {
1471
+ const roles = patch[key];
1472
+ if (roles !== null && typeof roles === "object" && !Array.isArray(roles)) {
1473
+ for (const nestedKey of Object.keys(roles)) if (!Object.hasOwn(ROLES_KEYS, nestedKey)) throw new Error(`dsh-llm-fallbacks: unknown config key "roles.${nestedKey}"`);
1474
+ }
1475
+ }
1476
+ }
1477
+ Config(patch);
1478
+ }
1479
+ function fallbacksTypertContribution() {
1480
+ return {
1481
+ package: "dsh-llm-fallbacks",
1482
+ face: "host",
1483
+ schemas: [],
1484
+ model: {
1485
+ services: [],
1486
+ events: [],
1487
+ objects: []
1488
+ },
1489
+ invocations: [
1490
+ {
1491
+ id: "dsh-llm-fallbacks#fallbacks/get",
1492
+ service: "fallbacks",
1493
+ namespace: "fallbacks",
1494
+ method: "get",
1495
+ invocation: { kind: "direct" },
1496
+ parameters: [],
1497
+ result: { mode: "src-json" }
1498
+ },
1499
+ {
1500
+ id: "dsh-llm-fallbacks#fallbacks/set",
1501
+ service: "fallbacks",
1502
+ namespace: "fallbacks",
1503
+ method: "set",
1504
+ invocation: { kind: "direct" },
1505
+ parameters: [{
1506
+ name: "patch",
1507
+ wire: "patch",
1508
+ source: "json",
1509
+ codec: { mode: "src-json" }
1510
+ }],
1511
+ result: { mode: "src-json" }
1512
+ },
1513
+ {
1514
+ id: "dsh-llm-fallbacks#fallbacks/reset",
1515
+ service: "fallbacks",
1516
+ namespace: "fallbacks",
1517
+ method: "reset",
1518
+ invocation: { kind: "direct" },
1519
+ parameters: [],
1520
+ result: { mode: "src-json" }
1521
+ }
1522
+ ]
1523
+ };
1524
+ }
1525
+ //#endregion
1526
+ //#region .build/host/commands.js
1527
+ const FALLBACKS_COMMAND_LOCALES = {
1528
+ zh: {
1529
+ title: "当前会话 fallback 诊断(只读)",
1530
+ description: "查看当前会话的降级链、最近切换与冷却状态(只读)",
1531
+ origin: "会话来源",
1532
+ role: "角色",
1533
+ chain: "链",
1534
+ inheritRoot: "(inherit-root)",
1535
+ chainNone: "未配置",
1536
+ switches: "最近切换",
1537
+ switchesNone: "本会话暂无 fallback 切换",
1538
+ switchLine: "{from} → {to}(role={role},reason={reason})",
1539
+ cooldown: "冷却",
1540
+ cooldownNone: "无活跃冷却",
1541
+ cooldownLine: "{key} 冷却至 {time}",
1542
+ cooldownNever: "{key} 会话内不再回主",
1543
+ reason: {
1544
+ "trigger-code": "触发码",
1545
+ "always-cap": "always 上限"
1546
+ }
1547
+ },
1548
+ en: {
1549
+ title: "Session fallback diagnostics (read-only)",
1550
+ description: "Inspect fallback chain, recent switches, and cooldown for this session (read-only)",
1551
+ origin: "Session origin",
1552
+ role: "Role",
1553
+ chain: "Chain",
1554
+ inheritRoot: " (inherit-root)",
1555
+ chainNone: "not configured",
1556
+ switches: "Recent switches",
1557
+ switchesNone: "No fallback switches in this session",
1558
+ switchLine: "{from} → {to} (role={role}, reason={reason})",
1559
+ cooldown: "Cooldown",
1560
+ cooldownNone: "none active",
1561
+ cooldownLine: "{key} suppressed until {time}",
1562
+ cooldownNever: "{key} not reverting this session",
1563
+ reason: {
1564
+ "trigger-code": "trigger-code",
1565
+ "always-cap": "always-cap"
1566
+ }
1567
+ }
1568
+ };
1569
+ function isFallbacksSwitchData(data) {
1570
+ if (typeof data !== "object" || data === null) return false;
1571
+ const payload = data;
1572
+ if (typeof payload.turn !== "number" || typeof payload.step !== "number") return false;
1573
+ if (typeof payload.role !== "string" || typeof payload.reason !== "string") return false;
1574
+ const from = payload.from;
1575
+ const to = payload.to;
1576
+ return typeof from?.provider === "string" && typeof from?.model === "string" && typeof to?.provider === "string" && typeof to?.model === "string";
1577
+ }
1578
+ function recentFallbacksSwitches(events, limit) {
1579
+ const found = [];
1580
+ for (let index = events.length - 1; index >= 0 && found.length < limit; index -= 1) {
1581
+ const event = events[index];
1582
+ if (event?.type !== "fallbacks/switch") continue;
1583
+ if (!isFallbacksSwitchData(event.data)) continue;
1584
+ found.push(event.data);
1585
+ }
1586
+ return found;
1587
+ }
1588
+ function resolveChainForDiagnostic(roles, rootChain, role, warn = console.warn) {
1589
+ if (role.trim() === "inherit") return {
1590
+ chainRole: false,
1591
+ chain: rootChain,
1592
+ inherit: rootChain.length > 0
1593
+ };
1594
+ const roleDef = roles.find((declared) => declared.id.trim() === role.trim());
1595
+ if (roleDef === void 0) warn(`llm-fallbacks: unknown role "${role}" — falling back to rootChain`);
1596
+ const roleChain = roleDef?.chain ?? [];
1597
+ const chain = roleChain.length > 0 ? roleChain : roleDef?.fallback === "none" ? [] : rootChain;
1598
+ const inherit = rootChain.length > 0 && (roleDef === void 0 || roleDef.fallback !== "none");
1599
+ return {
1600
+ chainRole: roleChain.length > 0,
1601
+ chain,
1602
+ inherit
1603
+ };
1604
+ }
1605
+ function formatSwitch(entry, t) {
1606
+ const from = `${entry.from.provider}/${entry.from.model}`;
1607
+ const to = `${entry.to.provider}/${entry.to.model}`;
1608
+ return t.switchLine.replace("{from}", from).replace("{to}", to).replace("{role}", entry.role).replace("{reason}", t.reason[entry.reason] ?? entry.reason);
1609
+ }
1610
+ function formatCooldown(entry, t) {
1611
+ if (!Number.isFinite(entry.untilEpochMs)) return t.cooldownNever.replace("{key}", entry.key);
1612
+ return t.cooldownLine.replace("{key}", entry.key).replace("{time}", new Date(entry.untilEpochMs).toISOString());
1613
+ }
1614
+ function fallbacksCommandText(snapshot, locale = "zh") {
1615
+ const t = FALLBACKS_COMMAND_LOCALES[locale];
1616
+ const lines = [t.title];
1617
+ lines.push(`${t.origin}: ${snapshot.origin}`);
1618
+ lines.push(`${t.role}: ${snapshot.role}`);
1619
+ if (snapshot.chain.length === 0) lines.push(`${t.chain}: ${t.chainNone}`);
1620
+ else {
1621
+ const suffix = snapshot.inherit ? t.inheritRoot : "";
1622
+ lines.push(`${t.chain}: ${snapshot.chain.join(" → ")}${suffix}`);
1623
+ }
1624
+ if (snapshot.switches.length === 0) lines.push(`${t.switches}: ${t.switchesNone}`);
1625
+ else {
1626
+ lines.push(`${t.switches} (${snapshot.switches.length}):`);
1627
+ for (const entry of snapshot.switches) lines.push(` · ${formatSwitch(entry, t)}`);
1628
+ }
1629
+ if (snapshot.cooldown.length === 0) lines.push(`${t.cooldown}: ${t.cooldownNone}`);
1630
+ else {
1631
+ lines.push(`${t.cooldown} (${snapshot.cooldown.length}):`);
1632
+ for (const entry of snapshot.cooldown) lines.push(` · ${formatCooldown(entry, t)}`);
1633
+ }
1634
+ return lines.join("\n");
1635
+ }
1636
+ function createFallbacksCommandHandler(controller, locale = "zh") {
1637
+ return (invocation) => ({
1638
+ kind: "success",
1639
+ text: fallbacksCommandText(controller.getSnapshot(invocation.agent), locale)
1640
+ });
1641
+ }
1642
+ function registerFallbacksCommands(registry, controller, locale = "zh") {
1643
+ return registry.register({
1644
+ name: "fallbacks",
1645
+ description: FALLBACKS_COMMAND_LOCALES[locale].description,
1646
+ input: { hint: "" },
1647
+ handler: createFallbacksCommandHandler(controller, locale)
1648
+ });
1649
+ }
1650
+ //#endregion
1651
+ //#region .build/host/index.js
1652
+ const name = "llm-fallbacks";
1653
+ const stateStores = new WeakMap();
1654
+ function stateStore(ctx) {
1655
+ return stateStores.get(ctx);
1656
+ }
1657
+ async function makeModelExists(ctx, providers) {
1658
+ const llm = ctx.get("llm");
1659
+ if (llm === void 0 || typeof llm.listModels !== "function") return () => true;
1660
+ const catalog = new Map();
1661
+ await Promise.all(providers.map(async (provider) => {
1662
+ try {
1663
+ const models = await llm.listModels(provider);
1664
+ catalog.set(provider, new Set(models.map((model) => model.id)));
1665
+ } catch {
1666
+ catalog.set(provider, new Set());
1667
+ }
1668
+ }));
1669
+ return (provider, model) => catalog.get(provider)?.has(model) ?? false;
1670
+ }
1671
+ function countRetryEvents(session, turn, step, provider) {
1672
+ let count = 0;
1673
+ const events = session.events;
1674
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1675
+ const event = events[index];
1676
+ const data = event.data;
1677
+ if (typeof data.turn === "number" && typeof data.step === "number" && (data.turn < turn || data.turn === turn && data.step < step)) break;
1678
+ if (event.type !== "llm/retry") continue;
1679
+ if (data.turn === turn && data.step === step && event.data.provider === provider && event.data.mode === "always") count += 1;
1680
+ }
1681
+ return count;
1682
+ }
1683
+ function currentModel(agent, provider) {
1684
+ return {
1685
+ provider,
1686
+ model: agent.session.requestHeader()?.config.model ?? agent.options.model ?? ""
1687
+ };
1688
+ }
1689
+ function overrideConfig(seed, to) {
1690
+ const { reasoningEffort: _inherited, ...withoutInheritedEffort } = seed;
1691
+ return {
1692
+ ...withoutInheritedEffort,
1693
+ provider: to.provider,
1694
+ model: to.model
1695
+ };
1696
+ }
1697
+ function apply(ctx, config = defaultFallbacksConfig) {
1698
+ const logger = ctx.logger("llm-fallbacks");
1699
+ const entry = Config(config);
1700
+ let source = () => entry;
1701
+ validateFallbacksConfig(entry, logger);
1702
+ const legacyKeys = detectLegacyKeys(source());
1703
+ if (legacyKeys.length > 0) logger.warn("llm-fallbacks: legacy config keys detected (chains/roles.default/undeclared role refs); see docs/configuration.md migration table — %o", legacyKeys);
1704
+ let roleIds = new Map(entry.roles.list.map((role) => [role.id.trim(), role.id]));
1705
+ let hasChains = entry.rootChain.length > 0 || entry.roles.list.some((role) => (role.chain?.length ?? 0) > 0);
1706
+ installSettingsSection(ctx, FALLBACKS_SETTINGS_NAMESPACE, Config, entry, {
1707
+ setSource: (current) => {
1708
+ source = current;
1709
+ },
1710
+ onChange: () => {
1711
+ const current = source();
1712
+ roleIds = new Map(current.roles.list.map((role) => [role.id.trim(), role.id]));
1713
+ hasChains = current.rootChain.length > 0 || current.roles.list.some((role) => (role.chain?.length ?? 0) > 0);
1714
+ }
1715
+ });
1716
+ const bridge = { source: () => source() };
1717
+ try {
1718
+ new FallbacksConfigGateway(ctx, bridge);
1719
+ } catch (error) {
1720
+ if (!(error instanceof Error) || !error.message.includes("has been registered")) throw error;
1721
+ ctx.logger("llm-fallbacks").debug("fallbacks gateway already registered — no gateway on this fiber (multi-fiber dedupe)");
1722
+ }
1723
+ ctx.inject(["typert"], (tctx) => {
1724
+ try {
1725
+ return tctx.typert.register(fallbacksTypertContribution());
1726
+ } catch (error) {
1727
+ if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
1728
+ tctx.logger("llm-fallbacks").debug("fallbacks typert endpoints already registered — no endpoints on this fiber (multi-fiber dedupe)");
1729
+ return () => {};
1730
+ }
1731
+ });
1732
+ const states = new FallbackStateStore();
1733
+ stateStores.set(ctx, states);
1734
+ async function decide(agent, turn, step, current, reason, state) {
1735
+ const config = source();
1736
+ if (state !== void 0) {
1737
+ states.syncStep(state, turn, step);
1738
+ if (state.stepFailures.switchCount >= config.maxSwitchesPerStep) return null;
1739
+ }
1740
+ const role = resolveRole(agent, config.roles.rules, roleIds, logger.warn);
1741
+ const { all, wildcard } = resolveChainViews(config.roles.list, config.rootChain, role, current.provider, current.model, logger.warn);
1742
+ if (all.length === 0) return null;
1743
+ const modelExists = hasWildcardEntry(config.roles.list, config.rootChain, role) ? await makeModelExists(ctx, [...new Set(all.map((candidate) => candidate.provider))]) : void 0;
1744
+ const cooldown = { isSuppressed: (key) => state !== void 0 && states.isSuppressed(state, key) };
1745
+ const failed = { has: (key) => state !== void 0 && state.stepFailures.failed.has(key) };
1746
+ const surviving = selectCandidates(all, wildcard, createCandidateFilter({
1747
+ current,
1748
+ cooldown,
1749
+ failed
1750
+ }), modelExists);
1751
+ const target = surviving[0];
1752
+ if (target === void 0 || target.model === void 0) return null;
1753
+ logger.info("llm-fallbacks: agent \"%s\" switch %s/%s -> %s/%s (role=%s, reason=%s, candidates=%o)", agent.id, current.provider, current.model, target.provider, target.model, role, reason, annotateCandidates(all, surviving, {
1754
+ current,
1755
+ cooldown,
1756
+ failed
1757
+ }).map(({ candidate, skip }) => skip === void 0 ? `${candidate.provider}/${candidate.model}` : `${candidate.provider}/${candidate.model} (skipped: ${skip})`));
1758
+ return {
1759
+ from: {
1760
+ provider: current.provider,
1761
+ model: current.model
1762
+ },
1763
+ to: {
1764
+ provider: target.provider,
1765
+ model: target.model
1766
+ },
1767
+ role,
1768
+ reason
1769
+ };
1770
+ }
1771
+ function commit(agent, state, pending, turn, step) {
1772
+ const config = source();
1773
+ const fromKey = selectorKey(pending.from.provider, pending.from.model);
1774
+ const until = config.revertPolicy === "never" ? Number.POSITIVE_INFINITY : Date.now() + config.cooldownMs;
1775
+ states.syncStep(state, turn, step);
1776
+ states.writePending(state, pending);
1777
+ states.suppress(state, fromKey, until);
1778
+ states.recordFailure(state, fromKey);
1779
+ states.recordSwitch(state);
1780
+ agent.session.append("fallbacks/switch", {
1781
+ turn,
1782
+ step,
1783
+ from: pending.from,
1784
+ to: pending.to,
1785
+ role: pending.role,
1786
+ reason: pending.reason
1787
+ });
1788
+ }
1789
+ ctx.on("agent/request-error", async ({ agent, turn, step, provider, failure }, next) => {
1790
+ const config = source();
1791
+ if (!config.enabled || !config.triggerCodes.includes(failure.code)) return next();
1792
+ const current = currentModel(agent, provider);
1793
+ if (!current.model) return next();
1794
+ try {
1795
+ const pending = await decide(agent, turn, step, current, "trigger-code", states.peek(agent.id));
1796
+ if (pending === null) return next();
1797
+ commit(agent, states.get(agent.id), pending, turn, step);
1798
+ return { kind: "retry" };
1799
+ } catch (error) {
1800
+ logger.warn("llm-fallbacks: decision path failed, passing the original failure through: %s", error?.message ?? String(error));
1801
+ return next();
1802
+ }
1803
+ });
1804
+ ctx.on("agent/request", async ({ agent, turn, step }, next) => {
1805
+ const seed = await next();
1806
+ const state = states.peek(agent.id);
1807
+ const applied = state === void 0 ? void 0 : states.applyPending(state, turn, step);
1808
+ if (applied !== void 0) return overrideConfig(seed, applied.to);
1809
+ const config = source();
1810
+ if (hasChains && config.enabled && config.alwaysModeRetryCap > 0 && countRetryEvents(agent.session, turn, step, seed.provider) >= config.alwaysModeRetryCap) {
1811
+ const decisionState = states.peek(agent.id);
1812
+ const pending = await decide(agent, turn, step, {
1813
+ provider: seed.provider,
1814
+ model: seed.model
1815
+ }, "always-cap", decisionState);
1816
+ if (pending !== null) {
1817
+ const commitState = states.get(agent.id);
1818
+ commit(agent, commitState, pending, turn, step);
1819
+ const appliedCap = states.applyPending(commitState, turn, step);
1820
+ if (appliedCap !== void 0) return overrideConfig(seed, appliedCap.to);
1821
+ }
1822
+ }
1823
+ return seed;
1824
+ });
1825
+ ctx.on("agent/status", ({ agent, status }) => {
1826
+ if (status !== "idle") return;
1827
+ const state = states.peek(agent.id);
1828
+ if (state !== void 0) states.clearStepState(state);
1829
+ });
1830
+ ctx.on("agent/disposed", ({ agent }) => {
1831
+ states.delete(agent.id);
1832
+ });
1833
+ ctx.effect(() => () => {
1834
+ states.clear();
1835
+ }, "llm-fallbacks: clear per-agent state");
1836
+ const fallbacksCommandController = { getSnapshot(agent) {
1837
+ const config = source();
1838
+ const role = resolveRole(agent, config.roles.rules, roleIds, logger.warn);
1839
+ const state = states.peek(agent.id);
1840
+ return {
1841
+ origin: agent.session.header?.origin ?? "root",
1842
+ role,
1843
+ ...resolveChainForDiagnostic(config.roles.list, config.rootChain, role, logger.warn),
1844
+ switches: recentFallbacksSwitches(agent.session.events, 5),
1845
+ cooldown: state === void 0 ? [] : state.cooldown.snapshot()
1846
+ };
1847
+ } };
1848
+ ctx.inject(["commands"], (commandCtx) => {
1849
+ return registerFallbacksCommands(commandCtx.commands, fallbacksCommandController);
1850
+ });
1851
+ }
1852
+ //#endregion
1853
+ export { Config, apply, countRetryEvents, name, stateStore };