@dipertq/dsh-openviking-status 0.1.7 → 0.2.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/lib/index.js CHANGED
@@ -1,12 +1,1213 @@
1
+ // node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.3/node_modules/@deepseek-ai/cosmokit/lib/index.js
2
+ function isNullable(value) {
3
+ return value === null || value === void 0;
4
+ }
5
+ function isPlainObject(data) {
6
+ return data && typeof data === "object" && !Array.isArray(data);
7
+ }
8
+ function filterKeys(object, filter) {
9
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
10
+ }
11
+ function mapValues(object, transform) {
12
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
13
+ }
14
+ function pick(source, keys, forced) {
15
+ if (!keys) return { ...source };
16
+ const result = {};
17
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
18
+ return result;
19
+ }
20
+ function is(type, value) {
21
+ if (arguments.length === 1) return (value2) => is(type, value2);
22
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
23
+ }
24
+ function isArrayBufferLike(value) {
25
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
26
+ }
27
+ function isArrayBufferSource(value) {
28
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
29
+ }
30
+ var Binary;
31
+ (function(Binary2) {
32
+ Binary2.is = isArrayBufferLike;
33
+ Binary2.isSource = isArrayBufferSource;
34
+ function fromSource(source) {
35
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
36
+ else return source;
37
+ }
38
+ Binary2.fromSource = fromSource;
39
+ function toBase64(source) {
40
+ source = fromSource(source);
41
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
42
+ let binary = "";
43
+ const bytes = new Uint8Array(source);
44
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
45
+ return btoa(binary);
46
+ }
47
+ Binary2.toBase64 = toBase64;
48
+ function fromBase64(source) {
49
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
50
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
51
+ }
52
+ Binary2.fromBase64 = fromBase64;
53
+ function toHex(source) {
54
+ source = fromSource(source);
55
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
56
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
57
+ }
58
+ Binary2.toHex = toHex;
59
+ function fromHex(source) {
60
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
61
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
62
+ const buffer = [];
63
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
64
+ return Uint8Array.from(buffer).buffer;
65
+ }
66
+ Binary2.fromHex = fromHex;
67
+ })(Binary || (Binary = {}));
68
+ var base64ToArrayBuffer = Binary.fromBase64;
69
+ var arrayBufferToBase64 = Binary.toBase64;
70
+ var hexToArrayBuffer = Binary.fromHex;
71
+ var arrayBufferToHex = Binary.toHex;
72
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
73
+ if (!source || typeof source !== "object") return source;
74
+ if (is("Date", source)) return new Date(source.valueOf());
75
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
76
+ if (isArrayBufferLike(source)) return source.slice(0);
77
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
78
+ const cached = refs.get(source);
79
+ if (cached) return cached;
80
+ if (Array.isArray(source)) {
81
+ const result2 = [];
82
+ refs.set(source, result2);
83
+ source.forEach((value, index) => {
84
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
85
+ });
86
+ return result2;
87
+ }
88
+ const result = Object.create(Object.getPrototypeOf(source));
89
+ refs.set(source, result);
90
+ for (const key of Reflect.ownKeys(source)) {
91
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
92
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
93
+ Reflect.defineProperty(result, key, descriptor);
94
+ }
95
+ return result;
96
+ }
97
+ function deepEqual(a, b, strict) {
98
+ if (a === b) return true;
99
+ if (!strict && isNullable(a) && isNullable(b)) return true;
100
+ if (typeof a !== typeof b) return false;
101
+ if (typeof a !== "object") return false;
102
+ if (!a || !b) return false;
103
+ function check(test, then) {
104
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
105
+ }
106
+ return check(Array.isArray, (a2, b2) => a2.length === b2.length && a2.every((item, index) => deepEqual(item, b2[index]))) ?? check(is("Date"), (a2, b2) => a2.valueOf() === b2.valueOf()) ?? check(is("RegExp"), (a2, b2) => a2.source === b2.source && a2.flags === b2.flags) ?? check(isArrayBufferLike, (a2, b2) => {
107
+ if (a2.byteLength !== b2.byteLength) return false;
108
+ const viewA = new Uint8Array(a2);
109
+ const viewB = new Uint8Array(b2);
110
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
111
+ return true;
112
+ }) ?? Object.keys({
113
+ ...a,
114
+ ...b
115
+ }).every((key) => deepEqual(a[key], b[key], strict));
116
+ }
117
+ var Time;
118
+ (function(Time2) {
119
+ Time2.millisecond = 1;
120
+ Time2.second = 1e3;
121
+ Time2.minute = Time2.second * 60;
122
+ Time2.hour = Time2.minute * 60;
123
+ Time2.day = Time2.hour * 24;
124
+ Time2.week = Time2.day * 7;
125
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
126
+ function setTimezoneOffset(offset) {
127
+ timezoneOffset = offset;
128
+ }
129
+ Time2.setTimezoneOffset = setTimezoneOffset;
130
+ function getTimezoneOffset() {
131
+ return timezoneOffset;
132
+ }
133
+ Time2.getTimezoneOffset = getTimezoneOffset;
134
+ function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
135
+ if (typeof date2 === "number") date2 = new Date(date2);
136
+ if (offset === void 0) offset = timezoneOffset;
137
+ return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
138
+ }
139
+ Time2.getDateNumber = getDateNumber;
140
+ function fromDateNumber(value, offset) {
141
+ const date2 = new Date(value * Time2.day);
142
+ if (offset === void 0) offset = timezoneOffset;
143
+ return new Date(+date2 + offset * Time2.minute);
144
+ }
145
+ Time2.fromDateNumber = fromDateNumber;
146
+ const numeric = /\d+(?:\.\d+)?/.source;
147
+ const timeRegExp = new RegExp(`^${[
148
+ "w(?:eek(?:s)?)?",
149
+ "d(?:ay(?:s)?)?",
150
+ "h(?:our(?:s)?)?",
151
+ "m(?:in(?:ute)?(?:s)?)?",
152
+ "s(?:ec(?:ond)?(?:s)?)?"
153
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
154
+ function parseTime(source) {
155
+ const capture = timeRegExp.exec(source);
156
+ if (!capture) return 0;
157
+ 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);
158
+ }
159
+ Time2.parseTime = parseTime;
160
+ function parseDate(date2) {
161
+ const parsed = parseTime(date2);
162
+ if (parsed) date2 = Date.now() + parsed;
163
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
164
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
165
+ return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
166
+ }
167
+ Time2.parseDate = parseDate;
168
+ function format(ms) {
169
+ const abs = Math.abs(ms);
170
+ if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
171
+ else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
172
+ else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
173
+ else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
174
+ return ms + "ms";
175
+ }
176
+ Time2.format = format;
177
+ function toDigits(source, length = 2) {
178
+ return source.toString().padStart(length, "0");
179
+ }
180
+ Time2.toDigits = toDigits;
181
+ function template(template2, time = /* @__PURE__ */ new Date()) {
182
+ 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));
183
+ }
184
+ Time2.template = template;
185
+ })(Time || (Time = {}));
186
+
187
+ // node_modules/.pnpm/@deepseek-ai+schemastery@3.18.2/node_modules/@deepseek-ai/schemastery/lib/index.mjs
188
+ var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
189
+ var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
190
+ globalThis.__schemastery_index__ ??= 0;
191
+ globalThis.__schemastery_refs__ = void 0;
192
+ var ValidationError = class extends TypeError {
193
+ options;
194
+ name = "ValidationError";
195
+ constructor(message, options) {
196
+ let prefix = "$";
197
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
198
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
199
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
200
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
201
+ super((prefix === "$" ? "" : `${prefix} `) + message);
202
+ this.options = options;
203
+ }
204
+ static is(error) {
205
+ return !!error?.[kValidationError];
206
+ }
207
+ };
208
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
209
+ var Schema = function(options) {
210
+ const schema = function(data, options2 = {}) {
211
+ return Schema.resolve(data, schema, options2)[0];
212
+ };
213
+ if (options.refs) {
214
+ const refs = mapValues(options.refs, (options2) => new Schema(options2));
215
+ const getRef = (uid) => refs[uid];
216
+ for (const key in refs) {
217
+ const options2 = refs[key];
218
+ options2.sKey = getRef(options2.sKey);
219
+ options2.inner = getRef(options2.inner);
220
+ options2.list = options2.list && options2.list.map(getRef);
221
+ options2.dict = options2.dict && mapValues(options2.dict, getRef);
222
+ }
223
+ return refs[options.uid];
224
+ }
225
+ Object.assign(schema, options);
226
+ if (typeof schema.callback === "string") try {
227
+ schema.callback = new Function("return " + schema.callback)();
228
+ } catch {
229
+ }
230
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
231
+ Object.setPrototypeOf(schema, Schema.prototype);
232
+ schema.meta ||= {};
233
+ schema.toString = schema.toString.bind(schema);
234
+ return schema;
235
+ };
236
+ Schema.prototype = Object.create(Function.prototype);
237
+ Schema.prototype[kSchema] = true;
238
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
239
+ return {
240
+ version: 1,
241
+ vendor: "schemastery",
242
+ validate: (value) => {
243
+ try {
244
+ return { value: Schema.resolve(value, this, {})[0] };
245
+ } catch (error) {
246
+ if (ValidationError.is(error)) return { issues: [{
247
+ message: error.message,
248
+ path: error.options.path
249
+ }] };
250
+ throw error;
251
+ }
252
+ }
253
+ };
254
+ } });
255
+ Schema.ValidationError = ValidationError;
256
+ Schema.prototype.toJSON = function toJSON() {
257
+ if (globalThis.__schemastery_refs__) {
258
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
259
+ return this.uid;
260
+ }
261
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
262
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
263
+ const result = {
264
+ uid: this.uid,
265
+ refs: globalThis.__schemastery_refs__
266
+ };
267
+ globalThis.__schemastery_refs__ = void 0;
268
+ return result;
269
+ };
270
+ Schema.prototype.set = function set(key, value) {
271
+ this.dict[key] = value;
272
+ return this;
273
+ };
274
+ Schema.prototype.push = function push(value) {
275
+ this.list.push(value);
276
+ return this;
277
+ };
278
+ function mergeDesc(original, messages) {
279
+ const result = typeof original === "string" ? { "": original } : { ...original };
280
+ for (const locale in messages) {
281
+ const value = messages[locale];
282
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
283
+ else if (typeof value === "string") result[locale] = value;
284
+ }
285
+ return result;
286
+ }
287
+ function getInner(value) {
288
+ return value?.$value ?? value?.$inner;
289
+ }
290
+ function extractKeys(data) {
291
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
292
+ }
293
+ Schema.prototype.i18n = function i18n(messages) {
294
+ const schema = Schema(this);
295
+ const desc = mergeDesc(schema.meta.description, messages);
296
+ if (Object.keys(desc).length) schema.meta.description = desc;
297
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
298
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
299
+ });
300
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
301
+ return inner.i18n(mapValues(messages, (data = {}) => {
302
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
303
+ if (Array.isArray(data)) return data[index];
304
+ return extractKeys(data);
305
+ }));
306
+ });
307
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
308
+ if (getInner(data)) return getInner(data);
309
+ return extractKeys(data);
310
+ }));
311
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
312
+ return schema;
313
+ };
314
+ Schema.prototype.extra = function extra(key, value) {
315
+ const schema = Schema(this);
316
+ schema.meta = {
317
+ ...schema.meta,
318
+ [key]: value
319
+ };
320
+ return schema;
321
+ };
322
+ for (const key of [
323
+ "required",
324
+ "disabled",
325
+ "collapse",
326
+ "hidden",
327
+ "loose"
328
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
329
+ const schema = Schema(this);
330
+ schema.meta = {
331
+ ...schema.meta,
332
+ [key]: value
333
+ };
334
+ return schema;
335
+ } });
336
+ Schema.prototype.deprecated = function deprecated() {
337
+ const schema = Schema(this);
338
+ schema.meta.badges ||= [];
339
+ schema.meta.badges.push({
340
+ text: "deprecated",
341
+ type: "danger"
342
+ });
343
+ return schema;
344
+ };
345
+ Schema.prototype.experimental = function experimental() {
346
+ const schema = Schema(this);
347
+ schema.meta.badges ||= [];
348
+ schema.meta.badges.push({
349
+ text: "experimental",
350
+ type: "warning"
351
+ });
352
+ return schema;
353
+ };
354
+ Schema.prototype.pattern = function pattern(regexp) {
355
+ const schema = Schema(this);
356
+ const pattern2 = pick(regexp, ["source", "flags"]);
357
+ schema.meta = {
358
+ ...schema.meta,
359
+ pattern: pattern2
360
+ };
361
+ return schema;
362
+ };
363
+ Schema.prototype.simplify = function simplify(value) {
364
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
365
+ if (isNullable(value)) return value;
366
+ if (this.type === "object" || this.type === "dict") {
367
+ const result = {};
368
+ for (const key in value) {
369
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
370
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
371
+ }
372
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
373
+ return result;
374
+ } else if (this.type === "array" || this.type === "tuple") {
375
+ const result = [];
376
+ value.forEach((value2, index) => {
377
+ const schema = this.type === "array" ? this.inner : this.list[index];
378
+ const item = schema ? schema.simplify(value2) : value2;
379
+ result.push(item);
380
+ });
381
+ return result;
382
+ } else if (this.type === "intersect") {
383
+ const result = {};
384
+ for (const item of this.list) Object.assign(result, item.simplify(value));
385
+ return result;
386
+ } else if (this.type === "union") for (const schema of this.list) try {
387
+ Schema.resolve(value, schema, {});
388
+ return schema.simplify(value);
389
+ } catch {
390
+ }
391
+ return value;
392
+ };
393
+ Schema.prototype.toString = function toString(inline) {
394
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
395
+ };
396
+ Schema.prototype.role = function role(role, extra2) {
397
+ const schema = Schema(this);
398
+ schema.meta = {
399
+ ...schema.meta,
400
+ role,
401
+ extra: extra2
402
+ };
403
+ return schema;
404
+ };
405
+ for (const key of [
406
+ "default",
407
+ "link",
408
+ "comment",
409
+ "description",
410
+ "max",
411
+ "min",
412
+ "step"
413
+ ]) Object.assign(Schema.prototype, { [key](value) {
414
+ const schema = Schema(this);
415
+ schema.meta = {
416
+ ...schema.meta,
417
+ [key]: value
418
+ };
419
+ return schema;
420
+ } });
421
+ var resolvers = {};
422
+ Schema.extend = function extend(type, resolve2) {
423
+ resolvers[type] = resolve2;
424
+ };
425
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
426
+ if (!schema) return [data];
427
+ if (options.ignore?.(data, schema)) return [data];
428
+ if (isNullable(data) && schema.type !== "lazy") {
429
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
430
+ let current = schema;
431
+ let fallback = schema.meta.default;
432
+ while (current?.type === "intersect" && isNullable(fallback)) {
433
+ current = current.list[0];
434
+ fallback = current?.meta.default;
435
+ }
436
+ if (isNullable(fallback)) return [data];
437
+ data = clone(fallback);
438
+ }
439
+ const callback = resolvers[schema.type];
440
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
441
+ try {
442
+ return callback(data, schema, options, strict);
443
+ } catch (error) {
444
+ if (!schema.meta.loose) throw error;
445
+ return [schema.meta.default];
446
+ }
447
+ };
448
+ Schema.from = function from(source) {
449
+ if (isNullable(source)) return Schema.any();
450
+ else if ([
451
+ "string",
452
+ "number",
453
+ "boolean"
454
+ ].includes(typeof source)) return Schema.const(source).required();
455
+ else if (source[kSchema]) return source;
456
+ else if (typeof source === "function") switch (source) {
457
+ case String:
458
+ return Schema.string().required();
459
+ case Number:
460
+ return Schema.number().required();
461
+ case Boolean:
462
+ return Schema.boolean().required();
463
+ case Function:
464
+ return Schema.function().required();
465
+ default:
466
+ return Schema.is(source).required();
467
+ }
468
+ else throw new TypeError(`cannot infer schema from ${source}`);
469
+ };
470
+ Schema.lazy = function lazy(builder) {
471
+ const toJSON2 = () => {
472
+ if (!schema.inner[kSchema]) {
473
+ schema.inner = schema.builder();
474
+ schema.inner.meta = {
475
+ ...schema.meta,
476
+ ...schema.inner.meta
477
+ };
478
+ }
479
+ return schema.inner.toJSON();
480
+ };
481
+ const schema = new Schema({
482
+ type: "lazy",
483
+ builder,
484
+ inner: { toJSON: toJSON2 }
485
+ });
486
+ return schema;
487
+ };
488
+ Schema.natural = function natural() {
489
+ return Schema.number().step(1).min(0);
490
+ };
491
+ Schema.percent = function percent() {
492
+ return Schema.number().step(0.01).min(0).max(1).role("slider");
493
+ };
494
+ Schema.date = function date() {
495
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
496
+ const date2 = new Date(value);
497
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
498
+ return date2;
499
+ }, true)]);
500
+ };
501
+ Schema.regExp = function regExp(flag = "") {
502
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
503
+ try {
504
+ return new RegExp(value, flag);
505
+ } catch (e) {
506
+ throw new ValidationError(e.message, options);
507
+ }
508
+ }, true)]);
509
+ };
510
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
511
+ return Schema.union([
512
+ Schema.is(ArrayBuffer),
513
+ Schema.is(SharedArrayBuffer),
514
+ Schema.transform(Schema.any(), (value, options) => {
515
+ if (Binary.isSource(value)) return Binary.fromSource(value);
516
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
517
+ }, true),
518
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
519
+ try {
520
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
521
+ } catch (e) {
522
+ throw new ValidationError(e.message, options);
523
+ }
524
+ }, true)] : []
525
+ ]);
526
+ };
527
+ Schema.extend("lazy", (data, schema, options, strict) => {
528
+ if (!schema.inner[kSchema]) {
529
+ schema.inner = schema.builder();
530
+ schema.inner.meta = {
531
+ ...schema.meta,
532
+ ...schema.inner.meta
533
+ };
534
+ }
535
+ return Schema.resolve(data, schema.inner, options, strict);
536
+ });
537
+ Schema.extend("any", (data) => {
538
+ return [data];
539
+ });
540
+ Schema.extend("never", (data, _, options) => {
541
+ throw new ValidationError(`expected nullable but got ${data}`, options);
542
+ });
543
+ Schema.extend("const", (data, { value }, options) => {
544
+ if (deepEqual(data, value)) return [value];
545
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
546
+ });
547
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
548
+ const { max = Infinity, min = -Infinity } = meta;
549
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
550
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
551
+ }
552
+ Schema.extend("string", (data, { meta }, options) => {
553
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
554
+ if (meta.pattern) {
555
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
556
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
557
+ }
558
+ checkWithinRange(data.length, meta, "string length", options);
559
+ return [data];
560
+ });
561
+ function decimalShift(data, digits) {
562
+ const str = data.toString();
563
+ if (str.includes("e")) return data * Math.pow(10, digits);
564
+ const index = str.indexOf(".");
565
+ if (index === -1) return data * Math.pow(10, digits);
566
+ const frac = str.slice(index + 1);
567
+ const integer = str.slice(0, index);
568
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
569
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
570
+ }
571
+ function isMultipleOf(data, min, step) {
572
+ step = Math.abs(step);
573
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
574
+ const index = step.toString().indexOf(".");
575
+ const digits = step.toString().slice(index + 1).length;
576
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
577
+ }
578
+ Schema.extend("number", (data, { meta }, options) => {
579
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
580
+ checkWithinRange(data, meta, "number", options);
581
+ const { step } = meta;
582
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
583
+ return [data];
584
+ });
585
+ Schema.extend("boolean", (data, _, options) => {
586
+ if (typeof data === "boolean") return [data];
587
+ throw new ValidationError(`expected boolean but got ${data}`, options);
588
+ });
589
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
590
+ let value = 0, keys = [];
591
+ if (typeof data === "number") {
592
+ value = data;
593
+ for (const key in bits) if (data & bits[key]) keys.push(key);
594
+ } else if (Array.isArray(data)) {
595
+ keys = data;
596
+ for (const key of keys) {
597
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
598
+ if (key in bits) value |= bits[key];
599
+ }
600
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
601
+ if (value === meta.default) return [value];
602
+ return [value, keys];
603
+ });
604
+ Schema.extend("function", (data, _, options) => {
605
+ if (typeof data === "function") return [data];
606
+ throw new ValidationError(`expected function but got ${data}`, options);
607
+ });
608
+ Schema.extend("is", (data, { constructor }, options) => {
609
+ if (typeof constructor === "function") {
610
+ if (data instanceof constructor) return [data];
611
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
612
+ } else {
613
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
614
+ let prototype = Object.getPrototypeOf(data);
615
+ while (prototype) {
616
+ if (prototype.constructor?.name === constructor) return [data];
617
+ prototype = Object.getPrototypeOf(prototype);
618
+ }
619
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
620
+ }
621
+ });
622
+ function property(data, key, schema, options) {
623
+ try {
624
+ const [value, adapted] = Schema.resolve(data[key], schema, {
625
+ ...options,
626
+ path: [...options.path || [], key]
627
+ });
628
+ if (adapted !== void 0) data[key] = adapted;
629
+ return value;
630
+ } catch (e) {
631
+ if (!options?.autofix) throw e;
632
+ delete data[key];
633
+ return schema.meta.default;
634
+ }
635
+ }
636
+ Schema.extend("array", (data, { inner, meta }, options) => {
637
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
638
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
639
+ return [data.map((_, index) => property(data, index, inner, options))];
640
+ });
641
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
642
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
643
+ const result = {};
644
+ for (const key in data) {
645
+ let rKey;
646
+ try {
647
+ rKey = Schema.resolve(key, sKey, options)[0];
648
+ } catch (error) {
649
+ if (strict) continue;
650
+ throw error;
651
+ }
652
+ result[rKey] = property(data, key, inner, options);
653
+ data[rKey] = data[key];
654
+ if (key !== rKey) delete data[key];
655
+ }
656
+ return [result];
657
+ });
658
+ Schema.extend("tuple", (data, { list }, options, strict) => {
659
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
660
+ const result = list.map((inner, index) => property(data, index, inner, options));
661
+ if (strict) return [result];
662
+ result.push(...data.slice(list.length));
663
+ return [result];
664
+ });
665
+ function merge(result, data) {
666
+ for (const key in data) {
667
+ if (key in result) continue;
668
+ result[key] = data[key];
669
+ }
670
+ }
671
+ Schema.extend("object", (data, { dict }, options, strict) => {
672
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
673
+ const result = {};
674
+ for (const key in dict) {
675
+ const value = property(data, key, dict[key], options);
676
+ if (!isNullable(value) || key in data) result[key] = value;
677
+ }
678
+ if (!strict) merge(result, data);
679
+ return [result];
680
+ });
681
+ Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
682
+ const messages = [];
683
+ for (const inner of list) try {
684
+ return Schema.resolve(data, inner, options, strict);
685
+ } catch (error) {
686
+ messages.push(error);
687
+ }
688
+ throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
689
+ });
690
+ Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
691
+ if (!list.length) return [data];
692
+ let result;
693
+ for (const inner of list) {
694
+ const value = Schema.resolve(data, inner, options, true)[0];
695
+ if (isNullable(value)) continue;
696
+ if (isNullable(result)) result = value;
697
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
698
+ else if (typeof value === "object") merge(result ??= {}, value);
699
+ else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
700
+ }
701
+ if (!strict && isPlainObject(data)) merge(result, data);
702
+ return [result];
703
+ });
704
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
705
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
706
+ if (preserve) return [callback(result)];
707
+ else return [callback(result), callback(adapted)];
708
+ });
709
+ var formatters = {};
710
+ function defineMethod(name2, keys, format) {
711
+ formatters[name2] = format;
712
+ Object.assign(Schema, { [name2](...args) {
713
+ const schema = new Schema({ type: name2 });
714
+ keys.forEach((key, index) => {
715
+ switch (key) {
716
+ case "sKey":
717
+ schema.sKey = args[index] ?? Schema.string();
718
+ break;
719
+ case "inner":
720
+ schema.inner = Schema.from(args[index]);
721
+ break;
722
+ case "list":
723
+ schema.list = args[index].map(Schema.from);
724
+ break;
725
+ case "dict":
726
+ schema.dict = mapValues(args[index], Schema.from);
727
+ break;
728
+ case "bits":
729
+ schema.bits = {};
730
+ for (const key2 in args[index]) {
731
+ if (typeof args[index][key2] !== "number") continue;
732
+ schema.bits[key2] = args[index][key2];
733
+ }
734
+ break;
735
+ case "callback": {
736
+ const callback = schema.callback = args[index];
737
+ callback["toJSON"] ||= () => callback.toString();
738
+ break;
739
+ }
740
+ case "constructor": {
741
+ const constructor = schema.constructor = args[index];
742
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
743
+ break;
744
+ }
745
+ default:
746
+ schema[key] = args[index];
747
+ }
748
+ });
749
+ if (name2 === "object" || name2 === "dict") schema.meta.default = {};
750
+ else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
751
+ else if (name2 === "bitset") schema.meta.default = 0;
752
+ return schema;
753
+ } });
754
+ }
755
+ defineMethod("is", ["constructor"], ({ constructor }) => {
756
+ if (typeof constructor === "function") return constructor.name;
757
+ else return constructor;
758
+ });
759
+ defineMethod("any", [], () => "any");
760
+ defineMethod("never", [], () => "never");
761
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
762
+ defineMethod("string", [], () => "string");
763
+ defineMethod("number", [], () => "number");
764
+ defineMethod("boolean", [], () => "boolean");
765
+ defineMethod("bitset", ["bits"], () => "bitset");
766
+ defineMethod("function", [], () => "function");
767
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
768
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
769
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
770
+ defineMethod("object", ["dict"], ({ dict }) => {
771
+ if (Object.keys(dict).length === 0) return "{}";
772
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
773
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
774
+ }).join(", ")} }`;
775
+ });
776
+ defineMethod("union", ["list"], ({ list }, inline) => {
777
+ const result = list.map(({ toString: format }) => format()).join(" | ");
778
+ return inline ? `(${result})` : result;
779
+ });
780
+ defineMethod("intersect", ["list"], ({ list }) => {
781
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
782
+ });
783
+ defineMethod("transform", [
784
+ "inner",
785
+ "callback",
786
+ "preserve"
787
+ ], ({ inner }, isInner) => inner.toString(isInner));
788
+
789
+ // src/credentials.ts
790
+ import { readFileSync } from "fs";
791
+ import { homedir } from "os";
792
+ import { join } from "path";
793
+ var DEFAULT_ENDPOINT = "http://127.0.0.1:1933";
794
+ function cleanStr(val) {
795
+ if (typeof val === "string" && val.trim().length > 0) {
796
+ return val.trim();
797
+ }
798
+ return void 0;
799
+ }
800
+ function cleanUrl(val) {
801
+ const s = cleanStr(val);
802
+ return s ? s.replace(/\/+$/, "") : void 0;
803
+ }
804
+ function tryReadJson(path) {
805
+ try {
806
+ const raw = readFileSync(path, "utf-8");
807
+ return JSON.parse(raw);
808
+ } catch {
809
+ return null;
810
+ }
811
+ }
812
+ function resolveHostCredentials(env = process.env, options) {
813
+ let endpoint = cleanUrl(env.OPENVIKING_URL || env.OPENVIKING_BASE_URL);
814
+ let apiKey = cleanStr(env.OPENVIKING_API_KEY || env.OPENVIKING_BEARER_TOKEN);
815
+ let source = endpoint || apiKey ? "env" : "default";
816
+ if (!endpoint || !apiKey) {
817
+ const cliPath = options?.cliConfigPath || env.OPENVIKING_CLI_CONFIG_FILE || join(homedir(), ".openviking", "ovcli.conf");
818
+ const cliData = tryReadJson(cliPath);
819
+ if (cliData) {
820
+ if (!endpoint && cleanUrl(cliData.url)) {
821
+ endpoint = cleanUrl(cliData.url);
822
+ if (source === "default") source = "ovcli";
823
+ }
824
+ if (!apiKey && cleanStr(cliData.api_key)) {
825
+ apiKey = cleanStr(cliData.api_key);
826
+ if (source === "default") source = "ovcli";
827
+ }
828
+ }
829
+ }
830
+ if (!endpoint || !apiKey) {
831
+ const ovPath = options?.ovConfigPath || env.OPENVIKING_CONFIG_FILE || join(homedir(), ".openviking", "ov.conf");
832
+ const ovData = tryReadJson(ovPath);
833
+ if (ovData) {
834
+ const server = ovData.server || {};
835
+ if (!endpoint) {
836
+ let ovUrl = cleanUrl(server.url);
837
+ if (!ovUrl && server.port) {
838
+ const host = cleanStr(server.host) || "127.0.0.1";
839
+ ovUrl = `http://${host.replace("0.0.0.0", "127.0.0.1")}:${server.port}`;
840
+ }
841
+ if (ovUrl) {
842
+ endpoint = ovUrl;
843
+ if (source === "default") source = "ov";
844
+ }
845
+ }
846
+ if (!apiKey && cleanStr(server.root_api_key)) {
847
+ apiKey = cleanStr(server.root_api_key);
848
+ if (source === "default") source = "ov";
849
+ }
850
+ }
851
+ }
852
+ return {
853
+ endpoint: endpoint || DEFAULT_ENDPOINT,
854
+ apiKey,
855
+ source
856
+ };
857
+ }
858
+
1
859
  // src/index.ts
