dsh-plugin-tlmemory 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1647 @@
1
+ // ../../node_modules/.pnpm/cosmokit@1.8.1/node_modules/cosmokit/lib/index.mjs
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) {
18
+ if (forced || source[key] !== void 0) result[key] = source[key];
19
+ }
20
+ return result;
21
+ }
22
+ function is(type, value) {
23
+ if (arguments.length === 1) return (value2) => is(type, value2);
24
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
25
+ }
26
+ function isArrayBufferLike(value) {
27
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
28
+ }
29
+ function isArrayBufferSource(value) {
30
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
31
+ }
32
+ var Binary;
33
+ ((Binary2) => {
34
+ Binary2.is = isArrayBufferLike;
35
+ Binary2.isSource = isArrayBufferSource;
36
+ function fromSource(source) {
37
+ if (ArrayBuffer.isView(source)) {
38
+ return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
39
+ } else {
40
+ return source;
41
+ }
42
+ }
43
+ Binary2.fromSource = fromSource;
44
+ function toBase64(source) {
45
+ source = fromSource(source);
46
+ if (typeof Buffer !== "undefined") {
47
+ return Buffer.from(source).toString("base64");
48
+ }
49
+ let binary = "";
50
+ const bytes = new Uint8Array(source);
51
+ for (let i = 0; i < bytes.byteLength; i++) {
52
+ binary += String.fromCharCode(bytes[i]);
53
+ }
54
+ return btoa(binary);
55
+ }
56
+ Binary2.toBase64 = toBase64;
57
+ function fromBase64(source) {
58
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
59
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
60
+ }
61
+ Binary2.fromBase64 = fromBase64;
62
+ function toHex(source) {
63
+ source = fromSource(source);
64
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
65
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
66
+ }
67
+ Binary2.toHex = toHex;
68
+ function fromHex(source) {
69
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
70
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
71
+ const buffer = [];
72
+ for (let i = 0; i < hex.length; i += 2) {
73
+ buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
74
+ }
75
+ return Uint8Array.from(buffer).buffer;
76
+ }
77
+ Binary2.fromHex = fromHex;
78
+ })(Binary || (Binary = {}));
79
+ var base64ToArrayBuffer = Binary.fromBase64;
80
+ var arrayBufferToBase64 = Binary.toBase64;
81
+ var hexToArrayBuffer = Binary.fromHex;
82
+ var arrayBufferToHex = Binary.toHex;
83
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
84
+ if (!source || typeof source !== "object") return source;
85
+ if (is("Date", source)) return new Date(source.valueOf());
86
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
87
+ if (isArrayBufferLike(source)) return source.slice(0);
88
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
89
+ const cached = refs.get(source);
90
+ if (cached) return cached;
91
+ if (Array.isArray(source)) {
92
+ const result2 = [];
93
+ refs.set(source, result2);
94
+ source.forEach((value, index) => {
95
+ result2[index] = Reflect.apply(clone, null, [value, refs]);
96
+ });
97
+ return result2;
98
+ }
99
+ const result = Object.create(Object.getPrototypeOf(source));
100
+ refs.set(source, result);
101
+ for (const key of Reflect.ownKeys(source)) {
102
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
103
+ if ("value" in descriptor) {
104
+ descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
105
+ }
106
+ Reflect.defineProperty(result, key, descriptor);
107
+ }
108
+ return result;
109
+ }
110
+ function deepEqual(a, b, strict) {
111
+ if (a === b) return true;
112
+ if (!strict && isNullable(a) && isNullable(b)) return true;
113
+ if (typeof a !== typeof b) return false;
114
+ if (typeof a !== "object") return false;
115
+ if (!a || !b) return false;
116
+ function check(test, then) {
117
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
118
+ }
119
+ 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) => {
120
+ if (a2.byteLength !== b2.byteLength) return false;
121
+ const viewA = new Uint8Array(a2);
122
+ const viewB = new Uint8Array(b2);
123
+ for (let i = 0; i < viewA.length; i++) {
124
+ if (viewA[i] !== viewB[i]) return false;
125
+ }
126
+ return true;
127
+ }) ?? Object.keys({ ...a, ...b }).every((key) => deepEqual(a[key], b[key], strict));
128
+ }
129
+ var Time;
130
+ ((Time2) => {
131
+ Time2.millisecond = 1;
132
+ Time2.second = 1e3;
133
+ Time2.minute = Time2.second * 60;
134
+ Time2.hour = Time2.minute * 60;
135
+ Time2.day = Time2.hour * 24;
136
+ Time2.week = Time2.day * 7;
137
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
138
+ function setTimezoneOffset(offset) {
139
+ timezoneOffset = offset;
140
+ }
141
+ Time2.setTimezoneOffset = setTimezoneOffset;
142
+ function getTimezoneOffset() {
143
+ return timezoneOffset;
144
+ }
145
+ Time2.getTimezoneOffset = getTimezoneOffset;
146
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
147
+ if (typeof date === "number") date = new Date(date);
148
+ if (offset === void 0) offset = timezoneOffset;
149
+ return Math.floor((date.valueOf() / Time2.minute - offset) / 1440);
150
+ }
151
+ Time2.getDateNumber = getDateNumber;
152
+ function fromDateNumber(value, offset) {
153
+ const date = new Date(value * Time2.day);
154
+ if (offset === void 0) offset = timezoneOffset;
155
+ return new Date(+date + offset * Time2.minute);
156
+ }
157
+ Time2.fromDateNumber = fromDateNumber;
158
+ const numeric = /\d+(?:\.\d+)?/.source;
159
+ const timeRegExp = new RegExp(`^${[
160
+ "w(?:eek(?:s)?)?",
161
+ "d(?:ay(?:s)?)?",
162
+ "h(?:our(?:s)?)?",
163
+ "m(?:in(?:ute)?(?:s)?)?",
164
+ "s(?:ec(?:ond)?(?:s)?)?"
165
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
166
+ function parseTime(source) {
167
+ const capture = timeRegExp.exec(source);
168
+ if (!capture) return 0;
169
+ 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);
170
+ }
171
+ Time2.parseTime = parseTime;
172
+ function parseDate(date) {
173
+ const parsed = parseTime(date);
174
+ if (parsed) {
175
+ date = Date.now() + parsed;
176
+ } else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) {
177
+ date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
178
+ } else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) {
179
+ date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
180
+ }
181
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
182
+ }
183
+ Time2.parseDate = parseDate;
184
+ function format(ms) {
185
+ const abs = Math.abs(ms);
186
+ if (abs >= Time2.day - Time2.hour / 2) {
187
+ return Math.round(ms / Time2.day) + "d";
188
+ } else if (abs >= Time2.hour - Time2.minute / 2) {
189
+ return Math.round(ms / Time2.hour) + "h";
190
+ } else if (abs >= Time2.minute - Time2.second / 2) {
191
+ return Math.round(ms / Time2.minute) + "m";
192
+ } else if (abs >= Time2.second) {
193
+ return Math.round(ms / Time2.second) + "s";
194
+ }
195
+ return ms + "ms";
196
+ }
197
+ Time2.format = format;
198
+ function toDigits(source, length = 2) {
199
+ return source.toString().padStart(length, "0");
200
+ }
201
+ Time2.toDigits = toDigits;
202
+ function template(template2, time = /* @__PURE__ */ new Date()) {
203
+ 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));
204
+ }
205
+ Time2.template = template;
206
+ })(Time || (Time = {}));
207
+
208
+ // ../../node_modules/.pnpm/schemastery@3.18.0/node_modules/schemastery/lib/index.mjs
209
+ var __defProp = Object.defineProperty;
210
+ var __getOwnPropNames = Object.getOwnPropertyNames;
211
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
212
+ var __commonJS = (cb, mod) => function __require() {
213
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
214
+ };
215
+ var require_index = __commonJS({
216
+ "src/index.ts"(exports, module) {
217
+ var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
218
+ var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
219
+ globalThis.__schemastery_index__ ??= 0;
220
+ globalThis.__schemastery_refs__ = void 0;
221
+ var ValidationError = class extends TypeError {
222
+ constructor(message, options) {
223
+ let prefix = "$";
224
+ for (const segment of options.path || []) {
225
+ if (typeof segment === "string") {
226
+ prefix += "." + segment;
227
+ } else if (typeof segment === "number") {
228
+ prefix += "[" + segment + "]";
229
+ } else if (typeof segment === "symbol") {
230
+ prefix += `[Symbol(${segment.toString()})]`;
231
+ }
232
+ }
233
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
234
+ super((prefix === "$" ? "" : `${prefix} `) + message);
235
+ this.options = options;
236
+ }
237
+ static {
238
+ __name(this, "ValidationError");
239
+ }
240
+ name = "ValidationError";
241
+ static is(error) {
242
+ return !!error?.[kValidationError];
243
+ }
244
+ };
245
+ Object.defineProperty(ValidationError.prototype, kValidationError, {
246
+ value: true
247
+ });
248
+ var Schema = /* @__PURE__ */ __name(function(options) {
249
+ const schema = /* @__PURE__ */ __name(function(data, options2 = {}) {
250
+ return Schema.resolve(data, schema, options2)[0];
251
+ }, "schema");
252
+ if (options.refs) {
253
+ const refs = mapValues(options.refs, (options2) => new Schema(options2));
254
+ const getRef = /* @__PURE__ */ __name((uid) => refs[uid], "getRef");
255
+ for (const key in refs) {
256
+ const options2 = refs[key];
257
+ options2.sKey = getRef(options2.sKey);
258
+ options2.inner = getRef(options2.inner);
259
+ options2.list = options2.list && options2.list.map(getRef);
260
+ options2.dict = options2.dict && mapValues(options2.dict, getRef);
261
+ }
262
+ return refs[options.uid];
263
+ }
264
+ Object.assign(schema, options);
265
+ if (typeof schema.callback === "string") {
266
+ try {
267
+ schema.callback = new Function("return " + schema.callback)();
268
+ } catch {
269
+ }
270
+ }
271
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
272
+ Object.setPrototypeOf(schema, Schema.prototype);
273
+ schema.meta ||= {};
274
+ schema.toString = schema.toString.bind(schema);
275
+ return schema;
276
+ }, "Schema");
277
+ Schema.prototype = Object.create(Function.prototype);
278
+ Schema.prototype[kSchema] = true;
279
+ Object.defineProperty(Schema.prototype, "~standard", {
280
+ get() {
281
+ return {
282
+ version: 1,
283
+ vendor: "schemastery",
284
+ validate: /* @__PURE__ */ __name((value) => {
285
+ try {
286
+ return { value: Schema.resolve(value, this, {})[0] };
287
+ } catch (error) {
288
+ if (ValidationError.is(error)) {
289
+ return { issues: [{ message: error.message, path: error.options.path }] };
290
+ }
291
+ throw error;
292
+ }
293
+ }, "validate")
294
+ };
295
+ }
296
+ });
297
+ Schema.ValidationError = ValidationError;
298
+ Schema.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
299
+ if (globalThis.__schemastery_refs__) {
300
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
301
+ return this.uid;
302
+ }
303
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
304
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
305
+ const result = { uid: this.uid, refs: globalThis.__schemastery_refs__ };
306
+ globalThis.__schemastery_refs__ = void 0;
307
+ return result;
308
+ }, "toJSON");
309
+ Schema.prototype.set = /* @__PURE__ */ __name(function set(key, value) {
310
+ this.dict[key] = value;
311
+ return this;
312
+ }, "set");
313
+ Schema.prototype.push = /* @__PURE__ */ __name(function push(value) {
314
+ this.list.push(value);
315
+ return this;
316
+ }, "push");
317
+ function mergeDesc(original, messages) {
318
+ const result = typeof original === "string" ? { "": original } : { ...original };
319
+ for (const locale in messages) {
320
+ const value = messages[locale];
321
+ if (value?.$description || value?.$desc) {
322
+ result[locale] = value.$description || value.$desc;
323
+ } else if (typeof value === "string") {
324
+ result[locale] = value;
325
+ }
326
+ }
327
+ return result;
328
+ }
329
+ __name(mergeDesc, "mergeDesc");
330
+ function getInner(value) {
331
+ return value?.$value ?? value?.$inner;
332
+ }
333
+ __name(getInner, "getInner");
334
+ function extractKeys(data) {
335
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
336
+ }
337
+ __name(extractKeys, "extractKeys");
338
+ Schema.prototype.i18n = /* @__PURE__ */ __name(function i18n(messages) {
339
+ const schema = Schema(this);
340
+ const desc = mergeDesc(schema.meta.description, messages);
341
+ if (Object.keys(desc).length) schema.meta.description = desc;
342
+ if (schema.dict) {
343
+ schema.dict = mapValues(schema.dict, (inner, key) => {
344
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
345
+ });
346
+ }
347
+ if (schema.list) {
348
+ schema.list = schema.list.map((inner, index) => {
349
+ return inner.i18n(mapValues(messages, (data = {}) => {
350
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
351
+ if (Array.isArray(data)) return data[index];
352
+ return extractKeys(data);
353
+ }));
354
+ });
355
+ }
356
+ if (schema.inner) {
357
+ schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
358
+ if (getInner(data)) return getInner(data);
359
+ return extractKeys(data);
360
+ }));
361
+ }
362
+ if (schema.sKey) {
363
+ schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
364
+ }
365
+ return schema;
366
+ }, "i18n");
367
+ Schema.prototype.extra = /* @__PURE__ */ __name(function extra(key, value) {
368
+ const schema = Schema(this);
369
+ schema.meta = { ...schema.meta, [key]: value };
370
+ return schema;
371
+ }, "extra");
372
+ for (const key of ["required", "disabled", "collapse", "hidden", "loose"]) {
373
+ Object.assign(Schema.prototype, {
374
+ [key](value = true) {
375
+ const schema = Schema(this);
376
+ schema.meta = { ...schema.meta, [key]: value };
377
+ return schema;
378
+ }
379
+ });
380
+ }
381
+ Schema.prototype.deprecated = /* @__PURE__ */ __name(function deprecated() {
382
+ const schema = Schema(this);
383
+ schema.meta.badges ||= [];
384
+ schema.meta.badges.push({ text: "deprecated", type: "danger" });
385
+ return schema;
386
+ }, "deprecated");
387
+ Schema.prototype.experimental = /* @__PURE__ */ __name(function experimental() {
388
+ const schema = Schema(this);
389
+ schema.meta.badges ||= [];
390
+ schema.meta.badges.push({ text: "experimental", type: "warning" });
391
+ return schema;
392
+ }, "experimental");
393
+ Schema.prototype.pattern = /* @__PURE__ */ __name(function pattern(regexp) {
394
+ const schema = Schema(this);
395
+ const pattern2 = pick(regexp, ["source", "flags"]);
396
+ schema.meta = { ...schema.meta, pattern: pattern2 };
397
+ return schema;
398
+ }, "pattern");
399
+ Schema.prototype.simplify = /* @__PURE__ */ __name(function simplify(value) {
400
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
401
+ if (isNullable(value)) return value;
402
+ if (this.type === "object" || this.type === "dict") {
403
+ const result = {};
404
+ for (const key in value) {
405
+ const schema = this.type === "object" ? this.dict[key] : this.inner;
406
+ const item = schema?.simplify(value[key]);
407
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
408
+ }
409
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
410
+ return result;
411
+ } else if (this.type === "array" || this.type === "tuple") {
412
+ const result = [];
413
+ value.forEach((value2, index) => {
414
+ const schema = this.type === "array" ? this.inner : this.list[index];
415
+ const item = schema ? schema.simplify(value2) : value2;
416
+ result.push(item);
417
+ });
418
+ return result;
419
+ } else if (this.type === "intersect") {
420
+ const result = {};
421
+ for (const item of this.list) {
422
+ Object.assign(result, item.simplify(value));
423
+ }
424
+ return result;
425
+ } else if (this.type === "union") {
426
+ for (const schema of this.list) {
427
+ try {
428
+ Schema.resolve(value, schema, {});
429
+ return schema.simplify(value);
430
+ } catch {
431
+ }
432
+ }
433
+ }
434
+ return value;
435
+ }, "simplify");
436
+ Schema.prototype.toString = /* @__PURE__ */ __name(function toString(inline) {
437
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
438
+ }, "toString");
439
+ Schema.prototype.role = /* @__PURE__ */ __name(function role(role, extra) {
440
+ const schema = Schema(this);
441
+ schema.meta = { ...schema.meta, role, extra };
442
+ return schema;
443
+ }, "role");
444
+ for (const key of ["default", "link", "comment", "description", "max", "min", "step"]) {
445
+ Object.assign(Schema.prototype, {
446
+ [key](value) {
447
+ const schema = Schema(this);
448
+ schema.meta = { ...schema.meta, [key]: value };
449
+ return schema;
450
+ }
451
+ });
452
+ }
453
+ var resolvers = {};
454
+ Schema.extend = /* @__PURE__ */ __name(function extend(type, resolve) {
455
+ resolvers[type] = resolve;
456
+ }, "extend");
457
+ Schema.resolve = /* @__PURE__ */ __name(function resolve(data, schema, options = {}, strict = false) {
458
+ if (!schema) return [data];
459
+ if (options.ignore?.(data, schema)) return [data];
460
+ if (isNullable(data) && schema.type !== "lazy") {
461
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
462
+ let current = schema;
463
+ let fallback = schema.meta.default;
464
+ while (current?.type === "intersect" && isNullable(fallback)) {
465
+ current = current.list[0];
466
+ fallback = current?.meta.default;
467
+ }
468
+ if (isNullable(fallback)) return [data];
469
+ data = clone(fallback);
470
+ }
471
+ const callback = resolvers[schema.type];
472
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
473
+ try {
474
+ return callback(data, schema, options, strict);
475
+ } catch (error) {
476
+ if (!schema.meta.loose) throw error;
477
+ return [schema.meta.default];
478
+ }
479
+ }, "resolve");
480
+ Schema.from = /* @__PURE__ */ __name(function from(source) {
481
+ if (isNullable(source)) {
482
+ return Schema.any();
483
+ } else if (["string", "number", "boolean"].includes(typeof source)) {
484
+ return Schema.const(source).required();
485
+ } else if (source[kSchema]) {
486
+ return source;
487
+ } else if (typeof source === "function") {
488
+ switch (source) {
489
+ case String:
490
+ return Schema.string().required();
491
+ case Number:
492
+ return Schema.number().required();
493
+ case Boolean:
494
+ return Schema.boolean().required();
495
+ case Function:
496
+ return Schema.function().required();
497
+ default:
498
+ return Schema.is(source).required();
499
+ }
500
+ } else {
501
+ throw new TypeError(`cannot infer schema from ${source}`);
502
+ }
503
+ }, "from");
504
+ Schema.lazy = /* @__PURE__ */ __name(function lazy(builder) {
505
+ const toJSON = /* @__PURE__ */ __name(() => {
506
+ if (!schema.inner[kSchema]) {
507
+ schema.inner = schema.builder();
508
+ schema.inner.meta = { ...schema.meta, ...schema.inner.meta };
509
+ }
510
+ return schema.inner.toJSON();
511
+ }, "toJSON");
512
+ const schema = new Schema({ type: "lazy", builder, inner: { toJSON } });
513
+ return schema;
514
+ }, "lazy");
515
+ Schema.natural = /* @__PURE__ */ __name(function natural() {
516
+ return Schema.number().step(1).min(0);
517
+ }, "natural");
518
+ Schema.percent = /* @__PURE__ */ __name(function percent() {
519
+ return Schema.number().step(0.01).min(0).max(1).role("slider");
520
+ }, "percent");
521
+ Schema.date = /* @__PURE__ */ __name(function date() {
522
+ return Schema.union([
523
+ Schema.is(Date),
524
+ Schema.transform(Schema.string().role("datetime"), (value, options) => {
525
+ const date2 = new Date(value);
526
+ if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
527
+ return date2;
528
+ }, true)
529
+ ]);
530
+ }, "date");
531
+ Schema.regExp = /* @__PURE__ */ __name(function regExp(flag = "") {
532
+ return Schema.union([
533
+ Schema.is(RegExp),
534
+ Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
535
+ try {
536
+ return new RegExp(value, flag);
537
+ } catch (e) {
538
+ throw new ValidationError(e.message, options);
539
+ }
540
+ }, true)
541
+ ]);
542
+ }, "regExp");
543
+ Schema.arrayBuffer = /* @__PURE__ */ __name(function arrayBuffer(encoding) {
544
+ return Schema.union([
545
+ Schema.is(ArrayBuffer),
546
+ Schema.is(SharedArrayBuffer),
547
+ Schema.transform(Schema.any(), (value, options) => {
548
+ if (Binary.isSource(value)) return Binary.fromSource(value);
549
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
550
+ }, true),
551
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
552
+ try {
553
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
554
+ } catch (e) {
555
+ throw new ValidationError(e.message, options);
556
+ }
557
+ }, true)] : []
558
+ ]);
559
+ }, "arrayBuffer");
560
+ Schema.extend("lazy", (data, schema, options, strict) => {
561
+ if (!schema.inner[kSchema]) {
562
+ schema.inner = schema.builder();
563
+ schema.inner.meta = { ...schema.meta, ...schema.inner.meta };
564
+ }
565
+ return Schema.resolve(data, schema.inner, options, strict);
566
+ });
567
+ Schema.extend("any", (data) => {
568
+ return [data];
569
+ });
570
+ Schema.extend("never", (data, _, options) => {
571
+ throw new ValidationError(`expected nullable but got ${data}`, options);
572
+ });
573
+ Schema.extend("const", (data, { value }, options) => {
574
+ if (deepEqual(data, value)) return [value];
575
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
576
+ });
577
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
578
+ const { max = Infinity, min = -Infinity } = meta;
579
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
580
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
581
+ }
582
+ __name(checkWithinRange, "checkWithinRange");
583
+ Schema.extend("string", (data, { meta }, options) => {
584
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
585
+ if (meta.pattern) {
586
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
587
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
588
+ }
589
+ checkWithinRange(data.length, meta, "string length", options);
590
+ return [data];
591
+ });
592
+ function decimalShift(data, digits) {
593
+ const str = data.toString();
594
+ if (str.includes("e")) return data * Math.pow(10, digits);
595
+ const index = str.indexOf(".");
596
+ if (index === -1) return data * Math.pow(10, digits);
597
+ const frac = str.slice(index + 1);
598
+ const integer = str.slice(0, index);
599
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
600
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
601
+ }
602
+ __name(decimalShift, "decimalShift");
603
+ function isMultipleOf(data, min, step) {
604
+ step = Math.abs(step);
605
+ if (!/^\d+\.\d+$/.test(step.toString())) {
606
+ return (data - min) % step === 0;
607
+ }
608
+ const index = step.toString().indexOf(".");
609
+ const digits = step.toString().slice(index + 1).length;
610
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
611
+ }
612
+ __name(isMultipleOf, "isMultipleOf");
613
+ Schema.extend("number", (data, { meta }, options) => {
614
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
615
+ checkWithinRange(data, meta, "number", options);
616
+ const { step } = meta;
617
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) {
618
+ throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
619
+ }
620
+ return [data];
621
+ });
622
+ Schema.extend("boolean", (data, _, options) => {
623
+ if (typeof data === "boolean") return [data];
624
+ throw new ValidationError(`expected boolean but got ${data}`, options);
625
+ });
626
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
627
+ let value = 0, keys = [];
628
+ if (typeof data === "number") {
629
+ value = data;
630
+ for (const key in bits) {
631
+ if (data & bits[key]) {
632
+ keys.push(key);
633
+ }
634
+ }
635
+ } else if (Array.isArray(data)) {
636
+ keys = data;
637
+ for (const key of keys) {
638
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
639
+ if (key in bits) value |= bits[key];
640
+ }
641
+ } else {
642
+ throw new ValidationError(`expected number or array but got ${data}`, options);
643
+ }
644
+ if (value === meta.default) return [value];
645
+ return [value, keys];
646
+ });
647
+ Schema.extend("function", (data, _, options) => {
648
+ if (typeof data === "function") return [data];
649
+ throw new ValidationError(`expected function but got ${data}`, options);
650
+ });
651
+ Schema.extend("is", (data, { constructor }, options) => {
652
+ if (typeof constructor === "function") {
653
+ if (data instanceof constructor) return [data];
654
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
655
+ } else {
656
+ if (isNullable(data)) {
657
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
658
+ }
659
+ let prototype = Object.getPrototypeOf(data);
660
+ while (prototype) {
661
+ if (prototype.constructor?.name === constructor) return [data];
662
+ prototype = Object.getPrototypeOf(prototype);
663
+ }
664
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
665
+ }
666
+ });
667
+ function property(data, key, schema, options) {
668
+ try {
669
+ const [value, adapted] = Schema.resolve(data[key], schema, {
670
+ ...options,
671
+ path: [...options.path || [], key]
672
+ });
673
+ if (adapted !== void 0) data[key] = adapted;
674
+ return value;
675
+ } catch (e) {
676
+ if (!options?.autofix) throw e;
677
+ delete data[key];
678
+ return schema.meta.default;
679
+ }
680
+ }
681
+ __name(property, "property");
682
+ Schema.extend("array", (data, { inner, meta }, options) => {
683
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
684
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
685
+ return [data.map((_, index) => property(data, index, inner, options))];
686
+ });
687
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
688
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
689
+ const result = {};
690
+ for (const key in data) {
691
+ let rKey;
692
+ try {
693
+ rKey = Schema.resolve(key, sKey, options)[0];
694
+ } catch (error) {
695
+ if (strict) continue;
696
+ throw error;
697
+ }
698
+ result[rKey] = property(data, key, inner, options);
699
+ data[rKey] = data[key];
700
+ if (key !== rKey) delete data[key];
701
+ }
702
+ return [result];
703
+ });
704
+ Schema.extend("tuple", (data, { list }, options, strict) => {
705
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
706
+ const result = list.map((inner, index) => property(data, index, inner, options));
707
+ if (strict) return [result];
708
+ result.push(...data.slice(list.length));
709
+ return [result];
710
+ });
711
+ function merge(result, data) {
712
+ for (const key in data) {
713
+ if (key in result) continue;
714
+ result[key] = data[key];
715
+ }
716
+ }
717
+ __name(merge, "merge");
718
+ Schema.extend("object", (data, { dict }, options, strict) => {
719
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
720
+ const result = {};
721
+ for (const key in dict) {
722
+ const value = property(data, key, dict[key], options);
723
+ if (!isNullable(value) || key in data) {
724
+ result[key] = value;
725
+ }
726
+ }
727
+ if (!strict) merge(result, data);
728
+ return [result];
729
+ });
730
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
731
+ const messages = [];
732
+ for (const inner of list) {
733
+ try {
734
+ return Schema.resolve(data, inner, options, strict);
735
+ } catch (error) {
736
+ messages.push(error);
737
+ }
738
+ }
739
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
740
+ });
741
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
742
+ if (!list.length) return [data];
743
+ let result;
744
+ for (const inner of list) {
745
+ const value = Schema.resolve(data, inner, options, true)[0];
746
+ if (isNullable(value)) continue;
747
+ if (isNullable(result)) {
748
+ result = value;
749
+ } else if (typeof result !== typeof value) {
750
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
751
+ } else if (typeof value === "object") {
752
+ merge(result ??= {}, value);
753
+ } else if (result !== value) {
754
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
755
+ }
756
+ }
757
+ if (!strict && isPlainObject(data)) merge(result, data);
758
+ return [result];
759
+ });
760
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
761
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
762
+ if (preserve) {
763
+ return [callback(result)];
764
+ } else {
765
+ return [callback(result), callback(adapted)];
766
+ }
767
+ });
768
+ var formatters = {};
769
+ function defineMethod(name2, keys, format) {
770
+ formatters[name2] = format;
771
+ Object.assign(Schema, {
772
+ [name2](...args) {
773
+ const schema = new Schema({ type: name2 });
774
+ keys.forEach((key, index) => {
775
+ switch (key) {
776
+ case "sKey":
777
+ schema.sKey = args[index] ?? Schema.string();
778
+ break;
779
+ case "inner":
780
+ schema.inner = Schema.from(args[index]);
781
+ break;
782
+ case "list":
783
+ schema.list = args[index].map(Schema.from);
784
+ break;
785
+ case "dict":
786
+ schema.dict = mapValues(args[index], Schema.from);
787
+ break;
788
+ case "bits": {
789
+ schema.bits = {};
790
+ for (const key2 in args[index]) {
791
+ if (typeof args[index][key2] !== "number") continue;
792
+ schema.bits[key2] = args[index][key2];
793
+ }
794
+ break;
795
+ }
796
+ case "callback": {
797
+ const callback = schema.callback = args[index];
798
+ callback["toJSON"] ||= () => callback.toString();
799
+ break;
800
+ }
801
+ case "constructor": {
802
+ const constructor = schema.constructor = args[index];
803
+ if (typeof constructor === "function") {
804
+ ;
805
+ constructor["toJSON"] ||= () => constructor["name"];
806
+ }
807
+ break;
808
+ }
809
+ default:
810
+ schema[key] = args[index];
811
+ }
812
+ });
813
+ if (name2 === "object" || name2 === "dict") {
814
+ schema.meta.default = {};
815
+ } else if (name2 === "array" || name2 === "tuple") {
816
+ schema.meta.default = [];
817
+ } else if (name2 === "bitset") {
818
+ schema.meta.default = 0;
819
+ }
820
+ return schema;
821
+ }
822
+ });
823
+ }
824
+ __name(defineMethod, "defineMethod");
825
+ defineMethod("is", ["constructor"], ({ constructor }) => {
826
+ if (typeof constructor === "function") {
827
+ return constructor.name;
828
+ } else {
829
+ return constructor;
830
+ }
831
+ });
832
+ defineMethod("any", [], () => "any");
833
+ defineMethod("never", [], () => "never");
834
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
835
+ defineMethod("string", [], () => "string");
836
+ defineMethod("number", [], () => "number");
837
+ defineMethod("boolean", [], () => "boolean");
838
+ defineMethod("bitset", ["bits"], () => "bitset");
839
+ defineMethod("function", [], () => "function");
840
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
841
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
842
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
843
+ defineMethod("object", ["dict"], ({ dict }) => {
844
+ if (Object.keys(dict).length === 0) return "{}";
845
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
846
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
847
+ }).join(", ")} }`;
848
+ });
849
+ defineMethod("union", ["list"], ({ list }, inline) => {
850
+ const result = list.map(({ toString: format }) => format()).join(" | ");
851
+ return inline ? `(${result})` : result;
852
+ });
853
+ defineMethod("intersect", ["list"], ({ list }) => {
854
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
855
+ });
856
+ defineMethod("transform", ["inner", "callback", "preserve"], ({ inner }, isInner) => inner.toString(isInner));
857
+ module.exports = Schema;
858
+ }
859
+ });
860
+ var lib_default = require_index();
861
+
862
+ // src/index.ts
863
+ import path3 from "path";
864
+ import fs3 from "fs";
865
+ import crypto from "crypto";
866
+
867
+ // src/db.ts
868
+ import path from "path";
869
+ import fs from "fs";
870
+ import os from "os";
871
+ import Database from "better-sqlite3";
872
+ var SEGMENT_WHITELIST = /[^a-zA-Z0-9_\u4e00-\u9fa5\-]/g;
873
+ function sanitizeSegment(seg) {
874
+ return String(seg ?? "").replace(SEGMENT_WHITELIST, "").trim();
875
+ }
876
+ function escapeLikePattern(input) {
877
+ return input.replace(/[\\%_]/g, (m) => `\\${m}`);
878
+ }
879
+ var MemoryDB = class {
880
+ db;
881
+ constructor(dbPath) {
882
+ const resolvedPath = dbPath === ":memory:" ? ":memory:" : dbPath ?? path.join(os.homedir(), ".dsh", "tlmemory.db");
883
+ if (resolvedPath !== ":memory:") {
884
+ fs.mkdirSync(path.dirname(resolvedPath), { recursive: true });
885
+ }
886
+ this.db = new Database(resolvedPath);
887
+ this.db.pragma("journal_mode = WAL");
888
+ this.db.pragma("foreign_keys = ON");
889
+ this.migrate();
890
+ }
891
+ migrate() {
892
+ this.db.exec(`
893
+ CREATE TABLE IF NOT EXISTS nodes (
894
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
895
+ tree_type TEXT NOT NULL,
896
+ parent_id INTEGER REFERENCES nodes(id),
897
+ path TEXT NOT NULL,
898
+ name TEXT NOT NULL,
899
+ is_leaf INTEGER NOT NULL DEFAULT 0,
900
+ content TEXT,
901
+ keywords TEXT,
902
+ reinforce_count INTEGER NOT NULL DEFAULT 1,
903
+ is_pinned INTEGER NOT NULL DEFAULT 0,
904
+ created_at INTEGER NOT NULL,
905
+ updated_at INTEGER NOT NULL,
906
+ UNIQUE (tree_type, path, name)
907
+ );
908
+
909
+ CREATE INDEX IF NOT EXISTS idx_nodes_tree_path ON nodes(tree_type, path);
910
+
911
+ CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(
912
+ tree_type, path, name, content, keywords,
913
+ tokenize = 'trigram'
914
+ );
915
+
916
+ CREATE TRIGGER IF NOT EXISTS trg_nodes_ai AFTER INSERT ON nodes BEGIN
917
+ INSERT INTO memory_fts(rowid, tree_type, path, name, content, keywords)
918
+ VALUES (new.id, new.tree_type, new.path, new.name, new.content, new.keywords);
919
+ END;
920
+
921
+ CREATE TRIGGER IF NOT EXISTS trg_nodes_ad AFTER DELETE ON nodes BEGIN
922
+ DELETE FROM memory_fts WHERE rowid = old.id;
923
+ END;
924
+
925
+ CREATE TRIGGER IF NOT EXISTS trg_nodes_au AFTER UPDATE ON nodes BEGIN
926
+ DELETE FROM memory_fts WHERE rowid = old.id;
927
+ INSERT INTO memory_fts(rowid, tree_type, path, name, content, keywords)
928
+ VALUES (new.id, new.tree_type, new.path, new.name, new.content, new.keywords);
929
+ END;
930
+ `);
931
+ }
932
+ /**
933
+ * 沿物化路径递归构建目录节点并在末端挂载/强化原子断言叶子。
934
+ * 同 (tree_type, path, name) 冲突时执行强化:reinforce_count + 1 并更新内容与关键词。
935
+ */
936
+ upsertLeaf(treeType, pathSegments, name2, content, keywords) {
937
+ const cleanSegments = (Array.isArray(pathSegments) ? pathSegments : []).map(sanitizeSegment).filter(Boolean);
938
+ const fallbackSegments = cleanSegments.length > 0 ? cleanSegments : ["\u672A\u5206\u7C7B"];
939
+ const cleanName = sanitizeSegment(name2) || "\u672A\u547D\u540D\u89C4\u5219";
940
+ const cleanContent = String(content ?? "").trim().slice(0, 80);
941
+ const cleanKeywords = (Array.isArray(keywords) ? keywords : []).map((k) => sanitizeSegment(k)).filter(Boolean).join(" ");
942
+ let parentId = null;
943
+ let fullPath = "";
944
+ for (const seg of fallbackSegments) {
945
+ fullPath += `/${seg}`;
946
+ parentId = this.upsertDirectory(treeType, parentId, `${fullPath}/`, seg);
947
+ }
948
+ return this.upsertNode(treeType, parentId, `${fullPath}/`, cleanName, 1, cleanContent, cleanKeywords);
949
+ }
950
+ upsertDirectory(treeType, parentId, dirPath, name2) {
951
+ const row = this.upsertNode(treeType, parentId, dirPath, name2, 0, null, null);
952
+ return Number(row.id);
953
+ }
954
+ upsertNode(treeType, parentId, nodePath, name2, isLeaf, content, keywords) {
955
+ const now = Date.now();
956
+ const result = this.db.prepare(`
957
+ INSERT INTO nodes (tree_type, parent_id, path, name, is_leaf, content, keywords, reinforce_count, is_pinned, created_at, updated_at)
958
+ VALUES (?, ?, ?, ?, ?, ?, ?, 1, 0, ?, ?)
959
+ ON CONFLICT(tree_type, path, name) DO UPDATE SET
960
+ content = excluded.content,
961
+ keywords = excluded.keywords,
962
+ reinforce_count = reinforce_count + 1,
963
+ updated_at = excluded.updated_at
964
+ RETURNING *
965
+ `).get(treeType, parentId, nodePath, name2, isLeaf, content, keywords, now, now);
966
+ return this.rowToNode(result);
967
+ }
968
+ /** FTS5 Trigram 全文检索:BM25 排序,输出 score(越高越相关)与 bm25_rank */
969
+ search(query, options = {}) {
970
+ const cleanQuery = String(query ?? "").trim();
971
+ if (!cleanQuery) return [];
972
+ const { treeType, pathPrefix, limit = 5 } = options;
973
+ const matchQuery = `"${cleanQuery.replace(/"/g, '""')}"`;
974
+ const where = ["memory_fts MATCH ?"];
975
+ const params = [matchQuery];
976
+ if (treeType) {
977
+ where.push("n.tree_type = ?");
978
+ params.push(treeType);
979
+ }
980
+ if (pathPrefix) {
981
+ where.push(`n.path LIKE ? ESCAPE '\\'`);
982
+ params.push(`${escapeLikePattern(pathPrefix)}%`);
983
+ }
984
+ params.push(limit);
985
+ const rows = this.db.prepare(`
986
+ SELECT n.*, bm25(memory_fts) AS bm25_score
987
+ FROM memory_fts
988
+ JOIN nodes n ON n.id = memory_fts.rowid
989
+ WHERE ${where.join(" AND ")}
990
+ ORDER BY bm25(memory_fts)
991
+ LIMIT ?
992
+ `).all(...params);
993
+ return rows.map((row, index) => {
994
+ const node = this.rowToNode(row);
995
+ const bm25 = Number(row.bm25_score ?? 0);
996
+ return {
997
+ ...node,
998
+ score: Math.round(-bm25 * 100) / 100,
999
+ bm25_rank: index + 1
1000
+ };
1001
+ });
1002
+ }
1003
+ getAllNodes(treeType) {
1004
+ const rows = treeType ? this.db.prepare("SELECT * FROM nodes WHERE tree_type = ? ORDER BY tree_type, path, name").all(treeType) : this.db.prepare("SELECT * FROM nodes ORDER BY tree_type, path, name").all();
1005
+ return rows.map((row) => this.rowToNode(row));
1006
+ }
1007
+ /**
1008
+ * 人工剪枝:删除指定节点并级联移除其全部后代(沿 parent_id 外键链递归收敛),
1009
+ * 每行删除均经 trg_nodes_ad 触发器同步清理 FTS5 索引,杜绝孤立句柄残留。
1010
+ */
1011
+ deleteNode(id) {
1012
+ const result = this.db.prepare(`
1013
+ WITH RECURSIVE subtree(id) AS (
1014
+ SELECT id FROM nodes WHERE id = ?
1015
+ UNION ALL
1016
+ SELECT n.id FROM nodes n JOIN subtree s ON n.parent_id = s.id
1017
+ )
1018
+ DELETE FROM nodes WHERE id IN (SELECT id FROM subtree)
1019
+ `).run(Number(id));
1020
+ return result.changes > 0;
1021
+ }
1022
+ close() {
1023
+ if (this.db.open) this.db.close();
1024
+ }
1025
+ rowToNode(row) {
1026
+ return {
1027
+ id: String(row.id),
1028
+ tree_type: String(row.tree_type),
1029
+ parent_id: row.parent_id == null ? null : String(row.parent_id),
1030
+ path: String(row.path),
1031
+ name: String(row.name),
1032
+ is_leaf: Number(row.is_leaf ?? 0),
1033
+ content: row.content == null ? null : String(row.content),
1034
+ keywords: row.keywords == null ? null : String(row.keywords),
1035
+ reinforce_count: Number(row.reinforce_count ?? 0),
1036
+ is_pinned: Number(row.is_pinned ?? 0),
1037
+ created_at: Number(row.created_at ?? 0),
1038
+ updated_at: Number(row.updated_at ?? 0)
1039
+ };
1040
+ }
1041
+ };
1042
+
1043
+ // src/extractor.ts
1044
+ var REFLECTION_SYSTEM_PROMPT = `\u4F60\u662F\u4E00\u4E2A\u8F6F\u4EF6\u5DE5\u7A0B\u7ECF\u9A8C\u6C89\u6DC0\u5F15\u64CE\u3002\u8BF7\u5BA1\u89C6\u521A\u624D\u8FD9\u4E00\u8F6E\u4EBA\u673A\u4EA4\u4E92\uFF0C\u63D0\u53D6\u957F\u671F\u6709\u6548\u7684\u9AD8\u4EF7\u503C\u67B6\u6784\u89C4\u7EA6\u3001\u5F00\u53D1\u89C4\u8303\u6216\u907F\u5751\u7ECF\u9A8C\u3002
1045
+
1046
+ \u3010\u63D0\u70BC\u89C4\u5219\u3011
1047
+ 1. \u575A\u51B3\u820D\u5F03\uFF1A\u5355\u6B21\u4E34\u65F6\u5BF9\u8BDD\u3001\u95F2\u804A\u5BA2\u5957\u3001\u7B80\u5355\u62FC\u5199\u4FEE\u590D\u4EE5\u53CA\u672A\u5F97\u51FA\u660E\u786E\u7ED3\u8BBA\u7684\u63A8\u6F14\u8FC7\u7A0B\u3002
1048
+ 2. \u4F5C\u7528\u57DF\u5212\u5206\u6807\u51C6\uFF1A
1049
+ - global\uFF1A\u8DE8\u9879\u76EE\u901A\u7528\u7684\u7528\u6237\u7F16\u7801\u504F\u597D\u3001\u901A\u7528\u5DE5\u5177\u94FE\u89C4\u7EA6\u6216\u901A\u7528\u5F00\u53D1\u4E60\u60EF\u3002
1050
+ - project\uFF1A\u5F53\u524D\u4ED3\u5E93\u4E13\u6709\u7684\u67B6\u6784\u8BBE\u8BA1\u3001\u6A21\u5757\u5212\u5206\u7EA6\u5B9A\u3001\u7279\u5B9A\u4F9D\u8D56\u7248\u672C\u89C4\u7EA6\u4E0E\u7279\u6709\u8E29\u5751\u53CD\u601D\u3002
1051
+ 3. \u6587\u672C\u538B\u7F29\u7EA6\u675F\uFF1A
1052
+ - content \u5B57\u6BB5\u5FC5\u987B\u662F\u63D0\u70BC\u540E\u7684\u539F\u5B50\u65AD\u8A00\u6216\u64CD\u4F5C\u7EA6\u675F\uFF0C\u4E25\u7981\u8F93\u51FA\u4EE3\u7801\u5757\u6216\u60C5\u7EEA\u5316\u957F\u6587\u3002
1053
+ - \u5B57\u7B26\u957F\u5EA6\u4E25\u683C\u9650\u5236\u5728 40 \u81F3 80 \u4E2A\u4E2D\u6587\u5B57\u7B26\u4EE5\u5185\u3002
1054
+ 4. \u8DEF\u5F84\u5206\u6BB5\uFF08path_segments\uFF09\u901A\u5E38\u5305\u542B 2 \u81F3 3 \u7EA7\u4E2D\u6587\u5206\u7C7B\u540D\uFF08\u4F8B\u5982 ["\u6280\u672F\u9009\u578B", "\u6784\u5EFA\u5DE5\u5177"]\uFF09\u3002
1055
+
1056
+ \u3010\u8F93\u51FA\u683C\u5F0F\u3011
1057
+ \u5FC5\u987B\u4E25\u683C\u8F93\u51FA\u7EAF JSON \u5BF9\u8C61\uFF0C\u4E25\u7981\u5305\u88F9\u4EFB\u4F55\u4EE3\u7801\u5757\u5916\u7684 Markdown \u89E3\u91CA\u6027\u6587\u672C\uFF1A
1058
+ {
1059
+ "reflections": [
1060
+ {
1061
+ "tree": "global" | "project",
1062
+ "path_segments": ["\u5206\u7C7B\u4E00\u7EA7", "\u5206\u7C7B\u4E8C\u7EA7"],
1063
+ "name": "\u89C4\u5219\u7B80\u540D",
1064
+ "content": "40\u523080\u5B57\u9AD8\u5EA6\u7CBE\u70BC\u7684\u6838\u5FC3\u65AD\u8A00\u89C4\u5219",
1065
+ "keywords": ["\u5173\u952E\u8BCD1", "\u5173\u952E\u8BCD2"]
1066
+ }
1067
+ ]
1068
+ }
1069
+ \u82E5\u672C\u8F6E\u4EA4\u4E92\u65E0\u957F\u671F\u4EF7\u503C\uFF0C\u8BF7\u76F4\u63A5\u8F93\u51FA {"reflections": []}\u3002`;
1070
+ var MemoryExtractor = class {
1071
+ constructor(ctx, db) {
1072
+ this.ctx = ctx;
1073
+ this.db = db;
1074
+ }
1075
+ ctx;
1076
+ db;
1077
+ /** 第一重门禁:启发式过滤网关,丢弃寒暄客套与长度不足的文本 */
1078
+ passesFilterGate(text) {
1079
+ if (!text || text.trim().length < 15) return false;
1080
+ const trivialPatterns = [
1081
+ /^(你好|在吗|hi|hello|继续|收到|好的|ok|yes)$/i,
1082
+ /^(谢谢|thank you|thanks)$/i
1083
+ ];
1084
+ return !trivialPatterns.some((pattern) => pattern.test(text.trim()));
1085
+ }
1086
+ async extractAndConsolidate(userMessage, assistantResponse, projectScope) {
1087
+ if (!this.passesFilterGate(userMessage) && !this.passesFilterGate(assistantResponse)) {
1088
+ return;
1089
+ }
1090
+ if (!this.ctx.llm?.stream) {
1091
+ this.ctx.logger?.warn?.("[tlmemory] \u5BBF\u4E3B ctx.llm \u672A\u5C31\u7EEA\uFF0C\u8DF3\u8FC7\u53CD\u601D\u63D0\u53D6");
1092
+ return;
1093
+ }
1094
+ const conversationContext = `[\u7528\u6237\u8F93\u5165]
1095
+ ${userMessage}
1096
+
1097
+ [\u667A\u80FD\u4F53\u7B54\u590D\u4E0E\u64CD\u4F5C]
1098
+ ${assistantResponse}`;
1099
+ try {
1100
+ const stream = this.ctx.llm.stream({
1101
+ messages: [
1102
+ { role: "system", content: REFLECTION_SYSTEM_PROMPT },
1103
+ { role: "user", content: conversationContext }
1104
+ ],
1105
+ temperature: 0.1
1106
+ });
1107
+ let rawOutput = "";
1108
+ for await (const chunk of stream) {
1109
+ rawOutput += chunk.delta || chunk.text || chunk.content || "";
1110
+ }
1111
+ const cleanJson = this.sanitizeJsonString(rawOutput);
1112
+ const parsed = JSON.parse(cleanJson);
1113
+ if (!parsed.reflections || !Array.isArray(parsed.reflections)) {
1114
+ return;
1115
+ }
1116
+ for (const item of parsed.reflections) {
1117
+ this.processSingleReflection(item, projectScope);
1118
+ }
1119
+ } catch (err) {
1120
+ this.ctx.logger?.error?.("[tlmemory] \u5F02\u6B65\u53CD\u601D\u63D0\u70BC\u8FC7\u7A0B\u5F02\u5E38:", err);
1121
+ }
1122
+ }
1123
+ /** 剥离 Markdown 代码块围栏并收敛至首个 JSON 对象边界 */
1124
+ sanitizeJsonString(raw) {
1125
+ let sanitized = raw.trim();
1126
+ if (sanitized.startsWith("```json")) {
1127
+ sanitized = sanitized.slice(7);
1128
+ } else if (sanitized.startsWith("```")) {
1129
+ sanitized = sanitized.slice(3);
1130
+ }
1131
+ if (sanitized.endsWith("```")) {
1132
+ sanitized = sanitized.slice(0, -3);
1133
+ }
1134
+ sanitized = sanitized.trim();
1135
+ const start = sanitized.indexOf("{");
1136
+ const end = sanitized.lastIndexOf("}");
1137
+ if (start !== -1 && end !== -1 && end > start) {
1138
+ sanitized = sanitized.slice(start, end + 1);
1139
+ }
1140
+ return sanitized.trim();
1141
+ }
1142
+ processSingleReflection(item, projectScope) {
1143
+ if (!item.content || !item.name) return;
1144
+ const boundedContent = item.content.trim().slice(0, 80);
1145
+ const targetTreeType = item.tree === "global" ? "global" : projectScope;
1146
+ const cleanSegments = (item.path_segments || ["\u9ED8\u8BA4"]).map((seg) => seg.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "")).filter(Boolean);
1147
+ if (cleanSegments.length === 0) cleanSegments.push("\u901A\u7528");
1148
+ const cleanKeywords = Array.isArray(item.keywords) ? item.keywords.map((k) => k.trim()).filter((k) => k.length > 0) : [item.name];
1149
+ this.db.upsertLeaf(
1150
+ targetTreeType,
1151
+ cleanSegments,
1152
+ item.name.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, ""),
1153
+ boundedContent,
1154
+ cleanKeywords
1155
+ );
1156
+ this.ctx.logger?.info?.(`[tlmemory] \u77E5\u8BC6\u6C89\u6DC0\u5165\u5E93 [${targetTreeType}]: ${item.name}`);
1157
+ }
1158
+ };
1159
+
1160
+ // src/tools.ts
1161
+ function registerMemoryTools(ctx, db, resolveCurrentScope) {
1162
+ if (!ctx.tools?.register) {
1163
+ ctx.logger?.warn?.("[tlmemory] ctx.tools \u672A\u5C31\u7EEA\uFF0C\u8DF3\u8FC7\u5DE5\u5177\u6CE8\u518C");
1164
+ return () => {
1165
+ };
1166
+ }
1167
+ const unregisterSave = ctx.tools.register({
1168
+ name: "tlmemory_save",
1169
+ description: "\u663E\u5F0F\u5C06\u91CD\u8981\u7528\u6237\u89C4\u8303\u3001\u6280\u672F\u67B6\u6784\u7EA6\u675F\u6216\u8E29\u5751\u907F\u5751\u65AD\u8A00\u6301\u4E45\u5316\u81F3\u957F\u671F\u8BB0\u5FC6\u6811\u4E2D",
1170
+ parameters: {
1171
+ type: "object",
1172
+ properties: {
1173
+ tree_scope: {
1174
+ type: "string",
1175
+ enum: ["global", "project"],
1176
+ description: "\u4F5C\u7528\u57DF\uFF1Aglobal \u5C5E\u4E8E\u8DE8\u5DE5\u7A0B\u5168\u5C40\u504F\u597D\uFF0Cproject \u5C5E\u4E8E\u5F53\u524D\u4ED3\u5E93\u4E13\u5C5E\u89C4\u7EA6"
1177
+ },
1178
+ path_segments: {
1179
+ type: "array",
1180
+ items: { type: "string" },
1181
+ description: '\u6811\u5F62\u5206\u7C7B\u8DEF\u5F84\u6BB5\uFF0C\u4F8B\u5982 ["\u5DE5\u7A0B\u5316", "\u5305\u7BA1\u7406"]'
1182
+ },
1183
+ rule_name: {
1184
+ type: "string",
1185
+ description: '\u89C4\u5219\u7B80\u8FF0\u6807\u9898\uFF0C\u4F8B\u5982 "pnpm\u4F9D\u8D56\u6784\u5EFA\u653E\u884C"'
1186
+ },
1187
+ content: {
1188
+ type: "string",
1189
+ description: "\u539F\u5B50\u65AD\u8A00\u6587\u672C\uFF0C\u4E25\u683C\u9650\u5236\u572840\u81F380\u5B57\u7B26\u4EE5\u5185\uFF0C\u7981\u6B62\u5305\u542B\u591A\u4F59\u4EE3\u7801\u5757"
1190
+ },
1191
+ keywords: {
1192
+ type: "array",
1193
+ items: { type: "string" },
1194
+ description: "\u68C0\u7D22\u5173\u952E\u8BCD\u5217\u8868"
1195
+ }
1196
+ },
1197
+ required: [
1198
+ "tree_scope",
1199
+ "path_segments",
1200
+ "rule_name",
1201
+ "content",
1202
+ "keywords"
1203
+ ]
1204
+ },
1205
+ output: {
1206
+ schema: {
1207
+ type: "object",
1208
+ properties: {
1209
+ status: { type: "string", description: "\u6267\u884C\u72B6\u6001" },
1210
+ message: { type: "string", description: "\u8BE6\u7EC6\u63D0\u793A\u4FE1\u606F" },
1211
+ node_id: { type: "string", description: "\u8BB0\u5FC6\u8282\u70B9\u552F\u4E00\u6807\u8BC6" }
1212
+ },
1213
+ required: ["status", "message", "node_id"]
1214
+ },
1215
+ render: (result) => result?.message ?? JSON.stringify(result)
1216
+ },
1217
+ async execute(args) {
1218
+ const targetTree = args.tree_scope === "global" ? "global" : resolveCurrentScope();
1219
+ const sanitizedSegments = args.path_segments.map(
1220
+ (s) => s.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5]/g, "")
1221
+ );
1222
+ const sanitizedName = args.rule_name.replace(
1223
+ /[^a-zA-Z0-9_\u4e00-\u9fa5]/g,
1224
+ ""
1225
+ );
1226
+ const boundedContent = args.content.slice(0, 80);
1227
+ const node = db.upsertLeaf(
1228
+ targetTree,
1229
+ sanitizedSegments,
1230
+ sanitizedName,
1231
+ boundedContent,
1232
+ args.keywords || [sanitizedName]
1233
+ );
1234
+ return {
1235
+ status: "success",
1236
+ message: `\u8BB0\u5FC6\u5DF2\u6210\u529F\u5165\u5E93 [${node.tree_type}]: ${node.path}${node.name}`,
1237
+ node_id: node.id
1238
+ };
1239
+ }
1240
+ });
1241
+ const unregisterQuery = ctx.tools.register({
1242
+ name: "tlmemory_query",
1243
+ description: "\u901A\u8FC7 FTS5 Trigram \u5168\u6587\u7D22\u5F15\u68C0\u7D22\u4E0E\u5F53\u524D\u4EFB\u52A1\u7D27\u5BC6\u76F8\u5173\u7684\u957F\u671F\u8BB0\u5FC6\u65AD\u8A00",
1244
+ parameters: {
1245
+ type: "object",
1246
+ properties: {
1247
+ query: {
1248
+ type: "string",
1249
+ description: "\u67E5\u8BE2\u6587\u672C\u6216\u6280\u672F\u5173\u952E\u5B57"
1250
+ },
1251
+ scope: {
1252
+ type: "string",
1253
+ enum: ["all", "global", "project"],
1254
+ description: "\u67E5\u8BE2\u8303\u56F4\uFF0C\u9ED8\u8BA4 all \u8986\u76D6\u5168\u5C40\u4E0E\u5F53\u524D\u5DE5\u7A0B"
1255
+ },
1256
+ limit: {
1257
+ type: "number",
1258
+ description: "\u6700\u5927\u68C0\u7D22\u7ED3\u679C\u6570\uFF0C\u9ED8\u8BA4 5"
1259
+ }
1260
+ },
1261
+ required: ["query"]
1262
+ },
1263
+ output: {
1264
+ schema: {
1265
+ type: "object",
1266
+ properties: {
1267
+ status: { type: "string", description: "\u6267\u884C\u72B6\u6001" },
1268
+ hits_count: { type: "number", description: "\u547D\u4E2D\u6761\u6570" },
1269
+ memories: {
1270
+ type: "array",
1271
+ items: {
1272
+ type: "object",
1273
+ properties: {
1274
+ tree: { type: "string" },
1275
+ path: { type: "string" },
1276
+ content: { type: "string" },
1277
+ score: { type: "number" }
1278
+ }
1279
+ },
1280
+ description: "\u547D\u4E2D\u7684\u8BB0\u5FC6\u5217\u8868"
1281
+ }
1282
+ },
1283
+ required: ["status", "hits_count", "memories"]
1284
+ },
1285
+ render: (result) => {
1286
+ if (!result.memories || result.memories.length === 0) {
1287
+ return "\u672A\u68C0\u7D22\u5230\u76F8\u5173\u7684\u957F\u671F\u8BB0\u5FC6\u3002";
1288
+ }
1289
+ return result.memories.map(
1290
+ (m) => `* [${m.tree}] ${m.path}: ${m.content} (\u5F97\u5206: ${m.score.toFixed(1)})`
1291
+ ).join("\n");
1292
+ }
1293
+ },
1294
+ async execute(args) {
1295
+ const currentScope = resolveCurrentScope();
1296
+ let treeType;
1297
+ if (args.scope === "global") treeType = "global";
1298
+ if (args.scope === "project") treeType = currentScope;
1299
+ const results = db.search(args.query, {
1300
+ treeType,
1301
+ limit: args.limit || 5
1302
+ });
1303
+ return {
1304
+ status: "success",
1305
+ hits_count: results.length,
1306
+ memories: results.map((r) => ({
1307
+ tree: r.tree_type === "global" ? "\u5168\u5C40\u504F\u597D" : "\u5F53\u524D\u5DE5\u7A0B",
1308
+ path: `${r.path}${r.name}`,
1309
+ content: r.content ?? "",
1310
+ score: r.score
1311
+ }))
1312
+ };
1313
+ }
1314
+ });
1315
+ return () => {
1316
+ unregisterSave();
1317
+ unregisterQuery();
1318
+ };
1319
+ }
1320
+
1321
+ // src/recall.ts
1322
+ var PROJECT_SCOPE_BIAS = 5;
1323
+ function escapeXmlEntities(input) {
1324
+ return input.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1325
+ }
1326
+ var MemoryRecallEngine = class {
1327
+ constructor(db) {
1328
+ this.db = db;
1329
+ }
1330
+ db;
1331
+ /**
1332
+ * 双轨召回:项目记忆与全局记忆分别经 FTS5 检索后合流,
1333
+ * 项目命中叠加作用域偏置,按加权分数降序去重截断。
1334
+ * 用户输入为长句时,FTS5 Trigram 短语匹配要求完整连续子串、几乎必然零命中,
1335
+ * 因此先执行查询候选展开(整句 / 标点切分 token / 中英文段 / 中文滑窗子串),
1336
+ * 再跨候选聚合加权去重,保证长句输入同样能命中语义相关的记忆断言。
1337
+ */
1338
+ recall(query, projectScope, maxCount = 5) {
1339
+ const cleanQuery = query.trim();
1340
+ if (!cleanQuery) return [];
1341
+ const candidates = this.expandQueryCandidates(cleanQuery);
1342
+ const merged = /* @__PURE__ */ new Map();
1343
+ for (const candidate of candidates) {
1344
+ const projectHits = this.db.search(candidate, { treeType: projectScope, limit: maxCount });
1345
+ const globalHits = this.db.search(candidate, { treeType: "global", limit: maxCount });
1346
+ for (const hit of projectHits) {
1347
+ const uniqueKey = `${hit.tree_type}:${hit.path}${hit.name}`;
1348
+ merged.set(uniqueKey, { ...hit, score: hit.score + PROJECT_SCOPE_BIAS });
1349
+ }
1350
+ for (const hit of globalHits) {
1351
+ const uniqueKey = `${hit.tree_type}:${hit.path}${hit.name}`;
1352
+ if (!merged.has(uniqueKey)) merged.set(uniqueKey, hit);
1353
+ }
1354
+ }
1355
+ return Array.from(merged.values()).sort((a, b) => b.score - a.score).slice(0, maxCount);
1356
+ }
1357
+ /** 查询候选展开:整句 -> 标点/空白切分 -> 中英文边界分段 -> 中文长段 Trigram 级滑窗子串 */
1358
+ expandQueryCandidates(query) {
1359
+ const candidates = /* @__PURE__ */ new Set([query]);
1360
+ const tokens = query.split(/[\s,,。;;、::!!??"'()()\[\]{}]+/).filter((t) => t.length > 0);
1361
+ for (const token of tokens) {
1362
+ candidates.add(token);
1363
+ const segments = token.match(/[a-zA-Z0-9_-]+|[\u4e00-\u9fa5]+/g) ?? [token];
1364
+ for (const seg of segments) {
1365
+ candidates.add(seg);
1366
+ if (/[\u4e00-\u9fa5]/.test(seg) && seg.length > 3) {
1367
+ for (let i = 0; i <= seg.length - 3; i += 2) {
1368
+ candidates.add(seg.slice(i, i + 3));
1369
+ }
1370
+ candidates.add(seg.slice(-3));
1371
+ }
1372
+ }
1373
+ }
1374
+ return Array.from(candidates).slice(0, 16);
1375
+ }
1376
+ /** 将召回记忆格式化为受控 XML 标签包裹的同步注入文本,空结果返回空串 */
1377
+ formatPromptBlock(memories) {
1378
+ if (memories.length === 0) return "";
1379
+ const lines = memories.map((m) => {
1380
+ const scopeLabel = m.tree_type === "global" ? "\u5168\u5C40\u504F\u597D" : "\u5F53\u524D\u5DE5\u7A0B";
1381
+ const cleanPath = escapeXmlEntities(`${m.path}${m.name}`);
1382
+ const cleanContent = escapeXmlEntities(m.content || "");
1383
+ return ` - [${scopeLabel}] ${cleanPath}: ${cleanContent}`;
1384
+ });
1385
+ return [
1386
+ "<long_term_memory_context>",
1387
+ "\u4EE5\u4E0B\u662F\u7CFB\u7EDF\u81EA\u52A8\u68C0\u7D22\u5339\u914D\u7684\u957F\u671F\u5DE5\u7A0B\u5951\u7EA6\u4E0E\u907F\u5751\u7ECF\u9A8C\uFF0C\u4F60\u5728\u672C\u8F6E\u63A8\u7406\u4E0E\u5DE5\u5177\u8C03\u7528\u4E2D\u5FC5\u987B\u4E25\u683C\u9075\u5B88\uFF1A",
1388
+ ...lines,
1389
+ "</long_term_memory_context>"
1390
+ ].join("\n");
1391
+ }
1392
+ };
1393
+
1394
+ // src/server.ts
1395
+ import http from "http";
1396
+ import fs2 from "fs";
1397
+ import path2 from "path";
1398
+ import { fileURLToPath } from "url";
1399
+ import { WebSocketServer, WebSocket } from "ws";
1400
+ var LOOPBACK_HOST = "127.0.0.1";
1401
+ var MIME_MAP = {
1402
+ ".html": "text/html; charset=utf-8",
1403
+ ".js": "application/javascript",
1404
+ ".css": "text/css",
1405
+ ".svg": "image/svg+xml",
1406
+ ".png": "image/png",
1407
+ ".json": "application/json; charset=utf-8"
1408
+ };
1409
+ function isAllowedHost(hostHeader) {
1410
+ if (!hostHeader) return false;
1411
+ const hostname = hostHeader.split(":")[0].toLowerCase();
1412
+ return hostname === "127.0.0.1" || hostname === "localhost";
1413
+ }
1414
+ function isAllowedOrigin(originHeader) {
1415
+ if (!originHeader) return true;
1416
+ return originHeader.includes("127.0.0.1") || originHeader.includes("localhost");
1417
+ }
1418
+ function resolveWebDist() {
1419
+ const currentDir = typeof __dirname !== "undefined" ? __dirname : path2.dirname(fileURLToPath(import.meta.url));
1420
+ return path2.resolve(currentDir, "../web/dist");
1421
+ }
1422
+ var MemoryServer = class {
1423
+ constructor(db, port = 4890, logger) {
1424
+ this.db = db;
1425
+ this.port = port;
1426
+ this.logger = logger;
1427
+ this.distPath = resolveWebDist();
1428
+ }
1429
+ db;
1430
+ port;
1431
+ logger;
1432
+ server = null;
1433
+ wss = null;
1434
+ clients = /* @__PURE__ */ new Set();
1435
+ distPath;
1436
+ get actualPort() {
1437
+ const addr = this.server?.address();
1438
+ return typeof addr === "object" && addr !== null ? addr.port : 0;
1439
+ }
1440
+ start() {
1441
+ if (this.server) return;
1442
+ this.server = http.createServer((req, res) => {
1443
+ this.handleHttp(req, res);
1444
+ });
1445
+ this.wss = new WebSocketServer({ noServer: true });
1446
+ this.wss.on("connection", (ws) => {
1447
+ this.clients.add(ws);
1448
+ ws.on("close", () => this.clients.delete(ws));
1449
+ });
1450
+ this.server.on("upgrade", (request, socket, head) => {
1451
+ if (!isAllowedHost(request.headers.host) || !isAllowedOrigin(request.headers.origin)) {
1452
+ socket.destroy();
1453
+ return;
1454
+ }
1455
+ this.wss?.handleUpgrade(request, socket, head, (ws) => {
1456
+ this.wss?.emit("connection", ws, request);
1457
+ });
1458
+ });
1459
+ this.server.listen(this.port, LOOPBACK_HOST, () => {
1460
+ this.logger?.info?.(`[tlmemory-server] \u672C\u5730\u7BA1\u7406\u670D\u52A1\u5C31\u7EEA: http://127.0.0.1:${this.port}`);
1461
+ });
1462
+ this.server.on("error", (err) => {
1463
+ this.logger?.error?.("[tlmemory-server] \u672C\u5730\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38:", err.message);
1464
+ });
1465
+ }
1466
+ broadcastHits(treeType, hitNodeIds) {
1467
+ const payload = JSON.stringify({
1468
+ type: "MEMORY_HITS",
1469
+ treeType,
1470
+ hitNodeIds,
1471
+ timestamp: Date.now()
1472
+ });
1473
+ for (const client of this.clients) {
1474
+ if (client.readyState === WebSocket.OPEN) {
1475
+ client.send(payload);
1476
+ }
1477
+ }
1478
+ }
1479
+ notifyTreeChanged(treeType) {
1480
+ const payload = JSON.stringify({
1481
+ type: "TREE_CHANGED",
1482
+ treeType,
1483
+ timestamp: Date.now()
1484
+ });
1485
+ for (const client of this.clients) {
1486
+ if (client.readyState === WebSocket.OPEN) {
1487
+ client.send(payload);
1488
+ }
1489
+ }
1490
+ }
1491
+ handleHttp(req, res) {
1492
+ res.setHeader("Access-Control-Allow-Origin", "*");
1493
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
1494
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
1495
+ if (req.method === "OPTIONS") {
1496
+ res.writeHead(204);
1497
+ res.end();
1498
+ return;
1499
+ }
1500
+ const url = new URL(req.url || "/", `http://${req.headers.host || "127.0.0.1"}`);
1501
+ const pathname = url.pathname;
1502
+ try {
1503
+ if (req.method === "GET" && pathname === "/api/nodes") {
1504
+ const treeType = url.searchParams.get("treeType") ?? void 0;
1505
+ const nodes = this.db.getAllNodes(treeType);
1506
+ this.sendJson(res, 200, { data: nodes });
1507
+ return;
1508
+ }
1509
+ if (req.method === "GET" && pathname === "/api/memories") {
1510
+ const treeType = url.searchParams.get("tree") ?? url.searchParams.get("treeType") ?? void 0;
1511
+ const nodes = this.db.getAllNodes(treeType);
1512
+ this.sendJson(res, 200, { data: nodes });
1513
+ return;
1514
+ }
1515
+ if (req.method === "GET" && pathname === "/api/search") {
1516
+ const query = url.searchParams.get("q") || "";
1517
+ const treeType = url.searchParams.get("treeType") ?? void 0;
1518
+ const hits = this.db.search(query, { treeType });
1519
+ this.sendJson(res, 200, { data: hits });
1520
+ return;
1521
+ }
1522
+ if (req.method === "DELETE" && pathname.startsWith("/api/nodes/")) {
1523
+ const id = pathname.slice("/api/nodes/".length);
1524
+ const removed = this.db.deleteNode(id);
1525
+ this.sendJson(res, 200, { success: removed });
1526
+ return;
1527
+ }
1528
+ this.serveStatic(req, res, pathname);
1529
+ } catch (e) {
1530
+ this.sendJson(res, 500, { error: e.message });
1531
+ }
1532
+ }
1533
+ serveStatic(req, res, pathname) {
1534
+ const distPath = this.distPath;
1535
+ let safePath = path2.normalize(path2.join(distPath, pathname === "/" ? "index.html" : pathname));
1536
+ if (!safePath.startsWith(distPath + path2.sep)) {
1537
+ res.writeHead(403);
1538
+ res.end("Forbidden");
1539
+ return;
1540
+ }
1541
+ if (!fs2.existsSync(safePath) || fs2.statSync(safePath).isDirectory()) {
1542
+ safePath = path2.join(distPath, "index.html");
1543
+ }
1544
+ if (!fs2.existsSync(safePath)) {
1545
+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
1546
+ res.end("\u524D\u7AEF\u9759\u6001\u8D44\u6E90\u5C1A\u672A\u6784\u5EFA\uFF0C\u8BF7\u8FDB\u5165 packages/tlmemory/web \u6267\u884C pnpm build");
1547
+ return;
1548
+ }
1549
+ const ext = path2.extname(safePath);
1550
+ res.writeHead(200, { "Content-Type": MIME_MAP[ext] || "application/octet-stream" });
1551
+ fs2.createReadStream(safePath).pipe(res);
1552
+ }
1553
+ sendJson(res, statusCode, data) {
1554
+ res.writeHead(statusCode, { "Content-Type": "application/json; charset=utf-8" });
1555
+ res.end(JSON.stringify(data));
1556
+ }
1557
+ stop() {
1558
+ for (const client of this.clients) {
1559
+ client.terminate();
1560
+ }
1561
+ this.clients.clear();
1562
+ this.wss?.close();
1563
+ this.server?.close();
1564
+ this.wss = null;
1565
+ this.server = null;
1566
+ }
1567
+ };
1568
+
1569
+ // src/index.ts
1570
+ var Config = lib_default.object({
1571
+ dbPath: lib_default.string().description("SQLite \u6570\u636E\u5E93\u7269\u7406\u6587\u4EF6\u8DEF\u5F84\uFF08\u9ED8\u8BA4\u7F6E\u4E8E\u5168\u5C40 ~/.dsh/tlmemory.db\uFF09"),
1572
+ serverPort: lib_default.number().default(4890).description("\u4FA7\u8FB9\u680F\u4E0E REST API \u670D\u52A1\u7AEF\u53E3"),
1573
+ maxRecallCount: lib_default.number().default(5).description("\u5355\u8F6E\u6700\u5927\u7CFB\u7EDF\u63D0\u793A\u8BCD\u6CE8\u5165\u8BB0\u5FC6\u6761\u6570"),
1574
+ enableAutoReflection: lib_default.boolean().default(true).description("\u662F\u5426\u5F00\u542F\u4F1A\u8BDD\u7ED3\u675F\u5F02\u6B65\u81EA\u52A8\u53CD\u601D\u63D0\u70BC")
1575
+ });
1576
+ var name = "tlmemory";
1577
+ var inject = ["tools", "llm", "systemPrompt"];
1578
+ function resolveProjectScope() {
1579
+ let currentDir = process.cwd();
1580
+ while (currentDir !== path3.parse(currentDir).root) {
1581
+ if (fs3.existsSync(path3.join(currentDir, ".git"))) {
1582
+ const hash = crypto.createHash("sha256").update(path3.normalize(currentDir)).digest("hex");
1583
+ return `repo:${hash.slice(0, 12)}`;
1584
+ }
1585
+ currentDir = path3.dirname(currentDir);
1586
+ }
1587
+ const fallbackHash = crypto.createHash("sha256").update(path3.normalize(process.cwd())).digest("hex");
1588
+ return `repo:${fallbackHash.slice(0, 12)}`;
1589
+ }
1590
+ function apply(ctx, config) {
1591
+ ctx.logger?.info?.(`[tlmemory] \u63D2\u4EF6\u88C5\u914D\u542F\u52A8\u4E2D...`);
1592
+ const db = new MemoryDB(config.dbPath);
1593
+ const recallEngine = new MemoryRecallEngine(db);
1594
+ const extractor = new MemoryExtractor(ctx, db);
1595
+ const projectScope = resolveProjectScope();
1596
+ let activeRecalledMemories = [];
1597
+ let activePromptSectionText = "";
1598
+ const unregisterSection = ctx.systemPrompt?.section?.({
1599
+ name: "tlmemory:injected-context",
1600
+ order: 115,
1601
+ text: () => activePromptSectionText
1602
+ }) ?? (() => {
1603
+ });
1604
+ const unregisterTools = registerMemoryTools(ctx, db, () => projectScope);
1605
+ const server = new MemoryServer(db, config.serverPort ?? 4890, ctx.logger);
1606
+ server.start();
1607
+ let lastUserMessage = "";
1608
+ const unregisterSessionEvent = ctx.on("session/event", (event) => {
1609
+ if (event?.type === "user/message") {
1610
+ const text = typeof event.content === "string" ? event.content : event.content?.text ?? "";
1611
+ lastUserMessage = text;
1612
+ activeRecalledMemories = recallEngine.recall(text, projectScope, config.maxRecallCount ?? 5);
1613
+ activePromptSectionText = recallEngine.formatPromptBlock(activeRecalledMemories);
1614
+ server.broadcastHits(projectScope, activeRecalledMemories.map((m) => m.id));
1615
+ }
1616
+ if (event?.type === "turn/end" && (config.enableAutoReflection ?? true)) {
1617
+ const assistantText = event.last_assistant_message ?? "";
1618
+ if (lastUserMessage && assistantText) {
1619
+ setImmediate(() => {
1620
+ extractor.extractAndConsolidate(lastUserMessage, assistantText, projectScope).then(() => server.notifyTreeChanged(projectScope)).catch((err) => ctx.logger?.error?.("[tlmemory] \u540E\u53F0\u63D0\u70BC\u957F\u53F6\u5931\u8D25:", err));
1621
+ });
1622
+ }
1623
+ activePromptSectionText = "";
1624
+ lastUserMessage = "";
1625
+ }
1626
+ });
1627
+ return () => {
1628
+ ctx.logger?.info?.("[tlmemory] \u6B63\u5728\u6267\u884C\u5168\u91CF\u526F\u4F5C\u7528\u6CE8\u9500...");
1629
+ unregisterSection();
1630
+ unregisterTools();
1631
+ unregisterSessionEvent();
1632
+ server.stop();
1633
+ db.close();
1634
+ ctx.logger?.info?.("[tlmemory] \u63D2\u4EF6\u5DF2\u5F7B\u5E95\u5B89\u5168\u6CE8\u9500");
1635
+ };
1636
+ }
1637
+ export {
1638
+ Config,
1639
+ MemoryDB,
1640
+ MemoryExtractor,
1641
+ MemoryServer,
1642
+ apply,
1643
+ inject,
1644
+ name,
1645
+ registerMemoryTools
1646
+ };
1647
+ //# sourceMappingURL=index.js.map