@ngosangns/ns-bridge 0.1.23 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/NOTICE +35 -0
  2. package/README.md +58 -28
  3. package/dist/catalog.d.ts +2 -1
  4. package/dist/catalog.js +5 -3
  5. package/dist/catalog.js.map +1 -1
  6. package/dist/cli.d.ts +6 -3
  7. package/dist/cli.js +83 -61
  8. package/dist/cli.js.map +1 -1
  9. package/dist/dsh-patch.d.ts +42 -0
  10. package/dist/dsh-patch.js +186 -0
  11. package/dist/dsh-patch.js.map +1 -0
  12. package/dist/hosts/dsh/arnict/dist/index.js +2297 -0
  13. package/dist/hosts/dsh/arnict/package.json +28 -0
  14. package/dist/hosts/dsh/devin/dist/index.js +5034 -0
  15. package/dist/hosts/dsh/devin/package.json +28 -0
  16. package/dist/hosts/dsh/grok/dist/index.js +2523 -0
  17. package/dist/hosts/dsh/grok/package.json +28 -0
  18. package/dist/hosts/dsh/kiro/dist/index.js +5996 -0
  19. package/dist/hosts/dsh/kiro/package.json +28 -0
  20. package/dist/hosts/dsh/qoder/dist/index.js +21194 -0
  21. package/dist/hosts/dsh/qoder/package.json +28 -0
  22. package/dist/hosts/omp/dist/index.js +26632 -0
  23. package/dist/hosts/omp/package.json +25 -0
  24. package/dist/hosts/pi/dist/index.js +31924 -0
  25. package/dist/hosts/pi/package.json +13 -0
  26. package/dist/hosts.d.ts +52 -11
  27. package/dist/hosts.js +244 -33
  28. package/dist/hosts.js.map +1 -1
  29. package/dist/providers.d.ts +4 -5
  30. package/dist/providers.js +23 -39
  31. package/dist/providers.js.map +1 -1
  32. package/dist/refresh-entry.js +1053 -773
  33. package/dist/refresh.d.ts +2 -1
  34. package/dist/refresh.js +1 -1
  35. package/dist/refresh.js.map +1 -1
  36. package/dist/selection.d.ts +1 -1
  37. package/dist/selection.js +11 -5
  38. package/dist/selection.js.map +1 -1
  39. package/dist/self.d.ts +1 -1
  40. package/dist/self.js +1 -1
  41. package/dist/serve-entry.js +3 -12
  42. package/dist/usage.d.ts +4 -0
  43. package/dist/usage.js +33 -1
  44. package/dist/usage.js.map +1 -1
  45. package/dist/zcode.d.ts +1 -1
  46. package/dist/zcode.js +14 -8
  47. package/dist/zcode.js.map +1 -1
  48. package/package.json +13 -4