2
- var name = "dsh-openviking-status";
3
- var inject = ["sessions"];
4
- function apply(ctx) {
5
- ctx.logger?.info?.("[dsh-openviking-status] Plugin loaded");
860
+ var name = "@dipertq/dsh-openviking-status";
861
+ var inject = ["webServer"];
862
+ var NS = "openviking-status";
863
+ var API_PREFIX = "/openviking-status/api";
864
+ var Config = Schema.object({
865
+ endpoint: Schema.string().default("http://127.0.0.1:1933"),
866
+ apiKey: Schema.string().role("secret").default("")
867
+ });
868
+ async function readJson(req) {
869
+ let data = "";
870
+ for await (const chunk of req) {
871
+ data += chunk;
872
+ }
873
+ try {
874
+ return data ? JSON.parse(data) : {};
875
+ } catch {
876
+ return {};
877
+ }
878
+ }
879
+ function sendJson(res, status, body) {
880
+ res.writeHead(status, {
881
+ "Content-Type": "application/json; charset=utf-8",
882
+ "Cache-Control": "no-store"
883
+ });
884
+ res.end(JSON.stringify(body));
885
+ }
886
+ function getCandidateSessionIds(sessionId) {
887
+ const raw = sessionId.trim();
888
+ const candidates = [];
889
+ if (raw.startsWith("dsh-session-")) {
890
+ const suffix = raw.slice("dsh-session-".length);
891
+ candidates.push(raw, `dsh-${suffix}`);
892
+ } else if (raw.startsWith("dsh-")) {
893
+ const suffix = raw.slice("dsh-".length);
894
+ candidates.push(raw, `dsh-session-${suffix}`);
895
+ } else if (raw.startsWith("session-")) {
896
+ candidates.push(`dsh-${raw}`, raw);
897
+ } else {
898
+ candidates.push(`dsh-session-${raw}`, `dsh-${raw}`, raw);
899
+ }
900
+ return Array.from(new Set(candidates));
901
+ }
902
+ function apply(ctx, config) {
903
+ let currentSettings = () => config ?? {};
904
+ let settingsService = null;
905
+ ctx.inject?.(["settings"], (settingsCtx) => {
906
+ settingsService = settingsCtx.settings;
907
+ settingsCtx.settings?.installSection(
908
+ ctx,
909
+ NS,
910
+ Config,
911
+ config ?? { endpoint: "http://127.0.0.1:1933", apiKey: "" },
912
+ {
913
+ setSource: (src) => {
914
+ currentSettings = src;
915
+ },
916
+ onChange: () => {
917
+ }
918
+ }
919
+ );
920
+ });
921
+ function resolveEffective() {
922
+ const saved = currentSettings();
923
+ const auto = resolveHostCredentials();
924
+ const hasSavedEndpoint = typeof saved?.endpoint === "string" && saved.endpoint.trim().length > 0;
925
+ const hasSavedKey = typeof saved?.apiKey === "string" && saved.apiKey.trim().length > 0;
926
+ const endpoint = (hasSavedEndpoint ? saved.endpoint.trim() : auto.endpoint).replace(/\/+$/, "");
927
+ const apiKey = hasSavedKey ? saved.apiKey.trim() : auto.apiKey;
928
+ const source = hasSavedEndpoint || hasSavedKey ? "settings" : auto.source;
929
+ return { endpoint, apiKey, source };
930
+ }
931
+ function getHeaders(apiKey, extra2 = {}) {
932
+ const headers = {
933
+ "Content-Type": "application/json",
934
+ ...extra2
935
+ };
936
+ if (apiKey) {
937
+ headers["Authorization"] = `Bearer ${apiKey}`;
938
+ }
939
+ return headers;
940
+ }
941
+ ctx.effect?.(() => {
942
+ return ctx.webServer?.register({
943
+ kind: "exact",
944
+ path: `${API_PREFIX}/config`,
945
+ handler: async (_req, res) => {
946
+ try {
947
+ const effective = resolveEffective();
948
+ const maskedApiKey = effective.apiKey ? effective.apiKey.length > 8 ? `${effective.apiKey.slice(0, 4)}\u2022\u2022\u2022\u2022${effective.apiKey.slice(-4)}` : "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" : void 0;
949
+ sendJson(res, 200, {
950
+ endpoint: effective.endpoint,
951
+ hasApiKey: Boolean(effective.apiKey),
952
+ maskedApiKey,
953
+ source: effective.source
954
+ });
955
+ } catch (err) {
956
+ sendJson(res, 500, { error: String(err) });
957
+ }
958
+ }
959
+ });
960
+ }, "openviking-status: config read route");
961
+ ctx.effect?.(() => {
962
+ return ctx.webServer?.register({
963
+ kind: "exact",
964
+ path: `${API_PREFIX}/config`,
965
+ handler: async (req, res) => {
966
+ try {
967
+ if (req.method !== "POST") {
968
+ sendJson(res, 405, { error: "Method not allowed" });
969
+ return;
970
+ }
971
+ const body = await readJson(req);
972
+ const settings = settingsService || ctx.get?.("settings") || ctx.settings;
973
+ if (!settings) {
974
+ sendJson(res, 503, { error: "Settings service unavailable" });
975
+ return;
976
+ }
977
+ if (body.reset) {
978
+ await settings.mutate(NS, [
979
+ { op: "unset", path: ["endpoint"] },
980
+ { op: "unset", path: ["apiKey"] }
981
+ ]);
982
+ sendJson(res, 200, { ok: true, reset: true });
983
+ return;
984
+ }
985
+ const ops = [];
986
+ if (typeof body.endpoint === "string" && body.endpoint.trim().length > 0) {
987
+ const ep = body.endpoint.trim();
988
+ if (!ep.startsWith("http://") && !ep.startsWith("https://")) {
989
+ sendJson(res, 400, {
990
+ error: "Endpoint must start with http:// or https://"
991
+ });
992
+ return;
993
+ }
994
+ ops.push({
995
+ op: "set",
996
+ path: ["endpoint"],
997
+ value: ep.replace(/\/+$/, "")
998
+ });
999
+ }
1000
+ if (typeof body.apiKey === "string") {
1001
+ ops.push({
1002
+ op: "set",
1003
+ path: ["apiKey"],
1004
+ value: body.apiKey.trim()
1005
+ });
1006
+ }
1007
+ if (ops.length > 0) {
1008
+ await settings.mutate(NS, ops);
1009
+ }
1010
+ sendJson(res, 200, { ok: true, config: resolveEffective() });
1011
+ } catch (err) {
1012
+ sendJson(res, 500, { error: String(err) });
1013
+ }
1014
+ }
1015
+ });
1016
+ }, "openviking-status: config update route");
1017
+ ctx.effect?.(() => {
1018
+ return ctx.webServer?.register({
1019
+ kind: "exact",
1020
+ path: `${API_PREFIX}/test-connection`,
1021
+ handler: async (req, res) => {
1022
+ try {
1023
+ const body = await readJson(req);
1024
+ const effective = resolveEffective();
1025
+ const targetUrl = body.endpoint && String(body.endpoint).trim().replace(/\/+$/, "") || effective.endpoint;
1026
+ const targetKey = typeof body.apiKey === "string" ? body.apiKey.trim() : effective.apiKey;
1027
+ const healthRes = await fetch(`${targetUrl}/health`, {
1028
+ method: "GET",
1029
+ headers: getHeaders(targetKey)
1030
+ }).catch(
1031
+ (err) => ({ ok: false, status: 0, statusText: err.message })
1032
+ );
1033
+ if (!healthRes.ok) {
1034
+ sendJson(res, 200, {
1035
+ ok: false,
1036
+ authenticated: false,
1037
+ error: healthRes.status === 0 ? `Connection failed: ${healthRes.statusText}` : `HTTP ${healthRes.status}: ${healthRes.statusText}`
1038
+ });
1039
+ return;
1040
+ }
1041
+ const healthData = await healthRes.json().catch(() => ({}));
1042
+ const probeCandidate = "dsh-session-test-probe";
1043
+ const authProbe = await fetch(
1044
+ `${targetUrl}/api/v1/sessions/${probeCandidate}`,
1045
+ {
1046
+ method: "GET",
1047
+ headers: getHeaders(targetKey)
1048
+ }
1049
+ ).catch(() => null);
1050
+ let authenticated = true;
1051
+ if (authProbe && (authProbe.status === 401 || authProbe.status === 403)) {
1052
+ authenticated = false;
1053
+ }
1054
+ sendJson(res, 200, {
1055
+ ok: true,
1056
+ version: typeof healthData.version === "string" ? healthData.version : void 0,
1057
+ storage: typeof healthData.storage === "string" ? healthData.storage : void 0,
1058
+ authenticated,
1059
+ error: authenticated ? void 0 : "Daemon reachable, but API key is missing or invalid (HTTP 401)"
1060
+ });
1061
+ } catch (err) {
1062
+ sendJson(res, 500, { ok: false, error: String(err) });
1063
+ }
1064
+ }
1065
+ });
1066
+ }, "openviking-status: test connection route");
1067
+ ctx.effect?.(() => {
1068
+ return ctx.webServer?.register({
1069
+ kind: "exact",
1070
+ path: `${API_PREFIX}/health`,
1071
+ handler: async (_req, res) => {
1072
+ try {
1073
+ const effective = resolveEffective();
1074
+ const daemonRes = await fetch(`${effective.endpoint}/health`, {
1075
+ method: "GET",
1076
+ headers: getHeaders(effective.apiKey)
1077
+ }).catch(
1078
+ (err) => ({ ok: false, status: 502, statusText: err.message })
1079
+ );
1080
+ if (!daemonRes.ok) {
1081
+ sendJson(res, daemonRes.status || 502, {
1082
+ ok: false,
1083
+ healthy: false,
1084
+ error: `Daemon returned ${daemonRes.status}: ${daemonRes.statusText}`
1085
+ });
1086
+ return;
1087
+ }
1088
+ const body = await daemonRes.json().catch(() => ({}));
1089
+ sendJson(res, 200, body);
1090
+ } catch (err) {
1091
+ sendJson(res, 502, { ok: false, healthy: false, error: String(err) });
1092
+ }
1093
+ }
1094
+ });
1095
+ }, "openviking-status: health proxy route");
1096
+ ctx.effect?.(() => {
1097
+ return ctx.webServer?.register({
1098
+ kind: "exact",
1099
+ path: `${API_PREFIX}/session`,
1100
+ handler: async (req, res) => {
1101
+ try {
1102
+ const url = new URL(req.url || "/", "http://localhost");
1103
+ const sessionId = url.searchParams.get("id");
1104
+ if (!sessionId || !sessionId.trim()) {
1105
+ sendJson(res, 400, {
1106
+ status: "missing",
1107
+ error: "Missing session id"
1108
+ });
1109
+ return;
1110
+ }
1111
+ const effective = resolveEffective();
1112
+ const candidates = getCandidateSessionIds(sessionId);
1113
+ for (const candidateId of candidates) {
1114
+ const daemonRes = await fetch(
1115
+ `${effective.endpoint}/api/v1/sessions/${encodeURIComponent(candidateId)}`,
1116
+ {
1117
+ method: "GET",
1118
+ headers: getHeaders(effective.apiKey)
1119
+ }
1120
+ ).catch(() => null);
1121
+ if (!daemonRes) continue;
1122
+ if (daemonRes.status === 404) continue;
1123
+ if (daemonRes.status === 401 || daemonRes.status === 403) {
1124
+ sendJson(res, 200, { status: "unauthorized" });
1125
+ return;
1126
+ }
1127
+ if (!daemonRes.ok) {
1128
+ sendJson(res, 200, {
1129
+ status: "error",
1130
+ detail: `HTTP ${daemonRes.status}`
1131
+ });
1132
+ return;
1133
+ }
1134
+ const data = await daemonRes.json().catch(() => ({}));
1135
+ const raw = data?.result ?? data?.data ?? data;
1136
+ sendJson(res, 200, {
1137
+ status: "ok",
1138
+ session: {
1139
+ session_id: typeof raw.session_id === "string" ? raw.session_id : candidateId,
1140
+ peer_id: typeof raw.peer_id === "string" ? raw.peer_id : void 0,
1141
+ pending_tokens: typeof raw.pending_tokens === "number" ? raw.pending_tokens : 0,
1142
+ message_count: typeof raw.message_count === "number" ? raw.message_count : void 0,
1143
+ commit_count: typeof raw.commit_count === "number" ? raw.commit_count : void 0,
1144
+ last_commit_at: typeof raw.last_commit_at === "string" ? raw.last_commit_at : void 0,
1145
+ created_at: typeof raw.created_at === "string" ? raw.created_at : void 0,
1146
+ updated_at: typeof raw.updated_at === "string" ? raw.updated_at : void 0
1147
+ }
1148
+ });
1149
+ return;
1150
+ }
1151
+ sendJson(res, 200, { status: "missing" });
1152
+ } catch (err) {
1153
+ sendJson(res, 200, { status: "unreachable", detail: String(err) });
1154
+ }
1155
+ }
1156
+ });
1157
+ }, "openviking-status: session proxy route");
1158
+ ctx.effect?.(() => {
1159
+ return ctx.webServer?.register({
1160
+ kind: "exact",
1161
+ path: `${API_PREFIX}/session/commit`,
1162
+ handler: async (req, res) => {
1163
+ try {
1164
+ const body = await readJson(req);
1165
+ const sessionId = body.sessionId;
1166
+ if (!sessionId || typeof sessionId !== "string") {
1167
+ sendJson(res, 400, { ok: false, error: "Missing sessionId" });
1168
+ return;
1169
+ }
1170
+ const effective = resolveEffective();
1171
+ const candidates = getCandidateSessionIds(sessionId);
1172
+ const payload = JSON.stringify({
1173
+ keep_recent_count: body.keep_recent_count ?? 10
1174
+ });
1175
+ for (const candidateId of candidates) {
1176
+ const daemonRes = await fetch(
1177
+ `${effective.endpoint}/api/v1/sessions/${encodeURIComponent(candidateId)}/commit`,
1178
+ {
1179
+ method: "POST",
1180
+ headers: getHeaders(effective.apiKey),
1181
+ body: payload
1182
+ }
1183
+ ).catch(() => null);
1184
+ if (!daemonRes) continue;
1185
+ if (daemonRes.status === 404) continue;
1186
+ if (!daemonRes.ok) {
1187
+ const errBody = await daemonRes.json().catch(() => null);
1188
+ const errorMsg = errBody?.error?.message || errBody?.message || errBody?.error || `HTTP ${daemonRes.status}`;
1189
+ sendJson(res, 200, { ok: false, error: String(errorMsg) });
1190
+ return;
1191
+ }
1192
+ sendJson(res, 200, { ok: true });
1193
+ return;
1194
+ }
1195
+ sendJson(res, 200, {
1196
+ ok: false,
1197
+ error: "Session not found on commit"
1198
+ });
1199
+ } catch (err) {
1200
+ sendJson(res, 500, { ok: false, error: String(err) });
1201
+ }
1202
+ }
1203
+ });
1204
+ }, "openviking-status: session commit proxy route");
6
1205
  }
7
1206
  export {
1207
+ Config,
8
1208
  apply,
9
1209
  inject,
10
- name
1210
+ name,
1211
+ resolveHostCredentials
11
1212
  };
12
1213
  //# sourceMappingURL=index.js.map