@dungsil/dsh-plugin-cli-proxy-api 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1737 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { clientRequestSchema } from "@deepseek-ai/dsh-client-connection";
3
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
+ // ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.6/node_modules/@deepseek-ai/cosmokit/lib/index.js
5
+ /** Return true when a value is `null` or `undefined`. */
6
+ function isNullable(value) {
7
+ return value === null || value === void 0;
8
+ }
9
+ /** Return true for non-array object values. */
10
+ function isPlainObject(data) {
11
+ return data && typeof data === "object" && !Array.isArray(data);
12
+ }
13
+ /** Filter object entries and return a new object. */
14
+ function filterKeys(object, filter) {
15
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
16
+ }
17
+ /** Map object values while preserving the original key set. */
18
+ function mapValues(object, transform) {
19
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
20
+ }
21
+ /** Pick selected keys from an object, optionally including `undefined` values. */
22
+ function pick(source, keys, forced) {
23
+ if (!keys) return { ...source };
24
+ const result = {};
25
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
26
+ return result;
27
+ }
28
+ /** Shared config references used by schema validators and plugin runtimes. */
29
+ const write = Symbol.for("cosmokit.volatile.write");
30
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
31
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
32
+ if (value === null || typeof value !== "object") return value;
33
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
34
+ ancestors.add(value);
35
+ try {
36
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
37
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
38
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
39
+ } finally {
40
+ ancestors.delete(value);
41
+ }
42
+ }
43
+ /**
44
+ * Create a detached reference containing an immutable copy of the supplied data.
45
+ * @param value - validated config data; class instances and functions are unsupported.
46
+ * @returns a reference whose value is updated only by its owning runtime.
47
+ */
48
+ function createVolatile(value) {
49
+ let current = snapshot(value);
50
+ return Object.freeze({
51
+ get: () => current,
52
+ [write]: (value) => {
53
+ current = value;
54
+ }
55
+ });
56
+ }
57
+ /**
58
+ * Identify references across ESM/CJS copies of the shared library.
59
+ * @param value - a parsed config value.
60
+ * @returns whether the value implements the shared reference protocol.
61
+ */
62
+ function isVolatile(value) {
63
+ return typeof value === "object" && value !== null && write in value;
64
+ }
65
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
66
+ function is(type, value) {
67
+ if (arguments.length === 1) return (value) => is(type, value);
68
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
69
+ }
70
+ function isArrayBufferLike(value) {
71
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
72
+ }
73
+ function isArrayBufferSource(value) {
74
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
75
+ }
76
+ /** Binary source detection and base64/hex conversion helpers. */
77
+ var Binary;
78
+ (function(Binary) {
79
+ Binary.is = isArrayBufferLike;
80
+ Binary.isSource = isArrayBufferSource;
81
+ function fromSource(source) {
82
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
83
+ else return source;
84
+ }
85
+ Binary.fromSource = fromSource;
86
+ function toBase64(source) {
87
+ source = fromSource(source);
88
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
89
+ let binary = "";
90
+ const bytes = new Uint8Array(source);
91
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
92
+ return btoa(binary);
93
+ }
94
+ Binary.toBase64 = toBase64;
95
+ function fromBase64(source) {
96
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
97
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
98
+ }
99
+ Binary.fromBase64 = fromBase64;
100
+ function toHex(source) {
101
+ source = fromSource(source);
102
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
103
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
104
+ }
105
+ Binary.toHex = toHex;
106
+ function fromHex(source) {
107
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
108
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
109
+ const buffer = [];
110
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
111
+ return Uint8Array.from(buffer).buffer;
112
+ }
113
+ Binary.fromHex = fromHex;
114
+ })(Binary || (Binary = {}));
115
+ Binary.fromBase64;
116
+ Binary.toBase64;
117
+ Binary.fromHex;
118
+ Binary.toHex;
119
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
120
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
121
+ if (!source || typeof source !== "object") return source;
122
+ if (is("Date", source)) return new Date(source.valueOf());
123
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
124
+ if (isArrayBufferLike(source)) return source.slice(0);
125
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
126
+ const cached = refs.get(source);
127
+ if (cached) return cached;
128
+ if (Array.isArray(source)) {
129
+ const result = [];
130
+ refs.set(source, result);
131
+ source.forEach((value, index) => {
132
+ result[index] = Reflect.apply(clone, null, [value, refs]);
133
+ });
134
+ return result;
135
+ }
136
+ const result = Object.create(Object.getPrototypeOf(source));
137
+ refs.set(source, result);
138
+ for (const key of Reflect.ownKeys(source)) {
139
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
140
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
141
+ Reflect.defineProperty(result, key, descriptor);
142
+ }
143
+ return result;
144
+ }
145
+ /**
146
+ * Compare values recursively, treating two volatile references as equal regardless of value.
147
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
148
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
149
+ * @param a - first value.
150
+ * @param b - second value.
151
+ * @param strict - whether to require strict data equality outside volatile references.
152
+ * @returns whether the values compare equal.
153
+ */
154
+ function deepEqual(a, b, strict) {
155
+ const ancestors = /* @__PURE__ */ new Set();
156
+ function compare(a, b) {
157
+ if (a === b) return true;
158
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
159
+ if (!strict && isNullable(a) && isNullable(b)) return true;
160
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
161
+ if (ancestors.has(a)) return false;
162
+ function check(test, then) {
163
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
164
+ }
165
+ ancestors.add(a);
166
+ try {
167
+ return check(Array.isArray, (a, b) => {
168
+ if (a.length !== b.length) return false;
169
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
170
+ return true;
171
+ }) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("URL"), (a, b) => a.href === b.href) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
172
+ if (a.byteLength !== b.byteLength) return false;
173
+ const viewA = new Uint8Array(a);
174
+ const viewB = new Uint8Array(b);
175
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
176
+ return true;
177
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
178
+ ...a,
179
+ ...b
180
+ }).every((key) => compare(a[key], b[key])));
181
+ } finally {
182
+ ancestors.delete(a);
183
+ }
184
+ }
185
+ return compare(a, b);
186
+ }
187
+ /** Time constants plus parsing and formatting helpers. */
188
+ var Time;
189
+ (function(Time) {
190
+ Time.millisecond = 1;
191
+ Time.second = 1e3;
192
+ Time.minute = Time.second * 60;
193
+ Time.hour = Time.minute * 60;
194
+ Time.day = Time.hour * 24;
195
+ Time.week = Time.day * 7;
196
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
197
+ function setTimezoneOffset(offset) {
198
+ timezoneOffset = offset;
199
+ }
200
+ Time.setTimezoneOffset = setTimezoneOffset;
201
+ function getTimezoneOffset() {
202
+ return timezoneOffset;
203
+ }
204
+ Time.getTimezoneOffset = getTimezoneOffset;
205
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
206
+ if (typeof date === "number") date = new Date(date);
207
+ if (offset === void 0) offset = timezoneOffset;
208
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
209
+ }
210
+ Time.getDateNumber = getDateNumber;
211
+ function fromDateNumber(value, offset) {
212
+ const date = new Date(value * Time.day);
213
+ if (offset === void 0) offset = timezoneOffset;
214
+ return new Date(+date + offset * Time.minute);
215
+ }
216
+ Time.fromDateNumber = fromDateNumber;
217
+ const numeric = /\d+(?:\.\d+)?/.source;
218
+ const timeRegExp = new RegExp(`^${[
219
+ "w(?:eek(?:s)?)?",
220
+ "d(?:ay(?:s)?)?",
221
+ "h(?:our(?:s)?)?",
222
+ "m(?:in(?:ute)?(?:s)?)?",
223
+ "s(?:ec(?:ond)?(?:s)?)?"
224
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
225
+ function parseTime(source) {
226
+ const capture = timeRegExp.exec(source);
227
+ if (!capture) return 0;
228
+ return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
229
+ }
230
+ Time.parseTime = parseTime;
231
+ function parseDate(date) {
232
+ const parsed = parseTime(date);
233
+ if (parsed) date = Date.now() + parsed;
234
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
235
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
236
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
237
+ }
238
+ Time.parseDate = parseDate;
239
+ function format(ms) {
240
+ const abs = Math.abs(ms);
241
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
242
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
243
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
244
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
245
+ return ms + "ms";
246
+ }
247
+ Time.format = format;
248
+ function toDigits(source, length = 2) {
249
+ return source.toString().padStart(length, "0");
250
+ }
251
+ Time.toDigits = toDigits;
252
+ function template(template, time = /* @__PURE__ */ new Date()) {
253
+ return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
254
+ }
255
+ Time.template = template;
256
+ })(Time || (Time = {}));
257
+ // ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.5/node_modules/@deepseek-ai/schemastery/lib/index.mjs
258
+ const kSchema = Symbol.for("schemastery");
259
+ const kValidationError = Symbol.for("ValidationError");
260
+ globalThis.__schemastery_index__ ??= 0;
261
+ globalThis.__schemastery_refs__ = void 0;
262
+ var ValidationError = class extends TypeError {
263
+ options;
264
+ name = "ValidationError";
265
+ constructor(message, options) {
266
+ let prefix = "$";
267
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
268
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
269
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
270
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
271
+ super((prefix === "$" ? "" : `${prefix} `) + message);
272
+ this.options = options;
273
+ }
274
+ static is(error) {
275
+ return !!error?.[kValidationError];
276
+ }
277
+ };
278
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
279
+ const Schema = function(options) {
280
+ const schema = function(data, options = {}) {
281
+ return Schema.resolve(data, schema, options)[0];
282
+ };
283
+ if (options.refs) {
284
+ const refs = mapValues(options.refs, (options) => new Schema(options));
285
+ const getRef = (uid) => refs[uid];
286
+ for (const key in refs) {
287
+ const options = refs[key];
288
+ options.sKey = getRef(options.sKey);
289
+ options.inner = getRef(options.inner);
290
+ options.list = options.list && options.list.map(getRef);
291
+ options.dict = options.dict && mapValues(options.dict, getRef);
292
+ }
293
+ return refs[options.uid];
294
+ }
295
+ Object.assign(schema, options);
296
+ if (typeof schema.callback === "string") try {
297
+ schema.callback = new Function("return " + schema.callback)();
298
+ } catch {}
299
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
300
+ Object.setPrototypeOf(schema, Schema.prototype);
301
+ schema.meta ||= {};
302
+ schema.toString = schema.toString.bind(schema);
303
+ return schema;
304
+ };
305
+ Schema.prototype = Object.create(Function.prototype);
306
+ Schema.prototype[kSchema] = true;
307
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
308
+ return {
309
+ version: 1,
310
+ vendor: "schemastery",
311
+ validate: (value) => {
312
+ try {
313
+ return { value: Schema.resolve(value, this, {})[0] };
314
+ } catch (error) {
315
+ if (ValidationError.is(error)) return { issues: [{
316
+ message: error.message,
317
+ path: error.options.path
318
+ }] };
319
+ throw error;
320
+ }
321
+ }
322
+ };
323
+ } });
324
+ Schema.ValidationError = ValidationError;
325
+ Schema.prototype.toJSON = function toJSON() {
326
+ if (globalThis.__schemastery_refs__) {
327
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
328
+ return this.uid;
329
+ }
330
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
331
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
332
+ const result = {
333
+ uid: this.uid,
334
+ refs: globalThis.__schemastery_refs__
335
+ };
336
+ globalThis.__schemastery_refs__ = void 0;
337
+ return result;
338
+ };
339
+ Schema.prototype.set = function set(key, value) {
340
+ this.dict[key] = value;
341
+ return this;
342
+ };
343
+ Schema.prototype.push = function push(value) {
344
+ this.list.push(value);
345
+ return this;
346
+ };
347
+ function mergeDesc(original, messages) {
348
+ const result = typeof original === "string" ? { "": original } : { ...original };
349
+ for (const locale in messages) {
350
+ const value = messages[locale];
351
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
352
+ else if (typeof value === "string") result[locale] = value;
353
+ }
354
+ return result;
355
+ }
356
+ function getInner(value) {
357
+ return value?.$value ?? value?.$inner;
358
+ }
359
+ function extractKeys(data) {
360
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
361
+ }
362
+ Schema.prototype.i18n = function i18n(messages) {
363
+ const schema = Schema(this);
364
+ const desc = mergeDesc(schema.meta.description, messages);
365
+ if (Object.keys(desc).length) schema.meta.description = desc;
366
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
367
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
368
+ });
369
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
370
+ return inner.i18n(mapValues(messages, (data = {}) => {
371
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
372
+ if (Array.isArray(data)) return data[index];
373
+ return extractKeys(data);
374
+ }));
375
+ });
376
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
377
+ if (getInner(data)) return getInner(data);
378
+ return extractKeys(data);
379
+ }));
380
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
381
+ return schema;
382
+ };
383
+ Schema.prototype.extra = function extra(key, value) {
384
+ const schema = Schema(this);
385
+ schema.meta = {
386
+ ...schema.meta,
387
+ [key]: value
388
+ };
389
+ return schema;
390
+ };
391
+ for (const key of [
392
+ "required",
393
+ "disabled",
394
+ "collapse",
395
+ "hidden",
396
+ "loose"
397
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
398
+ const schema = Schema(this);
399
+ schema.meta = {
400
+ ...schema.meta,
401
+ [key]: value
402
+ };
403
+ return schema;
404
+ } });
405
+ Schema.prototype.deprecated = function deprecated() {
406
+ const schema = Schema(this);
407
+ schema.meta.badges ||= [];
408
+ schema.meta.badges.push({
409
+ text: "deprecated",
410
+ type: "danger"
411
+ });
412
+ return schema;
413
+ };
414
+ Schema.prototype.experimental = function experimental() {
415
+ const schema = Schema(this);
416
+ schema.meta.badges ||= [];
417
+ schema.meta.badges.push({
418
+ text: "experimental",
419
+ type: "warning"
420
+ });
421
+ return schema;
422
+ };
423
+ Schema.prototype.pattern = function pattern(regexp) {
424
+ const schema = Schema(this);
425
+ const pattern = pick(regexp, ["source", "flags"]);
426
+ schema.meta = {
427
+ ...schema.meta,
428
+ pattern
429
+ };
430
+ return schema;
431
+ };
432
+ Schema.prototype.simplify = function simplify(value) {
433
+ if (isVolatile(value)) value = value.get();
434
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
435
+ if (isNullable(value)) return value;
436
+ if (this.type === "object" || this.type === "dict") {
437
+ const result = {};
438
+ for (const key in value) {
439
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
440
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
441
+ }
442
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
443
+ return result;
444
+ } else if (this.type === "array" || this.type === "tuple") {
445
+ const result = [];
446
+ value.forEach((value, index) => {
447
+ const schema = this.type === "array" ? this.inner : this.list[index];
448
+ const item = schema ? schema.simplify(value) : value;
449
+ result.push(item);
450
+ });
451
+ return result;
452
+ } else if (this.type === "intersect") {
453
+ const result = {};
454
+ for (const item of this.list) Object.assign(result, item.simplify(value));
455
+ return result;
456
+ } else if (this.type === "union") for (const schema of this.list) try {
457
+ Schema.resolve(value, schema, {});
458
+ return schema.simplify(value);
459
+ } catch {}
460
+ return value;
461
+ };
462
+ Schema.prototype.toString = function toString(inline) {
463
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
464
+ };
465
+ Schema.prototype.role = function role(role, extra) {
466
+ const schema = Schema(this);
467
+ schema.meta = {
468
+ ...schema.meta,
469
+ role,
470
+ extra
471
+ };
472
+ return schema;
473
+ };
474
+ for (const key of [
475
+ "default",
476
+ "link",
477
+ "comment",
478
+ "description",
479
+ "max",
480
+ "min",
481
+ "step"
482
+ ]) Object.assign(Schema.prototype, { [key](value) {
483
+ const schema = Schema(this);
484
+ schema.meta = {
485
+ ...schema.meta,
486
+ [key]: value
487
+ };
488
+ return schema;
489
+ } });
490
+ Schema.prototype.volatile = function volatile() {
491
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
492
+ return this.extra("volatile", true);
493
+ };
494
+ const resolvers = {};
495
+ const checkedVolatile = Symbol("checked-volatile-schema");
496
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
497
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
498
+ if (states.has(blocked)) return;
499
+ states.add(blocked);
500
+ seen.set(schema, states);
501
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
502
+ const nested = blocked || !!schema.meta?.volatile;
503
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
504
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
505
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
506
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
507
+ }
508
+ Schema.extend = function extend(type, resolve) {
509
+ resolvers[type] = resolve;
510
+ };
511
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
512
+ if (!schema) return [data];
513
+ if (!options[checkedVolatile]) {
514
+ validateVolatileSchema(schema, options.path);
515
+ options = {
516
+ ...options,
517
+ [checkedVolatile]: true
518
+ };
519
+ }
520
+ if (schema.meta?.volatile) {
521
+ const inner = Schema(schema);
522
+ inner.meta = {
523
+ ...schema.meta,
524
+ volatile: false
525
+ };
526
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
527
+ try {
528
+ return [createVolatile(value), adapted];
529
+ } catch (error) {
530
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
531
+ }
532
+ }
533
+ if (options.ignore?.(data, schema)) return [data];
534
+ if (isNullable(data) && schema.type !== "lazy") {
535
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
536
+ let current = schema;
537
+ let fallback = schema.meta.default;
538
+ while (current?.type === "intersect" && isNullable(fallback)) {
539
+ current = current.list[0];
540
+ fallback = current?.meta.default;
541
+ }
542
+ if (isNullable(fallback)) return [data];
543
+ data = clone(fallback);
544
+ }
545
+ const callback = resolvers[schema.type];
546
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
547
+ try {
548
+ return callback(data, schema, options, strict);
549
+ } catch (error) {
550
+ if (!schema.meta.loose) throw error;
551
+ return [schema.meta.default];
552
+ }
553
+ };
554
+ Schema.from = function from(source) {
555
+ if (isNullable(source)) return Schema.any();
556
+ else if ([
557
+ "string",
558
+ "number",
559
+ "boolean"
560
+ ].includes(typeof source)) return Schema.const(source).required();
561
+ else if (source[kSchema]) return source;
562
+ else if (typeof source === "function") switch (source) {
563
+ case String: return Schema.string().required();
564
+ case Number: return Schema.number().required();
565
+ case Boolean: return Schema.boolean().required();
566
+ case Function: return Schema.function().required();
567
+ default: return Schema.is(source).required();
568
+ }
569
+ else throw new TypeError(`cannot infer schema from ${source}`);
570
+ };
571
+ Schema.lazy = function lazy(builder) {
572
+ const toJSON = () => {
573
+ if (!schema.inner[kSchema]) {
574
+ schema.inner = schema.builder();
575
+ schema.inner.meta = {
576
+ ...schema.meta,
577
+ ...schema.inner.meta
578
+ };
579
+ }
580
+ return schema.inner.toJSON();
581
+ };
582
+ const schema = new Schema({
583
+ type: "lazy",
584
+ builder,
585
+ inner: { toJSON }
586
+ });
587
+ return schema;
588
+ };
589
+ Schema.natural = function natural() {
590
+ return Schema.number().step(1).min(0);
591
+ };
592
+ Schema.percent = function percent() {
593
+ return Schema.number().step(.01).min(0).max(1).role("slider");
594
+ };
595
+ Schema.date = function date() {
596
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
597
+ const date = new Date(value);
598
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
599
+ return date;
600
+ }, true)]);
601
+ };
602
+ Schema.regExp = function regExp(flag = "") {
603
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
604
+ try {
605
+ return new RegExp(value, flag);
606
+ } catch (e) {
607
+ throw new ValidationError(e.message, options);
608
+ }
609
+ }, true)]);
610
+ };
611
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
612
+ return Schema.union([
613
+ Schema.is(ArrayBuffer),
614
+ Schema.is(SharedArrayBuffer),
615
+ Schema.transform(Schema.any(), (value, options) => {
616
+ if (Binary.isSource(value)) return Binary.fromSource(value);
617
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
618
+ }, true),
619
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
620
+ try {
621
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
622
+ } catch (e) {
623
+ throw new ValidationError(e.message, options);
624
+ }
625
+ }, true)] : []
626
+ ]);
627
+ };
628
+ Schema.extend("lazy", (data, schema, options, strict) => {
629
+ if (!schema.inner[kSchema]) {
630
+ schema.inner = schema.builder();
631
+ schema.inner.meta = {
632
+ ...schema.meta,
633
+ ...schema.inner.meta
634
+ };
635
+ validateVolatileSchema(schema.inner, options.path, true);
636
+ }
637
+ return Schema.resolve(data, schema.inner, options, strict);
638
+ });
639
+ Schema.extend("any", (data) => {
640
+ return [data];
641
+ });
642
+ Schema.extend("never", (data, _, options) => {
643
+ throw new ValidationError(`expected nullable but got ${data}`, options);
644
+ });
645
+ Schema.extend("const", (data, { value }, options) => {
646
+ if (deepEqual(data, value)) return [value];
647
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
648
+ });
649
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
650
+ const { max = Infinity, min = -Infinity } = meta;
651
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
652
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
653
+ }
654
+ Schema.extend("string", (data, { meta }, options) => {
655
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
656
+ if (meta.pattern) {
657
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
658
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
659
+ }
660
+ checkWithinRange(data.length, meta, "string length", options);
661
+ return [data];
662
+ });
663
+ function decimalShift(data, digits) {
664
+ const str = data.toString();
665
+ if (str.includes("e")) return data * Math.pow(10, digits);
666
+ const index = str.indexOf(".");
667
+ if (index === -1) return data * Math.pow(10, digits);
668
+ const frac = str.slice(index + 1);
669
+ const integer = str.slice(0, index);
670
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
671
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
672
+ }
673
+ function isMultipleOf(data, min, step) {
674
+ step = Math.abs(step);
675
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
676
+ const index = step.toString().indexOf(".");
677
+ const digits = step.toString().slice(index + 1).length;
678
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
679
+ }
680
+ Schema.extend("number", (data, { meta }, options) => {
681
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
682
+ checkWithinRange(data, meta, "number", options);
683
+ const { step } = meta;
684
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
685
+ return [data];
686
+ });
687
+ Schema.extend("boolean", (data, _, options) => {
688
+ if (typeof data === "boolean") return [data];
689
+ throw new ValidationError(`expected boolean but got ${data}`, options);
690
+ });
691
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
692
+ let value = 0, keys = [];
693
+ if (typeof data === "number") {
694
+ value = data;
695
+ for (const key in bits) if (data & bits[key]) keys.push(key);
696
+ } else if (Array.isArray(data)) {
697
+ keys = data;
698
+ for (const key of keys) {
699
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
700
+ if (key in bits) value |= bits[key];
701
+ }
702
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
703
+ if (value === meta.default) return [value];
704
+ return [value, keys];
705
+ });
706
+ Schema.extend("function", (data, _, options) => {
707
+ if (typeof data === "function") return [data];
708
+ throw new ValidationError(`expected function but got ${data}`, options);
709
+ });
710
+ Schema.extend("is", (data, { constructor }, options) => {
711
+ if (typeof constructor === "function") {
712
+ if (data instanceof constructor) return [data];
713
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
714
+ } else {
715
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
716
+ let prototype = Object.getPrototypeOf(data);
717
+ while (prototype) {
718
+ if (prototype.constructor?.name === constructor) return [data];
719
+ prototype = Object.getPrototypeOf(prototype);
720
+ }
721
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
722
+ }
723
+ });
724
+ function property(data, key, schema, options) {
725
+ try {
726
+ const [value, adapted] = Schema.resolve(data[key], schema, {
727
+ ...options,
728
+ path: [...options.path || [], key]
729
+ });
730
+ if (adapted !== void 0) data[key] = adapted;
731
+ return value;
732
+ } catch (e) {
733
+ if (!options?.autofix) throw e;
734
+ delete data[key];
735
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
736
+ }
737
+ }
738
+ Schema.extend("array", (data, { inner, meta }, options) => {
739
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
740
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
741
+ return [data.map((_, index) => property(data, index, inner, options))];
742
+ });
743
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
744
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
745
+ const result = {};
746
+ for (const key in data) {
747
+ let rKey;
748
+ try {
749
+ rKey = Schema.resolve(key, sKey, options)[0];
750
+ } catch (error) {
751
+ if (strict) continue;
752
+ throw error;
753
+ }
754
+ result[rKey] = property(data, key, inner, options);
755
+ data[rKey] = data[key];
756
+ if (key !== rKey) delete data[key];
757
+ }
758
+ return [result];
759
+ });
760
+ Schema.extend("tuple", (data, { list }, options, strict) => {
761
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
762
+ const result = list.map((inner, index) => property(data, index, inner, options));
763
+ if (strict) return [result];
764
+ result.push(...data.slice(list.length));
765
+ return [result];
766
+ });
767
+ function merge(result, data) {
768
+ for (const key in data) {
769
+ if (key in result) continue;
770
+ result[key] = data[key];
771
+ }
772
+ }
773
+ Schema.extend("object", (data, { dict }, options, strict) => {
774
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
775
+ const result = {};
776
+ for (const key in dict) {
777
+ const value = property(data, key, dict[key], options);
778
+ if (!isNullable(value) || key in data) result[key] = value;
779
+ }
780
+ if (!strict) merge(result, data);
781
+ return [result];
782
+ });
783
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
784
+ const messages = [];
785
+ for (const inner of list) try {
786
+ return Schema.resolve(data, inner, options, strict);
787
+ } catch (error) {
788
+ messages.push(error);
789
+ }
790
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
791
+ });
792
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
793
+ if (!list.length) return [data];
794
+ let result;
795
+ for (const inner of list) {
796
+ const value = Schema.resolve(data, inner, options, true)[0];
797
+ if (isNullable(value)) continue;
798
+ if (isNullable(result)) result = value;
799
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
800
+ else if (typeof value === "object") merge(result ??= {}, value);
801
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
802
+ }
803
+ if (!strict && isPlainObject(data)) merge(result, data);
804
+ return [result];
805
+ });
806
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
807
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
808
+ if (preserve) return [callback(result)];
809
+ else return [callback(result), callback(adapted)];
810
+ });
811
+ const formatters = {};
812
+ function defineMethod(name, keys, format) {
813
+ formatters[name] = format;
814
+ Object.assign(Schema, { [name](...args) {
815
+ const schema = new Schema({ type: name });
816
+ keys.forEach((key, index) => {
817
+ switch (key) {
818
+ case "sKey":
819
+ schema.sKey = args[index] ?? Schema.string();
820
+ break;
821
+ case "inner":
822
+ schema.inner = Schema.from(args[index]);
823
+ break;
824
+ case "list":
825
+ schema.list = args[index].map(Schema.from);
826
+ break;
827
+ case "dict":
828
+ schema.dict = mapValues(args[index], Schema.from);
829
+ break;
830
+ case "bits":
831
+ schema.bits = {};
832
+ for (const key in args[index]) {
833
+ if (typeof args[index][key] !== "number") continue;
834
+ schema.bits[key] = args[index][key];
835
+ }
836
+ break;
837
+ case "callback": {
838
+ const callback = schema.callback = args[index];
839
+ callback["toJSON"] ||= () => callback.toString();
840
+ break;
841
+ }
842
+ case "constructor": {
843
+ const constructor = schema.constructor = args[index];
844
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
845
+ break;
846
+ }
847
+ default: schema[key] = args[index];
848
+ }
849
+ });
850
+ if (name === "object" || name === "dict") schema.meta.default = {};
851
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
852
+ else if (name === "bitset") schema.meta.default = 0;
853
+ return schema;
854
+ } });
855
+ }
856
+ defineMethod("is", ["constructor"], ({ constructor }) => {
857
+ if (typeof constructor === "function") return constructor.name;
858
+ else return constructor;
859
+ });
860
+ defineMethod("any", [], () => "any");
861
+ defineMethod("never", [], () => "never");
862
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
863
+ defineMethod("string", [], () => "string");
864
+ defineMethod("number", [], () => "number");
865
+ defineMethod("boolean", [], () => "boolean");
866
+ defineMethod("bitset", ["bits"], () => "bitset");
867
+ defineMethod("function", [], () => "function");
868
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
869
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
870
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
871
+ defineMethod("object", ["dict"], ({ dict }) => {
872
+ if (Object.keys(dict).length === 0) return "{}";
873
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
874
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
875
+ }).join(", ")} }`;
876
+ });
877
+ defineMethod("union", ["list"], ({ list }, inline) => {
878
+ const result = list.map(({ toString: format }) => format()).join(" | ");
879
+ return inline ? `(${result})` : result;
880
+ });
881
+ defineMethod("intersect", ["list"], ({ list }) => {
882
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
883
+ });
884
+ defineMethod("transform", [
885
+ "inner",
886
+ "callback",
887
+ "preserve"
888
+ ], ({ inner }, isInner) => inner.toString(isInner));
889
+ // src/protocol.ts
890
+ const channel = "/api";
891
+ const endpointPrefix = "dungsil-cli-proxy-api/";
892
+ const providerFamilies = [
893
+ "gemini",
894
+ "interactions",
895
+ "codex",
896
+ "meta",
897
+ "xai",
898
+ "claude",
899
+ "vertex",
900
+ "openai-compatibility"
901
+ ];
902
+ const oauthProviders = [
903
+ "claude",
904
+ "codex",
905
+ "antigravity",
906
+ "kimi",
907
+ "kimi-ai",
908
+ "xai",
909
+ "devin",
910
+ "meta"
911
+ ];
912
+ // src/quota.ts
913
+ function fail(code) {
914
+ throw new Error(code);
915
+ }
916
+ function record$1(value) {
917
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
918
+ }
919
+ function text$1(value) {
920
+ return typeof value === "string" ? value.trim() : "";
921
+ }
922
+ function encoded(value) {
923
+ try {
924
+ return encodeURIComponent(value);
925
+ } catch {
926
+ fail("invalid");
927
+ }
928
+ }
929
+ function jsonRecord(value) {
930
+ if (typeof value === "string") try {
931
+ value = JSON.parse(value);
932
+ } catch {
933
+ fail("invalid_response");
934
+ }
935
+ if (value === null || typeof value !== "object" || Array.isArray(value)) fail("invalid_response");
936
+ return value;
937
+ }
938
+ function number(value) {
939
+ if (typeof value !== "number" && (typeof value !== "string" || !value.trim())) return;
940
+ const parsed = Number(value);
941
+ return Number.isFinite(parsed) ? parsed : void 0;
942
+ }
943
+ function percent(value) {
944
+ const parsed = number(value);
945
+ return parsed !== void 0 && parsed >= 0 && parsed <= 100 ? parsed : void 0;
946
+ }
947
+ function positive(value) {
948
+ const parsed = number(value);
949
+ return parsed !== void 0 && parsed > 0 ? parsed : void 0;
950
+ }
951
+ function instant(value) {
952
+ const seconds = number(value);
953
+ const ms = seconds !== void 0 ? seconds * 1e3 : typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value) ? Date.parse(value) : NaN;
954
+ return Number.isFinite(ms) && ms >= 0 && Number.isFinite(new Date(ms).getTime()) ? new Date(ms).toISOString() : void 0;
955
+ }
956
+ function planName(value) {
957
+ const name = text$1(value);
958
+ return name && name.length <= 64 && /^[\p{L}\p{N} _+().-]+$/u.test(name) ? name : void 0;
959
+ }
960
+ function provider$1(account) {
961
+ const key = text$1(account.provider ?? account.type).toLowerCase().replace(/_/g, "-");
962
+ if (key === "kimi-ai") return "kimi";
963
+ if (key === "grok" || key === "x-ai") return "xai";
964
+ return key;
965
+ }
966
+ function pluginId(account) {
967
+ const supported = account.supports_quota ?? account.supportsQuota;
968
+ return supported === true || supported === "true" || supported === "1" ? text$1(account.quota_plugin_id ?? account.quotaPluginId) : "";
969
+ }
970
+ function supportsQuota(account) {
971
+ const disabled = account.disabled;
972
+ if (disabled === true || typeof disabled === "number" && disabled !== 0 || ["true", "1"].includes(text$1(disabled).toLowerCase())) return false;
973
+ return [
974
+ "claude",
975
+ "codex",
976
+ "antigravity",
977
+ "kimi",
978
+ "devin",
979
+ "meta",
980
+ "xai"
981
+ ].includes(provider$1(account)) || Boolean(pluginId(account));
982
+ }
983
+ async function managementCall(management, path, method = "GET", body) {
984
+ try {
985
+ return await management(path, method, body);
986
+ } catch {
987
+ fail("upstream_failed");
988
+ }
989
+ }
990
+ async function download(account, management) {
991
+ const name = text$1(account.name);
992
+ if (!name || [account.runtimeOnly, account.runtime_only].some((value) => value === true || value === "true")) fail("invalid");
993
+ return jsonRecord(await managementCall(management, `credentials/download?name=${encoded(name)}`));
994
+ }
995
+ async function apiCall(management, authIndex, url, header, data) {
996
+ const response = record$1(await managementCall(management, "requests/api-call", "POST", {
997
+ auth_index: authIndex,
998
+ method: data === void 0 ? "GET" : "POST",
999
+ url,
1000
+ header,
1001
+ ...data === void 0 ? {} : { data: JSON.stringify(data) }
1002
+ }));
1003
+ if (typeof response.status_code !== "number" || !Number.isInteger(response.status_code)) fail("invalid_response");
1004
+ if (response.status_code < 200 || response.status_code >= 300) fail("upstream_failed");
1005
+ if (typeof response.body !== "string") fail("invalid_response");
1006
+ return jsonRecord(response.body);
1007
+ }
1008
+ function addWindow(windows, id, used, reset, duration) {
1009
+ if (windows.length >= 100) return;
1010
+ const usedPercent = percent(used);
1011
+ const resetAt = instant(reset);
1012
+ const periodSeconds = positive(duration);
1013
+ if (usedPercent === void 0 && resetAt === void 0 && periodSeconds === void 0) return;
1014
+ windows.push({
1015
+ id,
1016
+ ...usedPercent === void 0 ? {} : { usedPercent },
1017
+ ...resetAt === void 0 ? {} : { resetAt },
1018
+ ...periodSeconds === void 0 ? {} : { periodSeconds }
1019
+ });
1020
+ }
1021
+ function fromRemaining(value, scale) {
1022
+ const remaining = number(value);
1023
+ return remaining !== void 0 && remaining >= 0 && remaining <= scale ? 100 - remaining / scale * 100 : void 0;
1024
+ }
1025
+ function groupWindows(payload, windows) {
1026
+ if (payload.groups !== void 0 && !Array.isArray(payload.groups)) fail("invalid_response");
1027
+ if (!Array.isArray(payload.groups)) return;
1028
+ for (const [groupIndex, group] of payload.groups.entries()) {
1029
+ const buckets = record$1(group).buckets;
1030
+ if (!Array.isArray(buckets)) continue;
1031
+ for (const [bucketIndex, value] of buckets.entries()) {
1032
+ const bucket = record$1(value);
1033
+ const window = text$1(bucket.window).toLowerCase();
1034
+ const duration = [
1035
+ "5h",
1036
+ "five-hour",
1037
+ "five_hour"
1038
+ ].includes(window) ? 18e3 : ["weekly", "week"].includes(window) ? 604800 : void 0;
1039
+ addWindow(windows, [planName(record$1(group).displayName ?? record$1(group).display_name), planName(bucket.displayName ?? bucket.display_name) ?? planName(bucket.window)].filter(Boolean).join(" ").slice(0, 96) || `group-${groupIndex + 1}-bucket-${bucketIndex + 1}`, fromRemaining(bucket.remainingFraction ?? bucket.remaining_fraction, 1), bucket.resetTime ?? bucket.reset_time, duration);
1040
+ if (windows.length >= 100) return;
1041
+ }
1042
+ }
1043
+ }
1044
+ function codexAccountId(account) {
1045
+ const sources = [
1046
+ account,
1047
+ record$1(account.metadata),
1048
+ record$1(account.attributes)
1049
+ ];
1050
+ for (const source of sources) {
1051
+ const direct = text$1(source.chatgpt_account_id ?? source.chatgptAccountId);
1052
+ if (direct && !/[\r\n]/.test(direct)) return direct;
1053
+ }
1054
+ for (const source of sources) {
1055
+ let token = source.id_token;
1056
+ if (typeof token === "string") {
1057
+ const rawToken = token;
1058
+ try {
1059
+ token = JSON.parse(token);
1060
+ } catch {
1061
+ try {
1062
+ token = JSON.parse(Buffer.from(rawToken.split(".")[1] ?? "", "base64url").toString("utf8"));
1063
+ } catch {
1064
+ continue;
1065
+ }
1066
+ }
1067
+ }
1068
+ const claims = record$1(token);
1069
+ const auth = record$1(claims["https://api.openai.com/auth"]);
1070
+ const id = text$1(claims.chatgpt_account_id ?? claims.chatgptAccountId ?? auth.chatgpt_account_id);
1071
+ if (id && !/[\r\n]/.test(id)) return id;
1072
+ }
1073
+ return "";
1074
+ }
1075
+ function codexWindows(payload, windows, now) {
1076
+ const limits = [["", payload.rate_limit ?? payload.rateLimit], ["code_review_", payload.code_review_rate_limit ?? payload.codeReviewRateLimit]];
1077
+ const additional = payload.additional_rate_limits ?? payload.additionalRateLimits;
1078
+ if (Array.isArray(additional)) additional.slice(0, 50).forEach((value, i) => {
1079
+ const item = record$1(value);
1080
+ const name = planName(item.limit_name ?? item.limitName ?? item.metered_feature ?? item.meteredFeature);
1081
+ limits.push([`${name ?? `additional-${i + 1}`} `, item.rate_limit ?? item.rateLimit]);
1082
+ });
1083
+ for (const [prefix, value] of limits) {
1084
+ const limit = record$1(value);
1085
+ for (const [position, raw] of [limit.primary_window ?? limit.primaryWindow, limit.secondary_window ?? limit.secondaryWindow].entries()) {
1086
+ const window = record$1(raw);
1087
+ const duration = positive(window.limit_window_seconds ?? window.limitWindowSeconds);
1088
+ const id = position === 0 ? "primary_window" : "secondary_window";
1089
+ const offset = number(window.reset_after_seconds ?? window.resetAfterSeconds);
1090
+ const reset = instant(window.reset_at ?? window.resetAt) ?? (offset !== void 0 && offset >= 0 ? instant(now / 1e3 + offset) : void 0);
1091
+ addWindow(windows, `${prefix}${id}`, window.used_percent ?? window.usedPercent, reset, duration);
1092
+ }
1093
+ }
1094
+ }
1095
+ function kimiDomain(value, isUrl = false) {
1096
+ let domain = text$1(value).toLowerCase();
1097
+ if (isUrl) try {
1098
+ domain = new URL(domain).hostname;
1099
+ } catch {
1100
+ return;
1101
+ }
1102
+ if ([
1103
+ "ai",
1104
+ "kimi-ai",
1105
+ "kimi_ai",
1106
+ "kimi.ai"
1107
+ ].includes(domain) || domain.endsWith(".kimi.ai")) return "ai";
1108
+ if ([
1109
+ "com",
1110
+ "kimi",
1111
+ "kimi.com"
1112
+ ].includes(domain) || domain.endsWith(".kimi.com")) return "com";
1113
+ }
1114
+ function kimiWindows(payload, windows, now) {
1115
+ const rows = [];
1116
+ if (Array.isArray(payload.limits)) payload.limits.slice(0, 100).forEach((value, i) => {
1117
+ const item = record$1(value);
1118
+ const detail = record$1(item.detail ?? item);
1119
+ const name = planName(item.displayName ?? item.name ?? item.title ?? detail.name ?? detail.title);
1120
+ rows.push([
1121
+ name ?? `limit-${i + 1}`,
1122
+ detail,
1123
+ item
1124
+ ]);
1125
+ });
1126
+ if (payload.usage) rows.push([
1127
+ "weekly",
1128
+ record$1(payload.usage),
1129
+ {}
1130
+ ]);
1131
+ for (const [id, detail, item] of rows) {
1132
+ const limit = positive(detail.limit);
1133
+ const remaining = number(detail.remaining);
1134
+ const used = number(detail.used) ?? (limit !== void 0 && remaining !== void 0 ? limit - remaining : void 0);
1135
+ const offset = number(detail.reset_in ?? detail.resetIn ?? detail.ttl);
1136
+ const reset = instant(detail.reset_at ?? detail.resetAt ?? detail.reset_time ?? detail.resetTime) ?? (offset !== void 0 && offset >= 0 ? instant(now / 1e3 + offset) : void 0);
1137
+ const window = record$1(item.window);
1138
+ const duration = positive(window.duration ?? item.duration ?? detail.duration);
1139
+ const unit = text$1(window.timeUnit ?? item.timeUnit ?? detail.timeUnit).toUpperCase().replace(/^TIME_UNIT_/, "");
1140
+ const multiplier = /^SECONDS?$/.test(unit) ? 1 : /^HOURS?$/.test(unit) ? 3600 : /^DAYS?$/.test(unit) ? 86400 : /^WEEKS?$/.test(unit) ? 604800 : 60;
1141
+ addWindow(windows, id, limit !== void 0 && used !== void 0 ? used / limit * 100 : void 0, reset, duration === void 0 ? void 0 : duration * multiplier);
1142
+ }
1143
+ const monthly = record$1(record$1(payload.usages).limit_month_total);
1144
+ const ratio = number(monthly.used_ratio);
1145
+ addWindow(windows, "monthly", ratio === void 0 ? void 0 : ratio * 100, monthly.reset_time);
1146
+ }
1147
+ async function fetchQuota(account, management) {
1148
+ if (!supportsQuota(account)) fail("unsupported");
1149
+ const rawIndex = account.auth_index ?? account.authIndex;
1150
+ const authIndex = typeof rawIndex === "number" && Number.isFinite(rawIndex) ? String(rawIndex) : text$1(rawIndex);
1151
+ if (!authIndex) fail("invalid");
1152
+ const windows = [];
1153
+ const now = Date.now();
1154
+ let plan;
1155
+ const kind = provider$1(account);
1156
+ const bearer = { Authorization: "Bearer $TOKEN$" };
1157
+ const jsonHeaders = {
1158
+ ...bearer,
1159
+ "Content-Type": "application/json"
1160
+ };
1161
+ const id = pluginId(account);
1162
+ if (id) {
1163
+ const payload = jsonRecord(await managementCall(management, `plugins/${encoded(id)}/quota`, "POST", { auth_index: authIndex }));
1164
+ groupWindows(payload, windows);
1165
+ const subscription = record$1(payload.subscription);
1166
+ plan = planName(subscription.plan ?? subscription.tierName ?? subscription.tierId);
1167
+ } else if (kind === "claude") {
1168
+ const payload = await apiCall(management, authIndex, "https://api.anthropic.com/api/oauth/usage", {
1169
+ ...jsonHeaders,
1170
+ Accept: "application/json",
1171
+ "anthropic-beta": "oauth-2025-04-20",
1172
+ "User-Agent": "claude-cli/2.1.280 (external, cli)"
1173
+ });
1174
+ for (const key of [
1175
+ "five_hour",
1176
+ "seven_day",
1177
+ "seven_day_oauth_apps",
1178
+ "seven_day_opus",
1179
+ "seven_day_sonnet",
1180
+ "seven_day_cowork",
1181
+ "iguana_necktie"
1182
+ ]) {
1183
+ if (payload[key] === null || typeof payload[key] !== "object" || Array.isArray(payload[key])) continue;
1184
+ const window = record$1(payload[key]);
1185
+ addWindow(windows, key === "iguana_necktie" ? "credits" : key, window.utilization, window.resets_at, key === "five_hour" ? 18e3 : key === "iguana_necktie" ? void 0 : 604800);
1186
+ }
1187
+ plan = planName(payload.plan_type);
1188
+ } else if (kind === "codex") {
1189
+ const accountId = codexAccountId(account);
1190
+ const payload = await apiCall(management, authIndex, "https://chatgpt.com/backend-api/wham/usage", {
1191
+ ...jsonHeaders,
1192
+ "User-Agent": "codex-tui/0.149.1 (Mac OS 26.5.2; arm64) iTerm.app/3.6.11 (codex-tui; 0.149.1)",
1193
+ ...accountId ? { "Chatgpt-Account-Id": accountId } : {}
1194
+ });
1195
+ codexWindows(payload, windows, now);
1196
+ plan = planName(payload.plan_type ?? payload.planType);
1197
+ } else if (kind === "antigravity") {
1198
+ const metadata = record$1(account.metadata);
1199
+ const attributes = record$1(account.attributes);
1200
+ let project = text$1(account.project_id ?? account.projectId) || text$1(metadata.project_id ?? metadata.projectId) || text$1(attributes.project_id ?? attributes.projectId ?? attributes.gemini_virtual_project);
1201
+ if (!project) {
1202
+ const credential = await download(account, management);
1203
+ project = text$1(credential.project_id ?? credential.projectId) || text$1(record$1(credential.installed).project_id ?? record$1(credential.installed).projectId) || text$1(record$1(credential.web).project_id ?? record$1(credential.web).projectId);
1204
+ }
1205
+ if (!project) fail("invalid");
1206
+ let payload;
1207
+ let lastCode = "upstream_failed";
1208
+ for (const host of [
1209
+ "daily-cloudcode-pa.googleapis.com",
1210
+ "daily-cloudcode-pa.sandbox.googleapis.com",
1211
+ "cloudcode-pa.googleapis.com"
1212
+ ]) try {
1213
+ payload = await apiCall(management, authIndex, `https://${host}/v1internal:retrieveUserQuotaSummary`, {
1214
+ ...jsonHeaders,
1215
+ "User-Agent": "antigravity/hub/2.23.0 darwin/arm64"
1216
+ }, { project });
1217
+ if (!Array.isArray(payload.groups)) fail("invalid_response");
1218
+ break;
1219
+ } catch (error) {
1220
+ payload = void 0;
1221
+ lastCode = error instanceof Error && error.message === "invalid_response" ? "invalid_response" : "upstream_failed";
1222
+ }
1223
+ if (!payload) fail(lastCode);
1224
+ groupWindows(payload, windows);
1225
+ plan = planName(record$1(payload.subscription).plan);
1226
+ } else if (kind === "kimi") {
1227
+ const credential = await download(account, management);
1228
+ const explicit = text$1(credential.domain);
1229
+ kimiWindows(await apiCall(management, authIndex, `https://api.kimi.${(explicit ? kimiDomain(explicit) ?? "com" : void 0) ?? kimiDomain(Object.hasOwn(credential, "base_url") ? credential.base_url : credential["base-url"], true) ?? kimiDomain(credential.type) ?? kimiDomain(account.provider ?? account.type) ?? "com"}/coding/v1/usages`, bearer), windows, now);
1230
+ } else if (kind === "devin") {
1231
+ const status = record$1(record$1((await apiCall(management, authIndex, "https://server.codeium.com/exa.seat_management_pb.SeatManagementService/GetUserStatus", {
1232
+ "Content-Type": "application/json",
1233
+ "Connect-Protocol-Version": "1"
1234
+ }, { metadata: {
1235
+ ideName: "chisel",
1236
+ ideVersion: "3000.10.21",
1237
+ apiKey: "$TOKEN$",
1238
+ locale: "en",
1239
+ os: "darwin",
1240
+ extensionVersion: "3000.10.21",
1241
+ clientName: "chisel"
1242
+ } })).userStatus).planStatus);
1243
+ for (const id of ["daily", "weekly"]) {
1244
+ if (!Object.hasOwn(status, `${id}QuotaRemainingPercent`) && !Object.hasOwn(status, `${id}QuotaResetAtUnix`)) continue;
1245
+ addWindow(windows, id, fromRemaining(status[`${id}QuotaRemainingPercent`], 100), status[`${id}QuotaResetAtUnix`], id === "daily" ? 86400 : 604800);
1246
+ }
1247
+ plan = planName(record$1(status.planInfo).planName);
1248
+ } else if (kind === "meta") {
1249
+ const token = text$1((await download(account, management)).dca_token);
1250
+ if (!/^dca:[^\s]+$/.test(token)) fail("invalid");
1251
+ const payload = await apiCall(management, authIndex, "https://api.meta.ai/muse-code/key", {
1252
+ Accept: "application/json",
1253
+ "Content-Type": "application/json",
1254
+ Authorization: `Bearer ${token}`,
1255
+ "x-api-version": "1.0.0"
1256
+ }, {});
1257
+ const usage = record$1(payload.subs_usage);
1258
+ for (const id of ["window", "weekly"]) {
1259
+ const window = record$1(usage[id]);
1260
+ const minutes = positive(window.window_duration_mins);
1261
+ addWindow(windows, id === "window" ? "primary_window" : id, window.used_percent, window.resets_at, id === "window" && minutes !== void 0 ? minutes * 60 : void 0);
1262
+ }
1263
+ plan = planName(payload.subs_tier_name ?? usage.tier);
1264
+ } else if (kind === "xai") {
1265
+ const header = {
1266
+ ...bearer,
1267
+ "x-xai-token-auth": "xai-grok-cli",
1268
+ "x-grok-client-version": "1.0.46",
1269
+ accept: "*/*",
1270
+ "user-agent": "grok-pager/1.0.46 grok-shell/1.0.46 (macos; aarch64)"
1271
+ };
1272
+ const userId = [
1273
+ account,
1274
+ record$1(account.metadata),
1275
+ record$1(account.attributes)
1276
+ ].map((source) => text$1(source.sub ?? source.subject ?? source.user_id ?? source.userId) || text$1(record$1(source.oauth).sub ?? record$1(source.oauth).subject) || text$1(record$1(source.user).sub ?? record$1(source.user).id)).find(Boolean);
1277
+ if (userId && !/[\r\n]/.test(userId)) header["x-userid"] = userId;
1278
+ const results = await Promise.allSettled([apiCall(management, authIndex, "https://cli-chat-proxy.grok.com/v1/billing?format=credits", header), apiCall(management, authIndex, "https://cli-chat-proxy.grok.com/v1/billing", header)]);
1279
+ if (results.every((result) => result.status === "rejected")) fail(results.some((result) => result.status === "rejected" && result.reason instanceof Error && result.reason.message === "invalid_response") ? "invalid_response" : "upstream_failed");
1280
+ for (const [i, result] of results.entries()) {
1281
+ if (result.status !== "fulfilled") continue;
1282
+ const config = record$1(result.value.config);
1283
+ const period = record$1(config.currentPeriod ?? config.current_period);
1284
+ const end = period.end ?? config.billingPeriodEnd ?? config.billing_period_end;
1285
+ const startAt = instant(period.start ?? config.billingPeriodStart ?? config.billing_period_start);
1286
+ const endAt = instant(end);
1287
+ const duration = startAt && endAt ? (Date.parse(endAt) - Date.parse(startAt)) / 1e3 : void 0;
1288
+ const limitValue = config.monthlyLimit ?? config.monthly_limit;
1289
+ const limit = positive(record$1(limitValue).val ?? limitValue);
1290
+ const used = number(record$1(config.used).val ?? config.used);
1291
+ const credit = config.creditUsagePercent ?? config.credit_usage_percent;
1292
+ addWindow(windows, i === 0 ? [
1293
+ "daily",
1294
+ "weekly",
1295
+ "monthly"
1296
+ ].includes(text$1(period.type)) ? text$1(period.type) : "credits" : "monthly", i === 0 ? credit : limit !== void 0 && used !== void 0 ? used / limit * 100 : void 0, end, duration);
1297
+ }
1298
+ }
1299
+ return {
1300
+ windows,
1301
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
1302
+ ...plan ? { plan } : {}
1303
+ };
1304
+ }
1305
+ // src/index.ts
1306
+ const name = "dungsil-cli-proxy-api";
1307
+ const inject = [
1308
+ "connection",
1309
+ "configEditor",
1310
+ "credentials",
1311
+ "llm"
1312
+ ];
1313
+ const provider = "cli-proxy-api";
1314
+ const Config = Schema.object({
1315
+ baseURL: Schema.string().default("http://127.0.0.1:8317").volatile(),
1316
+ revision: Schema.string().default("").volatile()
1317
+ });
1318
+ function serverURL(value) {
1319
+ const url = new URL(value);
1320
+ const loopback = [
1321
+ "localhost",
1322
+ "127.0.0.1",
1323
+ "[::1]"
1324
+ ].includes(url.hostname);
1325
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback) || url.username || url.password || url.search || url.hash) throw new Error("invalid");
1326
+ return url.href.replace(/\/+$/, "");
1327
+ }
1328
+ function keyRef(baseURL, kind) {
1329
+ return credentialRef(`DSH_CLIPROXY_${kind.toUpperCase()}_${createHash("sha256").update(baseURL).digest("hex")}`);
1330
+ }
1331
+ function record(value) {
1332
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid_response");
1333
+ return value;
1334
+ }
1335
+ function text(value, max = 1024) {
1336
+ if (typeof value !== "string" || !value.trim() || value.length > max) throw new Error("invalid");
1337
+ return value;
1338
+ }
1339
+ function apply(ctx, config) {
1340
+ let busy = false;
1341
+ const sessions = /* @__PURE__ */ new Map();
1342
+ const lifetime = new AbortController();
1343
+ ctx.effect(() => () => lifetime.abort());
1344
+ const currentURL = () => serverURL(config.baseURL.get());
1345
+ const ownerEntry = () => {
1346
+ const entries = ctx.configEditor.entries().filter((entry) => entry.fiber === ctx.fiber);
1347
+ if (entries.length !== 1) throw new Error("unavailable");
1348
+ return entries[0];
1349
+ };
1350
+ const adapterEntry = () => {
1351
+ const entries = ctx.configEditor.entries().filter((entry) => entry.options.name === "@deepseek-ai/dsh-llm-pi-ai" && entry.fiber?.state === 2);
1352
+ if (entries.length !== 1) throw new Error("unavailable");
1353
+ return entries[0];
1354
+ };
1355
+ const revision = () => createHash("sha256").update(JSON.stringify(ownerEntry().options.config ?? {})).digest("hex");
1356
+ const describe = async () => {
1357
+ const baseURL = currentURL();
1358
+ const [api, management] = await Promise.all(["api", "management"].map((kind) => ctx.credentials.describe(keyRef(baseURL, kind))));
1359
+ return {
1360
+ baseURL,
1361
+ revision: revision(),
1362
+ apiKeySaved: api.configured,
1363
+ managementKeySaved: management.configured
1364
+ };
1365
+ };
1366
+ const request = async (baseURL, path, kind, signal, method = "GET", body, ifMatch) => {
1367
+ const key = (await ctx.credentials.resolve(keyRef(baseURL, kind)))?.value;
1368
+ if (!key) throw new Error(kind === "management" ? "management_key_missing" : "api_key_missing");
1369
+ const response = await fetch(`${baseURL}${path}`, {
1370
+ method,
1371
+ redirect: "error",
1372
+ signal: AbortSignal.any([
1373
+ signal,
1374
+ lifetime.signal,
1375
+ AbortSignal.timeout(15e3)
1376
+ ]),
1377
+ headers: {
1378
+ Authorization: `Bearer ${key}`,
1379
+ ...ifMatch ? { "If-Match": ifMatch } : {},
1380
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
1381
+ },
1382
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
1383
+ });
1384
+ if (!response.ok) {
1385
+ await response.body?.cancel();
1386
+ throw new Error(response.status === 401 || response.status === 403 ? "unauthorized" : response.status === 412 ? "conflict" : response.status === 404 ? "not_found" : "upstream_failed");
1387
+ }
1388
+ if (!response.body) throw new Error("invalid_response");
1389
+ const reader = response.body.getReader();
1390
+ const chunks = [];
1391
+ let size = 0;
1392
+ try {
1393
+ while (true) {
1394
+ const next = await reader.read();
1395
+ if (next.done) break;
1396
+ size += next.value.byteLength;
1397
+ if (size > 4194304) throw new Error("invalid_response");
1398
+ chunks.push(next.value);
1399
+ }
1400
+ return {
1401
+ data: JSON.parse(Buffer.concat(chunks).toString("utf8")),
1402
+ etag: response.headers.get("ETag")
1403
+ };
1404
+ } finally {
1405
+ await reader.cancel().catch(() => {});
1406
+ }
1407
+ };
1408
+ const syncModels = async (baseURL, models) => {
1409
+ const entry = adapterEntry();
1410
+ await ctx.configEditor.edit(entry, (current) => {
1411
+ const providers = { ...current.providers };
1412
+ const previous = providers[provider];
1413
+ if (!models?.length) delete providers[provider];
1414
+ else {
1415
+ const matching = previous?.baseURL === `${baseURL}/v1` ? previous : void 0;
1416
+ providers[provider] = {
1417
+ ...matching,
1418
+ displayName: "CLIProxyAPI",
1419
+ api: "openai-completions",
1420
+ baseURL: `${baseURL}/v1`,
1421
+ apiKeyEnv: keyRef(baseURL, "api"),
1422
+ models: models.map((model) => ({
1423
+ ...matching?.models?.find((item) => item.id === model.id),
1424
+ ...model
1425
+ }))
1426
+ };
1427
+ }
1428
+ return {
1429
+ ...current,
1430
+ providers
1431
+ };
1432
+ });
1433
+ };
1434
+ const handle = async (endpoint, payload, signal) => {
1435
+ if (endpoint === "describe") return describe();
1436
+ const input = record(payload);
1437
+ const baseURL = currentURL();
1438
+ const management = async (path, method = "GET", body) => (await request(baseURL, `/v8/management/${path}`, "management", signal, method, body)).data;
1439
+ if (endpoint === "providers" || endpoint === "provider-add") {
1440
+ const snapshot = await request(baseURL, "/v8/management/config", "management", signal);
1441
+ if (!snapshot.etag) throw new Error("unavailable");
1442
+ const families = record(record(snapshot.data)["api-keys"] ?? {});
1443
+ if (endpoint === "providers") {
1444
+ const groups = [];
1445
+ for (const family of providerFamilies) {
1446
+ const rows = families[family] ?? [];
1447
+ if (!Array.isArray(rows)) throw new Error("invalid_response");
1448
+ for (const value of rows) {
1449
+ const row = record(value);
1450
+ if (!Array.isArray(row.keys)) throw new Error("invalid_response");
1451
+ groups.push({
1452
+ family,
1453
+ name: text(row.name),
1454
+ keys: row.keys.length
1455
+ });
1456
+ }
1457
+ }
1458
+ return {
1459
+ revision: snapshot.etag,
1460
+ groups
1461
+ };
1462
+ }
1463
+ if (input.revision !== snapshot.etag) throw new Error("conflict");
1464
+ const family = text(input.family);
1465
+ if (!providerFamilies.includes(family)) throw new Error("invalid");
1466
+ const name = text(input.name, 256).trim();
1467
+ const apiKey = text(input.apiKey, 16384).trim();
1468
+ if (/[\r\n\0]/.test(apiKey)) throw new Error("invalid");
1469
+ const upstreamURL = typeof input.baseURL === "string" && input.baseURL.trim() ? serverURL(input.baseURL.trim()) : void 0;
1470
+ if (!Array.isArray(input.models) || input.models.length > 500) throw new Error("invalid");
1471
+ const models = [...new Set(input.models.map((model) => text(model, 256).trim()))];
1472
+ if (family === "openai-compatibility" && (!upstreamURL || models.length === 0)) throw new Error("invalid");
1473
+ const groups = families[family] ?? [];
1474
+ if (!Array.isArray(groups)) throw new Error("invalid_response");
1475
+ if (groups.some((group) => record(group).name === name)) throw new Error("conflict");
1476
+ await request(baseURL, `/v8/management/config/api-keys/${family}`, "management", signal, "PUT", [...groups, {
1477
+ name,
1478
+ ...upstreamURL ? { "base-url": upstreamURL } : {},
1479
+ keys: [{ "api-key": apiKey }],
1480
+ ...models.length ? { models: models.map((id) => ({
1481
+ name: id,
1482
+ alias: id
1483
+ })) } : {}
1484
+ }], snapshot.etag);
1485
+ return null;
1486
+ }
1487
+ if (endpoint === "save") {
1488
+ if (input.revision !== revision()) throw new Error("conflict");
1489
+ const nextURL = serverURL(text(input.baseURL, 4096));
1490
+ for (const kind of ["apiKey", "managementKey"]) {
1491
+ const value = input[kind];
1492
+ if (value !== void 0 && (typeof value !== "string" || value.length > 16384 || /[\r\n\0]/.test(value))) throw new Error("invalid");
1493
+ }
1494
+ const owner = ownerEntry();
1495
+ if (nextURL !== baseURL || typeof input.apiKey === "string" && !input.apiKey.trim()) await syncModels(baseURL);
1496
+ for (const [field, kind] of [["apiKey", "api"], ["managementKey", "management"]]) {
1497
+ const value = input[field];
1498
+ if (value === void 0 && nextURL === baseURL) continue;
1499
+ const ref = keyRef(nextURL, kind);
1500
+ if (typeof value === "string" && value.trim()) await ctx.credentials.set(ref, value.trim());
1501
+ else await ctx.credentials.unset(ref);
1502
+ }
1503
+ signal.throwIfAborted();
1504
+ await ctx.configEditor.edit(owner, (current) => {
1505
+ if (input.revision !== revision()) throw new Error("conflict");
1506
+ return {
1507
+ ...current,
1508
+ baseURL: nextURL,
1509
+ revision: randomUUID()
1510
+ };
1511
+ });
1512
+ sessions.clear();
1513
+ return null;
1514
+ }
1515
+ if (endpoint === "models") {
1516
+ const response = record((await request(baseURL, "/v1/models", "api", signal)).data);
1517
+ if (!Array.isArray(response.data)) throw new Error("invalid_response");
1518
+ const models = /* @__PURE__ */ new Map();
1519
+ for (const item of response.data) {
1520
+ const row = record(item);
1521
+ const id = text(row.id);
1522
+ models.set(id, {
1523
+ id,
1524
+ name: typeof row.name === "string" && row.name.trim() ? row.name : id
1525
+ });
1526
+ }
1527
+ signal.throwIfAborted();
1528
+ await syncModels(baseURL, [...models.values()]);
1529
+ return [...models.values()];
1530
+ }
1531
+ if (endpoint === "quota-list" || endpoint === "quota-fetch") {
1532
+ const getAccounts = async () => {
1533
+ const files = record(await management("credentials")).files;
1534
+ if (!Array.isArray(files)) throw new Error("invalid_response");
1535
+ return files.map(record);
1536
+ };
1537
+ const accounts = await getAccounts();
1538
+ if (endpoint === "quota-list") return accounts.map((row) => ({
1539
+ name: text(row.name),
1540
+ provider: typeof row.provider === "string" ? row.provider : typeof row.type === "string" ? row.type : "",
1541
+ status: "",
1542
+ disabled: row.disabled === true,
1543
+ authIndex: typeof row.auth_index === "string" ? row.auth_index : "",
1544
+ editable: row.source === "file" && row.runtime_only !== true,
1545
+ supported: supportsQuota(row)
1546
+ }));
1547
+ const find = (rows) => rows.find((row) => row.name === text(input.name) && row.auth_index === text(input.authIndex));
1548
+ const account = find(accounts);
1549
+ if (!account || account.disabled === true) throw new Error("conflict");
1550
+ const connectionRevision = revision();
1551
+ const result = await fetchQuota(account, management);
1552
+ const current = find(await getAccounts());
1553
+ if (revision() !== connectionRevision || !current || current.disabled === true || current.provider !== account.provider || current.type !== account.type || current.modtime !== account.modtime || current.updated_at !== account.updated_at) throw new Error("conflict");
1554
+ return result;
1555
+ }
1556
+ if (endpoint === "management") {
1557
+ const files = record(await management("credentials")).files;
1558
+ const routing = record(await management("config/routing"));
1559
+ if (!Array.isArray(files)) throw new Error("invalid_response");
1560
+ const retry = record(routing.retry ?? {})["request-retry"] ?? 3;
1561
+ if (typeof routing.strategy !== "string" || !Number.isInteger(retry)) throw new Error("invalid_response");
1562
+ return {
1563
+ accounts: files.map((item) => {
1564
+ const row = record(item);
1565
+ return {
1566
+ name: text(row.name),
1567
+ provider: typeof row.provider === "string" ? row.provider : "",
1568
+ status: typeof row.status === "string" ? row.status : "",
1569
+ disabled: row.disabled === true,
1570
+ authIndex: typeof row.auth_index === "string" ? row.auth_index : "",
1571
+ editable: row.source === "file" && row.runtime_only !== true
1572
+ };
1573
+ }),
1574
+ strategy: routing.strategy,
1575
+ requestRetry: retry
1576
+ };
1577
+ }
1578
+ if (endpoint === "routing") {
1579
+ if (![
1580
+ "round-robin",
1581
+ "weighted-round-robin",
1582
+ "fill-first"
1583
+ ].includes(String(input.strategy)) || typeof input.requestRetry !== "number" || !Number.isSafeInteger(input.requestRetry) || input.requestRetry < 0) throw new Error("invalid");
1584
+ await management("config/routing", "PATCH", {
1585
+ strategy: input.strategy,
1586
+ retry: { "request-retry": input.requestRetry }
1587
+ });
1588
+ return null;
1589
+ }
1590
+ if (endpoint === "account") {
1591
+ if (typeof input.disabled !== "boolean") throw new Error("invalid");
1592
+ await management("credentials/status", "PATCH", {
1593
+ name: text(input.name),
1594
+ disabled: input.disabled
1595
+ });
1596
+ return null;
1597
+ }
1598
+ if (endpoint === "reset") {
1599
+ await management("routing/cooldown/reset", "POST", { auth_index: text(input.authIndex) });
1600
+ return null;
1601
+ }
1602
+ if (endpoint === "oauth-start") {
1603
+ const selected = text(input.provider);
1604
+ if (!oauthProviders.includes(selected)) throw new Error("invalid");
1605
+ for (const [state, session] of sessions) if (session.expires <= Date.now()) sessions.delete(state);
1606
+ if (sessions.size >= 10) throw new Error("busy");
1607
+ const response = record(await management(`oauth/auth-url?provider=${encodeURIComponent(selected)}&is_webui=true`));
1608
+ const state = text(response.state);
1609
+ const url = new URL(text(response.url, 16384));
1610
+ if (url.protocol !== "https:" || url.username || url.password) throw new Error("invalid_response");
1611
+ sessions.set(state, {
1612
+ provider: selected,
1613
+ baseURL,
1614
+ expires: Date.now() + 18e5
1615
+ });
1616
+ return {
1617
+ provider: selected,
1618
+ state,
1619
+ url: url.href,
1620
+ ...typeof response.user_code === "string" ? { userCode: response.user_code } : {}
1621
+ };
1622
+ }
1623
+ if ([
1624
+ "oauth-status",
1625
+ "oauth-cancel",
1626
+ "oauth-callback"
1627
+ ].includes(endpoint)) {
1628
+ const state = text(input.state);
1629
+ const session = sessions.get(state);
1630
+ if (!session || session.baseURL !== baseURL || session.expires <= Date.now()) throw new Error("oauth_expired");
1631
+ if (endpoint === "oauth-cancel") {
1632
+ await management(`oauth/session?state=${encodeURIComponent(state)}`, "DELETE");
1633
+ sessions.delete(state);
1634
+ return null;
1635
+ }
1636
+ if (endpoint === "oauth-callback") {
1637
+ if (input.provider !== session.provider) throw new Error("invalid");
1638
+ const redirect = new URL(text(input.redirectURL, 16384));
1639
+ if (!["http:", "https:"].includes(redirect.protocol) || redirect.searchParams.get("state") !== state) throw new Error("invalid");
1640
+ await management("oauth/callback", "POST", {
1641
+ provider: session.provider,
1642
+ state,
1643
+ redirect_url: redirect.href
1644
+ });
1645
+ return null;
1646
+ }
1647
+ const response = record(await management(`oauth/status?state=${encodeURIComponent(state)}`));
1648
+ if (![
1649
+ "wait",
1650
+ "ok",
1651
+ "error"
1652
+ ].includes(String(response.status))) throw new Error("invalid_response");
1653
+ if (response.status !== "wait") sessions.delete(state);
1654
+ return { status: response.status };
1655
+ }
1656
+ throw new Error("invalid");
1657
+ };
1658
+ const errors = /* @__PURE__ */ new Set([
1659
+ "invalid",
1660
+ "invalid_response",
1661
+ "unavailable",
1662
+ "conflict",
1663
+ "api_key_missing",
1664
+ "management_key_missing",
1665
+ "unauthorized",
1666
+ "not_found",
1667
+ "upstream_failed",
1668
+ "unsupported",
1669
+ "oauth_expired",
1670
+ "busy"
1671
+ ]);
1672
+ for (const endpoint of [
1673
+ "describe",
1674
+ "save",
1675
+ "models",
1676
+ "management",
1677
+ "providers",
1678
+ "provider-add",
1679
+ "quota-list",
1680
+ "quota-fetch",
1681
+ "routing",
1682
+ "account",
1683
+ "reset",
1684
+ "oauth-start",
1685
+ "oauth-status",
1686
+ "oauth-cancel",
1687
+ "oauth-callback"
1688
+ ]) ctx.effect(() => ctx.connection.fetch.register({
1689
+ path: `${channel}/${endpointPrefix}${endpoint}`,
1690
+ methods: ["POST"],
1691
+ requestBody: "buffered",
1692
+ async fetch(request) {
1693
+ let body;
1694
+ try {
1695
+ body = clientRequestSchema.safeParse(await request.json());
1696
+ } catch {
1697
+ return new Response("Invalid request", { status: 400 });
1698
+ }
1699
+ if (!body.success || body.data.method !== `dungsil-cli-proxy-api/${endpoint}`) return new Response("Invalid request", { status: 400 });
1700
+ let result;
1701
+ if (busy) result = {
1702
+ ok: false,
1703
+ error: {
1704
+ code: "busy",
1705
+ message: "CLIProxyAPI operation in progress.",
1706
+ details: {}
1707
+ }
1708
+ };
1709
+ else {
1710
+ busy = true;
1711
+ try {
1712
+ result = {
1713
+ ok: true,
1714
+ value: await handle(endpoint, body.data.payload, request.signal)
1715
+ };
1716
+ } catch (error) {
1717
+ result = {
1718
+ ok: false,
1719
+ error: {
1720
+ code: error instanceof Error && errors.has(error.message) ? error.message : "operation_failed",
1721
+ message: "CLIProxyAPI operation could not be confirmed.",
1722
+ details: {}
1723
+ }
1724
+ };
1725
+ } finally {
1726
+ busy = false;
1727
+ }
1728
+ }
1729
+ return Response.json({
1730
+ type: "server-response",
1731
+ rpcId: body.data.rpcId,
1732
+ result
1733
+ }, { headers: { "Cache-Control": "no-store" } });
1734
+ }
1735
+ }), `cli-proxy-api: owner-only ${endpoint}`);
1736
+ }
1737
+ export { Config, apply, inject, name };