@ngosangns/ns-bridge 0.1.24 → 0.1.26

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 (45) hide show
  1. package/NOTICE +44 -0
  2. package/README.md +46 -16
  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 +3 -0
  7. package/dist/cli.js +59 -36
  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 +7837 -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 +28459 -0
  23. package/dist/hosts/omp/package.json +25 -0
  24. package/dist/hosts/pi/dist/index.js +33765 -0
  25. package/dist/hosts/pi/package.json +13 -0
  26. package/dist/hosts.d.ts +52 -11
  27. package/dist/hosts.js +241 -33
  28. package/dist/hosts.js.map +1 -1
  29. package/dist/providers.d.ts +4 -5
  30. package/dist/providers.js +22 -38
  31. package/dist/providers.js.map +1 -1
  32. package/dist/refresh-entry.js +1053 -773
  33. package/dist/refresh.d.ts +1 -0
  34. package/dist/refresh.js.map +1 -1
  35. package/dist/selection.d.ts +3 -3
  36. package/dist/selection.js +13 -7
  37. package/dist/selection.js.map +1 -1
  38. package/dist/serve-entry.js +3 -12
  39. package/dist/usage.d.ts +4 -0
  40. package/dist/usage.js +33 -1
  41. package/dist/usage.js.map +1 -1
  42. package/dist/zcode.d.ts +1 -1
  43. package/dist/zcode.js +10 -4
  44. package/dist/zcode.js.map +1 -1
  45. package/package.json +13 -4