@@ -0,0 +1,2297 @@
1
+ // @ngosangns/ns-bridge 0.1.25 — prebuilt host bundle.
2
+ import { createRequire as __nsBridgeCreateRequire } from 'node:module';
3
+ const require = __nsBridgeCreateRequire(import.meta.url);
4
+
5
+ // ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
6
+ function isNullable(value) {
7
+ return value === null || value === void 0;
8
+ }
9
+ function isPlainObject(data) {
10
+ return data && typeof data === "object" && !Array.isArray(data);
11
+ }
12
+ function filterKeys(object, filter) {
13
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
14
+ }
15
+ function mapValues(object, transform) {
16
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
17
+ }
18
+ function pick(source, keys, forced) {
19
+ if (!keys) return { ...source };
20
+ const result = {};
21
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
22
+ return result;
23
+ }
24
+ var write = /* @__PURE__ */ Symbol.for("cosmokit.volatile.write");
25
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
26
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
27
+ if (value === null || typeof value !== "object") return value;
28
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
29
+ ancestors.add(value);
30
+ try {
31
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
32
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
33
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
34
+ } finally {
35
+ ancestors.delete(value);
36
+ }
37
+ }
38
+ function createVolatile(value) {
39
+ let current = snapshot(value);
40
+ return Object.freeze({
41
+ get: () => current,
42
+ [write]: (value2) => {
43
+ current = value2;
44
+ }
45
+ });
46
+ }
47
+ function isVolatile(value) {
48
+ return typeof value === "object" && value !== null && write in value;
49
+ }
50
+ function is(type, value) {
51
+ if (arguments.length === 1) return (value2) => is(type, value2);
52
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
53
+ }
54
+ function isArrayBufferLike(value) {
55
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
56
+ }
57
+ function isArrayBufferSource(value) {
58
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
59
+ }
60
+ var Binary;
61
+ (function(Binary2) {
62
+ Binary2.is = isArrayBufferLike;
63
+ Binary2.isSource = isArrayBufferSource;
64
+ function fromSource(source) {
65
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
66
+ else return source;
67
+ }
68
+ Binary2.fromSource = fromSource;
69
+ function toBase64(source) {
70
+ source = fromSource(source);
71
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
72
+ let binary = "";
73
+ const bytes = new Uint8Array(source);
74
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
75
+ return btoa(binary);
76
+ }
77
+ Binary2.toBase64 = toBase64;
78
+ function fromBase64(source) {
79
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
80
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
81
+ }
82
+ Binary2.fromBase64 = fromBase64;
83
+ function toHex(source) {
84
+ source = fromSource(source);
85
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
86
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
87
+ }
88
+ Binary2.toHex = toHex;
89
+ function fromHex(source) {
90
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
91
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
92
+ const buffer = [];
93
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
94
+ return Uint8Array.from(buffer).buffer;
95
+ }
96
+ Binary2.fromHex = fromHex;
97
+ })(Binary || (Binary = {}));
98
+ var base64ToArrayBuffer = Binary.fromBase64;
99
+ var arrayBufferToBase64 = Binary.toBase64;
100
+ var hexToArrayBuffer = Binary.fromHex;
101
+ var arrayBufferToHex = Binary.toHex;
102
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
103
+ if (!source || typeof source !== "object") return source;
104
+ if (is("Date", source)) return new Date(source.valueOf());
105
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
106
+ if (isArrayBufferLike(source)) return source.slice(0);
107
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
108
+ const cached = refs.get(source);
109
+ if (cached) return cached;
110
+ if (Array.isArray(source)) {
111
+ const result2 = [];
112
+ refs.set(source, result2);
113
+ source.forEach((value, index) => {
114
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
115
+ });
116
+ return result2;
117
+ }
118
+ const result = Object.create(Object.getPrototypeOf(source));
119
+ refs.set(source, result);
120
+ for (const key of Reflect.ownKeys(source)) {
121
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
122
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
123
+ Reflect.defineProperty(result, key, descriptor);
124
+ }
125
+ return result;
126
+ }
127
+ function deepEqual(a, b, strict) {
128
+ const ancestors = /* @__PURE__ */ new Set();
129
+ function compare(a2, b2) {
130
+ if (a2 === b2) return true;
131
+ if (isVolatile(a2) || isVolatile(b2)) return isVolatile(a2) && isVolatile(b2);
132
+ if (!strict && isNullable(a2) && isNullable(b2)) return true;
133
+ if (typeof a2 !== typeof b2 || typeof a2 !== "object" || !a2 || !b2) return false;
134
+ if (ancestors.has(a2)) return false;
135
+ function check(test, then) {
136
+ return test(a2) ? test(b2) ? then(a2, b2) : false : test(b2) ? false : void 0;
137
+ }
138
+ ancestors.add(a2);
139
+ try {
140
+ return check(Array.isArray, (a3, b3) => {
141
+ if (a3.length !== b3.length) return false;
142
+ for (let index = 0; index < a3.length; index++) if (!compare(a3[index], b3[index])) return false;
143
+ return true;
144
+ }) ?? check(is("Date"), (a3, b3) => a3.valueOf() === b3.valueOf()) ?? check(is("URL"), (a3, b3) => a3.href === b3.href) ?? check(is("RegExp"), (a3, b3) => a3.source === b3.source && a3.flags === b3.flags) ?? check(isArrayBufferLike, (a3, b3) => {
145
+ if (a3.byteLength !== b3.byteLength) return false;
146
+ const viewA = new Uint8Array(a3);
147
+ const viewB = new Uint8Array(b3);
148
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
149
+ return true;
150
+ }) ?? ((!strict || [a2, b2].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
151
+ ...a2,
152
+ ...b2
153
+ }).every((key) => compare(a2[key], b2[key])));
154
+ } finally {
155
+ ancestors.delete(a2);
156
+ }
157
+ }
158
+ return compare(a, b);
159
+ }
160
+ var Time;
161
+ (function(Time2) {
162
+ Time2.millisecond = 1;
163
+ Time2.second = 1e3;
164
+ Time2.minute = Time2.second * 60;
165
+ Time2.hour = Time2.minute * 60;
166
+ Time2.day = Time2.hour * 24;
167
+ Time2.week = Time2.day * 7;
168
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
169
+ function setTimezoneOffset(offset) {
170
+ timezoneOffset = offset;
171
+ }
172
+ Time2.setTimezoneOffset = setTimezoneOffset;
173
+ function getTimezoneOffset() {
174
+ return timezoneOffset;
175
+ }
176
+ Time2.getTimezoneOffset = getTimezoneOffset;
177
+ function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
178
+ if (typeof date2 === "number") date2 = new Date(date2);
179
+ if (offset === void 0) offset = timezoneOffset;
180
+ return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
181
+ }
182
+ Time2.getDateNumber = getDateNumber;
183
+ function fromDateNumber(value, offset) {
184
+ const date2 = new Date(value * Time2.day);
185
+ if (offset === void 0) offset = timezoneOffset;
186
+ return new Date(+date2 + offset * Time2.minute);
187
+ }
188
+ Time2.fromDateNumber = fromDateNumber;
189
+ const numeric = /\d+(?:\.\d+)?/.source;
190
+ const timeRegExp = new RegExp(`^${[
191
+ "w(?:eek(?:s)?)?",
192
+ "d(?:ay(?:s)?)?",
193
+ "h(?:our(?:s)?)?",
194
+ "m(?:in(?:ute)?(?:s)?)?",
195
+ "s(?:ec(?:ond)?(?:s)?)?"
196
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
197
+ function parseTime(source) {
198
+ const capture = timeRegExp.exec(source);
199
+ if (!capture) return 0;
200
+ 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);
201
+ }
202
+ Time2.parseTime = parseTime;
203
+ function parseDate(date2) {
204
+ const parsed = parseTime(date2);
205
+ if (parsed) date2 = Date.now() + parsed;
206
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
207
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
208
+ return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
209
+ }
210
+ Time2.parseDate = parseDate;
211
+ function format(ms) {
212
+ const abs = Math.abs(ms);
213
+ if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
214
+ else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
215
+ else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
216
+ else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
217
+ return ms + "ms";
218
+ }
219
+ Time2.format = format;
220
+ function toDigits(source, length = 2) {
221
+ return source.toString().padStart(length, "0");
222
+ }
223
+ Time2.toDigits = toDigits;
224
+ function template(template2, time = /* @__PURE__ */ new Date()) {
225
+ 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));
226
+ }
227
+ Time2.template = template;
228
+ })(Time || (Time = {}));
229
+
230
+ // ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.4/node_modules/@deepseek-ai/schemastery/lib/index.mjs
231
+ var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
232
+ var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
233
+ globalThis.__schemastery_index__ ??= 0;
234
+ globalThis.__schemastery_refs__ = void 0;
235
+ var ValidationError = class extends TypeError {
236
+ options;
237
+ name = "ValidationError";
238
+ constructor(message, options) {
239
+ let prefix = "$";
240
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
241
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
242
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
243
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
244
+ super((prefix === "$" ? "" : `${prefix} `) + message);
245
+ this.options = options;
246
+ }
247
+ static is(error) {
248
+ return !!error?.[kValidationError];
249
+ }
250
+ };
251
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
252
+ var Schema = function(options) {
253
+ const schema = function(data, options2 = {}) {
254
+ return Schema.resolve(data, schema, options2)[0];
255
+ };
256
+ if (options.refs) {
257
+ const refs = mapValues(options.refs, (options2) => new Schema(options2));
258
+ const getRef = (uid) => refs[uid];
259
+ for (const key in refs) {
260
+ const options2 = refs[key];
261
+ options2.sKey = getRef(options2.sKey);
262
+ options2.inner = getRef(options2.inner);
263
+ options2.list = options2.list && options2.list.map(getRef);
264
+ options2.dict = options2.dict && mapValues(options2.dict, getRef);
265
+ }
266
+ return refs[options.uid];
267
+ }
268
+ Object.assign(schema, options);
269
+ if (typeof schema.callback === "string") try {
270
+ schema.callback = new Function("return " + schema.callback)();
271
+ } catch {
272
+ }
273
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
274
+ Object.setPrototypeOf(schema, Schema.prototype);
275
+ schema.meta ||= {};
276
+ schema.toString = schema.toString.bind(schema);
277
+ return schema;
278
+ };
279
+ Schema.prototype = Object.create(Function.prototype);
280
+ Schema.prototype[kSchema] = true;
281
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
282
+ return {
283
+ version: 1,
284
+ vendor: "schemastery",
285
+ validate: (value) => {
286
+ try {
287
+ return { value: Schema.resolve(value, this, {})[0] };
288
+ } catch (error) {
289
+ if (ValidationError.is(error)) return { issues: [{
290
+ message: error.message,
291
+ path: error.options.path
292
+ }] };
293
+ throw error;
294
+ }
295
+ }
296
+ };
297
+ } });
298
+ Schema.ValidationError = ValidationError;
299
+ Schema.prototype.toJSON = function toJSON() {
300
+ if (globalThis.__schemastery_refs__) {
301
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
302
+ return this.uid;
303
+ }
304
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
305
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
306
+ const result = {
307
+ uid: this.uid,
308
+ refs: globalThis.__schemastery_refs__
309
+ };
310
+ globalThis.__schemastery_refs__ = void 0;
311
+ return result;
312
+ };
313
+ Schema.prototype.set = function set(key, value) {
314
+ this.dict[key] = value;
315
+ return this;
316
+ };
317
+ Schema.prototype.push = function push(value) {
318
+ this.list.push(value);
319
+ return this;
320
+ };
321
+ function mergeDesc(original, messages) {
322
+ const result = typeof original === "string" ? { "": original } : { ...original };
323
+ for (const locale in messages) {
324
+ const value = messages[locale];
325
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
326
+ else if (typeof value === "string") result[locale] = value;
327
+ }
328
+ return result;
329
+ }
330
+ function getInner(value) {
331
+ return value?.$value ?? value?.$inner;
332
+ }
333
+ function extractKeys(data) {
334
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
335
+ }
336
+ Schema.prototype.i18n = function i18n(messages) {
337
+ const schema = Schema(this);
338
+ const desc = mergeDesc(schema.meta.description, messages);
339
+ if (Object.keys(desc).length) schema.meta.description = desc;
340
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
341
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
342
+ });
343
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
344
+ return inner.i18n(mapValues(messages, (data = {}) => {
345
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
346
+ if (Array.isArray(data)) return data[index];
347
+ return extractKeys(data);
348
+ }));
349
+ });
350
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
351
+ if (getInner(data)) return getInner(data);
352
+ return extractKeys(data);
353
+ }));
354
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
355
+ return schema;
356
+ };
357
+ Schema.prototype.extra = function extra(key, value) {
358
+ const schema = Schema(this);
359
+ schema.meta = {
360
+ ...schema.meta,
361
+ [key]: value
362
+ };
363
+ return schema;
364
+ };
365
+ for (const key of [
366
+ "required",
367
+ "disabled",
368
+ "collapse",
369
+ "hidden",
370
+ "loose"
371
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
372
+ const schema = Schema(this);
373
+ schema.meta = {
374
+ ...schema.meta,
375
+ [key]: value
376
+ };
377
+ return schema;
378
+ } });
379
+ Schema.prototype.deprecated = function deprecated() {
380
+ const schema = Schema(this);
381
+ schema.meta.badges ||= [];
382
+ schema.meta.badges.push({
383
+ text: "deprecated",
384
+ type: "danger"
385
+ });
386
+ return schema;
387
+ };
388
+ Schema.prototype.experimental = function experimental() {
389
+ const schema = Schema(this);
390
+ schema.meta.badges ||= [];
391
+ schema.meta.badges.push({
392
+ text: "experimental",
393
+ type: "warning"
394
+ });
395
+ return schema;
396
+ };
397
+ Schema.prototype.pattern = function pattern(regexp) {
398
+ const schema = Schema(this);
399
+ const pattern2 = pick(regexp, ["source", "flags"]);
400
+ schema.meta = {
401
+ ...schema.meta,
402
+ pattern: pattern2
403
+ };
404
+ return schema;
405
+ };
406
+ Schema.prototype.simplify = function simplify(value) {
407
+ if (isVolatile(value)) value = value.get();
408
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
409
+ if (isNullable(value)) return value;
410
+ if (this.type === "object" || this.type === "dict") {
411
+ const result = {};
412
+ for (const key in value) {
413
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
414
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
415
+ }
416
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
417
+ return result;
418
+ } else if (this.type === "array" || this.type === "tuple") {
419
+ const result = [];
420
+ value.forEach((value2, index) => {
421
+ const schema = this.type === "array" ? this.inner : this.list[index];
422
+ const item = schema ? schema.simplify(value2) : value2;
423
+ result.push(item);
424
+ });
425
+ return result;
426
+ } else if (this.type === "intersect") {
427
+ const result = {};
428
+ for (const item of this.list) Object.assign(result, item.simplify(value));
429
+ return result;
430
+ } else if (this.type === "union") for (const schema of this.list) try {
431
+ Schema.resolve(value, schema, {});
432
+ return schema.simplify(value);
433
+ } catch {
434
+ }
435
+ return value;
436
+ };
437
+ Schema.prototype.toString = function toString(inline) {
438
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
439
+ };
440
+ Schema.prototype.role = function role(role, extra2) {
441
+ const schema = Schema(this);
442
+ schema.meta = {
443
+ ...schema.meta,
444
+ role,
445
+ extra: extra2
446
+ };
447
+ return schema;
448
+ };
449
+ for (const key of [
450
+ "default",
451
+ "link",
452
+ "comment",
453
+ "description",
454
+ "max",
455
+ "min",
456
+ "step"
457
+ ]) Object.assign(Schema.prototype, { [key](value) {
458
+ const schema = Schema(this);
459
+ schema.meta = {
460
+ ...schema.meta,
461
+ [key]: value
462
+ };
463
+ return schema;
464
+ } });
465
+ Schema.prototype.volatile = function volatile() {
466
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
467
+ return this.extra("volatile", true);
468
+ };
469
+ var resolvers = {};
470
+ var checkedVolatile = /* @__PURE__ */ Symbol("checked-volatile-schema");
471
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
472
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
473
+ if (states.has(blocked)) return;
474
+ states.add(blocked);
475
+ seen.set(schema, states);
476
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
477
+ const nested = blocked || !!schema.meta?.volatile;
478
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
479
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
480
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
481
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
482
+ }
483
+ Schema.extend = function extend(type, resolve2) {
484
+ resolvers[type] = resolve2;
485
+ };
486
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
487
+ if (!schema) return [data];
488
+ if (!options[checkedVolatile]) {
489
+ validateVolatileSchema(schema, options.path);
490
+ options = {
491
+ ...options,
492
+ [checkedVolatile]: true
493
+ };
494
+ }
495
+ if (schema.meta?.volatile) {
496
+ const inner = Schema(schema);
497
+ inner.meta = {
498
+ ...schema.meta,
499
+ volatile: false
500
+ };
501
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
502
+ try {
503
+ return [createVolatile(value), adapted];
504
+ } catch (error) {
505
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
506
+ }
507
+ }
508
+ if (options.ignore?.(data, schema)) return [data];
509
+ if (isNullable(data) && schema.type !== "lazy") {
510
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
511
+ let current = schema;
512
+ let fallback = schema.meta.default;
513
+ while (current?.type === "intersect" && isNullable(fallback)) {
514
+ current = current.list[0];
515
+ fallback = current?.meta.default;
516
+ }
517
+ if (isNullable(fallback)) return [data];
518
+ data = clone(fallback);
519
+ }
520
+ const callback = resolvers[schema.type];
521
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
522
+ try {
523
+ return callback(data, schema, options, strict);
524
+ } catch (error) {
525
+ if (!schema.meta.loose) throw error;
526
+ return [schema.meta.default];
527
+ }
528
+ };
529
+ Schema.from = function from(source) {
530
+ if (isNullable(source)) return Schema.any();
531
+ else if ([
532
+ "string",
533
+ "number",
534
+ "boolean"
535
+ ].includes(typeof source)) return Schema.const(source).required();
536
+ else if (source[kSchema]) return source;
537
+ else if (typeof source === "function") switch (source) {
538
+ case String:
539
+ return Schema.string().required();
540
+ case Number:
541
+ return Schema.number().required();
542
+ case Boolean:
543
+ return Schema.boolean().required();
544
+ case Function:
545
+ return Schema.function().required();
546
+ default:
547
+ return Schema.is(source).required();
548
+ }
549
+ else throw new TypeError(`cannot infer schema from ${source}`);
550
+ };
551
+ Schema.lazy = function lazy(builder) {
552
+ const toJSON2 = () => {
553
+ if (!schema.inner[kSchema]) {
554
+ schema.inner = schema.builder();
555
+ schema.inner.meta = {
556
+ ...schema.meta,
557
+ ...schema.inner.meta
558
+ };
559
+ }
560
+ return schema.inner.toJSON();
561
+ };
562
+ const schema = new Schema({
563
+ type: "lazy",
564
+ builder,
565
+ inner: { toJSON: toJSON2 }
566
+ });
567
+ return schema;
568
+ };
569
+ Schema.natural = function natural() {
570
+ return Schema.number().step(1).min(0);
571
+ };
572
+ Schema.percent = function percent() {
573
+ return Schema.number().step(0.01).min(0).max(1).role("slider");
574
+ };
575
+ Schema.date = function date() {
576
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
577
+ const date2 = new Date(value);
578
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
579
+ return date2;
580
+ }, true)]);
581
+ };
582
+ Schema.regExp = function regExp(flag = "") {
583
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
584
+ try {
585
+ return new RegExp(value, flag);
586
+ } catch (e) {
587
+ throw new ValidationError(e.message, options);
588
+ }
589
+ }, true)]);
590
+ };
591
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
592
+ return Schema.union([
593
+ Schema.is(ArrayBuffer),
594
+ Schema.is(SharedArrayBuffer),
595
+ Schema.transform(Schema.any(), (value, options) => {
596
+ if (Binary.isSource(value)) return Binary.fromSource(value);
597
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
598
+ }, true),
599
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
600
+ try {
601
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
602
+ } catch (e) {
603
+ throw new ValidationError(e.message, options);
604
+ }
605
+ }, true)] : []
606
+ ]);
607
+ };
608
+ Schema.extend("lazy", (data, schema, options, strict) => {
609
+ if (!schema.inner[kSchema]) {
610
+ schema.inner = schema.builder();
611
+ schema.inner.meta = {
612
+ ...schema.meta,
613
+ ...schema.inner.meta
614
+ };
615
+ validateVolatileSchema(schema.inner, options.path, true);
616
+ }
617
+ return Schema.resolve(data, schema.inner, options, strict);
618
+ });
619
+ Schema.extend("any", (data) => {
620
+ return [data];
621
+ });
622
+ Schema.extend("never", (data, _, options) => {
623
+ throw new ValidationError(`expected nullable but got ${data}`, options);
624
+ });
625
+ Schema.extend("const", (data, { value }, options) => {
626
+ if (deepEqual(data, value)) return [value];
627
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
628
+ });
629
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
630
+ const { max = Infinity, min = -Infinity } = meta;
631
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
632
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
633
+ }
634
+ Schema.extend("string", (data, { meta }, options) => {
635
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
636
+ if (meta.pattern) {
637
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
638
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
639
+ }
640
+ checkWithinRange(data.length, meta, "string length", options);
641
+ return [data];
642
+ });
643
+ function decimalShift(data, digits) {
644
+ const str = data.toString();
645
+ if (str.includes("e")) return data * Math.pow(10, digits);
646
+ const index = str.indexOf(".");
647
+ if (index === -1) return data * Math.pow(10, digits);
648
+ const frac = str.slice(index + 1);
649
+ const integer = str.slice(0, index);
650
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
651
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
652
+ }
653
+ function isMultipleOf(data, min, step) {
654
+ step = Math.abs(step);
655
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
656
+ const index = step.toString().indexOf(".");
657
+ const digits = step.toString().slice(index + 1).length;
658
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
659
+ }
660
+ Schema.extend("number", (data, { meta }, options) => {
661
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
662
+ checkWithinRange(data, meta, "number", options);
663
+ const { step } = meta;
664
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
665
+ return [data];
666
+ });
667
+ Schema.extend("boolean", (data, _, options) => {
668
+ if (typeof data === "boolean") return [data];
669
+ throw new ValidationError(`expected boolean but got ${data}`, options);
670
+ });
671
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
672
+ let value = 0, keys = [];
673
+ if (typeof data === "number") {
674
+ value = data;
675
+ for (const key in bits) if (data & bits[key]) keys.push(key);
676
+ } else if (Array.isArray(data)) {
677
+ keys = data;
678
+ for (const key of keys) {
679
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
680
+ if (key in bits) value |= bits[key];
681
+ }
682
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
683
+ if (value === meta.default) return [value];
684
+ return [value, keys];
685
+ });
686
+ Schema.extend("function", (data, _, options) => {
687
+ if (typeof data === "function") return [data];
688
+ throw new ValidationError(`expected function but got ${data}`, options);
689
+ });
690
+ Schema.extend("is", (data, { constructor }, options) => {
691
+ if (typeof constructor === "function") {
692
+ if (data instanceof constructor) return [data];
693
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
694
+ } else {
695
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
696
+ let prototype = Object.getPrototypeOf(data);
697
+ while (prototype) {
698
+ if (prototype.constructor?.name === constructor) return [data];
699
+ prototype = Object.getPrototypeOf(prototype);
700
+ }
701
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
702
+ }
703
+ });
704
+ function property(data, key, schema, options) {
705
+ try {
706
+ const [value, adapted] = Schema.resolve(data[key], schema, {
707
+ ...options,
708
+ path: [...options.path || [], key]
709
+ });
710
+ if (adapted !== void 0) data[key] = adapted;
711
+ return value;
712
+ } catch (e) {
713
+ if (!options?.autofix) throw e;
714
+ delete data[key];
715
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
716
+ }
717
+ }
718
+ Schema.extend("array", (data, { inner, meta }, options) => {
719
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
720
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
721
+ return [data.map((_, index) => property(data, index, inner, options))];
722
+ });
723
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
724
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
725
+ const result = {};
726
+ for (const key in data) {
727
+ let rKey;
728
+ try {
729
+ rKey = Schema.resolve(key, sKey, options)[0];
730
+ } catch (error) {
731
+ if (strict) continue;
732
+ throw error;
733
+ }
734
+ result[rKey] = property(data, key, inner, options);
735
+ data[rKey] = data[key];
736
+ if (key !== rKey) delete data[key];
737
+ }
738
+ return [result];
739
+ });
740
+ Schema.extend("tuple", (data, { list }, options, strict) => {
741
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
742
+ const result = list.map((inner, index) => property(data, index, inner, options));
743
+ if (strict) return [result];
744
+ result.push(...data.slice(list.length));
745
+ return [result];
746
+ });
747
+ function merge(result, data) {
748
+ for (const key in data) {
749
+ if (key in result) continue;
750
+ result[key] = data[key];
751
+ }
752
+ }
753
+ Schema.extend("object", (data, { dict }, options, strict) => {
754
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
755
+ const result = {};
756
+ for (const key in dict) {
757
+ const value = property(data, key, dict[key], options);
758
+ if (!isNullable(value) || key in data) result[key] = value;
759
+ }
760
+ if (!strict) merge(result, data);
761
+ return [result];
762
+ });
763
+ Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
764
+ const messages = [];
765
+ for (const inner of list) try {
766
+ return Schema.resolve(data, inner, options, strict);
767
+ } catch (error) {
768
+ messages.push(error);
769
+ }
770
+ throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
771
+ });
772
+ Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
773
+ if (!list.length) return [data];
774
+ let result;
775
+ for (const inner of list) {
776
+ const value = Schema.resolve(data, inner, options, true)[0];
777
+ if (isNullable(value)) continue;
778
+ if (isNullable(result)) result = value;
779
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
780
+ else if (typeof value === "object") merge(result ??= {}, value);
781
+ else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
782
+ }
783
+ if (!strict && isPlainObject(data)) merge(result, data);
784
+ return [result];
785
+ });
786
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
787
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
788
+ if (preserve) return [callback(result)];
789
+ else return [callback(result), callback(adapted)];
790
+ });
791
+ var formatters = {};
792
+ function defineMethod(name2, keys, format) {
793
+ formatters[name2] = format;
794
+ Object.assign(Schema, { [name2](...args) {
795
+ const schema = new Schema({ type: name2 });
796
+ keys.forEach((key, index) => {
797
+ switch (key) {
798
+ case "sKey":
799
+ schema.sKey = args[index] ?? Schema.string();
800
+ break;
801
+ case "inner":
802
+ schema.inner = Schema.from(args[index]);
803
+ break;
804
+ case "list":
805
+ schema.list = args[index].map(Schema.from);
806
+ break;
807
+ case "dict":
808
+ schema.dict = mapValues(args[index], Schema.from);
809
+ break;
810
+ case "bits":
811
+ schema.bits = {};
812
+ for (const key2 in args[index]) {
813
+ if (typeof args[index][key2] !== "number") continue;
814
+ schema.bits[key2] = args[index][key2];
815
+ }
816
+ break;
817
+ case "callback": {
818
+ const callback = schema.callback = args[index];
819
+ callback["toJSON"] ||= () => callback.toString();
820
+ break;
821
+ }
822
+ case "constructor": {
823
+ const constructor = schema.constructor = args[index];
824
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
825
+ break;
826
+ }
827
+ default:
828
+ schema[key] = args[index];
829
+ }
830
+ });
831
+ if (name2 === "object" || name2 === "dict") schema.meta.default = {};
832
+ else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
833
+ else if (name2 === "bitset") schema.meta.default = 0;
834
+ return schema;
835
+ } });
836
+ }
837
+ defineMethod("is", ["constructor"], ({ constructor }) => {
838
+ if (typeof constructor === "function") return constructor.name;
839
+ else return constructor;
840
+ });
841
+ defineMethod("any", [], () => "any");
842
+ defineMethod("never", [], () => "never");
843
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
844
+ defineMethod("string", [], () => "string");
845
+ defineMethod("number", [], () => "number");
846
+ defineMethod("boolean", [], () => "boolean");
847
+ defineMethod("bitset", ["bits"], () => "bitset");
848
+ defineMethod("function", [], () => "function");
849
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
850
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
851
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
852
+ defineMethod("object", ["dict"], ({ dict }) => {
853
+ if (Object.keys(dict).length === 0) return "{}";
854
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
855
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
856
+ }).join(", ")} }`;
857
+ });
858
+ defineMethod("union", ["list"], ({ list }, inline) => {
859
+ const result = list.map(({ toString: format }) => format()).join(" | ");
860
+ return inline ? `(${result})` : result;
861
+ });
862
+ defineMethod("intersect", ["list"], ({ list }) => {
863
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
864
+ });
865
+ defineMethod("transform", [
866
+ "inner",
867
+ "callback",
868
+ "preserve"
869
+ ], ({ inner }, isInner) => inner.toString(isInner));
870
+
871
+ // ../arnict-core/dist/auth.js
872
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
873
+ import { homedir } from "node:os";
874
+ import { dirname, join } from "node:path";
875
+
876
+ // ../arnict-core/dist/errors.js
877
+ var ARNICT_LOGIN_MESSAGE = "Arnict API key not found. Set ARNICT_API_KEY or run `ns-bridge arnict login`.";
878
+ var ArnictAuthError = class extends Error {
879
+ constructor(message = ARNICT_LOGIN_MESSAGE) {
880
+ super(message);
881
+ this.name = "ArnictAuthError";
882
+ }
883
+ };
884
+ var ArnictApiError = class extends Error {
885
+ status;
886
+ code;
887
+ constructor(message, status, code) {
888
+ super(message);
889
+ this.name = "ArnictApiError";
890
+ this.status = status;
891
+ this.code = code;
892
+ }
893
+ };
894
+ var BEARER_PATTERN = /Bearer\s+\S+/gi;
895
+ function redact(text, apiKey) {
896
+ let out = text.replace(BEARER_PATTERN, "Bearer [redacted]");
897
+ if (apiKey && apiKey.length >= 8)
898
+ out = out.split(apiKey).join("[redacted]");
899
+ return out;
900
+ }
901
+ async function arnictApiErrorFromResponse(response, apiKey) {
902
+ let text = "";
903
+ try {
904
+ text = await response.text();
905
+ } catch {
906
+ text = "";
907
+ }
908
+ let message = "";
909
+ let code;
910
+ try {
911
+ const parsed = JSON.parse(text);
912
+ if (typeof parsed.error === "string") {
913
+ message = parsed.error;
914
+ } else if (parsed.error) {
915
+ message = parsed.error.message ?? parsed.error.type ?? "";
916
+ code = parsed.error.code;
917
+ if (parsed.error.param)
918
+ message += ` (param: ${parsed.error.param})`;
919
+ } else {
920
+ message = parsed.message ?? "";
921
+ }
922
+ } catch {
923
+ message = "";
924
+ }
925
+ const redactedMessage = redact(message, apiKey).slice(0, 300);
926
+ const body = redactedMessage || redact(text, apiKey).replace(/\s+/g, " ").trim().slice(0, 300) || "no response body";
927
+ const requestId = redact(response.headers.get("x-request-id")?.trim() ?? "", apiKey);
928
+ const codeSuffix = code ? ` ${redact(code, apiKey)}` : "";
929
+ return new ArnictApiError(`Arnict error (${response.status}${codeSuffix}): ${body}${requestId ? ` [request id: ${requestId}]` : ""}`, response.status, code);
930
+ }
931
+
932
+ // ../arnict-core/dist/auth.js
933
+ var ARNICT_API_KEY_ENV = "ARNICT_API_KEY";
934
+ var ARNICT_CONFIG_PATH_ENV = "NS_BRIDGE_ARNICT_CONFIG";
935
+ function arnictConfigPath(home = homedir(), env = process.env) {
936
+ const override = env[ARNICT_CONFIG_PATH_ENV]?.trim();
937
+ if (override)
938
+ return override;
939
+ return join(home, ".ns-bridge", "arnict.json");
940
+ }
941
+ async function configApiKey(path, read) {
942
+ let raw;
943
+ try {
944
+ raw = await read(path);
945
+ } catch {
946
+ return void 0;
947
+ }
948
+ try {
949
+ const parsed = JSON.parse(raw);
950
+ const key = typeof parsed?.apiKey === "string" ? parsed.apiKey.trim() : "";
951
+ return key || void 0;
952
+ } catch {
953
+ return void 0;
954
+ }
955
+ }
956
+ async function resolveArnictApiKey(options = {}) {
957
+ const env = options.env ?? process.env;
958
+ const fromEnv = env[ARNICT_API_KEY_ENV]?.trim();
959
+ if (fromEnv)
960
+ return { apiKey: fromEnv, source: "env" };
961
+ const path = options.configPath ?? arnictConfigPath(homedir(), env);
962
+ const read = options.readFile ?? ((file) => readFile(file, "utf8"));
963
+ const fromConfig = await configApiKey(path, read);
964
+ if (fromConfig)
965
+ return { apiKey: fromConfig, source: "config" };
966
+ return void 0;
967
+ }
968
+ async function loadArnictApiKey(options = {}) {
969
+ const resolved = await resolveArnictApiKey(options);
970
+ if (!resolved)
971
+ throw new ArnictAuthError(ARNICT_LOGIN_MESSAGE);
972
+ return resolved;
973
+ }
974
+
975
+ // ../arnict-core/dist/catalog.js
976
+ import { readFileSync as readFileSync2 } from "node:fs";
977
+ import { join as join3 } from "node:path";
978
+
979
+ // ../core-utils/dist/compaction.js
980
+ var COMPACTION_RESERVE_FLOOR = 16384;
981
+ function compactionBudget(model) {
982
+ const { contextWindow, maxTokens } = model;
983
+ if (!Number.isFinite(contextWindow) || contextWindow <= 0)
984
+ return void 0;
985
+ if (!Number.isFinite(maxTokens) || maxTokens <= 0)
986
+ return void 0;
987
+ const ceiling = Math.floor(maxTokens);
988
+ const reserveTokens = contextWindow <= COMPACTION_RESERVE_FLOOR ? ceiling : Math.max(1, Math.min(ceiling, COMPACTION_RESERVE_FLOOR));
989
+ return { reserveTokens, thresholdTokens: contextWindow - reserveTokens };
990
+ }
991
+
992
+ // ../core-utils/dist/retry.js
993
+ function parseRetryAfterMs(headers, nowMs = Date.now()) {
994
+ const get = headers?.get?.bind(headers);
995
+ if (!get)
996
+ return void 0;
997
+ const milliseconds = nonNegativeNumber(get("retry-after-ms"));
998
+ if (milliseconds !== void 0)
999
+ return Math.round(milliseconds);
1000
+ const retryAfter = get("retry-after");
1001
+ if (retryAfter !== null && retryAfter.trim() !== "") {
1002
+ const seconds = Number(retryAfter);
1003
+ if (Number.isFinite(seconds)) {
1004
+ if (seconds >= 0) {
1005
+ const delayMs = seconds * 1e3;
1006
+ if (Number.isFinite(delayMs))
1007
+ return Math.round(delayMs);
1008
+ }
1009
+ } else {
1010
+ const dateMs = Date.parse(retryAfter);
1011
+ if (!Number.isNaN(dateMs))
1012
+ return Math.max(0, dateMs - nowMs);
1013
+ }
1014
+ }
1015
+ const resetAfterSeconds = nonNegativeNumber(get("x-ratelimit-reset-after"));
1016
+ if (resetAfterSeconds !== void 0) {
1017
+ const delayMs = resetAfterSeconds * 1e3;
1018
+ if (Number.isFinite(delayMs))
1019
+ return Math.round(delayMs);
1020
+ }
1021
+ return void 0;
1022
+ }
1023
+ function exponentialBackoff(attempt, baseMs, maxMs) {
1024
+ return Math.min(baseMs * 2 ** attempt, maxMs);
1025
+ }
1026
+ function nonNegativeNumber(value) {
1027
+ if (value === null || value.trim() === "")
1028
+ return void 0;
1029
+ const parsed = Number(value);
1030
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
1031
+ }
1032
+
1033
+ // ../core-utils/dist/timing.js
1034
+ function abortableDelay(ms, signal) {
1035
+ if (signal?.aborted)
1036
+ return Promise.reject(signal.reason);
1037
+ return new Promise((resolve2, reject) => {
1038
+ const onAbort = () => {
1039
+ clearTimeout(timer);
1040
+ signal?.removeEventListener("abort", onAbort);
1041
+ reject(signal?.reason);
1042
+ };
1043
+ const timer = setTimeout(() => {
1044
+ signal?.removeEventListener("abort", onAbort);
1045
+ resolve2();
1046
+ }, ms);
1047
+ signal?.addEventListener("abort", onAbort, { once: true });
1048
+ });
1049
+ }
1050
+
1051
+ // ../core-utils/dist/usage-ledger.js
1052
+ import { createHash } from "node:crypto";
1053
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
1054
+ import { homedir as homedir2 } from "node:os";
1055
+ import { join as join2 } from "node:path";
1056
+ var USAGE_RETENTION_DAYS = 30;
1057
+ var USAGE_MAX_BYTES = 50 * 1024 * 1024;
1058
+ var NO_SESSION_FILE = "_no-session";
1059
+ var MAX_TRACKED_SESSIONS = 256;
1060
+ var HOST_KEY = /* @__PURE__ */ Symbol.for("ns-bridge.usage.host");
1061
+ function setUsageHost(host) {
1062
+ const holder = globalThis;
1063
+ if (holder[HOST_KEY] === void 0)
1064
+ holder[HOST_KEY] = host;
1065
+ }
1066
+ function getUsageHost() {
1067
+ return globalThis[HOST_KEY] ?? "unknown";
1068
+ }
1069
+ function usageRecordingEnabled(env = process.env) {
1070
+ const flag = env.NS_BRIDGE_USAGE?.trim().toLowerCase();
1071
+ return !(flag === "0" || flag === "false" || flag === "off");
1072
+ }
1073
+ function usageRoot(env = process.env) {
1074
+ return env.NS_BRIDGE_USAGE_DIR?.trim() || join2(homedir2(), ".ns-bridge", "usage");
1075
+ }
1076
+ function usageDay(at) {
1077
+ const date2 = new Date(at);
1078
+ const month = String(date2.getMonth() + 1).padStart(2, "0");
1079
+ const day = String(date2.getDate()).padStart(2, "0");
1080
+ return `${date2.getFullYear()}-${month}-${day}`;
1081
+ }
1082
+ function usageFileName(sessionId) {
1083
+ const id = sessionId?.trim();
1084
+ if (!id)
1085
+ return NO_SESSION_FILE;
1086
+ if (/^[A-Za-z0-9_-]{1,80}$/.test(id))
1087
+ return id;
1088
+ return `h-${createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
1089
+ }
1090
+ function ratio(part, whole) {
1091
+ if (part === void 0 || whole <= 0)
1092
+ return null;
1093
+ return part / whole;
1094
+ }
1095
+ function providerUsage(usage) {
1096
+ if (!usage.cacheEstimated && usage.cacheDerived === void 0)
1097
+ return usage;
1098
+ const { cacheRead, cacheEstimated: _guess, cacheDerived: _derived, ...rest } = usage;
1099
+ return { ...rest, input: usage.input + (cacheRead ?? 0) };
1100
+ }
1101
+ function isUsage(value) {
1102
+ if (!value || typeof value !== "object")
1103
+ return false;
1104
+ const usage = value;
1105
+ return typeof usage.input === "number" && typeof usage.output === "number";
1106
+ }
1107
+ function buildUsageRecord(input) {
1108
+ const { context } = input;
1109
+ let usage = providerUsage(input.usage);
1110
+ const promptTokens = usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
1111
+ let cacheHitMax;
1112
+ let cacheSource = usage.cacheRead !== void 0 || usage.cacheWrite !== void 0 ? "wire" : "none";
1113
+ if (cacheSource === "none" && context.deriveCache) {
1114
+ let derived;
1115
+ try {
1116
+ derived = context.deriveCache({
1117
+ promptTokens,
1118
+ outputTokens: usage.output,
1119
+ credits: usage.credits,
1120
+ creditUnit: usage.creditUnit
1121
+ });
1122
+ } catch {
1123
+ derived = void 0;
1124
+ }
1125
+ if (derived?.exact) {
1126
+ cacheSource = "credits";
1127
+ usage = { ...usage, input: promptTokens - derived.cacheRead, cacheRead: derived.cacheRead };
1128
+ } else if (derived) {
1129
+ cacheSource = "credits-capped";
1130
+ cacheHitMax = derived.maxRatio;
1131
+ }
1132
+ }
1133
+ const hasCache = cacheSource === "wire" || cacheSource === "credits";
1134
+ const contextFill = context.contextWindow !== void 0 && context.contextWindow > 0 ? promptTokens / context.contextWindow : null;
1135
+ return {
1136
+ ts: new Date(input.at).toISOString(),
1137
+ vendor: context.vendor,
1138
+ host: input.host,
1139
+ model: context.model,
1140
+ session: context.sessionId?.trim() || null,
1141
+ step: input.step,
1142
+ gapMs: input.gapMs,
1143
+ ms: input.ms,
1144
+ input: usage.input,
1145
+ output: usage.output,
1146
+ total: usage.totalTokens,
1147
+ promptTokens,
1148
+ ...usage.cacheRead !== void 0 ? { cacheRead: usage.cacheRead } : {},
1149
+ ...usage.cacheWrite !== void 0 ? { cacheWrite: usage.cacheWrite } : {},
1150
+ cacheHitRatio: hasCache ? ratio(usage.cacheRead ?? 0, promptTokens) : null,
1151
+ cacheWriteRatio: cacheSource === "wire" ? ratio(usage.cacheWrite, promptTokens) : null,
1152
+ cacheSource,
1153
+ ...cacheHitMax !== void 0 ? { cacheHitMax } : {},
1154
+ ...usage.credits !== void 0 ? { credits: usage.credits } : {},
1155
+ ...usage.creditUnit !== void 0 ? { creditUnit: usage.creditUnit } : {},
1156
+ ...context.contextWindow !== void 0 ? { contextWindow: context.contextWindow } : {},
1157
+ ...contextFill !== null ? { contextFill } : {},
1158
+ ...usage.contextPercent !== void 0 ? { contextPercent: usage.contextPercent } : {},
1159
+ ...context.effort ? { effort: context.effort } : {},
1160
+ ...input.stop ? { stop: input.stop } : {}
1161
+ };
1162
+ }
1163
+ var sessions = /* @__PURE__ */ new Map();
1164
+ var lastPrunedDay;
1165
+ var failedWrites = 0;
1166
+ function resumeFromDisk(path) {
1167
+ try {
1168
+ const lines = readFileSync(path, "utf8").split("\n").filter((line) => line.trim());
1169
+ if (lines.length === 0)
1170
+ return void 0;
1171
+ const last = JSON.parse(lines[lines.length - 1]);
1172
+ const endedAt = typeof last.ts === "string" ? Date.parse(last.ts) : Number.NaN;
1173
+ return { step: lines.length, lastEndedAt: Number.isFinite(endedAt) ? endedAt : Number.NaN };
1174
+ } catch {
1175
+ return void 0;
1176
+ }
1177
+ }
1178
+ function nextStep(vendor, sessionId, now, env) {
1179
+ const id = sessionId?.trim();
1180
+ if (!id)
1181
+ return { step: null, gapMs: null };
1182
+ const key = `${vendor}\0${id}`;
1183
+ const previous = sessions.get(key) ?? resumeFromDisk(join2(usageRoot(env), usageDay(now), usageFileName(vendor), `${usageFileName(id)}.jsonl`));
1184
+ const state = { step: (previous?.step ?? 0) + 1, lastEndedAt: now };
1185
+ sessions.delete(key);
1186
+ sessions.set(key, state);
1187
+ if (sessions.size > MAX_TRACKED_SESSIONS) {
1188
+ const oldest = sessions.keys().next().value;
1189
+ if (oldest !== void 0)
1190
+ sessions.delete(oldest);
1191
+ }
1192
+ const gapMs = previous && Number.isFinite(previous.lastEndedAt) ? Math.max(0, now - previous.lastEndedAt) : null;
1193
+ return { step: state.step, gapMs };
1194
+ }
1195
+ function dirBytes(path) {
1196
+ let total = 0;
1197
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
1198
+ const child = join2(path, entry.name);
1199
+ total += entry.isDirectory() ? dirBytes(child) : statSync(child).size;
1200
+ }
1201
+ return total;
1202
+ }
1203
+ function pruneUsage(root, options = {}) {
1204
+ const now = options.now ?? Date.now();
1205
+ const maxAgeDays = options.maxAgeDays ?? USAGE_RETENTION_DAYS;
1206
+ const maxBytes = options.maxBytes ?? USAGE_MAX_BYTES;
1207
+ const removed = [];
1208
+ let days;
1209
+ try {
1210
+ days = readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory() && /^\d{4}-\d{2}-\d{2}$/.test(entry.name)).map((entry) => entry.name).sort();
1211
+ } catch {
1212
+ return removed;
1213
+ }
1214
+ const cutoff = usageDay(now - maxAgeDays * 864e5);
1215
+ const drop = (day) => {
1216
+ rmSync(join2(root, day), { recursive: true, force: true });
1217
+ removed.push(day);
1218
+ };
1219
+ while (days.length > 1 && days[0] < cutoff)
1220
+ drop(days.shift());
1221
+ const sizes = new Map(days.map((day) => [day, dirBytes(join2(root, day))]));
1222
+ let total = [...sizes.values()].reduce((sum, bytes) => sum + bytes, 0);
1223
+ while (days.length > 1 && total > maxBytes) {
1224
+ const oldest = days.shift();
1225
+ total -= sizes.get(oldest) ?? 0;
1226
+ drop(oldest);
1227
+ }
1228
+ return removed;
1229
+ }
1230
+ function writeUsageRecord(record, at, env = process.env) {
1231
+ try {
1232
+ const root = usageRoot(env);
1233
+ const day = usageDay(at);
1234
+ if (lastPrunedDay !== day) {
1235
+ lastPrunedDay = day;
1236
+ try {
1237
+ pruneUsage(root, { now: at });
1238
+ } catch {
1239
+ }
1240
+ }
1241
+ const dir = join2(root, day, usageFileName(record.vendor));
1242
+ mkdirSync(dir, { recursive: true });
1243
+ appendFileSync(join2(dir, `${usageFileName(record.session ?? void 0)}.jsonl`), `${JSON.stringify(record)}
1244
+ `);
1245
+ } catch {
1246
+ failedWrites++;
1247
+ }
1248
+ }
1249
+ async function* recordUsage(events, context) {
1250
+ const startedAt = Date.now();
1251
+ let usage;
1252
+ let stop;
1253
+ try {
1254
+ for await (const event of events) {
1255
+ const candidate = event;
1256
+ if (event.type === "usage" && isUsage(candidate.usage))
1257
+ usage = candidate.usage;
1258
+ else if (event.type === "done" && typeof candidate.stopReason === "string")
1259
+ stop = candidate.stopReason;
1260
+ yield event;
1261
+ }
1262
+ } finally {
1263
+ if (usage && usageRecordingEnabled()) {
1264
+ try {
1265
+ const now = Date.now();
1266
+ const { step, gapMs } = nextStep(context.vendor, context.sessionId, now, process.env);
1267
+ writeUsageRecord(buildUsageRecord({
1268
+ context,
1269
+ usage,
1270
+ host: getUsageHost(),
1271
+ at: now,
1272
+ ms: now - startedAt,
1273
+ step,
1274
+ gapMs,
1275
+ stop
1276
+ }), now);
1277
+ } catch {
1278
+ failedWrites++;
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+
1284
+ // ../arnict-core/dist/catalog.js
1285
+ var ARNICT_CATALOG_PROVIDER_ID = "arnict";
1286
+ var ARNICT_CATALOG_FILE = `${ARNICT_CATALOG_PROVIDER_ID}.models.json`;
1287
+ var ARNICT_CATALOG_CACHE_DIR_ENV = "NS_ARNICT_CATALOG_CACHE_DIR";
1288
+ function isArnictGlm53Id(id) {
1289
+ return /^zai\/glm-5\.3(?:[-.:/].*)?$/i.test(id);
1290
+ }
1291
+ var ARNICT_GLM_STANDARD_CONTEXT_WINDOW = 4e5;
1292
+ var ARNICT_KNOWN_MODELS = [
1293
+ {
1294
+ id: "zai/glm-5.3-flash-uncensored",
1295
+ name: "GLM 5.3 Flash Abliterated",
1296
+ contextWindow: ARNICT_GLM_STANDARD_CONTEXT_WINDOW,
1297
+ nativeContextWindow: 1048576,
1298
+ maxTokens: 131072,
1299
+ reasoning: true,
1300
+ input: ["text", "image"],
1301
+ rates: { input: 0.125, cachedInput: 0.05, output: 0.5 }
1302
+ },
1303
+ {
1304
+ id: "zai/glm-5.3-uncensored",
1305
+ name: "GLM 5.3 Abliterated",
1306
+ contextWindow: ARNICT_GLM_STANDARD_CONTEXT_WINDOW,
1307
+ nativeContextWindow: 1048576,
1308
+ maxTokens: 131072,
1309
+ reasoning: true,
1310
+ input: ["text"],
1311
+ rates: { input: 1.25, cachedInput: 0.3, output: 2.25 }
1312
+ }
1313
+ ];
1314
+ var ARNICT_DEFAULT_CONTEXT_WINDOW = 262144;
1315
+ var ARNICT_DEFAULT_MAX_TOKENS = 32768;
1316
+ var knownById = new Map(ARNICT_KNOWN_MODELS.map((model) => [model.id, model]));
1317
+ function glm53Spec(id, name2) {
1318
+ return {
1319
+ id,
1320
+ name: name2,
1321
+ contextWindow: ARNICT_GLM_STANDARD_CONTEXT_WINDOW,
1322
+ nativeContextWindow: 1048576,
1323
+ maxTokens: 131072,
1324
+ reasoning: true,
1325
+ input: ["text"]
1326
+ };
1327
+ }
1328
+ function arnictNativeContextWindow(id) {
1329
+ return knownById.get(id)?.nativeContextWindow ?? (isArnictGlm53Id(id) ? 1048576 : ARNICT_DEFAULT_CONTEXT_WINDOW);
1330
+ }
1331
+ function withArnictCompaction(model) {
1332
+ const budget = compactionBudget(model);
1333
+ return budget ? { ...model, compaction: budget } : model;
1334
+ }
1335
+ function arnictModelSpec(id) {
1336
+ const known = knownById.get(id);
1337
+ if (known)
1338
+ return withArnictCompaction(known);
1339
+ if (isArnictGlm53Id(id))
1340
+ return withArnictCompaction(glm53Spec(id, id));
1341
+ return withArnictCompaction({
1342
+ id,
1343
+ name: id,
1344
+ contextWindow: ARNICT_DEFAULT_CONTEXT_WINDOW,
1345
+ nativeContextWindow: ARNICT_DEFAULT_CONTEXT_WINDOW,
1346
+ maxTokens: ARNICT_DEFAULT_MAX_TOKENS,
1347
+ reasoning: false,
1348
+ input: ["text"]
1349
+ });
1350
+ }
1351
+ function arnictBootstrapModels() {
1352
+ return ARNICT_KNOWN_MODELS.map((model) => withArnictCompaction(model));
1353
+ }
1354
+ function arnictModelsFromCatalogJson(raw) {
1355
+ if (!raw?.trim())
1356
+ return arnictBootstrapModels();
1357
+ try {
1358
+ const parsed = JSON.parse(raw);
1359
+ if (!Array.isArray(parsed?.models))
1360
+ return arnictBootstrapModels();
1361
+ const models = [];
1362
+ for (const entry of parsed.models) {
1363
+ if (!entry || typeof entry !== "object")
1364
+ continue;
1365
+ const row = entry;
1366
+ if (typeof row.id !== "string" || row.id.length === 0)
1367
+ continue;
1368
+ const name2 = typeof row.name === "string" && row.name.length > 0 ? row.name : row.id;
1369
+ const known = knownById.get(row.id);
1370
+ if (!known && isArnictGlm53Id(row.id)) {
1371
+ models.push(withArnictCompaction(glm53Spec(row.id, name2)));
1372
+ continue;
1373
+ }
1374
+ const input = Array.isArray(row.input) ? row.input.filter((item) => item === "text" || item === "image") : ["text"];
1375
+ const contextWindow = known?.contextWindow ?? (typeof row.contextWindow === "number" ? row.contextWindow : ARNICT_DEFAULT_CONTEXT_WINDOW);
1376
+ models.push(withArnictCompaction({
1377
+ id: row.id,
1378
+ name: name2,
1379
+ contextWindow,
1380
+ nativeContextWindow: known?.nativeContextWindow ?? contextWindow,
1381
+ maxTokens: typeof row.maxTokens === "number" ? row.maxTokens : ARNICT_DEFAULT_MAX_TOKENS,
1382
+ reasoning: row.reasoning === true,
1383
+ input: input.length > 0 ? input : ["text"],
1384
+ rates: known?.rates
1385
+ }));
1386
+ }
1387
+ return models.length > 0 ? models : arnictBootstrapModels();
1388
+ } catch {
1389
+ return arnictBootstrapModels();
1390
+ }
1391
+ }
1392
+ function arnictCatalogPath(cacheDir) {
1393
+ return join3(cacheDir, ARNICT_CATALOG_FILE);
1394
+ }
1395
+ function readArnictCatalog(options) {
1396
+ const path = arnictCatalogPath(options.cacheDir);
1397
+ try {
1398
+ const read = options.readFile ?? ((file) => readFileSync2(file, "utf8"));
1399
+ return arnictModelsFromCatalogJson(read(path));
1400
+ } catch {
1401
+ return arnictModelsFromCatalogJson(void 0);
1402
+ }
1403
+ }
1404
+
1405
+ // ../arnict-core/dist/request.js
1406
+ function textOf(content) {
1407
+ return content.filter((part) => part.type === "text").map((part) => part.text).filter((text) => text.length > 0).join("\n");
1408
+ }
1409
+ function userContent(content) {
1410
+ const hasImages = content.some((part) => part.type === "image");
1411
+ if (!hasImages)
1412
+ return textOf(content);
1413
+ const parts = [];
1414
+ for (const part of content) {
1415
+ if (part.type === "text") {
1416
+ if (part.text)
1417
+ parts.push({ type: "text", text: part.text });
1418
+ } else if (part.data) {
1419
+ parts.push({ type: "image_url", image_url: { url: `data:${part.mimeType};base64,${part.data}` } });
1420
+ }
1421
+ }
1422
+ return parts;
1423
+ }
1424
+ function resultText(content) {
1425
+ return content.map((part) => part.type === "text" ? part.text : "[image omitted]").filter((text) => text.length > 0).join("\n");
1426
+ }
1427
+ function chatMessages(input) {
1428
+ const messages = [];
1429
+ const system = input.systemPrompt?.trim();
1430
+ if (system)
1431
+ messages.push({ role: "system", content: system });
1432
+ for (const message of input.messages) {
1433
+ if (message.role === "user") {
1434
+ const content = userContent(message.content);
1435
+ if (content.length > 0) {
1436
+ messages.push({ role: "user", content });
1437
+ }
1438
+ continue;
1439
+ }
1440
+ if (message.role === "assistant") {
1441
+ const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("");
1442
+ const toolCalls = message.content.filter((part) => part.type === "toolCall").map((part) => ({
1443
+ id: part.id,
1444
+ type: "function",
1445
+ function: { name: part.name, arguments: JSON.stringify(part.arguments ?? {}) }
1446
+ }));
1447
+ if (!text && toolCalls.length === 0)
1448
+ continue;
1449
+ messages.push({
1450
+ role: "assistant",
1451
+ content: text || null,
1452
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
1453
+ });
1454
+ continue;
1455
+ }
1456
+ messages.push({ role: "tool", tool_call_id: message.toolCallId, content: resultText(message.content) });
1457
+ }
1458
+ return messages;
1459
+ }
1460
+ function buildChatCompletionsBody(input) {
1461
+ const body = {
1462
+ model: input.model,
1463
+ messages: chatMessages(input),
1464
+ stream: true,
1465
+ stream_options: { include_usage: true }
1466
+ };
1467
+ if (input.maxTokens !== void 0)
1468
+ body.max_tokens = input.maxTokens;
1469
+ if (input.tools && input.tools.length > 0) {
1470
+ body.tools = input.tools.map((tool) => ({
1471
+ type: "function",
1472
+ function: { name: tool.name, description: tool.description, parameters: tool.parameters }
1473
+ }));
1474
+ }
1475
+ return body;
1476
+ }
1477
+
1478
+ // ../arnict-core/dist/usage.js
1479
+ function nonNegative(value) {
1480
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
1481
+ return 0;
1482
+ return value;
1483
+ }
1484
+ function toArnictUsage(usage, rates) {
1485
+ const prompt = nonNegative(usage.prompt_tokens);
1486
+ const cached = nonNegative(usage.prompt_tokens_details?.cached_tokens ?? usage.cached_tokens ?? usage.prompt_cache_hit_tokens);
1487
+ const cacheRead = Math.min(cached, prompt);
1488
+ const input = prompt - cacheRead;
1489
+ const output = nonNegative(usage.completion_tokens);
1490
+ const totalTokens = usage.total_tokens === void 0 ? input + cacheRead + output : nonNegative(usage.total_tokens);
1491
+ if (!rates) {
1492
+ return {
1493
+ input,
1494
+ output,
1495
+ totalTokens,
1496
+ cacheRead,
1497
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
1498
+ };
1499
+ }
1500
+ const costInput = input * rates.input / 1e6;
1501
+ const costCacheRead = cacheRead * rates.cachedInput / 1e6;
1502
+ const costOutput = output * rates.output / 1e6;
1503
+ const total = costInput + costCacheRead + costOutput;
1504
+ return {
1505
+ input,
1506
+ output,
1507
+ totalTokens,
1508
+ cacheRead,
1509
+ credits: total,
1510
+ creditUnit: "USD",
1511
+ cost: { input: costInput, output: costOutput, cacheRead: costCacheRead, cacheWrite: 0, total }
1512
+ };
1513
+ }
1514
+
1515
+ // ../arnict-core/dist/sse.js
1516
+ function createChatState(requestedModel) {
1517
+ return {
1518
+ requestedModel,
1519
+ nextIndex: 0,
1520
+ started: false,
1521
+ settled: false,
1522
+ sawTool: false,
1523
+ sawFinishReason: false,
1524
+ stopReason: "stop",
1525
+ tools: /* @__PURE__ */ new Map()
1526
+ };
1527
+ }
1528
+ function ensureStart(state, events) {
1529
+ if (state.started)
1530
+ return;
1531
+ state.started = true;
1532
+ events.push({ type: "start" });
1533
+ }
1534
+ function closeBlock(block) {
1535
+ if (block.closed)
1536
+ return void 0;
1537
+ block.closed = true;
1538
+ if (block.kind === "thinking")
1539
+ return { type: "thinking_end", index: block.index, thinking: block.text };
1540
+ if (block.kind === "text")
1541
+ return { type: "text_end", index: block.index, text: block.text };
1542
+ const argumentsJson = block.text.trim() ? block.text : "{}";
1543
+ let arguments_ = {};
1544
+ try {
1545
+ const parsed = JSON.parse(argumentsJson);
1546
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1547
+ arguments_ = parsed;
1548
+ }
1549
+ } catch {
1550
+ }
1551
+ return {
1552
+ type: "tool_call_end",
1553
+ index: block.index,
1554
+ id: block.id,
1555
+ name: block.name,
1556
+ arguments: arguments_,
1557
+ argumentsJson
1558
+ };
1559
+ }
1560
+ function closeTextAndThinking(state, events) {
1561
+ for (const block of [state.openText, state.openThinking]) {
1562
+ if (!block)
1563
+ continue;
1564
+ const event = closeBlock(block);
1565
+ if (event)
1566
+ events.push(event);
1567
+ }
1568
+ }
1569
+ function closeTools(state, events) {
1570
+ const ordered = [...state.tools.entries()].sort((left, right) => left[0] - right[0]);
1571
+ for (const [, block] of ordered) {
1572
+ const event = closeBlock(block);
1573
+ if (event)
1574
+ events.push(event);
1575
+ }
1576
+ }
1577
+ function mapFinishReason(reason) {
1578
+ if (reason === "length")
1579
+ return "length";
1580
+ if (reason === "tool_calls" || reason === "function_call")
1581
+ return "toolUse";
1582
+ return "stop";
1583
+ }
1584
+ function toolCallEvents(state, calls) {
1585
+ const events = [];
1586
+ calls.forEach((call, position) => {
1587
+ const key = typeof call.index === "number" ? call.index : position;
1588
+ let block = state.tools.get(key);
1589
+ if (!block) {
1590
+ closeTextAndThinking(state, events);
1591
+ block = {
1592
+ kind: "tool",
1593
+ index: state.nextIndex,
1594
+ id: call.id ?? "",
1595
+ name: call.function?.name ?? "",
1596
+ text: "",
1597
+ closed: false
1598
+ };
1599
+ state.nextIndex += 1;
1600
+ state.tools.set(key, block);
1601
+ state.sawTool = true;
1602
+ ensureStart(state, events);
1603
+ events.push({ type: "tool_call_start", index: block.index, id: block.id, name: block.name });
1604
+ } else {
1605
+ if (call.id)
1606
+ block.id = call.id;
1607
+ if (call.function?.name)
1608
+ block.name = call.function.name;
1609
+ }
1610
+ const delta = call.function?.arguments;
1611
+ if (delta) {
1612
+ block.text += delta;
1613
+ events.push({ type: "tool_call_delta", index: block.index, id: block.id, argumentsDelta: delta });
1614
+ }
1615
+ });
1616
+ return events;
1617
+ }
1618
+ function reduceChatChunk(state, chunk) {
1619
+ if (state.settled)
1620
+ return [];
1621
+ const events = [];
1622
+ if (chunk.id)
1623
+ state.responseId = chunk.id;
1624
+ if (chunk.model)
1625
+ state.upstreamModel = chunk.model;
1626
+ if (chunk.usage)
1627
+ state.usage = chunk.usage;
1628
+ const choice = chunk.choices?.[0];
1629
+ if (!choice)
1630
+ return events;
1631
+ const delta = choice.delta ?? {};
1632
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
1633
+ if (reasoning) {
1634
+ if (!state.openThinking || state.openThinking.closed) {
1635
+ closeTextAndThinking(state, events);
1636
+ state.openThinking = {
1637
+ kind: "thinking",
1638
+ index: state.nextIndex,
1639
+ id: "",
1640
+ name: "",
1641
+ text: "",
1642
+ closed: false
1643
+ };
1644
+ state.nextIndex += 1;
1645
+ ensureStart(state, events);
1646
+ events.push({ type: "thinking_start", index: state.openThinking.index });
1647
+ }
1648
+ state.openThinking.text += reasoning;
1649
+ events.push({ type: "thinking_delta", index: state.openThinking.index, delta: reasoning });
1650
+ }
1651
+ if (delta.content) {
1652
+ if (!state.openText || state.openText.closed) {
1653
+ closeTextAndThinking(state, events);
1654
+ state.openText = { kind: "text", index: state.nextIndex, id: "", name: "", text: "", closed: false };
1655
+ state.nextIndex += 1;
1656
+ ensureStart(state, events);
1657
+ events.push({ type: "text_start", index: state.openText.index });
1658
+ }
1659
+ state.openText.text += delta.content;
1660
+ events.push({ type: "text_delta", index: state.openText.index, delta: delta.content });
1661
+ }
1662
+ if (delta.tool_calls && delta.tool_calls.length > 0)
1663
+ events.push(...toolCallEvents(state, delta.tool_calls));
1664
+ if (choice.finish_reason) {
1665
+ state.sawFinishReason = true;
1666
+ state.stopReason = mapFinishReason(choice.finish_reason);
1667
+ closeTextAndThinking(state, events);
1668
+ closeTools(state, events);
1669
+ }
1670
+ return events;
1671
+ }
1672
+ function finishChat(state) {
1673
+ if (state.settled)
1674
+ return [];
1675
+ state.settled = true;
1676
+ const events = [];
1677
+ closeTextAndThinking(state, events);
1678
+ closeTools(state, events);
1679
+ if (state.sawTool)
1680
+ state.stopReason = "toolUse";
1681
+ if (state.usage) {
1682
+ events.push({
1683
+ type: "usage",
1684
+ usage: toArnictUsage(state.usage, arnictModelSpec(state.requestedModel).rates)
1685
+ });
1686
+ }
1687
+ events.push({
1688
+ type: "done",
1689
+ stopReason: state.stopReason,
1690
+ ...state.sawFinishReason ? {} : { errorMessage: "Arnict stream ended early" },
1691
+ ...state.responseId ? { responseId: state.responseId } : {},
1692
+ ...state.upstreamModel ? { upstreamModel: state.upstreamModel } : {}
1693
+ });
1694
+ return events;
1695
+ }
1696
+ function chatCompletionChunks(completion) {
1697
+ const choice = completion.choices?.[0];
1698
+ const message = choice?.message;
1699
+ const reasoning = message?.reasoning_content ?? message?.reasoning;
1700
+ const content = message?.content ?? "";
1701
+ const toolCalls = (message?.tool_calls ?? []).map((call, index) => ({
1702
+ index,
1703
+ id: call.id,
1704
+ type: call.type,
1705
+ function: { name: call.function?.name, arguments: call.function?.arguments ?? "" }
1706
+ }));
1707
+ return [
1708
+ {
1709
+ id: completion.id,
1710
+ model: completion.model,
1711
+ choices: [
1712
+ {
1713
+ delta: {
1714
+ ...reasoning ? { reasoning_content: reasoning } : {},
1715
+ ...content ? { content } : {},
1716
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
1717
+ }
1718
+ }
1719
+ ]
1720
+ },
1721
+ {
1722
+ id: completion.id,
1723
+ model: completion.model,
1724
+ choices: [{ delta: {}, finish_reason: choice?.finish_reason ?? "stop" }],
1725
+ usage: completion.usage
1726
+ }
1727
+ ];
1728
+ }
1729
+ function sseData(frame) {
1730
+ const dataLines = [];
1731
+ for (const line of frame.split(/\r?\n/)) {
1732
+ if (!line.startsWith("data:"))
1733
+ continue;
1734
+ dataLines.push(line.slice("data:".length).replace(/^ /, ""));
1735
+ }
1736
+ if (dataLines.length === 0)
1737
+ return void 0;
1738
+ return dataLines.join("\n");
1739
+ }
1740
+ async function* parseSseData(chunks) {
1741
+ const decoder = new TextDecoder();
1742
+ let buffer = "";
1743
+ const emit = function* (frame) {
1744
+ const data = sseData(frame);
1745
+ if (data === void 0 || data.trim() === "[DONE]")
1746
+ return;
1747
+ let parsed;
1748
+ try {
1749
+ parsed = JSON.parse(data);
1750
+ } catch {
1751
+ throw new ArnictApiError("Arnict chat stream was not JSON");
1752
+ }
1753
+ if (parsed && typeof parsed === "object")
1754
+ yield parsed;
1755
+ };
1756
+ for await (const chunk of chunks) {
1757
+ buffer += decoder.decode(chunk, { stream: true });
1758
+ const frames = buffer.split(/\r?\n\r?\n/);
1759
+ buffer = frames.pop() ?? "";
1760
+ for (const frame of frames) {
1761
+ const data = sseData(frame);
1762
+ if (data !== void 0 && data.trim() === "[DONE]")
1763
+ return;
1764
+ yield* emit(frame);
1765
+ }
1766
+ }
1767
+ buffer += decoder.decode();
1768
+ if (buffer.trim()) {
1769
+ const data = sseData(buffer);
1770
+ if (data !== void 0 && data.trim() === "[DONE]")
1771
+ return;
1772
+ yield* emit(buffer);
1773
+ }
1774
+ }
1775
+
1776
+ // ../arnict-core/dist/stream.js
1777
+ var ARNICT_BASE_URL_ENV = "ARNICT_BASE_URL";
1778
+ var ARNICT_DEFAULT_BASE_URL = "https://api.arnict.com/v1";
1779
+ function arnictBaseUrl(env = process.env) {
1780
+ return (env[ARNICT_BASE_URL_ENV]?.trim() || ARNICT_DEFAULT_BASE_URL).replace(/\/$/, "");
1781
+ }
1782
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
1783
+ var RETRY_BASE_MS = 500;
1784
+ var RETRY_MAX_MS = 8e3;
1785
+ function aborted() {
1786
+ const error = new Error("This operation was aborted");
1787
+ error.name = "AbortError";
1788
+ return error;
1789
+ }
1790
+ function isAbort(error, signal) {
1791
+ return signal?.aborted === true || error instanceof Error && error.name === "AbortError";
1792
+ }
1793
+ async function* readBody(body) {
1794
+ const reader = body.getReader();
1795
+ try {
1796
+ for (; ; ) {
1797
+ const { done, value } = await reader.read();
1798
+ if (done)
1799
+ return;
1800
+ if (value)
1801
+ yield value;
1802
+ }
1803
+ } finally {
1804
+ reader.releaseLock();
1805
+ }
1806
+ }
1807
+ async function* eventsFromChunks(chunks, requestedModel, signal) {
1808
+ const state = createChatState(requestedModel);
1809
+ for await (const chunk of chunks) {
1810
+ if (signal?.aborted)
1811
+ throw aborted();
1812
+ yield* reduceChatChunk(state, chunk);
1813
+ }
1814
+ if (signal?.aborted)
1815
+ throw aborted();
1816
+ yield* finishChat(state);
1817
+ }
1818
+ function streamArnict(options) {
1819
+ return recordUsage(streamArnictResponse(options), {
1820
+ vendor: "arnict",
1821
+ model: options.model,
1822
+ // The ledger fills against the window Arnict serves, not the smaller
1823
+ // standard window a host may compact inside.
1824
+ contextWindow: options.contextWindow ?? arnictNativeContextWindow(options.model),
1825
+ effort: options.effort,
1826
+ sessionId: options.sessionId
1827
+ });
1828
+ }
1829
+ async function* streamArnictResponse(options) {
1830
+ if (options.signal?.aborted)
1831
+ throw aborted();
1832
+ const fetchImpl = options.fetchImpl ?? fetch;
1833
+ const apiKey = options.apiKey ?? (await loadArnictApiKey()).apiKey;
1834
+ const base = (options.baseUrl ?? arnictBaseUrl()).replace(/\/$/, "");
1835
+ const maxRetries = options.maxRetries ?? 2;
1836
+ const sleep = options.sleep ?? ((ms) => abortableDelay(ms, options.signal));
1837
+ const body = buildChatCompletionsBody({
1838
+ model: options.model,
1839
+ systemPrompt: options.systemPrompt,
1840
+ messages: options.messages,
1841
+ tools: options.tools,
1842
+ maxTokens: options.maxTokens
1843
+ });
1844
+ for (let attempt = 0; ; attempt += 1) {
1845
+ let response;
1846
+ try {
1847
+ response = await fetchImpl(`${base}/chat/completions`, {
1848
+ method: "POST",
1849
+ headers: {
1850
+ "Content-Type": "application/json",
1851
+ Accept: "text/event-stream",
1852
+ Authorization: `Bearer ${apiKey}`
1853
+ },
1854
+ body: JSON.stringify(body),
1855
+ signal: options.signal
1856
+ });
1857
+ } catch (error) {
1858
+ if (isAbort(error, options.signal))
1859
+ throw aborted();
1860
+ if (attempt >= maxRetries) {
1861
+ throw new ArnictApiError(`Arnict request failed: ${(error instanceof Error ? error.message : "network error").slice(0, 300)}`);
1862
+ }
1863
+ await sleep(exponentialBackoff(attempt, RETRY_BASE_MS, RETRY_MAX_MS));
1864
+ continue;
1865
+ }
1866
+ if (!response.ok) {
1867
+ const apiError = await arnictApiErrorFromResponse(response, apiKey);
1868
+ const retryable = RETRYABLE_STATUSES.has(response.status) && apiError.code !== "insufficient_quota";
1869
+ if (!retryable || attempt >= maxRetries)
1870
+ throw apiError;
1871
+ await sleep(parseRetryAfterMs(response.headers) ?? exponentialBackoff(attempt, RETRY_BASE_MS, RETRY_MAX_MS));
1872
+ continue;
1873
+ }
1874
+ if (!response.body)
1875
+ throw new ArnictApiError("Arnict error: empty response body");
1876
+ const contentType = response.headers.get("content-type") ?? "";
1877
+ if (contentType.includes("application/json") && !contentType.includes("text/event-stream")) {
1878
+ const completion = await response.json();
1879
+ yield* eventsFromChunks(chatCompletionChunks(completion), options.model, options.signal);
1880
+ return;
1881
+ }
1882
+ yield* eventsFromChunks(parseSseData(readBody(response.body)), options.model, options.signal);
1883
+ return;
1884
+ }
1885
+ }
1886
+
1887
+ // ../bridge-core/dist/types.js
1888
+ var BRIDGE_EFFORT_ORDER = ["minimal", "low", "medium", "high", "xhigh", "max"];
1889
+
1890
+ // ../bridge-core/dist/effort.js
1891
+ var EFFORTS = {};
1892
+ for (const level of BRIDGE_EFFORT_ORDER)
1893
+ EFFORTS[level] = true;
1894
+ function toBridgeEffort(reasoning) {
1895
+ return typeof reasoning === "string" && EFFORTS[reasoning] === true ? reasoning : void 0;
1896
+ }
1897
+
1898
+ // ../bridge-core/dist/dsh/adapter.js
1899
+ import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
1900
+
1901
+ // ../bridge-core/dist/dsh/messages.js
1902
+ import { fileHandleText, offloadedImageText } from "@deepseek-ai/dsh-llm";
1903
+ function isLegacyToolResult(block) {
1904
+ return block.type === "tool-result";
1905
+ }
1906
+ async function userContent2(blocks, context) {
1907
+ const out = [];
1908
+ for (const block of blocks) {
1909
+ if (block.type === "text")
1910
+ out.push({ type: "text", text: block.text });
1911
+ else if (block.type === "reasoning")
1912
+ out.push({ type: "text", text: block.text });
1913
+ else if (block.type === "file") {
1914
+ out.push({
1915
+ type: "text",
1916
+ text: fileHandleText(block.attachment, context.attachments?.fileHostPath(block.attachment))
1917
+ });
1918
+ } else if (block.type === "image") {
1919
+ if (block.offloaded === true) {
1920
+ const hostPath = context.attachments?.imageHostPath(block.attachment);
1921
+ out.push({
1922
+ type: "text",
1923
+ text: offloadedImageText(block.attachment, hostPath ? { readonlyPath: hostPath } : void 0)
1924
+ });
1925
+ continue;
1926
+ }
1927
+ if (!context.attachments)
1928
+ continue;
1929
+ const stored = await context.attachments.readImage(block.attachment, context.signal);
1930
+ out.push({
1931
+ type: "image",
1932
+ data: Buffer.from(stored.data).toString("base64"),
1933
+ mimeType: block.attachment.mediaType
1934
+ });
1935
+ }
1936
+ }
1937
+ return out;
1938
+ }
1939
+ async function toBridgeMessagesFromDsh(messages, context = {}) {
1940
+ const out = [];
1941
+ const systemParts = [];
1942
+ const toolNames = /* @__PURE__ */ new Map();
1943
+ for (const message of messages) {
1944
+ if (message.role === "system") {
1945
+ for (const block of message.content)
1946
+ if (block.type === "text")
1947
+ systemParts.push(block.text);
1948
+ continue;
1949
+ }
1950
+ if (message.role === "developer")
1951
+ continue;
1952
+ if (message.role === "assistant") {
1953
+ const content = [];
1954
+ for (const block of message.content) {
1955
+ if (block.type === "text")
1956
+ content.push({ type: "text", text: block.text });
1957
+ else if (block.type === "reasoning")
1958
+ content.push({ type: "thinking", thinking: block.text });
1959
+ else if (block.type === "tool-call") {
1960
+ let args;
1961
+ try {
1962
+ args = JSON.parse(block.arguments || "{}");
1963
+ } catch {
1964
+ args = {};
1965
+ }
1966
+ toolNames.set(block.id, block.name);
1967
+ content.push({ type: "toolCall", id: block.id, name: block.name, arguments: args });
1968
+ }
1969
+ }
1970
+ out.push({ role: "assistant", content });
1971
+ continue;
1972
+ }
1973
+ if (message.role === "tool") {
1974
+ out.push({
1975
+ role: "toolResult",
1976
+ toolCallId: message.toolCallId,
1977
+ toolName: toolNames.get(message.toolCallId) ?? "tool",
1978
+ content: await userContent2(message.content, context),
1979
+ isError: message.isError === true
1980
+ });
1981
+ continue;
1982
+ }
1983
+ const blocks = message.content;
1984
+ const results = blocks.filter(isLegacyToolResult);
1985
+ const plain = blocks.filter((block) => !isLegacyToolResult(block));
1986
+ if (plain.length > 0)
1987
+ out.push({ role: "user", content: await userContent2(plain, context) });
1988
+ for (const result of results) {
1989
+ out.push({
1990
+ role: "toolResult",
1991
+ toolCallId: result.toolCallId,
1992
+ toolName: toolNames.get(result.toolCallId) ?? "tool",
1993
+ content: await userContent2(result.content, context),
1994
+ isError: result.isError === true
1995
+ });
1996
+ }
1997
+ }
1998
+ return { messages: out, ...systemParts.length > 0 ? { system: systemParts.join("\n\n") } : {} };
1999
+ }
2000
+
2001
+ // ../bridge-core/dist/dsh/stream.js
2002
+ function toDshUsage(usage) {
2003
+ const cacheReadTokens = usage.cacheRead ?? 0;
2004
+ const cacheWriteTokens = usage.cacheWrite ?? 0;
2005
+ const summed = usage.input + cacheReadTokens + cacheWriteTokens + usage.output;
2006
+ if (usage.totalTokens !== summed) {
2007
+ return {
2008
+ inputTokens: usage.input,
2009
+ outputTokens: usage.output,
2010
+ totalTokens: usage.totalTokens
2011
+ };
2012
+ }
2013
+ return {
2014
+ inputTokens: usage.input,
2015
+ outputTokens: usage.output,
2016
+ totalTokens: summed,
2017
+ cacheReadTokens,
2018
+ cacheWriteTokens
2019
+ };
2020
+ }
2021
+ function toolArguments(event) {
2022
+ if (event.argumentsJson !== void 0)
2023
+ return event.argumentsJson.trim() ? event.argumentsJson : "{}";
2024
+ return JSON.stringify(event.arguments);
2025
+ }
2026
+ async function* streamToDsh(events) {
2027
+ const openBlocks = /* @__PURE__ */ new Set();
2028
+ for await (const event of events) {
2029
+ switch (event.type) {
2030
+ case "text_start":
2031
+ openBlocks.add(event.index);
2032
+ yield { type: "block-start", index: event.index, blockType: "text" };
2033
+ break;
2034
+ case "text_delta":
2035
+ yield { type: "text-delta", index: event.index, text: event.delta };
2036
+ break;
2037
+ case "text_end":
2038
+ openBlocks.delete(event.index);
2039
+ yield { type: "block-end", index: event.index, block: { type: "text", text: event.text } };
2040
+ break;
2041
+ case "thinking_start":
2042
+ openBlocks.add(event.index);
2043
+ yield { type: "block-start", index: event.index, blockType: "reasoning" };
2044
+ break;
2045
+ case "thinking_delta":
2046
+ yield { type: "reasoning-delta", index: event.index, text: event.delta };
2047
+ break;
2048
+ case "thinking_end":
2049
+ openBlocks.delete(event.index);
2050
+ yield { type: "block-end", index: event.index, block: { type: "reasoning", text: event.thinking } };
2051
+ break;
2052
+ case "tool_call_start":
2053
+ openBlocks.add(event.index);
2054
+ yield { type: "block-start", index: event.index, blockType: "tool-call" };
2055
+ yield {
2056
+ type: "tool-call-delta",
2057
+ index: event.index,
2058
+ id: event.id,
2059
+ name: event.name,
2060
+ argumentsDelta: ""
2061
+ };
2062
+ break;
2063
+ case "tool_call_delta":
2064
+ yield {
2065
+ type: "tool-call-delta",
2066
+ index: event.index,
2067
+ id: event.id,
2068
+ argumentsDelta: event.argumentsDelta
2069
+ };
2070
+ break;
2071
+ case "tool_call_end":
2072
+ openBlocks.delete(event.index);
2073
+ yield {
2074
+ type: "block-end",
2075
+ index: event.index,
2076
+ block: { type: "tool-call", id: event.id, name: event.name, arguments: toolArguments(event) }
2077
+ };
2078
+ break;
2079
+ case "usage":
2080
+ yield { type: "usage", usage: toDshUsage(event.usage) };
2081
+ break;
2082
+ case "done":
2083
+ yield {
2084
+ type: "finish",
2085
+ reason: event.stopReason === "toolUse" ? { kind: "tool-calls" } : event.stopReason === "length" ? { kind: "max-tokens" } : { kind: "stop" },
2086
+ // The finish union carries no message field for a successful
2087
+ // reason, so a terminal diagnostic rides the replay envelope —
2088
+ // the harness stores it on the assembled message's model source.
2089
+ ...event.errorMessage ? { replayState: { response: { errorMessage: event.errorMessage } } } : {}
2090
+ };
2091
+ break;
2092
+ }
2093
+ }
2094
+ for (const index of openBlocks) {
2095
+ yield { type: "block-end", index, block: { type: "text", text: "" } };
2096
+ }
2097
+ }
2098
+
2099
+ // ../bridge-core/dist/dsh/adapter.js
2100
+ function compactionReserveTokens(model) {
2101
+ const budget = compactionBudget(model);
2102
+ if (!budget || budget.reserveTokens >= model.maxTokens)
2103
+ return void 0;
2104
+ return budget.reserveTokens;
2105
+ }
2106
+ var EFFORT_NAMES = {
2107
+ minimal: "Minimal",
2108
+ low: "Low",
2109
+ medium: "Medium",
2110
+ high: "High",
2111
+ xhigh: "Extra high",
2112
+ max: "Maximum"
2113
+ };
2114
+ function inputModalities(model) {
2115
+ return model.input.filter((modality) => modality === "text" || modality === "image");
2116
+ }
2117
+ function toModelInfo(provider, model) {
2118
+ return { provider, id: model.id, name: model.name, inputModalities: inputModalities(model) };
2119
+ }
2120
+ function toResolvedModel(provider, model) {
2121
+ return {
2122
+ ...toModelInfo(provider, model),
2123
+ context: { contextWindow: model.contextWindow },
2124
+ defaultMaxTokens: model.compactionReserveTokens ?? model.maxTokens,
2125
+ ...model.efforts?.length ? {
2126
+ reasoning: {
2127
+ efforts: model.efforts.map((effort) => ({
2128
+ id: effort,
2129
+ name: EFFORT_NAMES[effort] ?? effort
2130
+ }))
2131
+ }
2132
+ } : {}
2133
+ };
2134
+ }
2135
+ function createDshLlmAdapter(spec, toLlmError2) {
2136
+ setUsageHost("dsh");
2137
+ return new class extends LlmAdapter {
2138
+ providerInfo(provider) {
2139
+ return { id: provider, name: spec.displayName };
2140
+ }
2141
+ async listModels(provider) {
2142
+ return spec.catalog().map((model) => toModelInfo(provider, model));
2143
+ }
2144
+ async resolveModel(provider, model, _signal) {
2145
+ const known = spec.catalog().find((candidate) => candidate.id === model);
2146
+ if (!known)
2147
+ throw new LlmError(`Unknown ${spec.displayName} model: ${model}`, "UNKNOWN_MODEL");
2148
+ return toResolvedModel(provider, known);
2149
+ }
2150
+ async *stream(options) {
2151
+ try {
2152
+ yield* this.streamInner(options);
2153
+ } catch (error) {
2154
+ throw toLlmError2(error);
2155
+ }
2156
+ }
2157
+ async *streamInner(options) {
2158
+ const credentials = await spec.credentials();
2159
+ const projected = await toBridgeMessagesFromDsh(options.messages, {
2160
+ attachments: spec.attachments?.(),
2161
+ signal: options.signal
2162
+ });
2163
+ const system = [options.system, projected.system].filter((part) => !!part).join("\n\n") || void 0;
2164
+ const contextWindow = spec.contextWindow?.(options.model);
2165
+ yield* streamToDsh(spec.stream({
2166
+ ...options,
2167
+ messages: projected.messages,
2168
+ ...system !== void 0 ? { system } : {},
2169
+ ...contextWindow !== void 0 ? { contextWindow } : {}
2170
+ }, credentials));
2171
+ }
2172
+ }();
2173
+ }
2174
+
2175
+ // ../dsh-llm-arnict/src/catalog.ts
2176
+ import { homedir as homedir3 } from "node:os";
2177
+ import { join as join4 } from "node:path";
2178
+ var ARNICT_BOOTSTRAP_IDS = ARNICT_KNOWN_MODELS.map((model) => model.id);
2179
+ function arnictCatalogCacheDir(home = homedir3(), env = process.env) {
2180
+ const override = env[ARNICT_CATALOG_CACHE_DIR_ENV]?.trim();
2181
+ if (override) return override;
2182
+ return join4(home, ".pi", "agent", "cache", "ns-pi-provider");
2183
+ }
2184
+ function modelsFromCatalogJson(raw) {
2185
+ return arnictModelsFromCatalogJson(raw);
2186
+ }
2187
+ function readArnictCatalogFile(options) {
2188
+ return readArnictCatalog({
2189
+ cacheDir: arnictCatalogCacheDir(options?.home, options?.env),
2190
+ ...options?.readFile ? { readFile: options.readFile } : {}
2191
+ });
2192
+ }
2193
+
2194
+ // ../dsh-llm-arnict/src/errors.ts
2195
+ import { CONTEXT_WINDOW_EXCEEDED_CODE, isContextWindowExceededError, LlmError as LlmError2 } from "@deepseek-ai/dsh-llm";
2196
+ function statusOf(error) {
2197
+ return error instanceof ArnictApiError ? error.status : void 0;
2198
+ }
2199
+ function toLlmError(error) {
2200
+ if (error instanceof LlmError2) return error;
2201
+ const cause = error instanceof Error ? error : void 0;
2202
+ const message = cause?.message ?? String(error);
2203
+ if (cause?.name === "AbortError") return new LlmError2(message, "ABORTED", { cause });
2204
+ const status = statusOf(error);
2205
+ const options = { cause, ...status !== void 0 ? { status } : {} };
2206
+ if (error instanceof ArnictAuthError) return new LlmError2(message, "AUTH", options);
2207
+ if (status === 401 || status === 403) return new LlmError2(message, "AUTH", options);
2208
+ if (status === 429) return new LlmError2(message, "RATE_LIMIT", options);
2209
+ if (status === 413 || isContextWindowExceededError(message))
2210
+ return new LlmError2(message, CONTEXT_WINDOW_EXCEEDED_CODE, options);
2211
+ return new LlmError2(message, "PROVIDER_ERROR", options);
2212
+ }
2213
+
2214
+ // ../dsh-llm-arnict/src/adapter.ts
2215
+ function reserveField(model) {
2216
+ const reserve = model.compaction?.reserveTokens ?? compactionReserveTokens(model);
2217
+ return reserve !== void 0 && reserve < model.maxTokens ? { compactionReserveTokens: reserve } : {};
2218
+ }
2219
+ var EFFORTS2 = ["minimal", "low", "medium", "high", "xhigh", "max"];
2220
+ function toAdapterModel(model) {
2221
+ return {
2222
+ id: model.id,
2223
+ name: model.name,
2224
+ input: model.input,
2225
+ contextWindow: model.contextWindow,
2226
+ maxTokens: model.maxTokens,
2227
+ ...reserveField(model),
2228
+ ...model.reasoning ? { efforts: EFFORTS2 } : {}
2229
+ };
2230
+ }
2231
+ function createArnictAdapter(options) {
2232
+ const spec = {
2233
+ provider: options.provider,
2234
+ displayName: options.displayName,
2235
+ catalog: () => readArnictCatalogFile().map(toAdapterModel),
2236
+ // Arnict authenticates from ARNICT_API_KEY or the key file inside the core,
2237
+ // so there is no per-request credential to resolve here.
2238
+ credentials: async () => void 0,
2239
+ ...options.attachments ? { attachments: options.attachments } : {},
2240
+ stream: (request) => {
2241
+ const tools = request.tools?.map((tool) => ({
2242
+ name: tool.name,
2243
+ description: tool.description,
2244
+ parameters: tool.parameters
2245
+ }));
2246
+ return streamArnict({
2247
+ model: request.model,
2248
+ messages: request.messages,
2249
+ systemPrompt: request.system,
2250
+ tools,
2251
+ effort: toBridgeEffort(request.reasoningEffort),
2252
+ // The Harness session id is stable across every turn, compaction and
2253
+ // title call of one session, which is what the ledger keys a turn on.
2254
+ ...request.sessionId ? { sessionId: String(request.sessionId) } : {},
2255
+ signal: request.signal
2256
+ });
2257
+ }
2258
+ };
2259
+ return createDshLlmAdapter(spec, toLlmError);
2260
+ }
2261
+
2262
+ // ../dsh-llm-arnict/src/index.ts
2263
+ var name = "llm-arnict";
2264
+ var inject = ["llm"];
2265
+ var Config = Schema.object({
2266
+ provider: Schema.string().default("arnict").description("Provider route to register the adapter under."),
2267
+ displayName: Schema.string().default("Arnict").description("Display name shown in model selectors.")
2268
+ });
2269
+ function apply(ctx, config) {
2270
+ let attachments;
2271
+ ctx.inject(["attachments"], (scope) => {
2272
+ attachments = scope.attachments;
2273
+ scope.effect(
2274
+ () => () => {
2275
+ attachments = void 0;
2276
+ },
2277
+ "dsh-llm-arnict attachment store"
2278
+ );
2279
+ });
2280
+ ctx.llm.registerAdapter(
2281
+ [config.provider],
2282
+ createArnictAdapter({
2283
+ provider: config.provider,
2284
+ displayName: config.displayName,
2285
+ attachments: () => attachments
2286
+ })
2287
+ );
2288
+ }
2289
+ export {
2290
+ Config,
2291
+ apply,
2292
+ createArnictAdapter,
2293
+ inject,
2294
+ modelsFromCatalogJson,
2295
+ name,
2296
+ readArnictCatalogFile
2297
+ };