@liyang8246/dsh-codetime 0.0.0-stage → 0.1.8

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 ADDED
@@ -0,0 +1,1667 @@
1
+ import { homedir, hostname, platform } from "node:os";
2
+ import { dirname, join } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
+ import process from "node:process";
6
+ // ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.6/node_modules/@deepseek-ai/cosmokit/lib/index.js
7
+ /** Return true when a value is `null` or `undefined`. */
8
+ function isNullable(value) {
9
+ return value === null || value === void 0;
10
+ }
11
+ /** Return true for non-array object values. */
12
+ function isPlainObject(data) {
13
+ return data && typeof data === "object" && !Array.isArray(data);
14
+ }
15
+ /** Filter object entries and return a new object. */
16
+ function filterKeys(object, filter) {
17
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
18
+ }
19
+ /** Map object values while preserving the original key set. */
20
+ function mapValues(object, transform) {
21
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
22
+ }
23
+ /** Pick selected keys from an object, optionally including `undefined` values. */
24
+ function pick(source, keys, forced) {
25
+ if (!keys) return { ...source };
26
+ const result = {};
27
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
28
+ return result;
29
+ }
30
+ /** Shared config references used by schema validators and plugin runtimes. */
31
+ const write = Symbol.for("cosmokit.volatile.write");
32
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
33
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
34
+ if (value === null || typeof value !== "object") return value;
35
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
36
+ ancestors.add(value);
37
+ try {
38
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
39
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
40
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
41
+ } finally {
42
+ ancestors.delete(value);
43
+ }
44
+ }
45
+ /**
46
+ * Create a detached reference containing an immutable copy of the supplied data.
47
+ * @param value - validated config data; class instances and functions are unsupported.
48
+ * @returns a reference whose value is updated only by its owning runtime.
49
+ */
50
+ function createVolatile(value) {
51
+ let current = snapshot(value);
52
+ return Object.freeze({
53
+ get: () => current,
54
+ [write]: (value) => {
55
+ current = value;
56
+ }
57
+ });
58
+ }
59
+ /**
60
+ * Identify references across ESM/CJS copies of the shared library.
61
+ * @param value - a parsed config value.
62
+ * @returns whether the value implements the shared reference protocol.
63
+ */
64
+ function isVolatile(value) {
65
+ return typeof value === "object" && value !== null && write in value;
66
+ }
67
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
68
+ function is(type, value) {
69
+ if (arguments.length === 1) return (value) => is(type, value);
70
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
71
+ }
72
+ function isArrayBufferLike(value) {
73
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
74
+ }
75
+ function isArrayBufferSource(value) {
76
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
77
+ }
78
+ /** Binary source detection and base64/hex conversion helpers. */
79
+ var Binary;
80
+ (function(Binary) {
81
+ Binary.is = isArrayBufferLike;
82
+ Binary.isSource = isArrayBufferSource;
83
+ function fromSource(source) {
84
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
85
+ else return source;
86
+ }
87
+ Binary.fromSource = fromSource;
88
+ function toBase64(source) {
89
+ source = fromSource(source);
90
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
91
+ let binary = "";
92
+ const bytes = new Uint8Array(source);
93
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
94
+ return btoa(binary);
95
+ }
96
+ Binary.toBase64 = toBase64;
97
+ function fromBase64(source) {
98
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
99
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
100
+ }
101
+ Binary.fromBase64 = fromBase64;
102
+ function toHex(source) {
103
+ source = fromSource(source);
104
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
105
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
106
+ }
107
+ Binary.toHex = toHex;
108
+ function fromHex(source) {
109
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
110
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
111
+ const buffer = [];
112
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
113
+ return Uint8Array.from(buffer).buffer;
114
+ }
115
+ Binary.fromHex = fromHex;
116
+ })(Binary || (Binary = {}));
117
+ Binary.fromBase64;
118
+ Binary.toBase64;
119
+ Binary.fromHex;
120
+ Binary.toHex;
121
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
122
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
123
+ if (!source || typeof source !== "object") return source;
124
+ if (is("Date", source)) return new Date(source.valueOf());
125
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
126
+ if (isArrayBufferLike(source)) return source.slice(0);
127
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
128
+ const cached = refs.get(source);
129
+ if (cached) return cached;
130
+ if (Array.isArray(source)) {
131
+ const result = [];
132
+ refs.set(source, result);
133
+ source.forEach((value, index) => {
134
+ result[index] = Reflect.apply(clone, null, [value, refs]);
135
+ });
136
+ return result;
137
+ }
138
+ const result = Object.create(Object.getPrototypeOf(source));
139
+ refs.set(source, result);
140
+ for (const key of Reflect.ownKeys(source)) {
141
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
142
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
143
+ Reflect.defineProperty(result, key, descriptor);
144
+ }
145
+ return result;
146
+ }
147
+ /**
148
+ * Compare values recursively, treating two volatile references as equal regardless of value.
149
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
150
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
151
+ * @param a - first value.
152
+ * @param b - second value.
153
+ * @param strict - whether to require strict data equality outside volatile references.
154
+ * @returns whether the values compare equal.
155
+ */
156
+ function deepEqual(a, b, strict) {
157
+ const ancestors = /* @__PURE__ */ new Set();
158
+ function compare(a, b) {
159
+ if (a === b) return true;
160
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
161
+ if (!strict && isNullable(a) && isNullable(b)) return true;
162
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
163
+ if (ancestors.has(a)) return false;
164
+ function check(test, then) {
165
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
166
+ }
167
+ ancestors.add(a);
168
+ try {
169
+ return check(Array.isArray, (a, b) => {
170
+ if (a.length !== b.length) return false;
171
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
172
+ return true;
173
+ }) ?? 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) => {
174
+ if (a.byteLength !== b.byteLength) return false;
175
+ const viewA = new Uint8Array(a);
176
+ const viewB = new Uint8Array(b);
177
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
178
+ return true;
179
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
180
+ ...a,
181
+ ...b
182
+ }).every((key) => compare(a[key], b[key])));
183
+ } finally {
184
+ ancestors.delete(a);
185
+ }
186
+ }
187
+ return compare(a, b);
188
+ }
189
+ /** Time constants plus parsing and formatting helpers. */
190
+ var Time;
191
+ (function(Time) {
192
+ Time.millisecond = 1;
193
+ Time.second = 1e3;
194
+ Time.minute = Time.second * 60;
195
+ Time.hour = Time.minute * 60;
196
+ Time.day = Time.hour * 24;
197
+ Time.week = Time.day * 7;
198
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
199
+ function setTimezoneOffset(offset) {
200
+ timezoneOffset = offset;
201
+ }
202
+ Time.setTimezoneOffset = setTimezoneOffset;
203
+ function getTimezoneOffset() {
204
+ return timezoneOffset;
205
+ }
206
+ Time.getTimezoneOffset = getTimezoneOffset;
207
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
208
+ if (typeof date === "number") date = new Date(date);
209
+ if (offset === void 0) offset = timezoneOffset;
210
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
211
+ }
212
+ Time.getDateNumber = getDateNumber;
213
+ function fromDateNumber(value, offset) {
214
+ const date = new Date(value * Time.day);
215
+ if (offset === void 0) offset = timezoneOffset;
216
+ return new Date(+date + offset * Time.minute);
217
+ }
218
+ Time.fromDateNumber = fromDateNumber;
219
+ const numeric = /\d+(?:\.\d+)?/.source;
220
+ const timeRegExp = new RegExp(`^${[
221
+ "w(?:eek(?:s)?)?",
222
+ "d(?:ay(?:s)?)?",
223
+ "h(?:our(?:s)?)?",
224
+ "m(?:in(?:ute)?(?:s)?)?",
225
+ "s(?:ec(?:ond)?(?:s)?)?"
226
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
227
+ function parseTime(source) {
228
+ const capture = timeRegExp.exec(source);
229
+ if (!capture) return 0;
230
+ 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);
231
+ }
232
+ Time.parseTime = parseTime;
233
+ function parseDate(date) {
234
+ const parsed = parseTime(date);
235
+ if (parsed) date = Date.now() + parsed;
236
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
237
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
238
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
239
+ }
240
+ Time.parseDate = parseDate;
241
+ function format(ms) {
242
+ const abs = Math.abs(ms);
243
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
244
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
245
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
246
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
247
+ return ms + "ms";
248
+ }
249
+ Time.format = format;
250
+ function toDigits(source, length = 2) {
251
+ return source.toString().padStart(length, "0");
252
+ }
253
+ Time.toDigits = toDigits;
254
+ function template(template, time = /* @__PURE__ */ new Date()) {
255
+ 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));
256
+ }
257
+ Time.template = template;
258
+ })(Time || (Time = {}));
259
+ // ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.5/node_modules/@deepseek-ai/schemastery/lib/index.mjs
260
+ const kSchema = Symbol.for("schemastery");
261
+ const kValidationError = Symbol.for("ValidationError");
262
+ globalThis.__schemastery_index__ ??= 0;
263
+ globalThis.__schemastery_refs__ = void 0;
264
+ var ValidationError = class extends TypeError {
265
+ options;
266
+ name = "ValidationError";
267
+ constructor(message, options) {
268
+ let prefix = "$";
269
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
270
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
271
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
272
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
273
+ super((prefix === "$" ? "" : `${prefix} `) + message);
274
+ this.options = options;
275
+ }
276
+ static is(error) {
277
+ return !!error?.[kValidationError];
278
+ }
279
+ };
280
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
281
+ const Schema = function(options) {
282
+ const schema = function(data, options = {}) {
283
+ return Schema.resolve(data, schema, options)[0];
284
+ };
285
+ if (options.refs) {
286
+ const refs = mapValues(options.refs, (options) => new Schema(options));
287
+ const getRef = (uid) => refs[uid];
288
+ for (const key in refs) {
289
+ const options = refs[key];
290
+ options.sKey = getRef(options.sKey);
291
+ options.inner = getRef(options.inner);
292
+ options.list = options.list && options.list.map(getRef);
293
+ options.dict = options.dict && mapValues(options.dict, getRef);
294
+ }
295
+ return refs[options.uid];
296
+ }
297
+ Object.assign(schema, options);
298
+ if (typeof schema.callback === "string") try {
299
+ schema.callback = new Function("return " + schema.callback)();
300
+ } catch {}
301
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
302
+ Object.setPrototypeOf(schema, Schema.prototype);
303
+ schema.meta ||= {};
304
+ schema.toString = schema.toString.bind(schema);
305
+ return schema;
306
+ };
307
+ Schema.prototype = Object.create(Function.prototype);
308
+ Schema.prototype[kSchema] = true;
309
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
310
+ return {
311
+ version: 1,
312
+ vendor: "schemastery",
313
+ validate: (value) => {
314
+ try {
315
+ return { value: Schema.resolve(value, this, {})[0] };
316
+ } catch (error) {
317
+ if (ValidationError.is(error)) return { issues: [{
318
+ message: error.message,
319
+ path: error.options.path
320
+ }] };
321
+ throw error;
322
+ }
323
+ }
324
+ };
325
+ } });
326
+ Schema.ValidationError = ValidationError;
327
+ Schema.prototype.toJSON = function toJSON() {
328
+ if (globalThis.__schemastery_refs__) {
329
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
330
+ return this.uid;
331
+ }
332
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
333
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
334
+ const result = {
335
+ uid: this.uid,
336
+ refs: globalThis.__schemastery_refs__
337
+ };
338
+ globalThis.__schemastery_refs__ = void 0;
339
+ return result;
340
+ };
341
+ Schema.prototype.set = function set(key, value) {
342
+ this.dict[key] = value;
343
+ return this;
344
+ };
345
+ Schema.prototype.push = function push(value) {
346
+ this.list.push(value);
347
+ return this;
348
+ };
349
+ function mergeDesc(original, messages) {
350
+ const result = typeof original === "string" ? { "": original } : { ...original };
351
+ for (const locale in messages) {
352
+ const value = messages[locale];
353
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
354
+ else if (typeof value === "string") result[locale] = value;
355
+ }
356
+ return result;
357
+ }
358
+ function getInner(value) {
359
+ return value?.$value ?? value?.$inner;
360
+ }
361
+ function extractKeys(data) {
362
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
363
+ }
364
+ Schema.prototype.i18n = function i18n(messages) {
365
+ const schema = Schema(this);
366
+ const desc = mergeDesc(schema.meta.description, messages);
367
+ if (Object.keys(desc).length) schema.meta.description = desc;
368
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
369
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
370
+ });
371
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
372
+ return inner.i18n(mapValues(messages, (data = {}) => {
373
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
374
+ if (Array.isArray(data)) return data[index];
375
+ return extractKeys(data);
376
+ }));
377
+ });
378
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
379
+ if (getInner(data)) return getInner(data);
380
+ return extractKeys(data);
381
+ }));
382
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
383
+ return schema;
384
+ };
385
+ Schema.prototype.extra = function extra(key, value) {
386
+ const schema = Schema(this);
387
+ schema.meta = {
388
+ ...schema.meta,
389
+ [key]: value
390
+ };
391
+ return schema;
392
+ };
393
+ for (const key of [
394
+ "required",
395
+ "disabled",
396
+ "collapse",
397
+ "hidden",
398
+ "loose"
399
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
400
+ const schema = Schema(this);
401
+ schema.meta = {
402
+ ...schema.meta,
403
+ [key]: value
404
+ };
405
+ return schema;
406
+ } });
407
+ Schema.prototype.deprecated = function deprecated() {
408
+ const schema = Schema(this);
409
+ schema.meta.badges ||= [];
410
+ schema.meta.badges.push({
411
+ text: "deprecated",
412
+ type: "danger"
413
+ });
414
+ return schema;
415
+ };
416
+ Schema.prototype.experimental = function experimental() {
417
+ const schema = Schema(this);
418
+ schema.meta.badges ||= [];
419
+ schema.meta.badges.push({
420
+ text: "experimental",
421
+ type: "warning"
422
+ });
423
+ return schema;
424
+ };
425
+ Schema.prototype.pattern = function pattern(regexp) {
426
+ const schema = Schema(this);
427
+ const pattern = pick(regexp, ["source", "flags"]);
428
+ schema.meta = {
429
+ ...schema.meta,
430
+ pattern
431
+ };
432
+ return schema;
433
+ };
434
+ Schema.prototype.simplify = function simplify(value) {
435
+ if (isVolatile(value)) value = value.get();
436
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
437
+ if (isNullable(value)) return value;
438
+ if (this.type === "object" || this.type === "dict") {
439
+ const result = {};
440
+ for (const key in value) {
441
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
442
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
443
+ }
444
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
445
+ return result;
446
+ } else if (this.type === "array" || this.type === "tuple") {
447
+ const result = [];
448
+ value.forEach((value, index) => {
449
+ const schema = this.type === "array" ? this.inner : this.list[index];
450
+ const item = schema ? schema.simplify(value) : value;
451
+ result.push(item);
452
+ });
453
+ return result;
454
+ } else if (this.type === "intersect") {
455
+ const result = {};
456
+ for (const item of this.list) Object.assign(result, item.simplify(value));
457
+ return result;
458
+ } else if (this.type === "union") for (const schema of this.list) try {
459
+ Schema.resolve(value, schema, {});
460
+ return schema.simplify(value);
461
+ } catch {}
462
+ return value;
463
+ };
464
+ Schema.prototype.toString = function toString(inline) {
465
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
466
+ };
467
+ Schema.prototype.role = function role(role, extra) {
468
+ const schema = Schema(this);
469
+ schema.meta = {
470
+ ...schema.meta,
471
+ role,
472
+ extra
473
+ };
474
+ return schema;
475
+ };
476
+ for (const key of [
477
+ "default",
478
+ "link",
479
+ "comment",
480
+ "description",
481
+ "max",
482
+ "min",
483
+ "step"
484
+ ]) Object.assign(Schema.prototype, { [key](value) {
485
+ const schema = Schema(this);
486
+ schema.meta = {
487
+ ...schema.meta,
488
+ [key]: value
489
+ };
490
+ return schema;
491
+ } });
492
+ Schema.prototype.volatile = function volatile() {
493
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
494
+ return this.extra("volatile", true);
495
+ };
496
+ const resolvers = {};
497
+ const checkedVolatile = Symbol("checked-volatile-schema");
498
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
499
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
500
+ if (states.has(blocked)) return;
501
+ states.add(blocked);
502
+ seen.set(schema, states);
503
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
504
+ const nested = blocked || !!schema.meta?.volatile;
505
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
506
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
507
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
508
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
509
+ }
510
+ Schema.extend = function extend(type, resolve) {
511
+ resolvers[type] = resolve;
512
+ };
513
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
514
+ if (!schema) return [data];
515
+ if (!options[checkedVolatile]) {
516
+ validateVolatileSchema(schema, options.path);
517
+ options = {
518
+ ...options,
519
+ [checkedVolatile]: true
520
+ };
521
+ }
522
+ if (schema.meta?.volatile) {
523
+ const inner = Schema(schema);
524
+ inner.meta = {
525
+ ...schema.meta,
526
+ volatile: false
527
+ };
528
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
529
+ try {
530
+ return [createVolatile(value), adapted];
531
+ } catch (error) {
532
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
533
+ }
534
+ }
535
+ if (options.ignore?.(data, schema)) return [data];
536
+ if (isNullable(data) && schema.type !== "lazy") {
537
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
538
+ let current = schema;
539
+ let fallback = schema.meta.default;
540
+ while (current?.type === "intersect" && isNullable(fallback)) {
541
+ current = current.list[0];
542
+ fallback = current?.meta.default;
543
+ }
544
+ if (isNullable(fallback)) return [data];
545
+ data = clone(fallback);
546
+ }
547
+ const callback = resolvers[schema.type];
548
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
549
+ try {
550
+ return callback(data, schema, options, strict);
551
+ } catch (error) {
552
+ if (!schema.meta.loose) throw error;
553
+ return [schema.meta.default];
554
+ }
555
+ };
556
+ Schema.from = function from(source) {
557
+ if (isNullable(source)) return Schema.any();
558
+ else if ([
559
+ "string",
560
+ "number",
561
+ "boolean"
562
+ ].includes(typeof source)) return Schema.const(source).required();
563
+ else if (source[kSchema]) return source;
564
+ else if (typeof source === "function") switch (source) {
565
+ case String: return Schema.string().required();
566
+ case Number: return Schema.number().required();
567
+ case Boolean: return Schema.boolean().required();
568
+ case Function: return Schema.function().required();
569
+ default: return Schema.is(source).required();
570
+ }
571
+ else throw new TypeError(`cannot infer schema from ${source}`);
572
+ };
573
+ Schema.lazy = function lazy(builder) {
574
+ const toJSON = () => {
575
+ if (!schema.inner[kSchema]) {
576
+ schema.inner = schema.builder();
577
+ schema.inner.meta = {
578
+ ...schema.meta,
579
+ ...schema.inner.meta
580
+ };
581
+ }
582
+ return schema.inner.toJSON();
583
+ };
584
+ const schema = new Schema({
585
+ type: "lazy",
586
+ builder,
587
+ inner: { toJSON }
588
+ });
589
+ return schema;
590
+ };
591
+ Schema.natural = function natural() {
592
+ return Schema.number().step(1).min(0);
593
+ };
594
+ Schema.percent = function percent() {
595
+ return Schema.number().step(.01).min(0).max(1).role("slider");
596
+ };
597
+ Schema.date = function date() {
598
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
599
+ const date = new Date(value);
600
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
601
+ return date;
602
+ }, true)]);
603
+ };
604
+ Schema.regExp = function regExp(flag = "") {
605
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
606
+ try {
607
+ return new RegExp(value, flag);
608
+ } catch (e) {
609
+ throw new ValidationError(e.message, options);
610
+ }
611
+ }, true)]);
612
+ };
613
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
614
+ return Schema.union([
615
+ Schema.is(ArrayBuffer),
616
+ Schema.is(SharedArrayBuffer),
617
+ Schema.transform(Schema.any(), (value, options) => {
618
+ if (Binary.isSource(value)) return Binary.fromSource(value);
619
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
620
+ }, true),
621
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
622
+ try {
623
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
624
+ } catch (e) {
625
+ throw new ValidationError(e.message, options);
626
+ }
627
+ }, true)] : []
628
+ ]);
629
+ };
630
+ Schema.extend("lazy", (data, schema, options, strict) => {
631
+ if (!schema.inner[kSchema]) {
632
+ schema.inner = schema.builder();
633
+ schema.inner.meta = {
634
+ ...schema.meta,
635
+ ...schema.inner.meta
636
+ };
637
+ validateVolatileSchema(schema.inner, options.path, true);
638
+ }
639
+ return Schema.resolve(data, schema.inner, options, strict);
640
+ });
641
+ Schema.extend("any", (data) => {
642
+ return [data];
643
+ });
644
+ Schema.extend("never", (data, _, options) => {
645
+ throw new ValidationError(`expected nullable but got ${data}`, options);
646
+ });
647
+ Schema.extend("const", (data, { value }, options) => {
648
+ if (deepEqual(data, value)) return [value];
649
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
650
+ });
651
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
652
+ const { max = Infinity, min = -Infinity } = meta;
653
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
654
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
655
+ }
656
+ Schema.extend("string", (data, { meta }, options) => {
657
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
658
+ if (meta.pattern) {
659
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
660
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
661
+ }
662
+ checkWithinRange(data.length, meta, "string length", options);
663
+ return [data];
664
+ });
665
+ function decimalShift(data, digits) {
666
+ const str = data.toString();
667
+ if (str.includes("e")) return data * Math.pow(10, digits);
668
+ const index = str.indexOf(".");
669
+ if (index === -1) return data * Math.pow(10, digits);
670
+ const frac = str.slice(index + 1);
671
+ const integer = str.slice(0, index);
672
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
673
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
674
+ }
675
+ function isMultipleOf(data, min, step) {
676
+ step = Math.abs(step);
677
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
678
+ const index = step.toString().indexOf(".");
679
+ const digits = step.toString().slice(index + 1).length;
680
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
681
+ }
682
+ Schema.extend("number", (data, { meta }, options) => {
683
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
684
+ checkWithinRange(data, meta, "number", options);
685
+ const { step } = meta;
686
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
687
+ return [data];
688
+ });
689
+ Schema.extend("boolean", (data, _, options) => {
690
+ if (typeof data === "boolean") return [data];
691
+ throw new ValidationError(`expected boolean but got ${data}`, options);
692
+ });
693
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
694
+ let value = 0, keys = [];
695
+ if (typeof data === "number") {
696
+ value = data;
697
+ for (const key in bits) if (data & bits[key]) keys.push(key);
698
+ } else if (Array.isArray(data)) {
699
+ keys = data;
700
+ for (const key of keys) {
701
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
702
+ if (key in bits) value |= bits[key];
703
+ }
704
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
705
+ if (value === meta.default) return [value];
706
+ return [value, keys];
707
+ });
708
+ Schema.extend("function", (data, _, options) => {
709
+ if (typeof data === "function") return [data];
710
+ throw new ValidationError(`expected function but got ${data}`, options);
711
+ });
712
+ Schema.extend("is", (data, { constructor }, options) => {
713
+ if (typeof constructor === "function") {
714
+ if (data instanceof constructor) return [data];
715
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
716
+ } else {
717
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
718
+ let prototype = Object.getPrototypeOf(data);
719
+ while (prototype) {
720
+ if (prototype.constructor?.name === constructor) return [data];
721
+ prototype = Object.getPrototypeOf(prototype);
722
+ }
723
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
724
+ }
725
+ });
726
+ function property(data, key, schema, options) {
727
+ try {
728
+ const [value, adapted] = Schema.resolve(data[key], schema, {
729
+ ...options,
730
+ path: [...options.path || [], key]
731
+ });
732
+ if (adapted !== void 0) data[key] = adapted;
733
+ return value;
734
+ } catch (e) {
735
+ if (!options?.autofix) throw e;
736
+ delete data[key];
737
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
738
+ }
739
+ }
740
+ Schema.extend("array", (data, { inner, meta }, options) => {
741
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
742
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
743
+ return [data.map((_, index) => property(data, index, inner, options))];
744
+ });
745
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
746
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
747
+ const result = {};
748
+ for (const key in data) {
749
+ let rKey;
750
+ try {
751
+ rKey = Schema.resolve(key, sKey, options)[0];
752
+ } catch (error) {
753
+ if (strict) continue;
754
+ throw error;
755
+ }
756
+ result[rKey] = property(data, key, inner, options);
757
+ data[rKey] = data[key];
758
+ if (key !== rKey) delete data[key];
759
+ }
760
+ return [result];
761
+ });
762
+ Schema.extend("tuple", (data, { list }, options, strict) => {
763
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
764
+ const result = list.map((inner, index) => property(data, index, inner, options));
765
+ if (strict) return [result];
766
+ result.push(...data.slice(list.length));
767
+ return [result];
768
+ });
769
+ function merge(result, data) {
770
+ for (const key in data) {
771
+ if (key in result) continue;
772
+ result[key] = data[key];
773
+ }
774
+ }
775
+ Schema.extend("object", (data, { dict }, options, strict) => {
776
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
777
+ const result = {};
778
+ for (const key in dict) {
779
+ const value = property(data, key, dict[key], options);
780
+ if (!isNullable(value) || key in data) result[key] = value;
781
+ }
782
+ if (!strict) merge(result, data);
783
+ return [result];
784
+ });
785
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
786
+ const messages = [];
787
+ for (const inner of list) try {
788
+ return Schema.resolve(data, inner, options, strict);
789
+ } catch (error) {
790
+ messages.push(error);
791
+ }
792
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
793
+ });
794
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
795
+ if (!list.length) return [data];
796
+ let result;
797
+ for (const inner of list) {
798
+ const value = Schema.resolve(data, inner, options, true)[0];
799
+ if (isNullable(value)) continue;
800
+ if (isNullable(result)) result = value;
801
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
802
+ else if (typeof value === "object") merge(result ??= {}, value);
803
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
804
+ }
805
+ if (!strict && isPlainObject(data)) merge(result, data);
806
+ return [result];
807
+ });
808
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
809
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
810
+ if (preserve) return [callback(result)];
811
+ else return [callback(result), callback(adapted)];
812
+ });
813
+ const formatters = {};
814
+ function defineMethod(name, keys, format) {
815
+ formatters[name] = format;
816
+ Object.assign(Schema, { [name](...args) {
817
+ const schema = new Schema({ type: name });
818
+ keys.forEach((key, index) => {
819
+ switch (key) {
820
+ case "sKey":
821
+ schema.sKey = args[index] ?? Schema.string();
822
+ break;
823
+ case "inner":
824
+ schema.inner = Schema.from(args[index]);
825
+ break;
826
+ case "list":
827
+ schema.list = args[index].map(Schema.from);
828
+ break;
829
+ case "dict":
830
+ schema.dict = mapValues(args[index], Schema.from);
831
+ break;
832
+ case "bits":
833
+ schema.bits = {};
834
+ for (const key in args[index]) {
835
+ if (typeof args[index][key] !== "number") continue;
836
+ schema.bits[key] = args[index][key];
837
+ }
838
+ break;
839
+ case "callback": {
840
+ const callback = schema.callback = args[index];
841
+ callback["toJSON"] ||= () => callback.toString();
842
+ break;
843
+ }
844
+ case "constructor": {
845
+ const constructor = schema.constructor = args[index];
846
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
847
+ break;
848
+ }
849
+ default: schema[key] = args[index];
850
+ }
851
+ });
852
+ if (name === "object" || name === "dict") schema.meta.default = {};
853
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
854
+ else if (name === "bitset") schema.meta.default = 0;
855
+ return schema;
856
+ } });
857
+ }
858
+ defineMethod("is", ["constructor"], ({ constructor }) => {
859
+ if (typeof constructor === "function") return constructor.name;
860
+ else return constructor;
861
+ });
862
+ defineMethod("any", [], () => "any");
863
+ defineMethod("never", [], () => "never");
864
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
865
+ defineMethod("string", [], () => "string");
866
+ defineMethod("number", [], () => "number");
867
+ defineMethod("boolean", [], () => "boolean");
868
+ defineMethod("bitset", ["bits"], () => "bitset");
869
+ defineMethod("function", [], () => "function");
870
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
871
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
872
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
873
+ defineMethod("object", ["dict"], ({ dict }) => {
874
+ if (Object.keys(dict).length === 0) return "{}";
875
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
876
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
877
+ }).join(", ")} }`;
878
+ });
879
+ defineMethod("union", ["list"], ({ list }, inline) => {
880
+ const result = list.map(({ toString: format }) => format()).join(" | ");
881
+ return inline ? `(${result})` : result;
882
+ });
883
+ defineMethod("intersect", ["list"], ({ list }) => {
884
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
885
+ });
886
+ defineMethod("transform", [
887
+ "inner",
888
+ "callback",
889
+ "preserve"
890
+ ], ({ inner }, isInner) => inner.toString(isInner));
891
+ // src/host/history.ts
892
+ /**
893
+ * Fold stored session logs into the accumulator.
894
+ *
895
+ * The persisted cursor makes this idempotent: a session already seen through
896
+ * the live feed contributes only its new tail.
897
+ * @param ctx - plugin context providing the optional query service.
898
+ * @param folder - fold target.
899
+ * @param days - how far back `createdAt` may reach; 0 disables the pass.
900
+ * @returns counts for diagnostics.
901
+ */
902
+ async function scanHistory(ctx, folder, days) {
903
+ const result = {
904
+ sessions: 0,
905
+ events: 0,
906
+ failed: 0
907
+ };
908
+ if (days <= 0) return result;
909
+ const query = ctx.get("sessionQuery");
910
+ if (!query) return result;
911
+ const records = await query.listSessions();
912
+ const cutoff = Date.now() - days * 864e5;
913
+ for (const record of records) {
914
+ if (record.header.createdAt < cutoff) continue;
915
+ result.sessions += 1;
916
+ try {
917
+ const log = await query.readSession(record.header.id);
918
+ result.events += folder.ingest({
919
+ id: log.session.id,
920
+ cwd: log.session.cwd
921
+ }, log.events);
922
+ } catch {
923
+ result.failed += 1;
924
+ }
925
+ }
926
+ return result;
927
+ }
928
+ // src/host/remote.ts
929
+ /** The one ingest host this plugin reports to. */
930
+ const REMOTE_URL = "https://codetime.dev";
931
+ /** Directory the codetime CLI owns; the plugin shares it so one token works for both. */
932
+ function codetimeHome() {
933
+ return join(homedir(), ".codetime");
934
+ }
935
+ /** Path of the shared CLI config file. */
936
+ function configPath() {
937
+ return join(codetimeHome(), "config.json");
938
+ }
939
+ /** Raw shared config as the CLI wrote it; unknown keys are preserved on write. */
940
+ async function readConfig() {
941
+ let raw;
942
+ try {
943
+ raw = await readFile(configPath(), "utf8");
944
+ } catch (error) {
945
+ if (error.code === "ENOENT") return {};
946
+ throw error;
947
+ }
948
+ try {
949
+ const parsed = JSON.parse(raw);
950
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
951
+ } catch {
952
+ return {};
953
+ }
954
+ }
955
+ /** Resolve the effective upload token: process environment, then the CLI config. */
956
+ async function resolveToken() {
957
+ const fromEnv = process.env.CODETIME_TOKEN;
958
+ if (fromEnv && fromEnv.trim()) return fromEnv.trim();
959
+ const token = (await readConfig()).token;
960
+ return typeof token === "string" && token ? token : void 0;
961
+ }
962
+ /**
963
+ * Store or clear the token in the CLI's config file.
964
+ * @param token - token to persist; `undefined` removes it.
965
+ */
966
+ async function writeToken(token) {
967
+ const config = await readConfig();
968
+ if (token) config.token = token;
969
+ else delete config.token;
970
+ await mkdir(codetimeHome(), { recursive: true });
971
+ const temporary = `${configPath()}.tmp`;
972
+ await writeFile(temporary, `${JSON.stringify(config)}\n`, {
973
+ encoding: "utf8",
974
+ mode: 384
975
+ });
976
+ await rename(temporary, configPath()).catch(async (error) => {
977
+ await rm(temporary, { force: true });
978
+ throw error;
979
+ });
980
+ }
981
+ /** Read the machine id, minting and persisting one on first use. */
982
+ async function ensureMachineId() {
983
+ const path = join(codetimeHome(), "machine-id");
984
+ try {
985
+ const existing = (await readFile(path, "utf8")).trim();
986
+ if (existing) return existing;
987
+ } catch (error) {
988
+ if (error.code !== "ENOENT") throw error;
989
+ }
990
+ const created = randomUUID();
991
+ await mkdir(codetimeHome(), { recursive: true });
992
+ await writeFile(path, `${created}\n`, "utf8");
993
+ return created;
994
+ }
995
+ /** Mask a token for display: four leading and four trailing characters around twenty dots. */
996
+ function maskToken(token) {
997
+ const dots = "•".repeat(20);
998
+ if (token.length <= 8) return dots;
999
+ return `${token.slice(0, 4)}${dots}${token.slice(-4)}`;
1000
+ }
1001
+ /**
1002
+ * POST one batch of session rollups to `/v3/agent/ingest` with `replace: true`,
1003
+ * so re-uploading a session refreshes it instead of duplicating it.
1004
+ * @returns inserted, skipped, and conflict counts reported by the server.
1005
+ * @throws when the host rejects the batch; the response body is included.
1006
+ */
1007
+ async function uploadRollups(input) {
1008
+ const response = await fetch(`${REMOTE_URL}/v3/agent/ingest`, {
1009
+ method: "POST",
1010
+ headers: {
1011
+ "content-type": "application/json",
1012
+ "user-agent": "dsh-codetime/0.1.0",
1013
+ "authorization": `Bearer ${input.token}`,
1014
+ "x-machine-id": input.machineId,
1015
+ "x-machine-hostname": hostname(),
1016
+ "x-machine-name": hostname(),
1017
+ "x-machine-platform": platform()
1018
+ },
1019
+ body: JSON.stringify({
1020
+ rollups: input.rollups,
1021
+ replace: true
1022
+ })
1023
+ });
1024
+ if (!response.ok) {
1025
+ const body = await response.text();
1026
+ throw new Error(`codetime API ${response.status}: ${body.slice(0, 400)}`);
1027
+ }
1028
+ const data = await response.json();
1029
+ const record = typeof data === "object" && data !== null ? data : {};
1030
+ return {
1031
+ inserted: Number(record.inserted) || 0,
1032
+ skipped: Number(record.skipped) || 0,
1033
+ conflicts: Number(record.conflicts) || 0
1034
+ };
1035
+ }
1036
+ // src/host/state.ts
1037
+ const SAVE_DELAY_MS = 1e3;
1038
+ /** Blank token counters. */
1039
+ function emptyTokens() {
1040
+ return {
1041
+ inputTokens: 0,
1042
+ cachedInputTokens: 0,
1043
+ cacheCreationInputTokens: 0,
1044
+ cacheReadInputTokens: 0,
1045
+ outputTokens: 0,
1046
+ reasoningOutputTokens: 0,
1047
+ totalTokens: 0
1048
+ };
1049
+ }
1050
+ /** State with no folded activity. */
1051
+ function createState() {
1052
+ return {
1053
+ version: 1,
1054
+ sessions: {},
1055
+ settings: { autoUpload: true }
1056
+ };
1057
+ }
1058
+ /** Drop sessions that have been quiet past the retention window. */
1059
+ function prune(state, retentionDays, now) {
1060
+ const cutoff = now - retentionDays * 864e5;
1061
+ for (const [id, session] of Object.entries(state.sessions)) if (Date.parse(session.lastEventAt) < cutoff) delete state.sessions[id];
1062
+ }
1063
+ /**
1064
+ * Durable JSON state. Writes are debounced and atomic; concurrent writes are
1065
+ * serialized so the file never contains a partial body.
1066
+ */
1067
+ var StateFile = class {
1068
+ path;
1069
+ state = createState();
1070
+ timer;
1071
+ writing = Promise.resolve();
1072
+ closed = false;
1073
+ retentionDays;
1074
+ constructor(path, retentionDays) {
1075
+ this.path = path;
1076
+ this.retentionDays = retentionDays;
1077
+ }
1078
+ /** Load previous state, or start empty when the file is absent. */
1079
+ async load() {
1080
+ let raw;
1081
+ try {
1082
+ raw = await readFile(this.path, "utf8");
1083
+ } catch (error) {
1084
+ if (error.code === "ENOENT") return;
1085
+ throw error;
1086
+ }
1087
+ const parsed = JSON.parse(raw);
1088
+ this.state = isPluginState(parsed) ? parsed : createState();
1089
+ }
1090
+ /** Request a debounced write. */
1091
+ schedule() {
1092
+ if (this.closed || this.timer) return;
1093
+ this.timer = setTimeout(() => {
1094
+ this.timer = void 0;
1095
+ this.write();
1096
+ }, SAVE_DELAY_MS);
1097
+ this.timer.unref?.();
1098
+ }
1099
+ /** Write the current state now. */
1100
+ write() {
1101
+ this.writing = this.writing.then(() => this.writeNow());
1102
+ return this.writing;
1103
+ }
1104
+ /** Flush pending activity and stop accepting writes. */
1105
+ async flush() {
1106
+ if (this.timer) {
1107
+ clearTimeout(this.timer);
1108
+ this.timer = void 0;
1109
+ }
1110
+ this.closed = true;
1111
+ await this.write();
1112
+ }
1113
+ async writeNow() {
1114
+ prune(this.state, this.retentionDays, Date.now());
1115
+ const body = `${JSON.stringify(this.state)}\n`;
1116
+ const temporary = `${this.path}.tmp`;
1117
+ await mkdir(dirname(this.path), { recursive: true });
1118
+ await writeFile(temporary, body, "utf8");
1119
+ await rename(temporary, this.path).catch(async (error) => {
1120
+ await rm(temporary, { force: true });
1121
+ throw error;
1122
+ });
1123
+ }
1124
+ };
1125
+ /** Validate a decoded state file at the durable-file boundary. */
1126
+ function isPluginState(value) {
1127
+ if (typeof value !== "object" || value === null) return false;
1128
+ const candidate = value;
1129
+ return candidate.version === 1 && typeof candidate.sessions === "object" && candidate.sessions !== null && typeof candidate.settings === "object" && candidate.settings !== null && typeof candidate.settings.autoUpload === "boolean";
1130
+ }
1131
+ // src/host/rollups.ts
1132
+ const BUCKET_MS = 9e5;
1133
+ const MAX_TURN_MS = 72e5;
1134
+ /** ISO timestamp of the 15-minute bucket that owns `time`. */
1135
+ function bucketStamp(time) {
1136
+ return (/* @__PURE__ */ new Date(Math.floor(time / BUCKET_MS) * BUCKET_MS)).toISOString();
1137
+ }
1138
+ /** Last path segment of a working directory, used as the project label. */
1139
+ function projectName(cwd) {
1140
+ if (!cwd) return void 0;
1141
+ const segments = cwd.split(/[\\/]/).filter(Boolean);
1142
+ return segments[segments.length - 1];
1143
+ }
1144
+ /** Empty time bucket. */
1145
+ function emptyBucket(ts) {
1146
+ return {
1147
+ ts,
1148
+ activityCount: 0,
1149
+ sessionStarts: 0,
1150
+ modelCalls: 0,
1151
+ toolCalls: 0,
1152
+ commandCalls: 0,
1153
+ fileReads: 0,
1154
+ fileWrites: 0,
1155
+ linesAdded: 0,
1156
+ linesRemoved: 0,
1157
+ inputTokens: 0,
1158
+ cachedInputTokens: 0,
1159
+ cacheCreationInputTokens: 0,
1160
+ cacheReadInputTokens: 0,
1161
+ outputTokens: 0,
1162
+ reasoningOutputTokens: 0,
1163
+ totalTokens: 0,
1164
+ estimatedCostUsd: 0
1165
+ };
1166
+ }
1167
+ /** Empty model rollup. */
1168
+ function emptyModel(model) {
1169
+ return {
1170
+ model,
1171
+ callCount: 0,
1172
+ inputTokens: 0,
1173
+ cachedInputTokens: 0,
1174
+ cacheCreationInputTokens: 0,
1175
+ cacheCreation5mInputTokens: 0,
1176
+ cacheCreation1hInputTokens: 0,
1177
+ cacheReadInputTokens: 0,
1178
+ outputTokens: 0,
1179
+ reasoningOutputTokens: 0,
1180
+ totalTokens: 0,
1181
+ estimatedCostUsd: 0
1182
+ };
1183
+ }
1184
+ /**
1185
+ * Folds DSH session events into codetime rollups, one accumulator per session.
1186
+ * The persisted cursor makes a repeated history scan add only new events.
1187
+ */
1188
+ var SessionFolder = class {
1189
+ state;
1190
+ currentTurn = /* @__PURE__ */ new Map();
1191
+ callNames = /* @__PURE__ */ new Map();
1192
+ constructor(state) {
1193
+ this.state = state;
1194
+ }
1195
+ /** Fold one session's events; returns how many were new. */
1196
+ ingest(session, events) {
1197
+ let folded = 0;
1198
+ for (const event of events) {
1199
+ const existing = this.state.sessions[session.id];
1200
+ if (existing && event.seq <= existing.cursor) continue;
1201
+ const accumulator = this.accumulator(session, event.time);
1202
+ this.record(session.id, accumulator, event);
1203
+ folded += 1;
1204
+ }
1205
+ return folded;
1206
+ }
1207
+ /** Sessions whose local fold differs from the last accepted upload. */
1208
+ pendingSessions() {
1209
+ return Object.values(this.state.sessions).filter((session) => session.uploadedHash !== toWireRollup(session).payloadHash);
1210
+ }
1211
+ accumulator(session, time) {
1212
+ const existing = this.state.sessions[session.id];
1213
+ if (existing) return existing;
1214
+ const stamp = new Date(time).toISOString();
1215
+ const created = {
1216
+ sessionId: session.id,
1217
+ project: projectName(session.cwd),
1218
+ cwd: session.cwd,
1219
+ startedAt: stamp,
1220
+ lastEventAt: stamp,
1221
+ cursor: -1,
1222
+ eventCount: 0,
1223
+ promptCount: 0,
1224
+ turnCount: 0,
1225
+ toolCallCount: 0,
1226
+ commandCallCount: 0,
1227
+ tokens: emptyTokens(),
1228
+ timeBuckets: {},
1229
+ modelRollups: {},
1230
+ modelBuckets: {},
1231
+ toolRollups: {},
1232
+ turnRollups: {}
1233
+ };
1234
+ this.state.sessions[session.id] = created;
1235
+ return created;
1236
+ }
1237
+ bucket(accumulator, time) {
1238
+ const ts = bucketStamp(time);
1239
+ const existing = accumulator.timeBuckets[ts];
1240
+ if (existing) return existing;
1241
+ const created = emptyBucket(ts);
1242
+ accumulator.timeBuckets[ts] = created;
1243
+ return created;
1244
+ }
1245
+ turn(accumulator, turn, time) {
1246
+ const turnId = `turn-${turn}`;
1247
+ const existing = accumulator.turnRollups[turnId];
1248
+ if (existing) return existing;
1249
+ const stamp = new Date(time).toISOString();
1250
+ const created = {
1251
+ turnId,
1252
+ startedAt: stamp,
1253
+ lastEventAt: stamp,
1254
+ promptChars: 0,
1255
+ eventCount: 0,
1256
+ toolCallCount: 0,
1257
+ inputTokens: 0,
1258
+ outputTokens: 0,
1259
+ totalTokens: 0,
1260
+ durationMs: 0
1261
+ };
1262
+ accumulator.turnRollups[turnId] = created;
1263
+ return created;
1264
+ }
1265
+ record(sessionId, accumulator, event) {
1266
+ const time = event.time;
1267
+ const stamp = new Date(time).toISOString();
1268
+ accumulator.cursor = Math.max(accumulator.cursor, event.seq);
1269
+ accumulator.eventCount += 1;
1270
+ accumulator.lastEventAt = stamp;
1271
+ if (stamp < accumulator.startedAt) accumulator.startedAt = stamp;
1272
+ const bucket = this.bucket(accumulator, time);
1273
+ const current = this.currentTurn.get(sessionId);
1274
+ if (event.type === "turn/start") {
1275
+ accumulator.turnCount += 1;
1276
+ bucket.activityCount += 1;
1277
+ this.turn(accumulator, event.data.turn, time);
1278
+ this.currentTurn.set(sessionId, `turn-${event.data.turn}`);
1279
+ }
1280
+ const turn = current ? accumulator.turnRollups[current] : void 0;
1281
+ if (turn) {
1282
+ turn.lastEventAt = stamp;
1283
+ turn.eventCount += 1;
1284
+ }
1285
+ switch (event.type) {
1286
+ case "user/message":
1287
+ if (event.data.source.kind !== "user") break;
1288
+ accumulator.promptCount += 1;
1289
+ bucket.activityCount += 1;
1290
+ if (turn) {
1291
+ turn.promptSubmittedAt ??= stamp;
1292
+ turn.promptChars += textLength(event.data.content);
1293
+ }
1294
+ break;
1295
+ case "assistant/message": {
1296
+ const source = event.data.message.source;
1297
+ const model = `${source.provider}/${source.model}`;
1298
+ const usage = event.data.usage;
1299
+ const modelRollup = accumulator.modelRollups[model] ?? (accumulator.modelRollups[model] = emptyModel(model));
1300
+ modelRollup.callCount += 1;
1301
+ bucket.modelCalls += 1;
1302
+ bucket.activityCount += 1;
1303
+ const modelBucket = this.modelBucket(accumulator, time, model);
1304
+ modelBucket.callCount += 1;
1305
+ if (usage) {
1306
+ const tokens = {
1307
+ inputTokens: usage.inputTokens,
1308
+ cachedInputTokens: 0,
1309
+ cacheCreationInputTokens: usage.cacheWriteTokens ?? 0,
1310
+ cacheReadInputTokens: usage.cacheReadTokens ?? 0,
1311
+ outputTokens: usage.outputTokens,
1312
+ reasoningOutputTokens: usage.reasoningTokens ?? 0,
1313
+ totalTokens: usage.totalTokens ?? usage.inputTokens + usage.outputTokens
1314
+ };
1315
+ addTokens(modelRollup, tokens);
1316
+ addTokens(modelBucket, tokens);
1317
+ addTokens(accumulator.tokens, tokens);
1318
+ addTokens(bucket, tokens);
1319
+ if (turn) {
1320
+ turn.inputTokens += tokens.inputTokens;
1321
+ turn.outputTokens += tokens.outputTokens;
1322
+ turn.totalTokens += tokens.totalTokens;
1323
+ }
1324
+ }
1325
+ break;
1326
+ }
1327
+ case "tool/call": {
1328
+ const name = event.data.name;
1329
+ accumulator.toolCallCount += 1;
1330
+ bucket.toolCalls += 1;
1331
+ bucket.activityCount += 1;
1332
+ const toolRollup = accumulator.toolRollups[name] ?? (accumulator.toolRollups[name] = {
1333
+ tool: name,
1334
+ callCount: 0,
1335
+ failureCount: 0,
1336
+ totalDurationMs: 0
1337
+ });
1338
+ toolRollup.callCount += 1;
1339
+ this.callNames.set(`${sessionId}:${event.data.callId}`, name);
1340
+ if (turn) turn.toolCallCount += 1;
1341
+ break;
1342
+ }
1343
+ case "tool/result": {
1344
+ if (!event.data.message.isError) break;
1345
+ const key = `${sessionId}:${event.data.message.toolCallId}`;
1346
+ const name = this.callNames.get(key);
1347
+ this.callNames.delete(key);
1348
+ if (!name) break;
1349
+ const toolRollup = accumulator.toolRollups[name] ?? {
1350
+ tool: name,
1351
+ callCount: 0,
1352
+ failureCount: 0,
1353
+ totalDurationMs: 0
1354
+ };
1355
+ toolRollup.failureCount += 1;
1356
+ accumulator.toolRollups[name] = toolRollup;
1357
+ break;
1358
+ }
1359
+ case "turn/end": {
1360
+ const closing = accumulator.turnRollups[`turn-${event.data.turn}`];
1361
+ if (closing) {
1362
+ closing.completedAt = stamp;
1363
+ closing.durationMs = Math.min(Math.max(0, time - Date.parse(closing.startedAt)), MAX_TURN_MS);
1364
+ }
1365
+ this.currentTurn.delete(sessionId);
1366
+ break;
1367
+ }
1368
+ }
1369
+ }
1370
+ modelBucket(accumulator, time, model) {
1371
+ const ts = bucketStamp(time);
1372
+ const key = `${ts}\0${model}`;
1373
+ const existing = accumulator.modelBuckets[key];
1374
+ if (existing) return existing;
1375
+ const { estimatedCostUsd: _ignored, ...rest } = emptyModel(model);
1376
+ const created = {
1377
+ ...rest,
1378
+ ts
1379
+ };
1380
+ accumulator.modelBuckets[key] = created;
1381
+ return created;
1382
+ }
1383
+ };
1384
+ /** Sum text blocks of one message's content. */
1385
+ function textLength(content) {
1386
+ let total = 0;
1387
+ for (const block of content) if (block.type === "text" && block.text) total += block.text.length;
1388
+ return total;
1389
+ }
1390
+ /** Add token counters onto any record that carries the seven token fields. */
1391
+ function addTokens(target, tokens) {
1392
+ target.inputTokens += tokens.inputTokens;
1393
+ target.cachedInputTokens += tokens.cachedInputTokens;
1394
+ target.cacheCreationInputTokens += tokens.cacheCreationInputTokens;
1395
+ target.cacheReadInputTokens += tokens.cacheReadInputTokens;
1396
+ target.outputTokens += tokens.outputTokens;
1397
+ target.reasoningOutputTokens += tokens.reasoningOutputTokens;
1398
+ target.totalTokens += tokens.totalTokens;
1399
+ }
1400
+ /** Deterministic JSON with sorted object keys. */
1401
+ function stableStringify(value) {
1402
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
1403
+ if (value !== null && typeof value === "object") {
1404
+ const record = value;
1405
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
1406
+ }
1407
+ return JSON.stringify(value) ?? "null";
1408
+ }
1409
+ /** `sha256:` hash of a rollup without its own hash field. */
1410
+ function payloadHash(rollup) {
1411
+ const { payloadHash: _ignored, ...rest } = rollup;
1412
+ return `sha256:${createHash("sha256").update(stableStringify(rest)).digest("hex")}`;
1413
+ }
1414
+ /** Project one folded session into the ingest wire body. */
1415
+ function toWireRollup(session) {
1416
+ const durationMs = Math.max(0, Date.parse(session.lastEventAt) - Date.parse(session.startedAt));
1417
+ const base = {
1418
+ rollupKey: `rollup:dsh:${session.sessionId}`,
1419
+ payloadHash: "",
1420
+ schemaVersion: 3,
1421
+ source: "dsh",
1422
+ project: session.project,
1423
+ sessionId: session.sessionId,
1424
+ agent: "dsh",
1425
+ startedAt: session.startedAt,
1426
+ lastEventAt: session.lastEventAt,
1427
+ eventCount: session.eventCount,
1428
+ promptCount: session.promptCount,
1429
+ turnCount: session.turnCount,
1430
+ toolCallCount: session.toolCallCount,
1431
+ commandCallCount: session.commandCallCount,
1432
+ inputTokens: session.tokens.inputTokens,
1433
+ cachedInputTokens: session.tokens.cachedInputTokens,
1434
+ cacheCreationInputTokens: session.tokens.cacheCreationInputTokens,
1435
+ cacheReadInputTokens: session.tokens.cacheReadInputTokens,
1436
+ outputTokens: session.tokens.outputTokens,
1437
+ reasoningOutputTokens: session.tokens.reasoningOutputTokens,
1438
+ totalTokens: session.tokens.totalTokens,
1439
+ linesAdded: 0,
1440
+ linesRemoved: 0,
1441
+ durationMs,
1442
+ timeBuckets: Object.values(session.timeBuckets).sort((left, right) => left.ts.localeCompare(right.ts)),
1443
+ modelRollups: Object.values(session.modelRollups).sort((left, right) => right.callCount - left.callCount || left.model.localeCompare(right.model)),
1444
+ modelBuckets: Object.values(session.modelBuckets).sort((left, right) => left.ts.localeCompare(right.ts) || left.model.localeCompare(right.model)),
1445
+ toolRollups: Object.values(session.toolRollups).sort((left, right) => right.callCount - left.callCount || left.tool.localeCompare(right.tool)),
1446
+ fileRollups: [],
1447
+ turnRollups: Object.values(session.turnRollups).sort((left, right) => left.startedAt.localeCompare(right.startedAt))
1448
+ };
1449
+ return {
1450
+ ...base,
1451
+ payloadHash: payloadHash(base)
1452
+ };
1453
+ }
1454
+ // src/index.ts
1455
+ /** Cordis plugin name used by loader diagnostics. */
1456
+ const name = "codetime";
1457
+ /** The Host session store feeds the fold. */
1458
+ const inject = ["sessions"];
1459
+ /** Schemastery validation for {@link ConfigOptions}. */
1460
+ const Config = Schema.object({
1461
+ historyDays: Schema.number().min(0).max(3650).default(30),
1462
+ syncMinutes: Schema.number().min(0).max(1440).default(5),
1463
+ retentionDays: Schema.number().min(7).max(3650).default(120),
1464
+ statePath: Schema.string()
1465
+ });
1466
+ /** Rollups per ingest request. */
1467
+ const BATCH_SIZE = 10;
1468
+ /** Quiet period after the last folded event before an automatic upload. */
1469
+ const SETTLE_MS = 2e4;
1470
+ /** Largest request body the route accepts. */
1471
+ const MAX_BODY_BYTES = 4096;
1472
+ /** Read one JSON body, tolerating an empty payload. */
1473
+ async function readBody(request) {
1474
+ const text = await request.text();
1475
+ if (text.length > MAX_BODY_BYTES) throw new Error("request body too large");
1476
+ if (!text.trim()) return { action: "status" };
1477
+ const parsed = JSON.parse(text);
1478
+ if (typeof parsed !== "object" || parsed === null) throw new Error("request body must be an object");
1479
+ const record = parsed;
1480
+ const action = record.action;
1481
+ return {
1482
+ action: action === "save" || action === "clear" || action === "sync" ? action : "status",
1483
+ token: typeof record.token === "string" ? record.token : void 0,
1484
+ autoUpload: typeof record.autoUpload === "boolean" ? record.autoUpload : void 0
1485
+ };
1486
+ }
1487
+ /**
1488
+ * Fold Harness activity into codetime rollups and keep them uploaded.
1489
+ * @param ctx - plugin context; every registration is disposed with it.
1490
+ * @param config - fold window, upload cadence, retention, and host overrides.
1491
+ */
1492
+ function apply(ctx, config) {
1493
+ const state = new StateFile(config.statePath ?? join(homedir(), ".dsh", "codetime", "state.json"), config.retentionDays ?? 120);
1494
+ const historyDays = config.historyDays ?? 30;
1495
+ const syncMinutes = config.syncMinutes ?? 5;
1496
+ let folder;
1497
+ let scanning = false;
1498
+ let uploading = false;
1499
+ let settle;
1500
+ const queued = [];
1501
+ const scheduleSync = () => {
1502
+ if (settle || !state.state.settings.autoUpload) return;
1503
+ settle = setTimeout(() => {
1504
+ settle = void 0;
1505
+ sync();
1506
+ }, SETTLE_MS);
1507
+ settle.unref?.();
1508
+ };
1509
+ const fold = (id, cwd, events) => {
1510
+ if (!folder) {
1511
+ for (const event of events) queued.push({
1512
+ id,
1513
+ cwd,
1514
+ event
1515
+ });
1516
+ return;
1517
+ }
1518
+ if (folder.ingest({
1519
+ id,
1520
+ cwd
1521
+ }, events) > 0) {
1522
+ state.schedule();
1523
+ scheduleSync();
1524
+ }
1525
+ };
1526
+ ctx.effect(() => ctx.on("session/event", (session, event) => {
1527
+ fold(session.header.id, session.header.cwd, [event]);
1528
+ }));
1529
+ const sync = async () => {
1530
+ if (uploading || !folder) return;
1531
+ const changed = folder.pendingSessions();
1532
+ if (changed.length === 0) return;
1533
+ const token = await resolveToken();
1534
+ if (!token) {
1535
+ state.state.lastError = "token is not configured";
1536
+ await state.write();
1537
+ return;
1538
+ }
1539
+ uploading = true;
1540
+ try {
1541
+ const machineId = await ensureMachineId();
1542
+ const rollups = changed.map(toWireRollup);
1543
+ const totals = {
1544
+ inserted: 0,
1545
+ skipped: 0,
1546
+ conflicts: 0
1547
+ };
1548
+ for (let index = 0; index < rollups.length; index += BATCH_SIZE) {
1549
+ const batch = rollups.slice(index, index + BATCH_SIZE);
1550
+ const result = await uploadRollups({
1551
+ token,
1552
+ machineId,
1553
+ rollups: batch
1554
+ });
1555
+ totals.inserted += result.inserted;
1556
+ totals.skipped += result.skipped;
1557
+ totals.conflicts += result.conflicts;
1558
+ for (const rollup of batch) {
1559
+ const session = state.state.sessions[rollup.sessionId];
1560
+ if (session) session.uploadedHash = rollup.payloadHash;
1561
+ }
1562
+ }
1563
+ state.state.lastUploadAt = Date.now();
1564
+ state.state.lastSync = totals;
1565
+ state.state.lastError = void 0;
1566
+ await state.write();
1567
+ } catch (error) {
1568
+ state.state.lastError = error instanceof Error ? error.message : String(error);
1569
+ await state.write();
1570
+ } finally {
1571
+ uploading = false;
1572
+ }
1573
+ };
1574
+ const status = async () => {
1575
+ const token = await resolveToken();
1576
+ return {
1577
+ configured: Boolean(token),
1578
+ maskedToken: token ? maskToken(token) : void 0,
1579
+ autoUpload: state.state.settings.autoUpload,
1580
+ machineId: await ensureMachineId(),
1581
+ sessions: Object.keys(state.state.sessions).length,
1582
+ pending: folder ? folder.pendingSessions().length : 0,
1583
+ uploading,
1584
+ lastUploadAt: state.state.lastUploadAt,
1585
+ lastError: state.state.lastError,
1586
+ lastSync: state.state.lastSync
1587
+ };
1588
+ };
1589
+ const scan = async () => {
1590
+ if (!folder || scanning) return;
1591
+ scanning = true;
1592
+ try {
1593
+ await scanHistory(ctx, folder, historyDays);
1594
+ state.state.lastScanAt = Date.now();
1595
+ await state.write();
1596
+ } finally {
1597
+ scanning = false;
1598
+ if (state.state.settings.autoUpload) sync();
1599
+ }
1600
+ };
1601
+ const ready = (async () => {
1602
+ await state.load();
1603
+ folder = new SessionFolder(state.state);
1604
+ const pending = queued.splice(0);
1605
+ for (const item of pending) folder.ingest({
1606
+ id: item.id,
1607
+ cwd: item.cwd
1608
+ }, [item.event]);
1609
+ await scan();
1610
+ })().catch((error) => {
1611
+ console.error("codetime: initial fold failed:", error);
1612
+ });
1613
+ ctx.effect(() => {
1614
+ if (syncMinutes <= 0) return () => {};
1615
+ const timer = setInterval(() => {
1616
+ if (state.state.settings.autoUpload) sync();
1617
+ }, syncMinutes * 6e4);
1618
+ timer.unref?.();
1619
+ return () => {
1620
+ clearInterval(timer);
1621
+ if (settle) {
1622
+ clearTimeout(settle);
1623
+ settle = void 0;
1624
+ }
1625
+ };
1626
+ });
1627
+ ctx.effect(() => () => {
1628
+ state.flush();
1629
+ });
1630
+ const connection = ctx.get("connection");
1631
+ if (!connection) return;
1632
+ ctx.effect(() => connection.fetch.register({
1633
+ path: "/api/codetime",
1634
+ methods: ["POST"],
1635
+ requestBody: "buffered",
1636
+ async fetch(request) {
1637
+ try {
1638
+ const body = await readBody(request);
1639
+ await ready;
1640
+ if (body.action === "save") {
1641
+ const token = body.token?.trim();
1642
+ if (token !== void 0 && !token) throw new Error("token must not be empty");
1643
+ if (token !== void 0) await writeToken(token);
1644
+ if (body.autoUpload !== void 0) {
1645
+ state.state.settings.autoUpload = body.autoUpload;
1646
+ await state.write();
1647
+ }
1648
+ sync();
1649
+ }
1650
+ if (body.action === "clear") {
1651
+ await writeToken(void 0);
1652
+ state.state.lastError = void 0;
1653
+ await state.write();
1654
+ }
1655
+ if (body.action === "sync") await sync();
1656
+ return Response.json(await status(), { headers: { "Cache-Control": "no-store" } });
1657
+ } catch (error) {
1658
+ const message = error instanceof Error ? error.message : String(error);
1659
+ return Response.json({ error: message }, {
1660
+ status: 400,
1661
+ headers: { "Cache-Control": "no-store" }
1662
+ });
1663
+ }
1664
+ }
1665
+ }));
1666
+ }
1667
+ export { Config, apply, inject, name };