@@ -0,0 +1,2523 @@
1
+ // @ngosangns/ns-bridge 0.1.26 — 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
+ // ../core-utils/dist/compaction.js
872
+ var COMPACTION_RESERVE_FLOOR = 16384;
873
+ function compactionBudget(model) {
874
+ const { contextWindow, maxTokens } = model;
875
+ if (!Number.isFinite(contextWindow) || contextWindow <= 0)
876
+ return void 0;
877
+ if (!Number.isFinite(maxTokens) || maxTokens <= 0)
878
+ return void 0;
879
+ const ceiling = Math.floor(maxTokens);
880
+ const reserveTokens = contextWindow <= COMPACTION_RESERVE_FLOOR ? ceiling : Math.max(1, Math.min(ceiling, COMPACTION_RESERVE_FLOOR));
881
+ return { reserveTokens, thresholdTokens: contextWindow - reserveTokens };
882
+ }
883
+
884
+ // ../core-utils/dist/usage-ledger.js
885
+ import { createHash } from "node:crypto";
886
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
887
+ import { homedir } from "node:os";
888
+ import { join } from "node:path";
889
+ var USAGE_RETENTION_DAYS = 30;
890
+ var USAGE_MAX_BYTES = 50 * 1024 * 1024;
891
+ var NO_SESSION_FILE = "_no-session";
892
+ var MAX_TRACKED_SESSIONS = 256;
893
+ var HOST_KEY = /* @__PURE__ */ Symbol.for("ns-bridge.usage.host");
894
+ function setUsageHost(host) {
895
+ const holder = globalThis;
896
+ if (holder[HOST_KEY] === void 0)
897
+ holder[HOST_KEY] = host;
898
+ }
899
+ function getUsageHost() {
900
+ return globalThis[HOST_KEY] ?? "unknown";
901
+ }
902
+ function usageRecordingEnabled(env = process.env) {
903
+ const flag = env.NS_BRIDGE_USAGE?.trim().toLowerCase();
904
+ return !(flag === "0" || flag === "false" || flag === "off");
905
+ }
906
+ function usageRoot(env = process.env) {
907
+ return env.NS_BRIDGE_USAGE_DIR?.trim() || join(homedir(), ".ns-bridge", "usage");
908
+ }
909
+ function usageDay(at) {
910
+ const date2 = new Date(at);
911
+ const month = String(date2.getMonth() + 1).padStart(2, "0");
912
+ const day = String(date2.getDate()).padStart(2, "0");
913
+ return `${date2.getFullYear()}-${month}-${day}`;
914
+ }
915
+ function usageFileName(sessionId) {
916
+ const id = sessionId?.trim();
917
+ if (!id)
918
+ return NO_SESSION_FILE;
919
+ if (/^[A-Za-z0-9_-]{1,80}$/.test(id))
920
+ return id;
921
+ return `h-${createHash("sha256").update(id).digest("hex").slice(0, 16)}`;
922
+ }
923
+ function ratio(part, whole) {
924
+ if (part === void 0 || whole <= 0)
925
+ return null;
926
+ return part / whole;
927
+ }
928
+ function providerUsage(usage) {
929
+ if (!usage.cacheEstimated && usage.cacheDerived === void 0)
930
+ return usage;
931
+ const { cacheRead, cacheEstimated: _guess, cacheDerived: _derived, ...rest } = usage;
932
+ return { ...rest, input: usage.input + (cacheRead ?? 0) };
933
+ }
934
+ function isUsage(value) {
935
+ if (!value || typeof value !== "object")
936
+ return false;
937
+ const usage = value;
938
+ return typeof usage.input === "number" && typeof usage.output === "number";
939
+ }
940
+ function buildUsageRecord(input) {
941
+ const { context } = input;
942
+ let usage = providerUsage(input.usage);
943
+ const promptTokens = usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
944
+ let cacheHitMax;
945
+ let cacheSource = usage.cacheRead !== void 0 || usage.cacheWrite !== void 0 ? "wire" : "none";
946
+ if (cacheSource === "none" && context.deriveCache) {
947
+ let derived;
948
+ try {
949
+ derived = context.deriveCache({
950
+ promptTokens,
951
+ outputTokens: usage.output,
952
+ credits: usage.credits,
953
+ creditUnit: usage.creditUnit
954
+ });
955
+ } catch {
956
+ derived = void 0;
957
+ }
958
+ if (derived?.exact) {
959
+ cacheSource = "credits";
960
+ usage = { ...usage, input: promptTokens - derived.cacheRead, cacheRead: derived.cacheRead };
961
+ } else if (derived) {
962
+ cacheSource = "credits-capped";
963
+ cacheHitMax = derived.maxRatio;
964
+ }
965
+ }
966
+ const hasCache = cacheSource === "wire" || cacheSource === "credits";
967
+ const contextFill = context.contextWindow !== void 0 && context.contextWindow > 0 ? promptTokens / context.contextWindow : null;
968
+ return {
969
+ ts: new Date(input.at).toISOString(),
970
+ vendor: context.vendor,
971
+ host: input.host,
972
+ model: context.model,
973
+ session: context.sessionId?.trim() || null,
974
+ step: input.step,
975
+ gapMs: input.gapMs,
976
+ ms: input.ms,
977
+ input: usage.input,
978
+ output: usage.output,
979
+ total: usage.totalTokens,
980
+ promptTokens,
981
+ ...usage.cacheRead !== void 0 ? { cacheRead: usage.cacheRead } : {},
982
+ ...usage.cacheWrite !== void 0 ? { cacheWrite: usage.cacheWrite } : {},
983
+ cacheHitRatio: hasCache ? ratio(usage.cacheRead ?? 0, promptTokens) : null,
984
+ cacheWriteRatio: cacheSource === "wire" ? ratio(usage.cacheWrite, promptTokens) : null,
985
+ cacheSource,
986
+ ...cacheHitMax !== void 0 ? { cacheHitMax } : {},
987
+ ...usage.credits !== void 0 ? { credits: usage.credits } : {},
988
+ ...usage.creditUnit !== void 0 ? { creditUnit: usage.creditUnit } : {},
989
+ ...context.contextWindow !== void 0 ? { contextWindow: context.contextWindow } : {},
990
+ ...contextFill !== null ? { contextFill } : {},
991
+ ...usage.contextPercent !== void 0 ? { contextPercent: usage.contextPercent } : {},
992
+ ...context.effort ? { effort: context.effort } : {},
993
+ ...input.stop ? { stop: input.stop } : {}
994
+ };
995
+ }
996
+ var sessions = /* @__PURE__ */ new Map();
997
+ var lastPrunedDay;
998
+ var failedWrites = 0;
999
+ function resumeFromDisk(path) {
1000
+ try {
1001
+ const lines = readFileSync(path, "utf8").split("\n").filter((line) => line.trim());
1002
+ if (lines.length === 0)
1003
+ return void 0;
1004
+ const last = JSON.parse(lines[lines.length - 1]);
1005
+ const endedAt = typeof last.ts === "string" ? Date.parse(last.ts) : Number.NaN;
1006
+ return { step: lines.length, lastEndedAt: Number.isFinite(endedAt) ? endedAt : Number.NaN };
1007
+ } catch {
1008
+ return void 0;
1009
+ }
1010
+ }
1011
+ function nextStep(vendor, sessionId, now, env) {
1012
+ const id = sessionId?.trim();
1013
+ if (!id)
1014
+ return { step: null, gapMs: null };
1015
+ const key = `${vendor}\0${id}`;
1016
+ const previous = sessions.get(key) ?? resumeFromDisk(join(usageRoot(env), usageDay(now), usageFileName(vendor), `${usageFileName(id)}.jsonl`));
1017
+ const state = { step: (previous?.step ?? 0) + 1, lastEndedAt: now };
1018
+ sessions.delete(key);
1019
+ sessions.set(key, state);
1020
+ if (sessions.size > MAX_TRACKED_SESSIONS) {
1021
+ const oldest = sessions.keys().next().value;
1022
+ if (oldest !== void 0)
1023
+ sessions.delete(oldest);
1024
+ }
1025
+ const gapMs = previous && Number.isFinite(previous.lastEndedAt) ? Math.max(0, now - previous.lastEndedAt) : null;
1026
+ return { step: state.step, gapMs };
1027
+ }
1028
+ function dirBytes(path) {
1029
+ let total = 0;
1030
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
1031
+ const child = join(path, entry.name);
1032
+ total += entry.isDirectory() ? dirBytes(child) : statSync(child).size;
1033
+ }
1034
+ return total;
1035
+ }
1036
+ function pruneUsage(root, options = {}) {
1037
+ const now = options.now ?? Date.now();
1038
+ const maxAgeDays = options.maxAgeDays ?? USAGE_RETENTION_DAYS;
1039
+ const maxBytes = options.maxBytes ?? USAGE_MAX_BYTES;
1040
+ const removed = [];
1041
+ let days;
1042
+ try {
1043
+ days = readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory() && /^\d{4}-\d{2}-\d{2}$/.test(entry.name)).map((entry) => entry.name).sort();
1044
+ } catch {
1045
+ return removed;
1046
+ }
1047
+ const cutoff = usageDay(now - maxAgeDays * 864e5);
1048
+ const drop = (day) => {
1049
+ rmSync(join(root, day), { recursive: true, force: true });
1050
+ removed.push(day);
1051
+ };
1052
+ while (days.length > 1 && days[0] < cutoff)
1053
+ drop(days.shift());
1054
+ const sizes = new Map(days.map((day) => [day, dirBytes(join(root, day))]));
1055
+ let total = [...sizes.values()].reduce((sum, bytes) => sum + bytes, 0);
1056
+ while (days.length > 1 && total > maxBytes) {
1057
+ const oldest = days.shift();
1058
+ total -= sizes.get(oldest) ?? 0;
1059
+ drop(oldest);
1060
+ }
1061
+ return removed;
1062
+ }
1063
+ function writeUsageRecord(record, at, env = process.env) {
1064
+ try {
1065
+ const root = usageRoot(env);
1066
+ const day = usageDay(at);
1067
+ if (lastPrunedDay !== day) {
1068
+ lastPrunedDay = day;
1069
+ try {
1070
+ pruneUsage(root, { now: at });
1071
+ } catch {
1072
+ }
1073
+ }
1074
+ const dir = join(root, day, usageFileName(record.vendor));
1075
+ mkdirSync(dir, { recursive: true });
1076
+ appendFileSync(join(dir, `${usageFileName(record.session ?? void 0)}.jsonl`), `${JSON.stringify(record)}
1077
+ `);
1078
+ } catch {
1079
+ failedWrites++;
1080
+ }
1081
+ }
1082
+ async function* recordUsage(events, context) {
1083
+ const startedAt = Date.now();
1084
+ let usage;
1085
+ let stop;
1086
+ try {
1087
+ for await (const event of events) {
1088
+ const candidate = event;
1089
+ if (event.type === "usage" && isUsage(candidate.usage))
1090
+ usage = candidate.usage;
1091
+ else if (event.type === "done" && typeof candidate.stopReason === "string")
1092
+ stop = candidate.stopReason;
1093
+ yield event;
1094
+ }
1095
+ } finally {
1096
+ if (usage && usageRecordingEnabled()) {
1097
+ try {
1098
+ const now = Date.now();
1099
+ const { step, gapMs } = nextStep(context.vendor, context.sessionId, now, process.env);
1100
+ writeUsageRecord(buildUsageRecord({
1101
+ context,
1102
+ usage,
1103
+ host: getUsageHost(),
1104
+ at: now,
1105
+ ms: now - startedAt,
1106
+ step,
1107
+ gapMs,
1108
+ stop
1109
+ }), now);
1110
+ } catch {
1111
+ failedWrites++;
1112
+ }
1113
+ }
1114
+ }
1115
+ }
1116
+
1117
+ // ../bridge-core/dist/types.js
1118
+ var BRIDGE_EFFORT_ORDER = ["minimal", "low", "medium", "high", "xhigh", "max"];
1119
+
1120
+ // ../bridge-core/dist/effort.js
1121
+ var EFFORTS = {};
1122
+ for (const level of BRIDGE_EFFORT_ORDER)
1123
+ EFFORTS[level] = true;
1124
+ function toBridgeEffort(reasoning) {
1125
+ return typeof reasoning === "string" && EFFORTS[reasoning] === true ? reasoning : void 0;
1126
+ }
1127
+
1128
+ // ../bridge-core/dist/dsh/adapter.js
1129
+ import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
1130
+
1131
+ // ../bridge-core/dist/dsh/messages.js
1132
+ import { fileHandleText, offloadedImageText } from "@deepseek-ai/dsh-llm";
1133
+ function isLegacyToolResult(block) {
1134
+ return block.type === "tool-result";
1135
+ }
1136
+ async function userContent(blocks, context) {
1137
+ const out = [];
1138
+ for (const block of blocks) {
1139
+ if (block.type === "text")
1140
+ out.push({ type: "text", text: block.text });
1141
+ else if (block.type === "reasoning")
1142
+ out.push({ type: "text", text: block.text });
1143
+ else if (block.type === "file") {
1144
+ out.push({
1145
+ type: "text",
1146
+ text: fileHandleText(block.attachment, context.attachments?.fileHostPath(block.attachment))
1147
+ });
1148
+ } else if (block.type === "image") {
1149
+ if (block.offloaded === true) {
1150
+ const hostPath = context.attachments?.imageHostPath(block.attachment);
1151
+ out.push({
1152
+ type: "text",
1153
+ text: offloadedImageText(block.attachment, hostPath ? { readonlyPath: hostPath } : void 0)
1154
+ });
1155
+ continue;
1156
+ }
1157
+ if (!context.attachments)
1158
+ continue;
1159
+ const stored = await context.attachments.readImage(block.attachment, context.signal);
1160
+ out.push({
1161
+ type: "image",
1162
+ data: Buffer.from(stored.data).toString("base64"),
1163
+ mimeType: block.attachment.mediaType
1164
+ });
1165
+ }
1166
+ }
1167
+ return out;
1168
+ }
1169
+ async function toBridgeMessagesFromDsh(messages, context = {}) {
1170
+ const out = [];
1171
+ const systemParts = [];
1172
+ const toolNames = /* @__PURE__ */ new Map();
1173
+ for (const message of messages) {
1174
+ if (message.role === "system") {
1175
+ for (const block of message.content)
1176
+ if (block.type === "text")
1177
+ systemParts.push(block.text);
1178
+ continue;
1179
+ }
1180
+ if (message.role === "developer")
1181
+ continue;
1182
+ if (message.role === "assistant") {
1183
+ const content = [];
1184
+ for (const block of message.content) {
1185
+ if (block.type === "text")
1186
+ content.push({ type: "text", text: block.text });
1187
+ else if (block.type === "reasoning")
1188
+ content.push({ type: "thinking", thinking: block.text });
1189
+ else if (block.type === "tool-call") {
1190
+ let args;
1191
+ try {
1192
+ args = JSON.parse(block.arguments || "{}");
1193
+ } catch {
1194
+ args = {};
1195
+ }
1196
+ toolNames.set(block.id, block.name);
1197
+ content.push({ type: "toolCall", id: block.id, name: block.name, arguments: args });
1198
+ }
1199
+ }
1200
+ out.push({ role: "assistant", content });
1201
+ continue;
1202
+ }
1203
+ if (message.role === "tool") {
1204
+ out.push({
1205
+ role: "toolResult",
1206
+ toolCallId: message.toolCallId,
1207
+ toolName: toolNames.get(message.toolCallId) ?? "tool",
1208
+ content: await userContent(message.content, context),
1209
+ isError: message.isError === true
1210
+ });
1211
+ continue;
1212
+ }
1213
+ const blocks = message.content;
1214
+ const results = blocks.filter(isLegacyToolResult);
1215
+ const plain = blocks.filter((block) => !isLegacyToolResult(block));
1216
+ if (plain.length > 0)
1217
+ out.push({ role: "user", content: await userContent(plain, context) });
1218
+ for (const result of results) {
1219
+ out.push({
1220
+ role: "toolResult",
1221
+ toolCallId: result.toolCallId,
1222
+ toolName: toolNames.get(result.toolCallId) ?? "tool",
1223
+ content: await userContent(result.content, context),
1224
+ isError: result.isError === true
1225
+ });
1226
+ }
1227
+ }
1228
+ return { messages: out, ...systemParts.length > 0 ? { system: systemParts.join("\n\n") } : {} };
1229
+ }
1230
+
1231
+ // ../bridge-core/dist/dsh/stream.js
1232
+ function toDshUsage(usage) {
1233
+ const cacheReadTokens = usage.cacheRead ?? 0;
1234
+ const cacheWriteTokens = usage.cacheWrite ?? 0;
1235
+ const summed = usage.input + cacheReadTokens + cacheWriteTokens + usage.output;
1236
+ if (usage.totalTokens !== summed) {
1237
+ return {
1238
+ inputTokens: usage.input,
1239
+ outputTokens: usage.output,
1240
+ totalTokens: usage.totalTokens
1241
+ };
1242
+ }
1243
+ return {
1244
+ inputTokens: usage.input,
1245
+ outputTokens: usage.output,
1246
+ totalTokens: summed,
1247
+ cacheReadTokens,
1248
+ cacheWriteTokens
1249
+ };
1250
+ }
1251
+ function toolArguments(event) {
1252
+ if (event.argumentsJson !== void 0)
1253
+ return event.argumentsJson.trim() ? event.argumentsJson : "{}";
1254
+ return JSON.stringify(event.arguments);
1255
+ }
1256
+ async function* streamToDsh(events) {
1257
+ const openBlocks = /* @__PURE__ */ new Set();
1258
+ for await (const event of events) {
1259
+ switch (event.type) {
1260
+ case "text_start":
1261
+ openBlocks.add(event.index);
1262
+ yield { type: "block-start", index: event.index, blockType: "text" };
1263
+ break;
1264
+ case "text_delta":
1265
+ yield { type: "text-delta", index: event.index, text: event.delta };
1266
+ break;
1267
+ case "text_end":
1268
+ openBlocks.delete(event.index);
1269
+ yield { type: "block-end", index: event.index, block: { type: "text", text: event.text } };
1270
+ break;
1271
+ case "thinking_start":
1272
+ openBlocks.add(event.index);
1273
+ yield { type: "block-start", index: event.index, blockType: "reasoning" };
1274
+ break;
1275
+ case "thinking_delta":
1276
+ yield { type: "reasoning-delta", index: event.index, text: event.delta };
1277
+ break;
1278
+ case "thinking_end":
1279
+ openBlocks.delete(event.index);
1280
+ yield { type: "block-end", index: event.index, block: { type: "reasoning", text: event.thinking } };
1281
+ break;
1282
+ case "tool_call_start":
1283
+ openBlocks.add(event.index);
1284
+ yield { type: "block-start", index: event.index, blockType: "tool-call" };
1285
+ yield {
1286
+ type: "tool-call-delta",
1287
+ index: event.index,
1288
+ id: event.id,
1289
+ name: event.name,
1290
+ argumentsDelta: ""
1291
+ };
1292
+ break;
1293
+ case "tool_call_delta":
1294
+ yield {
1295
+ type: "tool-call-delta",
1296
+ index: event.index,
1297
+ id: event.id,
1298
+ argumentsDelta: event.argumentsDelta
1299
+ };
1300
+ break;
1301
+ case "tool_call_end":
1302
+ openBlocks.delete(event.index);
1303
+ yield {
1304
+ type: "block-end",
1305
+ index: event.index,
1306
+ block: { type: "tool-call", id: event.id, name: event.name, arguments: toolArguments(event) }
1307
+ };
1308
+ break;
1309
+ case "usage":
1310
+ yield { type: "usage", usage: toDshUsage(event.usage) };
1311
+ break;
1312
+ case "done":
1313
+ yield {
1314
+ type: "finish",
1315
+ reason: event.stopReason === "toolUse" ? { kind: "tool-calls" } : event.stopReason === "length" ? { kind: "max-tokens" } : { kind: "stop" },
1316
+ // The finish union carries no message field for a successful
1317
+ // reason, so a terminal diagnostic rides the replay envelope —
1318
+ // the harness stores it on the assembled message's model source.
1319
+ ...event.errorMessage ? { replayState: { response: { errorMessage: event.errorMessage } } } : {}
1320
+ };
1321
+ break;
1322
+ }
1323
+ }
1324
+ for (const index of openBlocks) {
1325
+ yield { type: "block-end", index, block: { type: "text", text: "" } };
1326
+ }
1327
+ }
1328
+
1329
+ // ../bridge-core/dist/dsh/adapter.js
1330
+ function compactionReserveTokens(model) {
1331
+ const budget = compactionBudget(model);
1332
+ if (!budget || budget.reserveTokens >= model.maxTokens)
1333
+ return void 0;
1334
+ return budget.reserveTokens;
1335
+ }
1336
+ var EFFORT_NAMES = {
1337
+ minimal: "Minimal",
1338
+ low: "Low",
1339
+ medium: "Medium",
1340
+ high: "High",
1341
+ xhigh: "Extra high",
1342
+ max: "Maximum"
1343
+ };
1344
+ function inputModalities(model) {
1345
+ return model.input.filter((modality) => modality === "text" || modality === "image");
1346
+ }
1347
+ function toModelInfo(provider, model) {
1348
+ return { provider, id: model.id, name: model.name, inputModalities: inputModalities(model) };
1349
+ }
1350
+ function toResolvedModel(provider, model) {
1351
+ return {
1352
+ ...toModelInfo(provider, model),
1353
+ context: { contextWindow: model.contextWindow },
1354
+ defaultMaxTokens: model.compactionReserveTokens ?? model.maxTokens,
1355
+ ...model.efforts?.length ? {
1356
+ reasoning: {
1357
+ efforts: model.efforts.map((effort) => ({
1358
+ id: effort,
1359
+ name: EFFORT_NAMES[effort] ?? effort
1360
+ }))
1361
+ }
1362
+ } : {}
1363
+ };
1364
+ }
1365
+ function createDshLlmAdapter(spec, toLlmError2) {
1366
+ setUsageHost("dsh");
1367
+ return new class extends LlmAdapter {
1368
+ providerInfo(provider) {
1369
+ return { id: provider, name: spec.displayName };
1370
+ }
1371
+ async listModels(provider) {
1372
+ return spec.catalog().map((model) => toModelInfo(provider, model));
1373
+ }
1374
+ async resolveModel(provider, model, _signal) {
1375
+ const known = spec.catalog().find((candidate) => candidate.id === model);
1376
+ if (!known)
1377
+ throw new LlmError(`Unknown ${spec.displayName} model: ${model}`, "UNKNOWN_MODEL");
1378
+ return toResolvedModel(provider, known);
1379
+ }
1380
+ async *stream(options) {
1381
+ try {
1382
+ yield* this.streamInner(options);
1383
+ } catch (error) {
1384
+ throw toLlmError2(error);
1385
+ }
1386
+ }
1387
+ async *streamInner(options) {
1388
+ const credentials = await spec.credentials();
1389
+ const projected = await toBridgeMessagesFromDsh(options.messages, {
1390
+ attachments: spec.attachments?.(),
1391
+ signal: options.signal
1392
+ });
1393
+ const system = [options.system, projected.system].filter((part) => !!part).join("\n\n") || void 0;
1394
+ const contextWindow = spec.contextWindow?.(options.model);
1395
+ yield* streamToDsh(spec.stream({
1396
+ ...options,
1397
+ messages: projected.messages,
1398
+ ...system !== void 0 ? { system } : {},
1399
+ ...contextWindow !== void 0 ? { contextWindow } : {}
1400
+ }, credentials));
1401
+ }
1402
+ }();
1403
+ }
1404
+
1405
+ // ../grok-core/dist/auth.js
1406
+ import { randomBytes } from "node:crypto";
1407
+ import { constants } from "node:fs";
1408
+ import { access, chmod, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
1409
+ import { homedir as homedir2 } from "node:os";
1410
+ import { join as join2 } from "node:path";
1411
+
1412
+ // ../grok-core/dist/errors.js
1413
+ var GROK_LOGIN_MESSAGE = "Grok CLI is not signed in. Run `grok login`.";
1414
+ var GrokAuthError = class extends Error {
1415
+ constructor(message = GROK_LOGIN_MESSAGE) {
1416
+ super(message);
1417
+ this.name = "GrokAuthError";
1418
+ }
1419
+ };
1420
+ var GrokApiError = class extends Error {
1421
+ status;
1422
+ constructor(message, status) {
1423
+ super(message);
1424
+ this.name = "GrokApiError";
1425
+ this.status = status;
1426
+ }
1427
+ };
1428
+
1429
+ // ../grok-core/dist/auth.js
1430
+ var DEFAULT_OIDC_ISSUER = "https://auth.x.ai";
1431
+ var DEFAULT_TOKEN_ENDPOINT = "https://auth.x.ai/oauth2/token";
1432
+ var REFRESH_SKEW_MS = 6e4;
1433
+ var FALLBACK_EXPIRES_IN_SECONDS = 3600;
1434
+ var tokenEndpoints = /* @__PURE__ */ new Map();
1435
+ var refreshFlights = /* @__PURE__ */ new Map();
1436
+ var LOCK_WAIT_MS = 2e4;
1437
+ var LOCK_STALE_MS = 3e4;
1438
+ function grokAuthCandidates(env = process.env, home = homedir2()) {
1439
+ const explicit = env.GROK_AUTH_PATH?.trim();
1440
+ const paths = [];
1441
+ if (explicit)
1442
+ paths.push(explicit);
1443
+ paths.push(join2(home, ".grok", "auth.json"));
1444
+ paths.push(join2("/workspace/.provider-creds/grok", "auth.json"));
1445
+ return paths;
1446
+ }
1447
+ function isAccount(value) {
1448
+ return !!value && typeof value === "object" && ("key" in value || "refresh_token" in value);
1449
+ }
1450
+ function pickGrokAccount(file) {
1451
+ const entries = Object.entries(file).filter((entry) => isAccount(entry[1]));
1452
+ const preferred = entries.find(([key, account]) => key.includes("auth.x.ai") && !!account.key && !!account.refresh_token);
1453
+ if (preferred)
1454
+ return { key: preferred[0], account: preferred[1] };
1455
+ const withBoth = entries.find(([, account]) => !!account.key && !!account.refresh_token);
1456
+ if (withBoth)
1457
+ return { key: withBoth[0], account: withBoth[1] };
1458
+ const withKey = entries.find(([, account]) => !!account.key);
1459
+ if (withKey)
1460
+ return { key: withKey[0], account: withKey[1] };
1461
+ return void 0;
1462
+ }
1463
+ function expiresAtMs(expiresAt) {
1464
+ if (!expiresAt)
1465
+ return void 0;
1466
+ const time = Date.parse(expiresAt);
1467
+ return Number.isNaN(time) ? void 0 : time;
1468
+ }
1469
+ function tokenExpiresSoon(expiresAt, now, skew = REFRESH_SKEW_MS) {
1470
+ const time = expiresAtMs(expiresAt);
1471
+ if (time === void 0)
1472
+ return false;
1473
+ return time - now <= skew;
1474
+ }
1475
+ function tokenStillValid(expiresAt, now) {
1476
+ const time = expiresAtMs(expiresAt);
1477
+ if (time === void 0)
1478
+ return !expiresAt;
1479
+ return time > now;
1480
+ }
1481
+ function clientIdOf(accountKey, account) {
1482
+ const stored = account.oidc_client_id?.trim();
1483
+ if (stored)
1484
+ return stored;
1485
+ const tail = accountKey.split("::").at(-1)?.trim();
1486
+ return tail || void 0;
1487
+ }
1488
+ async function resolveTokenEndpoint(issuer, fetchImpl) {
1489
+ const normalized = issuer.replace(/\/$/, "") || DEFAULT_OIDC_ISSUER;
1490
+ if (normalized === DEFAULT_OIDC_ISSUER)
1491
+ return DEFAULT_TOKEN_ENDPOINT;
1492
+ const cached = tokenEndpoints.get(normalized);
1493
+ if (cached)
1494
+ return cached;
1495
+ const response = await fetchImpl(`${normalized}/.well-known/openid-configuration`);
1496
+ if (!response.ok)
1497
+ throw new GrokAuthError();
1498
+ const json = await response.json();
1499
+ if (!json.token_endpoint)
1500
+ throw new GrokAuthError();
1501
+ tokenEndpoints.set(normalized, json.token_endpoint);
1502
+ return json.token_endpoint;
1503
+ }
1504
+ async function refreshGrokAccess(input) {
1505
+ const fetchImpl = input.fetchImpl ?? fetch;
1506
+ const endpoint = await resolveTokenEndpoint(input.issuer ?? DEFAULT_OIDC_ISSUER, fetchImpl);
1507
+ const body = new URLSearchParams({
1508
+ grant_type: "refresh_token",
1509
+ refresh_token: input.refreshToken,
1510
+ client_id: input.clientId
1511
+ });
1512
+ const response = await fetchImpl(endpoint, {
1513
+ method: "POST",
1514
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1515
+ body
1516
+ });
1517
+ if (!response.ok)
1518
+ throw new GrokAuthError();
1519
+ const json = await response.json();
1520
+ if (!json.access_token)
1521
+ throw new GrokAuthError();
1522
+ const expiresIn = typeof json.expires_in === "number" && json.expires_in > 0 ? json.expires_in : FALLBACK_EXPIRES_IN_SECONDS;
1523
+ return { accessToken: json.access_token, refreshToken: json.refresh_token, expiresIn };
1524
+ }
1525
+ async function firstExisting(paths) {
1526
+ for (const path of paths) {
1527
+ try {
1528
+ await access(path, constants.R_OK);
1529
+ return path;
1530
+ } catch {
1531
+ }
1532
+ }
1533
+ return void 0;
1534
+ }
1535
+ async function readAuthFile(path) {
1536
+ let text;
1537
+ try {
1538
+ text = await readFile(path, "utf8");
1539
+ } catch {
1540
+ throw new GrokAuthError();
1541
+ }
1542
+ try {
1543
+ const parsed = JSON.parse(text);
1544
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1545
+ throw new GrokAuthError();
1546
+ return parsed;
1547
+ } catch (error) {
1548
+ if (error instanceof GrokAuthError)
1549
+ throw error;
1550
+ throw new GrokAuthError();
1551
+ }
1552
+ }
1553
+ async function storeRefreshedToken(path, accountKey, originalRefreshToken, update) {
1554
+ const file = await readAuthFile(path);
1555
+ const current = file[accountKey];
1556
+ if (!isAccount(current))
1557
+ return "skipped";
1558
+ if (originalRefreshToken && current.refresh_token && current.refresh_token !== originalRefreshToken) {
1559
+ return "skipped";
1560
+ }
1561
+ current.key = update.accessToken;
1562
+ current.expires_at = update.expiresAt;
1563
+ if (update.refreshToken)
1564
+ current.refresh_token = update.refreshToken;
1565
+ file[accountKey] = current;
1566
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
1567
+ try {
1568
+ await writeFile(tmp, `${JSON.stringify(file, null, 2)}
1569
+ `, { mode: 384, flag: "wx" });
1570
+ await chmod(tmp, 384);
1571
+ await rename(tmp, path);
1572
+ await chmod(path, 384);
1573
+ } catch (error) {
1574
+ await rm(tmp, { force: true }).catch(() => void 0);
1575
+ throw error;
1576
+ }
1577
+ return "stored";
1578
+ }
1579
+ function delay(ms) {
1580
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1581
+ }
1582
+ async function acquireAuthLock(authPath) {
1583
+ const lockPath = `${authPath}.lock`;
1584
+ const deadline = Date.now() + LOCK_WAIT_MS;
1585
+ for (; ; ) {
1586
+ try {
1587
+ return await open(lockPath, "wx", 384);
1588
+ } catch (error) {
1589
+ const code = error.code;
1590
+ if (code !== "EEXIST")
1591
+ throw error;
1592
+ try {
1593
+ const info = await stat(lockPath);
1594
+ if (Date.now() - info.mtimeMs > LOCK_STALE_MS) {
1595
+ await rm(lockPath, { force: true });
1596
+ continue;
1597
+ }
1598
+ } catch {
1599
+ }
1600
+ if (Date.now() > deadline)
1601
+ throw new GrokAuthError(GROK_LOGIN_MESSAGE);
1602
+ await delay(25);
1603
+ }
1604
+ }
1605
+ }
1606
+ async function releaseAuthLock(authPath, handle) {
1607
+ await handle.close();
1608
+ await rm(`${authPath}.lock`, { force: true }).catch(() => void 0);
1609
+ }
1610
+ async function persistRefreshedToken(path, accountKey, originalRefreshToken, update) {
1611
+ let lastError;
1612
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1613
+ try {
1614
+ return await storeRefreshedToken(path, accountKey, originalRefreshToken, update);
1615
+ } catch (error) {
1616
+ lastError = error;
1617
+ }
1618
+ }
1619
+ throw lastError;
1620
+ }
1621
+ async function refreshSessionLocked(path, options) {
1622
+ const file = await readAuthFile(path);
1623
+ const picked = pickGrokAccount(file);
1624
+ const accessToken = picked?.account.key;
1625
+ if (!picked || !accessToken)
1626
+ throw new GrokAuthError(GROK_LOGIN_MESSAGE);
1627
+ const now = options.now ?? Date.now();
1628
+ if (!tokenExpiresSoon(picked.account.expires_at, now))
1629
+ return { accessToken };
1630
+ const clientId = clientIdOf(picked.key, picked.account);
1631
+ if (!picked.account.refresh_token || !clientId) {
1632
+ if (tokenStillValid(picked.account.expires_at, now))
1633
+ return { accessToken };
1634
+ throw new GrokAuthError(GROK_LOGIN_MESSAGE);
1635
+ }
1636
+ let refreshed;
1637
+ try {
1638
+ refreshed = await refreshGrokAccess({
1639
+ refreshToken: picked.account.refresh_token,
1640
+ clientId,
1641
+ issuer: picked.account.oidc_issuer,
1642
+ fetchImpl: options.fetchImpl
1643
+ });
1644
+ } catch (error) {
1645
+ if (tokenStillValid(picked.account.expires_at, now))
1646
+ return { accessToken };
1647
+ if (error instanceof GrokAuthError)
1648
+ throw error;
1649
+ throw new GrokAuthError(GROK_LOGIN_MESSAGE);
1650
+ }
1651
+ const expiresAt = new Date(now + refreshed.expiresIn * 1e3).toISOString();
1652
+ const update = {
1653
+ accessToken: refreshed.accessToken,
1654
+ refreshToken: refreshed.refreshToken,
1655
+ expiresAt
1656
+ };
1657
+ let outcome;
1658
+ try {
1659
+ outcome = await persistRefreshedToken(path, picked.key, picked.account.refresh_token, update);
1660
+ } catch {
1661
+ if (!refreshed.refreshToken)
1662
+ return { accessToken: refreshed.accessToken };
1663
+ throw new GrokAuthError(GROK_LOGIN_MESSAGE);
1664
+ }
1665
+ if (outcome === "skipped") {
1666
+ const latest = pickGrokAccount(await readAuthFile(path));
1667
+ if (latest?.account.key)
1668
+ return { accessToken: latest.account.key };
1669
+ }
1670
+ return { accessToken: refreshed.accessToken };
1671
+ }
1672
+ async function refreshSession(path, options) {
1673
+ const handle = await acquireAuthLock(path);
1674
+ try {
1675
+ return await refreshSessionLocked(path, options);
1676
+ } finally {
1677
+ await releaseAuthLock(path, handle);
1678
+ }
1679
+ }
1680
+ async function freshTokenWithoutLock(path, now) {
1681
+ let file;
1682
+ try {
1683
+ file = await readAuthFile(path);
1684
+ } catch {
1685
+ return void 0;
1686
+ }
1687
+ const picked = pickGrokAccount(file);
1688
+ const accessToken = picked?.account.key;
1689
+ if (!picked || !accessToken)
1690
+ return void 0;
1691
+ if (tokenExpiresSoon(picked.account.expires_at, now))
1692
+ return void 0;
1693
+ return { accessToken };
1694
+ }
1695
+ async function loadGrokAccess(options = {}) {
1696
+ const path = options.authPath ?? await firstExisting(grokAuthCandidates(options.env, options.home ?? homedir2()));
1697
+ if (!path)
1698
+ throw new GrokAuthError(GROK_LOGIN_MESSAGE);
1699
+ const fresh = await freshTokenWithoutLock(path, options.now ?? Date.now());
1700
+ if (fresh)
1701
+ return fresh;
1702
+ const current = refreshFlights.get(path);
1703
+ if (current)
1704
+ return current;
1705
+ const flight = refreshSession(path, options);
1706
+ refreshFlights.set(path, flight);
1707
+ try {
1708
+ return await flight;
1709
+ } finally {
1710
+ if (refreshFlights.get(path) === flight)
1711
+ refreshFlights.delete(path);
1712
+ }
1713
+ }
1714
+
1715
+ // ../grok-core/dist/catalog.js
1716
+ import { readFileSync as readFileSync2 } from "node:fs";
1717
+ import { join as join3 } from "node:path";
1718
+ var GROK_BOOTSTRAP_MODEL_IDS = ["grok-4.7", "grok-4.7-build-fast", "grok-4.6", "grok-4.5"];
1719
+ var GROK_DEFAULT_CONTEXT_WINDOW = 256e3;
1720
+ var GROK_DEFAULT_MAX_TOKENS = 128e3;
1721
+ var GROK_CATALOG_PROVIDER_ID = "grok";
1722
+ var GROK_CATALOG_FILE = `${GROK_CATALOG_PROVIDER_ID}.models.json`;
1723
+ var GROK_CATALOG_CACHE_DIR_ENV = "NS_GROK_CATALOG_CACHE_DIR";
1724
+ function withGrokCompaction(model) {
1725
+ const budget = compactionBudget(model);
1726
+ return budget ? { ...model, compaction: budget } : model;
1727
+ }
1728
+ function grokBootstrapModels() {
1729
+ return GROK_BOOTSTRAP_MODEL_IDS.map((id) => withGrokCompaction({
1730
+ id,
1731
+ name: id,
1732
+ contextWindow: GROK_DEFAULT_CONTEXT_WINDOW,
1733
+ maxTokens: GROK_DEFAULT_MAX_TOKENS,
1734
+ reasoning: true,
1735
+ input: ["text"]
1736
+ }));
1737
+ }
1738
+ function grokModelsFromCatalogJson(raw) {
1739
+ if (!raw?.trim())
1740
+ return grokBootstrapModels();
1741
+ try {
1742
+ const parsed = JSON.parse(raw);
1743
+ if (!Array.isArray(parsed?.models))
1744
+ return grokBootstrapModels();
1745
+ const models = [];
1746
+ for (const entry of parsed.models) {
1747
+ if (!entry || typeof entry !== "object")
1748
+ continue;
1749
+ const row = entry;
1750
+ if (typeof row.id !== "string" || row.id.length === 0)
1751
+ continue;
1752
+ const input = Array.isArray(row.input) ? row.input.filter((item) => item === "text" || item === "image") : ["text"];
1753
+ models.push(withGrokCompaction({
1754
+ id: row.id,
1755
+ name: typeof row.name === "string" && row.name.length > 0 ? row.name : row.id,
1756
+ contextWindow: typeof row.contextWindow === "number" ? row.contextWindow : GROK_DEFAULT_CONTEXT_WINDOW,
1757
+ maxTokens: typeof row.maxTokens === "number" ? row.maxTokens : GROK_DEFAULT_MAX_TOKENS,
1758
+ reasoning: row.reasoning !== false,
1759
+ input: input.length > 0 ? input : ["text"]
1760
+ }));
1761
+ }
1762
+ return models.length > 0 ? models : grokBootstrapModels();
1763
+ } catch {
1764
+ return grokBootstrapModels();
1765
+ }
1766
+ }
1767
+ function grokCatalogPath(cacheDir) {
1768
+ return join3(cacheDir, GROK_CATALOG_FILE);
1769
+ }
1770
+ function readGrokCatalog(options) {
1771
+ const path = grokCatalogPath(options.cacheDir);
1772
+ try {
1773
+ const read = options.readFile ?? ((file) => readFileSync2(file, "utf8"));
1774
+ return grokModelsFromCatalogJson(read(path));
1775
+ } catch {
1776
+ return grokModelsFromCatalogJson(void 0);
1777
+ }
1778
+ }
1779
+
1780
+ // ../grok-core/dist/headers.js
1781
+ import { readFile as readFile2 } from "node:fs/promises";
1782
+ import { homedir as homedir3 } from "node:os";
1783
+ import { join as join4 } from "node:path";
1784
+ var FALLBACK_GROK_CLIENT_VERSION = "1.0.62";
1785
+ var DEFAULT_PROXY_BASE = "https://cli-chat-proxy.grok.com/v1";
1786
+ function grokProxyBase(env = process.env) {
1787
+ return (env.GROK_CLI_CHAT_PROXY_BASE_URL?.trim() || DEFAULT_PROXY_BASE).replace(/\/$/, "");
1788
+ }
1789
+ async function resolveGrokClientVersion(options) {
1790
+ const env = options?.env ?? process.env;
1791
+ const fromEnv = env.GROK_CLIENT_VERSION?.trim();
1792
+ if (fromEnv)
1793
+ return fromEnv;
1794
+ const path = options?.cachePath ?? join4(options?.home ?? homedir3(), ".grok", "models_cache.json");
1795
+ try {
1796
+ const json = JSON.parse(await readFile2(path, "utf8"));
1797
+ const version = json.grok_version?.trim();
1798
+ if (version)
1799
+ return version;
1800
+ } catch {
1801
+ }
1802
+ return FALLBACK_GROK_CLIENT_VERSION;
1803
+ }
1804
+ function grokResponseHeaders(input) {
1805
+ const conversationId = input.conversationId?.trim();
1806
+ return {
1807
+ "Content-Type": "application/json",
1808
+ Authorization: `Bearer ${input.accessToken}`,
1809
+ "X-XAI-Token-Auth": "xai-grok-cli",
1810
+ "x-grok-client-version": input.clientVersion,
1811
+ "x-grok-client-identifier": "grok-shell",
1812
+ "x-grok-client-mode": "xai-grok-cli",
1813
+ "User-Agent": `grok-cli/${input.clientVersion}`,
1814
+ "x-grok-model-override": input.modelId,
1815
+ ...conversationId ? { "x-grok-conv-id": conversationId } : {}
1816
+ };
1817
+ }
1818
+
1819
+ // ../grok-core/dist/request.js
1820
+ function userParts(content) {
1821
+ const parts = [];
1822
+ for (const part of content) {
1823
+ if (part.type === "text") {
1824
+ if (part.text)
1825
+ parts.push({ type: "input_text", text: part.text });
1826
+ } else if (part.data) {
1827
+ parts.push({ type: "input_image", image_url: `data:${part.mimeType};base64,${part.data}` });
1828
+ }
1829
+ }
1830
+ return parts;
1831
+ }
1832
+ function outputText(content) {
1833
+ return content.map((part) => part.type === "text" ? part.text : `data:${part.mimeType};base64,${part.data}`).filter((part) => part.length > 0).join("\n");
1834
+ }
1835
+ function toResponsesInput(messages) {
1836
+ const items = [];
1837
+ for (const message of messages) {
1838
+ if (message.role === "user") {
1839
+ const content = userParts(message.content);
1840
+ if (content.length > 0)
1841
+ items.push({ type: "message", role: "user", content });
1842
+ continue;
1843
+ }
1844
+ if (message.role === "assistant") {
1845
+ const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("");
1846
+ if (text)
1847
+ items.push({ type: "message", role: "assistant", content: [{ type: "output_text", text }] });
1848
+ for (const part of message.content) {
1849
+ if (part.type !== "toolCall")
1850
+ continue;
1851
+ items.push({
1852
+ type: "function_call",
1853
+ call_id: part.id,
1854
+ name: part.name,
1855
+ arguments: JSON.stringify(part.arguments ?? {})
1856
+ });
1857
+ }
1858
+ continue;
1859
+ }
1860
+ if (!message.toolCallId)
1861
+ continue;
1862
+ items.push({
1863
+ type: "function_call_output",
1864
+ call_id: message.toolCallId,
1865
+ output: outputText(message.content)
1866
+ });
1867
+ }
1868
+ return items;
1869
+ }
1870
+ function toolItem(tool) {
1871
+ return {
1872
+ type: "function",
1873
+ name: tool.name,
1874
+ description: tool.description,
1875
+ parameters: tool.parameters,
1876
+ ...typeof tool.strict === "boolean" ? { strict: tool.strict } : {}
1877
+ };
1878
+ }
1879
+ function wireEffort(effort) {
1880
+ return effort === "max" ? "xhigh" : effort;
1881
+ }
1882
+ function estimateResponsesTokens(body) {
1883
+ return Math.ceil(JSON.stringify(body).length / 4);
1884
+ }
1885
+ function fitResponsesBody(body, contextWindow = GROK_DEFAULT_CONTEXT_WINDOW) {
1886
+ const input = body.input;
1887
+ if (!Array.isArray(input) || estimateResponsesTokens(body) <= contextWindow)
1888
+ return body;
1889
+ const kept = input.slice();
1890
+ while (kept.length > 1 && estimateResponsesTokens({ ...body, input: kept }) > contextWindow) {
1891
+ const dropped = kept[0];
1892
+ kept.shift();
1893
+ if (dropped?.type === "function_call" && kept[0]?.type === "function_call_output") {
1894
+ kept.shift();
1895
+ }
1896
+ }
1897
+ return { ...body, input: kept };
1898
+ }
1899
+ function buildResponsesBody(input) {
1900
+ const body = {
1901
+ model: input.model,
1902
+ input: toResponsesInput(input.messages),
1903
+ stream: true
1904
+ };
1905
+ const instructions = input.systemPrompt?.trim();
1906
+ if (instructions)
1907
+ body.instructions = instructions;
1908
+ if (input.tools && input.tools.length > 0)
1909
+ body.tools = input.tools.map(toolItem);
1910
+ const effort = wireEffort(input.effort);
1911
+ if (effort)
1912
+ body.reasoning = { effort, summary: "auto" };
1913
+ const cacheKey = input.promptCacheKey?.trim();
1914
+ if (cacheKey)
1915
+ body.prompt_cache_key = cacheKey;
1916
+ return fitResponsesBody(body, input.contextWindow);
1917
+ }
1918
+
1919
+ // ../grok-core/dist/usage.js
1920
+ function nonNegative(value) {
1921
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
1922
+ return 0;
1923
+ return value;
1924
+ }
1925
+ function toGrokUsage(usage) {
1926
+ const inputTokens = nonNegative(usage.input_tokens);
1927
+ const cached = nonNegative(usage.input_tokens_details?.cached_tokens);
1928
+ const cacheRead = Math.min(cached, inputTokens);
1929
+ const input = inputTokens - cacheRead;
1930
+ const output = nonNegative(usage.output_tokens);
1931
+ const totalTokens = usage.total_tokens === void 0 ? input + cacheRead + output : nonNegative(usage.total_tokens);
1932
+ return {
1933
+ input,
1934
+ output,
1935
+ cacheRead,
1936
+ totalTokens,
1937
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
1938
+ };
1939
+ }
1940
+
1941
+ // ../grok-core/dist/sse.js
1942
+ function createResponsesState(requestedModel) {
1943
+ return {
1944
+ nextIndex: 0,
1945
+ started: false,
1946
+ settled: false,
1947
+ sawTool: false,
1948
+ stopReason: "stop",
1949
+ blocks: /* @__PURE__ */ new Map(),
1950
+ ...requestedModel ? { requestedModel } : {}
1951
+ };
1952
+ }
1953
+ function summaryText(item) {
1954
+ return (item?.summary ?? []).map((part) => part.text ?? "").join("");
1955
+ }
1956
+ function messageText(item) {
1957
+ return (item?.content ?? []).filter((part) => !part.type || part.type === "output_text").map((part) => part.text ?? "").join("");
1958
+ }
1959
+ function errorText(error) {
1960
+ if (!error)
1961
+ return "Grok responses error";
1962
+ if (typeof error === "string")
1963
+ return error.slice(0, 300);
1964
+ return (error.message ?? "Grok responses error").slice(0, 300);
1965
+ }
1966
+ function parseToolArguments(raw) {
1967
+ const argumentsJson = raw.trim() ? raw : "{}";
1968
+ try {
1969
+ const parsed = JSON.parse(argumentsJson);
1970
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1971
+ return { arguments: parsed, argumentsJson };
1972
+ }
1973
+ } catch {
1974
+ }
1975
+ return { arguments: {}, argumentsJson };
1976
+ }
1977
+ function remember(state, block, keys) {
1978
+ for (const key of keys) {
1979
+ if (key === void 0 || key === "")
1980
+ continue;
1981
+ state.blocks.set(String(key), block);
1982
+ }
1983
+ }
1984
+ function lookup(state, event) {
1985
+ const keys = [
1986
+ event.item_id,
1987
+ event.item?.id,
1988
+ event.output_index === void 0 ? void 0 : `out:${event.output_index}`
1989
+ ];
1990
+ for (const key of keys) {
1991
+ if (key === void 0)
1992
+ continue;
1993
+ const block = state.blocks.get(String(key));
1994
+ if (block)
1995
+ return block;
1996
+ }
1997
+ return void 0;
1998
+ }
1999
+ function ensureStart(state) {
2000
+ if (state.started)
2001
+ return [];
2002
+ state.started = true;
2003
+ return [{ type: "start" }];
2004
+ }
2005
+ function openBlock(state, kind, event, extra2 = {}) {
2006
+ const existing = lookup(state, event);
2007
+ if (existing && existing.kind === kind)
2008
+ return { block: existing, events: ensureStart(state) };
2009
+ const item = event.item;
2010
+ const block = {
2011
+ kind,
2012
+ index: state.nextIndex,
2013
+ id: extra2.id ?? item?.call_id ?? item?.id ?? event.item_id ?? `block-${state.nextIndex}`,
2014
+ name: extra2.name ?? item?.name ?? event.name ?? "",
2015
+ text: "",
2016
+ closed: false
2017
+ };
2018
+ state.nextIndex += 1;
2019
+ remember(state, block, [
2020
+ item?.id,
2021
+ event.item_id,
2022
+ block.id,
2023
+ event.output_index === void 0 ? void 0 : `out:${event.output_index}`
2024
+ ]);
2025
+ const events = ensureStart(state);
2026
+ if (kind === "thinking")
2027
+ events.push({ type: "thinking_start", index: block.index });
2028
+ else if (kind === "text")
2029
+ events.push({ type: "text_start", index: block.index });
2030
+ else {
2031
+ state.sawTool = true;
2032
+ events.push({ type: "tool_call_start", index: block.index, id: block.id, name: block.name });
2033
+ }
2034
+ return { block, events };
2035
+ }
2036
+ function closeBlock(block, full) {
2037
+ if (block.closed)
2038
+ return [];
2039
+ block.closed = true;
2040
+ const text = block.text || full || "";
2041
+ if (block.kind === "thinking")
2042
+ return [{ type: "thinking_end", index: block.index, thinking: text }];
2043
+ if (block.kind === "text")
2044
+ return [{ type: "text_end", index: block.index, text }];
2045
+ const parsed = parseToolArguments(text);
2046
+ return [
2047
+ {
2048
+ type: "tool_call_end",
2049
+ index: block.index,
2050
+ id: block.id,
2051
+ name: block.name,
2052
+ arguments: parsed.arguments,
2053
+ argumentsJson: parsed.argumentsJson
2054
+ }
2055
+ ];
2056
+ }
2057
+ function closeOpen(state) {
2058
+ const seen = /* @__PURE__ */ new Set();
2059
+ const events = [];
2060
+ const blocks = [...state.blocks.values()].sort((left, right) => left.index - right.index);
2061
+ for (const block of blocks) {
2062
+ if (seen.has(block))
2063
+ continue;
2064
+ seen.add(block);
2065
+ events.push(...closeBlock(block));
2066
+ }
2067
+ return events;
2068
+ }
2069
+ function applyStop(state, response) {
2070
+ if (state.sawTool) {
2071
+ state.stopReason = "toolUse";
2072
+ return;
2073
+ }
2074
+ const reason = response?.incomplete_details?.reason;
2075
+ if (response?.status === "incomplete" && reason === "max_output_tokens")
2076
+ state.stopReason = "length";
2077
+ }
2078
+ function settle(state, response) {
2079
+ if (state.settled)
2080
+ return [];
2081
+ state.settled = true;
2082
+ if (response?.id)
2083
+ state.responseId = response.id;
2084
+ if (response?.model && state.requestedModel && response.model !== state.requestedModel) {
2085
+ state.upstreamModel = response.model;
2086
+ }
2087
+ if (response?.usage)
2088
+ state.usage = response.usage;
2089
+ applyStop(state, response);
2090
+ const events = [...ensureStart(state), ...closeOpen(state)];
2091
+ if (state.usage)
2092
+ events.push({ type: "usage", usage: toGrokUsage(state.usage) });
2093
+ events.push({
2094
+ type: "done",
2095
+ stopReason: state.stopReason,
2096
+ ...state.responseId ? { responseId: state.responseId } : {},
2097
+ ...state.upstreamModel ? { upstreamModel: state.upstreamModel } : {}
2098
+ });
2099
+ return events;
2100
+ }
2101
+ function fillFromItem(block, item) {
2102
+ if (!item || block.text)
2103
+ return;
2104
+ if (block.kind === "thinking")
2105
+ block.text = summaryText(item);
2106
+ else if (block.kind === "text")
2107
+ block.text = messageText(item);
2108
+ else if (item.arguments)
2109
+ block.text = item.arguments;
2110
+ if (item.name && block.kind === "tool" && !block.name)
2111
+ block.name = item.name;
2112
+ }
2113
+ function reduceResponsesEvent(state, event) {
2114
+ if (state.settled)
2115
+ return [];
2116
+ const type = event.type;
2117
+ if (type === "error" || type === "response.failed")
2118
+ throw new GrokApiError(errorText(event.error ?? event.response?.error));
2119
+ if (event.response?.id)
2120
+ state.responseId = event.response.id;
2121
+ if (type === "response.created" || type === "response.in_progress")
2122
+ return ensureStart(state);
2123
+ if (type === "response.output_item.added") {
2124
+ const item = event.item;
2125
+ if (item?.type === "reasoning")
2126
+ return openBlock(state, "thinking", event).events;
2127
+ if (item?.type === "function_call") {
2128
+ const opened = openBlock(state, "tool", event, { id: item.call_id ?? item.id, name: item.name });
2129
+ if (item.arguments && !opened.block.closed && !opened.block.text) {
2130
+ opened.block.text = item.arguments;
2131
+ opened.events.push({
2132
+ type: "tool_call_delta",
2133
+ index: opened.block.index,
2134
+ id: opened.block.id,
2135
+ argumentsDelta: item.arguments
2136
+ });
2137
+ }
2138
+ return opened.events;
2139
+ }
2140
+ if (item?.type === "message" || item?.type === void 0)
2141
+ return openBlock(state, "text", event).events;
2142
+ return ensureStart(state);
2143
+ }
2144
+ if (type === "response.reasoning_summary_text.delta") {
2145
+ const opened = openBlock(state, "thinking", event);
2146
+ const delta = event.delta ?? "";
2147
+ opened.block.text += delta;
2148
+ if (delta)
2149
+ opened.events.push({ type: "thinking_delta", index: opened.block.index, delta });
2150
+ return opened.events;
2151
+ }
2152
+ if (type === "response.output_text.delta") {
2153
+ const opened = openBlock(state, "text", event);
2154
+ const delta = event.delta ?? event.text ?? "";
2155
+ opened.block.text += delta;
2156
+ if (delta)
2157
+ opened.events.push({ type: "text_delta", index: opened.block.index, delta });
2158
+ return opened.events;
2159
+ }
2160
+ if (type === "response.function_call_arguments.delta") {
2161
+ const opened = openBlock(state, "tool", event, { id: event.item_id, name: event.name });
2162
+ const delta = event.delta ?? "";
2163
+ opened.block.text += delta;
2164
+ if (delta) {
2165
+ opened.events.push({
2166
+ type: "tool_call_delta",
2167
+ index: opened.block.index,
2168
+ id: opened.block.id,
2169
+ argumentsDelta: delta
2170
+ });
2171
+ }
2172
+ return opened.events;
2173
+ }
2174
+ if (type === "response.function_call_arguments.done") {
2175
+ const opened = openBlock(state, "tool", event, { id: event.item_id, name: event.name });
2176
+ if (event.name)
2177
+ opened.block.name = event.name;
2178
+ const full = event.arguments ?? opened.block.text;
2179
+ opened.block.text = full;
2180
+ return [...opened.events, ...closeBlock(opened.block, full)];
2181
+ }
2182
+ if (type === "response.reasoning_summary_text.done" || type === "response.output_text.done") {
2183
+ const kind = type === "response.output_text.done" ? "text" : "thinking";
2184
+ const opened = openBlock(state, kind, event);
2185
+ if (!opened.block.text && event.text)
2186
+ opened.block.text = event.text;
2187
+ return opened.events;
2188
+ }
2189
+ if (type === "response.output_item.done") {
2190
+ const item = event.item;
2191
+ const kind = item?.type === "reasoning" ? "thinking" : item?.type === "function_call" ? "tool" : "text";
2192
+ if (item?.type !== "reasoning" && item?.type !== "function_call" && item?.type !== "message" && item?.type !== void 0) {
2193
+ return [];
2194
+ }
2195
+ const opened = openBlock(state, kind, event, {
2196
+ id: item?.call_id ?? item?.id,
2197
+ name: item?.name
2198
+ });
2199
+ fillFromItem(opened.block, item);
2200
+ if (item?.name && opened.block.kind === "tool")
2201
+ opened.block.name = item.name;
2202
+ return [...opened.events, ...closeBlock(opened.block)];
2203
+ }
2204
+ if (type === "response.completed" || type === "response.incomplete") {
2205
+ if (event.response?.status === "failed")
2206
+ throw new GrokApiError(errorText(event.response.error));
2207
+ const prelude = state.blocks.size === 0 ? absorbOutput(state, event.response?.output ?? []) : [];
2208
+ return [...prelude, ...settle(state, event.response)];
2209
+ }
2210
+ return [];
2211
+ }
2212
+ function absorbOutput(state, output) {
2213
+ const events = [];
2214
+ for (let index = 0; index < output.length; index += 1) {
2215
+ const item = output[index];
2216
+ if (!item)
2217
+ continue;
2218
+ events.push(...reduceResponsesEvent(state, { type: "response.output_item.added", output_index: index, item }));
2219
+ if (item.type === "reasoning") {
2220
+ const text = summaryText(item);
2221
+ if (text) {
2222
+ events.push(...reduceResponsesEvent(state, {
2223
+ type: "response.reasoning_summary_text.delta",
2224
+ item_id: item.id,
2225
+ output_index: index,
2226
+ delta: text
2227
+ }));
2228
+ }
2229
+ } else if (item.type === "message") {
2230
+ const text = messageText(item);
2231
+ if (text) {
2232
+ events.push(...reduceResponsesEvent(state, {
2233
+ type: "response.output_text.delta",
2234
+ item_id: item.id,
2235
+ output_index: index,
2236
+ delta: text
2237
+ }));
2238
+ }
2239
+ } else if (item.type === "function_call" && item.arguments) {
2240
+ events.push(...reduceResponsesEvent(state, {
2241
+ type: "response.function_call_arguments.done",
2242
+ item_id: item.id,
2243
+ output_index: index,
2244
+ name: item.name,
2245
+ arguments: item.arguments
2246
+ }));
2247
+ }
2248
+ events.push(...reduceResponsesEvent(state, { type: "response.output_item.done", output_index: index, item }));
2249
+ }
2250
+ return events;
2251
+ }
2252
+ function finishResponses(state) {
2253
+ return settle(state, void 0);
2254
+ }
2255
+ function sseData(frame) {
2256
+ const dataLines = [];
2257
+ for (const line of frame.split(/\r?\n/)) {
2258
+ if (!line.startsWith("data:"))
2259
+ continue;
2260
+ dataLines.push(line.slice("data:".length).replace(/^ /, ""));
2261
+ }
2262
+ if (dataLines.length === 0)
2263
+ return void 0;
2264
+ return dataLines.join("\n");
2265
+ }
2266
+ async function* parseSseJson(body) {
2267
+ const decoder = new TextDecoder();
2268
+ let buffer = "";
2269
+ const emit = function* (frame) {
2270
+ const data = sseData(frame);
2271
+ if (data === void 0 || data === "[DONE]")
2272
+ return;
2273
+ try {
2274
+ const parsed = JSON.parse(data);
2275
+ if (parsed && typeof parsed === "object")
2276
+ yield parsed;
2277
+ } catch {
2278
+ throw new GrokApiError("Grok responses stream was not JSON");
2279
+ }
2280
+ };
2281
+ for await (const chunk of body) {
2282
+ buffer += decoder.decode(chunk, { stream: true });
2283
+ const frames = buffer.split(/\r?\n\r?\n/);
2284
+ buffer = frames.pop() ?? "";
2285
+ for (const frame of frames)
2286
+ yield* emit(frame);
2287
+ }
2288
+ buffer += decoder.decode();
2289
+ if (buffer.trim())
2290
+ yield* emit(buffer);
2291
+ }
2292
+
2293
+ // ../grok-core/dist/stream.js
2294
+ function aborted() {
2295
+ const error = new Error("This operation was aborted");
2296
+ error.name = "AbortError";
2297
+ return error;
2298
+ }
2299
+ async function errorDetail(response) {
2300
+ let text = "";
2301
+ try {
2302
+ text = await response.text();
2303
+ } catch {
2304
+ return "";
2305
+ }
2306
+ const redact = (value) => value.replace(/Bearer\s+\S+/gi, "Bearer [redacted]");
2307
+ const redacted = redact(text).replace(/\s+/g, " ").trim();
2308
+ if (!redacted)
2309
+ return "";
2310
+ try {
2311
+ const json = JSON.parse(text);
2312
+ const message = typeof json.error === "string" ? json.error : json.error?.message ?? json.message;
2313
+ if (message)
2314
+ return redact(message).slice(0, 300);
2315
+ } catch {
2316
+ }
2317
+ return redacted.slice(0, 300);
2318
+ }
2319
+ async function* readBody(body) {
2320
+ const reader = body.getReader();
2321
+ try {
2322
+ for (; ; ) {
2323
+ const { done, value } = await reader.read();
2324
+ if (done)
2325
+ return;
2326
+ if (value)
2327
+ yield value;
2328
+ }
2329
+ } finally {
2330
+ reader.releaseLock();
2331
+ }
2332
+ }
2333
+ async function* eventsFromWire(events, requestedModel, signal) {
2334
+ const state = createResponsesState(requestedModel);
2335
+ for await (const event of events) {
2336
+ if (signal?.aborted)
2337
+ throw aborted();
2338
+ yield* reduceResponsesEvent(state, event);
2339
+ }
2340
+ if (signal?.aborted)
2341
+ throw aborted();
2342
+ yield* finishResponses(state);
2343
+ }
2344
+ function streamGrok(options) {
2345
+ return recordUsage(streamGrokResponse(options), {
2346
+ vendor: "grok",
2347
+ model: options.model,
2348
+ contextWindow: options.contextWindow,
2349
+ effort: options.effort,
2350
+ sessionId: options.promptCacheKey
2351
+ });
2352
+ }
2353
+ async function* streamGrokResponse(options) {
2354
+ if (options.signal?.aborted)
2355
+ throw aborted();
2356
+ const fetchImpl = options.fetchImpl ?? fetch;
2357
+ const access2 = options.accessToken ? { accessToken: options.accessToken } : await (options.loadAccess ?? (() => loadGrokAccess({ fetchImpl })))();
2358
+ const clientVersion = options.clientVersion ?? await resolveGrokClientVersion();
2359
+ const base = (options.proxyBaseUrl ?? grokProxyBase()).replace(/\/$/, "");
2360
+ const body = buildResponsesBody({
2361
+ model: options.model,
2362
+ systemPrompt: options.systemPrompt,
2363
+ messages: options.messages,
2364
+ tools: options.tools,
2365
+ effort: options.effort,
2366
+ contextWindow: options.contextWindow,
2367
+ promptCacheKey: options.promptCacheKey
2368
+ });
2369
+ const response = await fetchImpl(`${base}/responses`, {
2370
+ method: "POST",
2371
+ headers: grokResponseHeaders({
2372
+ accessToken: access2.accessToken,
2373
+ clientVersion,
2374
+ modelId: options.model,
2375
+ conversationId: options.promptCacheKey
2376
+ }),
2377
+ body: JSON.stringify(body),
2378
+ signal: options.signal
2379
+ });
2380
+ if (!response.ok) {
2381
+ const detail = await errorDetail(response);
2382
+ throw new GrokApiError(`Grok responses error (${response.status})${detail ? `: ${detail}` : ""}`, response.status);
2383
+ }
2384
+ if (!response.body)
2385
+ throw new GrokApiError("Grok responses error: empty body");
2386
+ const contentType = response.headers.get("content-type") ?? "";
2387
+ if (contentType.includes("application/json") && !contentType.includes("text/event-stream")) {
2388
+ const json = await response.json();
2389
+ yield* eventsFromWire([{ type: "response.completed", response: json }], options.model, options.signal);
2390
+ return;
2391
+ }
2392
+ yield* eventsFromWire(parseSseJson(readBody(response.body)), options.model, options.signal);
2393
+ }
2394
+
2395
+ // ../dsh-llm-grok/src/catalog.ts
2396
+ import { homedir as homedir4 } from "node:os";
2397
+ import { join as join5 } from "node:path";
2398
+ function grokCatalogCacheDir(home = homedir4(), env = process.env) {
2399
+ const override = env[GROK_CATALOG_CACHE_DIR_ENV]?.trim();
2400
+ if (override) return override;
2401
+ return join5(home, ".pi", "agent", "cache", "ns-pi-provider");
2402
+ }
2403
+ function modelsFromCatalogJson(raw) {
2404
+ return grokModelsFromCatalogJson(raw);
2405
+ }
2406
+ function readGrokCatalogFile(options) {
2407
+ return readGrokCatalog({
2408
+ cacheDir: grokCatalogCacheDir(options?.home, options?.env),
2409
+ ...options?.readFile ? { readFile: options.readFile } : {}
2410
+ });
2411
+ }
2412
+
2413
+ // ../dsh-llm-grok/src/errors.ts
2414
+ import { CONTEXT_WINDOW_EXCEEDED_CODE, isContextWindowExceededError, LlmError as LlmError2 } from "@deepseek-ai/dsh-llm";
2415
+ function statusOf(error) {
2416
+ return error instanceof GrokApiError ? error.status : void 0;
2417
+ }
2418
+ function toLlmError(error) {
2419
+ if (error instanceof LlmError2) return error;
2420
+ const cause = error instanceof Error ? error : void 0;
2421
+ const message = cause?.message ?? String(error);
2422
+ if (cause?.name === "AbortError") return new LlmError2(message, "ABORTED", { cause });
2423
+ const status = statusOf(error);
2424
+ const options = { cause, ...status !== void 0 ? { status } : {} };
2425
+ if (error instanceof GrokAuthError || message.includes("grok login")) return new LlmError2(message, "AUTH", options);
2426
+ if (status === 401 || status === 403) return new LlmError2(message, "AUTH", options);
2427
+ if (status === 429) return new LlmError2(message, "RATE_LIMIT", options);
2428
+ if (isContextWindowExceededError(message)) return new LlmError2(message, CONTEXT_WINDOW_EXCEEDED_CODE, options);
2429
+ return new LlmError2(message, "PROVIDER_ERROR", options);
2430
+ }
2431
+
2432
+ // ../dsh-llm-grok/src/adapter.ts
2433
+ var INPUT_MODALITIES = ["text", "image"];
2434
+ function reserveField(model) {
2435
+ const reserve = model.compaction?.reserveTokens ?? compactionReserveTokens(model);
2436
+ return reserve !== void 0 && reserve < model.maxTokens ? { compactionReserveTokens: reserve } : {};
2437
+ }
2438
+ var EFFORTS2 = ["minimal", "low", "medium", "high", "xhigh", "max"];
2439
+ function toAdapterModel(model) {
2440
+ return {
2441
+ id: model.id,
2442
+ name: model.name,
2443
+ input: INPUT_MODALITIES,
2444
+ contextWindow: model.contextWindow,
2445
+ maxTokens: model.maxTokens,
2446
+ // The catalog ceiling is the most one completion may run to. Reporting all
2447
+ // of it as reserved output, on top of the Harness headroom, compacts
2448
+ // grok-4.7 near 62k of its 256k window. Hold back Pi's 16,384 instead.
2449
+ ...reserveField(model),
2450
+ ...model.reasoning ? { efforts: EFFORTS2 } : {}
2451
+ };
2452
+ }
2453
+ function createGrokAdapter(options) {
2454
+ const spec = {
2455
+ provider: options.provider,
2456
+ displayName: options.displayName,
2457
+ catalog: () => readGrokCatalogFile().map(toAdapterModel),
2458
+ // Read once per request: the catalog file is what names each model's window,
2459
+ // and a refresh between turns has to take effect without restarting.
2460
+ contextWindow: (model) => readGrokCatalogFile().find((candidate) => candidate.id === model)?.contextWindow ?? GROK_DEFAULT_CONTEXT_WINDOW,
2461
+ // Grok authenticates from the local CLI session inside the core, so there is
2462
+ // no per-request credential to resolve here.
2463
+ credentials: async () => void 0,
2464
+ ...options.attachments ? { attachments: options.attachments } : {},
2465
+ stream: (request) => {
2466
+ const tools = request.tools?.map((tool) => ({
2467
+ name: tool.name,
2468
+ description: tool.description,
2469
+ parameters: tool.parameters
2470
+ }));
2471
+ return streamGrok({
2472
+ model: request.model,
2473
+ messages: request.messages,
2474
+ systemPrompt: request.system,
2475
+ tools,
2476
+ effort: toBridgeEffort(request.reasoningEffort),
2477
+ contextWindow: request.contextWindow,
2478
+ // The Harness session id is stable across every turn, compaction and
2479
+ // title call of one session, which is exactly the cache-routing key xAI wants.
2480
+ ...request.sessionId ? { promptCacheKey: String(request.sessionId) } : {},
2481
+ signal: request.signal
2482
+ });
2483
+ }
2484
+ };
2485
+ return createDshLlmAdapter(spec, toLlmError);
2486
+ }
2487
+
2488
+ // ../dsh-llm-grok/src/index.ts
2489
+ var name = "llm-grok";
2490
+ var inject = ["llm"];
2491
+ var Config = Schema.object({
2492
+ provider: Schema.string().default("grok").description("Provider route to register the adapter under."),
2493
+ displayName: Schema.string().default("Grok").description("Display name shown in model selectors.")
2494
+ });
2495
+ function apply(ctx, config) {
2496
+ let attachments;
2497
+ ctx.inject(["attachments"], (scope) => {
2498
+ attachments = scope.attachments;
2499
+ scope.effect(
2500
+ () => () => {
2501
+ attachments = void 0;
2502
+ },
2503
+ "dsh-llm-grok attachment store"
2504
+ );
2505
+ });
2506
+ ctx.llm.registerAdapter(
2507
+ [config.provider],
2508
+ createGrokAdapter({
2509
+ provider: config.provider,
2510
+ displayName: config.displayName,
2511
+ attachments: () => attachments
2512
+ })
2513
+ );
2514
+ }
2515
+ export {
2516
+ Config,
2517
+ apply,
2518
+ createGrokAdapter,
2519
+ inject,
2520
+ modelsFromCatalogJson,
2521
+ name,
2522
+ readGrokCatalogFile
2523
+ };