@kanadego/dsh-heartbeat 1.9.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +103 -110
  3. package/client.js +12 -0
  4. package/config/policy.json +74 -74
  5. package/config/profile-schema.json +306 -306
  6. package/dist/{bindings-225SI7KC.js → bindings-U2M3CO2D.js} +3 -3
  7. package/dist/{chunk-TY6UP74X.js → chunk-3DNGY4DS.js} +2 -2
  8. package/dist/{chunk-CUOSICYJ.js → chunk-544QOJN5.js} +397 -23
  9. package/dist/chunk-544QOJN5.js.map +1 -0
  10. package/dist/{chunk-TRO4E6WG.js → chunk-6MVKWICX.js} +587 -139
  11. package/dist/chunk-6MVKWICX.js.map +1 -0
  12. package/dist/{chunk-WLZSABBH.js → chunk-6XM6KY7M.js} +27 -10
  13. package/dist/chunk-6XM6KY7M.js.map +1 -0
  14. package/dist/chunk-AKIJ4LS2.js +680 -0
  15. package/dist/chunk-AKIJ4LS2.js.map +1 -0
  16. package/dist/{chunk-KB5SMG3F.js → chunk-DC5HMCJC.js} +3 -3
  17. package/dist/{chunk-3MDBU6WY.js → chunk-DZ7YCFGX.js} +37 -7
  18. package/dist/chunk-DZ7YCFGX.js.map +1 -0
  19. package/dist/{chunk-WRUTATW4.js → chunk-IBBAISSW.js} +13 -2
  20. package/dist/chunk-IBBAISSW.js.map +1 -0
  21. package/dist/{chunk-XYYEJK3W.js → chunk-IFRMKVIC.js} +82 -21
  22. package/dist/chunk-IFRMKVIC.js.map +1 -0
  23. package/dist/{chunk-XFNCTOW7.js → chunk-NCPKOWS7.js} +52 -4
  24. package/dist/chunk-NCPKOWS7.js.map +1 -0
  25. package/dist/{chunk-JDH2LDFS.js → chunk-TVX4HV4Y.js} +4 -6
  26. package/dist/{chunk-JDH2LDFS.js.map → chunk-TVX4HV4Y.js.map} +1 -1
  27. package/dist/cli/index.js +149 -26
  28. package/dist/cli/index.js.map +1 -1
  29. package/dist/{inbox-P26DDMWC.js → inbox-OWBK6PE2.js} +8 -7
  30. package/dist/index.d.ts +48 -315
  31. package/dist/index.js +259 -918
  32. package/dist/index.js.map +1 -1
  33. package/dist/migrate-TQ5PB2DI.js +27 -0
  34. package/dist/{orchestrator-ZPRGVDCB.js → orchestrator-P7AEWVYR.js} +23 -12
  35. package/dist/{pool-UTXQJJ5C.js → pool-2T6TVS2L.js} +4 -5
  36. package/dist/{snapshot-K5VHETTK.js → snapshot-F5B2DD56.js} +5 -5
  37. package/package.json +84 -83
  38. package/dist/chunk-3MDBU6WY.js.map +0 -1
  39. package/dist/chunk-CUOSICYJ.js.map +0 -1
  40. package/dist/chunk-IV2ZWQA3.js +0 -56
  41. package/dist/chunk-IV2ZWQA3.js.map +0 -1
  42. package/dist/chunk-K5Y6JP2B.js +0 -399
  43. package/dist/chunk-K5Y6JP2B.js.map +0 -1
  44. package/dist/chunk-TRO4E6WG.js.map +0 -1
  45. package/dist/chunk-WLZSABBH.js.map +0 -1
  46. package/dist/chunk-WRUTATW4.js.map +0 -1
  47. package/dist/chunk-XFNCTOW7.js.map +0 -1
  48. package/dist/chunk-XYYEJK3W.js.map +0 -1
  49. package/dist/migrate-D4VKAKYT.js +0 -21
  50. /package/dist/{bindings-225SI7KC.js.map → bindings-U2M3CO2D.js.map} +0 -0
  51. /package/dist/{chunk-TY6UP74X.js.map → chunk-3DNGY4DS.js.map} +0 -0
  52. /package/dist/{chunk-KB5SMG3F.js.map → chunk-DC5HMCJC.js.map} +0 -0
  53. /package/dist/{inbox-P26DDMWC.js.map → inbox-OWBK6PE2.js.map} +0 -0
  54. /package/dist/{migrate-D4VKAKYT.js.map → migrate-TQ5PB2DI.js.map} +0 -0
  55. /package/dist/{orchestrator-ZPRGVDCB.js.map → orchestrator-P7AEWVYR.js.map} +0 -0
  56. /package/dist/{pool-UTXQJJ5C.js.map → pool-2T6TVS2L.js.map} +0 -0
  57. /package/dist/{snapshot-K5VHETTK.js.map → snapshot-F5B2DD56.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,33 +1,44 @@
1
1
  import {
2
+ EXCERPT_HEADER,
3
+ appendExcerpt,
2
4
  createPathGuard,
3
5
  deepMerge,
4
6
  describeInstall,
7
+ excerptFilePath,
5
8
  installBundledPreset,
6
9
  loadPolicy,
10
+ readExcerpts,
11
+ recentExcerpts,
12
+ removeExcerpt,
7
13
  updateUserPolicy,
8
14
  userPresetRoot
9
- } from "./chunk-XYYEJK3W.js";
15
+ } from "./chunk-IFRMKVIC.js";
10
16
  import {
11
17
  addBinding,
12
18
  loadBindings,
13
19
  removeBinding
14
- } from "./chunk-TY6UP74X.js";
20
+ } from "./chunk-3DNGY4DS.js";
15
21
  import {
16
22
  StatusReader,
17
23
  applyHeartbeatInterval,
18
24
  buildDigest,
19
25
  buildSeedReportTool,
26
+ clearNote,
20
27
  getLastBeat,
21
28
  homeSessionId,
22
29
  inQuietHours,
30
+ notepadFilePath,
31
+ notepadView,
32
+ readNotepad,
23
33
  readSentState,
24
34
  readStatus,
25
35
  reportFilePath,
26
36
  resetHomeSession,
27
37
  sessionEventCount,
28
38
  sessionEvents,
29
- startOrchestrator
30
- } from "./chunk-TRO4E6WG.js";
39
+ startOrchestrator,
40
+ writeNote
41
+ } from "./chunk-6MVKWICX.js";
31
42
  import {
32
43
  appendEntry,
33
44
  ledgerFilePath,
@@ -36,7 +47,7 @@ import {
36
47
  readLedger,
37
48
  readWeeklyReport,
38
49
  scanPending
39
- } from "./chunk-WLZSABBH.js";
50
+ } from "./chunk-6XM6KY7M.js";
40
51
  import {
41
52
  getRuntime,
42
53
  setRuntime
@@ -49,889 +60,26 @@ import {
49
60
  loadPool,
50
61
  restoreSeed,
51
62
  seedsFilePath
52
- } from "./chunk-JDH2LDFS.js";
53
- import "./chunk-3MDBU6WY.js";
54
- import "./chunk-IV2ZWQA3.js";
55
- import "./chunk-KB5SMG3F.js";
63
+ } from "./chunk-TVX4HV4Y.js";
64
+ import "./chunk-DZ7YCFGX.js";
65
+ import "./chunk-DC5HMCJC.js";
56
66
  import {
57
67
  appendAuditLine,
58
68
  loadProfile,
59
69
  profileFilePath
60
- } from "./chunk-CUOSICYJ.js";
70
+ } from "./chunk-544QOJN5.js";
61
71
  import {
72
+ dshHomeDir,
62
73
  initWorkspace,
63
74
  writeText
64
- } from "./chunk-K5Y6JP2B.js";
75
+ } from "./chunk-AKIJ4LS2.js";
65
76
  import {
66
77
  atomicWriteFileSync,
67
78
  atomicWriteJsonSync
68
- } from "./chunk-WRUTATW4.js";
79
+ } from "./chunk-IBBAISSW.js";
69
80
 
70
- // node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
71
- function isNullable(value) {
72
- return value === null || value === void 0;
73
- }
74
- function isPlainObject(data) {
75
- return data && typeof data === "object" && !Array.isArray(data);
76
- }
77
- function filterKeys(object, filter) {
78
- return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
79
- }
80
- function mapValues(object, transform) {
81
- return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
82
- }
83
- function pick(source, keys, forced) {
84
- if (!keys) return { ...source };
85
- const result = {};
86
- for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
87
- return result;
88
- }
89
- var write = /* @__PURE__ */ Symbol.for("cosmokit.volatile.write");
90
- function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
91
- if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
92
- if (value === null || typeof value !== "object") return value;
93
- if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
94
- ancestors.add(value);
95
- try {
96
- if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
97
- if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
98
- return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
99
- } finally {
100
- ancestors.delete(value);
101
- }
102
- }
103
- function createVolatile(value) {
104
- let current = snapshot(value);
105
- return Object.freeze({
106
- get: () => current,
107
- [write]: (value2) => {
108
- current = value2;
109
- }
110
- });
111
- }
112
- function isVolatile(value) {
113
- return typeof value === "object" && value !== null && write in value;
114
- }
115
- function is(type, value) {
116
- if (arguments.length === 1) return (value2) => is(type, value2);
117
- return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
118
- }
119
- function isArrayBufferLike(value) {
120
- return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
121
- }
122
- function isArrayBufferSource(value) {
123
- return isArrayBufferLike(value) || ArrayBuffer.isView(value);
124
- }
125
- var Binary;
126
- (function(Binary2) {
127
- Binary2.is = isArrayBufferLike;
128
- Binary2.isSource = isArrayBufferSource;
129
- function fromSource(source) {
130
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
131
- else return source;
132
- }
133
- Binary2.fromSource = fromSource;
134
- function toBase64(source) {
135
- source = fromSource(source);
136
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
137
- let binary = "";
138
- const bytes = new Uint8Array(source);
139
- for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
140
- return btoa(binary);
141
- }
142
- Binary2.toBase64 = toBase64;
143
- function fromBase64(source) {
144
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
145
- return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
146
- }
147
- Binary2.fromBase64 = fromBase64;
148
- function toHex(source) {
149
- source = fromSource(source);
150
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
151
- return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
152
- }
153
- Binary2.toHex = toHex;
154
- function fromHex(source) {
155
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
156
- const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
157
- const buffer = [];
158
- for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
159
- return Uint8Array.from(buffer).buffer;
160
- }
161
- Binary2.fromHex = fromHex;
162
- })(Binary || (Binary = {}));
163
- var base64ToArrayBuffer = Binary.fromBase64;
164
- var arrayBufferToBase64 = Binary.toBase64;
165
- var hexToArrayBuffer = Binary.fromHex;
166
- var arrayBufferToHex = Binary.toHex;
167
- function clone(source, refs = /* @__PURE__ */ new Map()) {
168
- if (!source || typeof source !== "object") return source;
169
- if (is("Date", source)) return new Date(source.valueOf());
170
- if (is("RegExp", source)) return new RegExp(source.source, source.flags);
171
- if (isArrayBufferLike(source)) return source.slice(0);
172
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
173
- const cached = refs.get(source);
174
- if (cached) return cached;
175
- if (Array.isArray(source)) {
176
- const result2 = [];
177
- refs.set(source, result2);
178
- source.forEach((value, index) => {
179
- result2[index] = Reflect.apply(clone, null, [value, refs]);
180
- });
181
- return result2;
182
- }
183
- const result = Object.create(Object.getPrototypeOf(source));
184
- refs.set(source, result);
185
- for (const key of Reflect.ownKeys(source)) {
186
- const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
187
- if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
188
- Reflect.defineProperty(result, key, descriptor);
189
- }
190
- return result;
191
- }
192
- function deepEqual(a, b, strict) {
193
- const ancestors = /* @__PURE__ */ new Set();
194
- function compare(a2, b2) {
195
- if (a2 === b2) return true;
196
- if (isVolatile(a2) || isVolatile(b2)) return isVolatile(a2) && isVolatile(b2);
197
- if (!strict && isNullable(a2) && isNullable(b2)) return true;
198
- if (typeof a2 !== typeof b2 || typeof a2 !== "object" || !a2 || !b2) return false;
199
- if (ancestors.has(a2)) return false;
200
- function check(test, then) {
201
- return test(a2) ? test(b2) ? then(a2, b2) : false : test(b2) ? false : void 0;
202
- }
203
- ancestors.add(a2);
204
- try {
205
- return check(Array.isArray, (a3, b3) => {
206
- if (a3.length !== b3.length) return false;
207
- for (let index = 0; index < a3.length; index++) if (!compare(a3[index], b3[index])) return false;
208
- return true;
209
- }) ?? check(is("Date"), (a3, b3) => a3.valueOf() === b3.valueOf()) ?? check(is("URL"), (a3, b3) => a3.href === b3.href) ?? check(is("RegExp"), (a3, b3) => a3.source === b3.source && a3.flags === b3.flags) ?? check(isArrayBufferLike, (a3, b3) => {
210
- if (a3.byteLength !== b3.byteLength) return false;
211
- const viewA = new Uint8Array(a3);
212
- const viewB = new Uint8Array(b3);
213
- for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
214
- return true;
215
- }) ?? ((!strict || [a2, b2].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
216
- ...a2,
217
- ...b2
218
- }).every((key) => compare(a2[key], b2[key])));
219
- } finally {
220
- ancestors.delete(a2);
221
- }
222
- }
223
- return compare(a, b);
224
- }
225
- var Time;
226
- (function(Time2) {
227
- Time2.millisecond = 1;
228
- Time2.second = 1e3;
229
- Time2.minute = Time2.second * 60;
230
- Time2.hour = Time2.minute * 60;
231
- Time2.day = Time2.hour * 24;
232
- Time2.week = Time2.day * 7;
233
- let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
234
- function setTimezoneOffset(offset) {
235
- timezoneOffset = offset;
236
- }
237
- Time2.setTimezoneOffset = setTimezoneOffset;
238
- function getTimezoneOffset() {
239
- return timezoneOffset;
240
- }
241
- Time2.getTimezoneOffset = getTimezoneOffset;
242
- function getDateNumber(date2 = /* @__PURE__ */ new Date(), offset) {
243
- if (typeof date2 === "number") date2 = new Date(date2);
244
- if (offset === void 0) offset = timezoneOffset;
245
- return Math.floor((date2.valueOf() / Time2.minute - offset) / 1440);
246
- }
247
- Time2.getDateNumber = getDateNumber;
248
- function fromDateNumber(value, offset) {
249
- const date2 = new Date(value * Time2.day);
250
- if (offset === void 0) offset = timezoneOffset;
251
- return new Date(+date2 + offset * Time2.minute);
252
- }
253
- Time2.fromDateNumber = fromDateNumber;
254
- const numeric = /\d+(?:\.\d+)?/.source;
255
- const timeRegExp = new RegExp(`^${[
256
- "w(?:eek(?:s)?)?",
257
- "d(?:ay(?:s)?)?",
258
- "h(?:our(?:s)?)?",
259
- "m(?:in(?:ute)?(?:s)?)?",
260
- "s(?:ec(?:ond)?(?:s)?)?"
261
- ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
262
- function parseTime(source) {
263
- const capture = timeRegExp.exec(source);
264
- if (!capture) return 0;
265
- 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);
266
- }
267
- Time2.parseTime = parseTime;
268
- function parseDate(date2) {
269
- const parsed = parseTime(date2);
270
- if (parsed) date2 = Date.now() + parsed;
271
- else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date2}`;
272
- else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date2)) date2 = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date2}`;
273
- return date2 ? new Date(date2) : /* @__PURE__ */ new Date();
274
- }
275
- Time2.parseDate = parseDate;
276
- function format(ms) {
277
- const abs = Math.abs(ms);
278
- if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d";
279
- else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h";
280
- else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m";
281
- else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s";
282
- return ms + "ms";
283
- }
284
- Time2.format = format;
285
- function toDigits(source, length = 2) {
286
- return source.toString().padStart(length, "0");
287
- }
288
- Time2.toDigits = toDigits;
289
- function template(template2, time = /* @__PURE__ */ new Date()) {
290
- 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));
291
- }
292
- Time2.template = template;
293
- })(Time || (Time = {}));
294
-
295
- // node_modules/.pnpm/@deepseek-ai+schemastery@3.18.4/node_modules/@deepseek-ai/schemastery/lib/index.mjs
296
- var kSchema = /* @__PURE__ */ Symbol.for("schemastery");
297
- var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError");
298
- globalThis.__schemastery_index__ ??= 0;
299
- globalThis.__schemastery_refs__ = void 0;
300
- var ValidationError = class extends TypeError {
301
- options;
302
- name = "ValidationError";
303
- constructor(message, options) {
304
- let prefix = "$";
305
- for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
306
- else if (typeof segment === "number") prefix += "[" + segment + "]";
307
- else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
308
- if (prefix.startsWith(".")) prefix = prefix.slice(1);
309
- super((prefix === "$" ? "" : `${prefix} `) + message);
310
- this.options = options;
311
- }
312
- static is(error) {
313
- return !!error?.[kValidationError];
314
- }
315
- };
316
- Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
317
- var Schema = function(options) {
318
- const schema = function(data, options2 = {}) {
319
- return Schema.resolve(data, schema, options2)[0];
320
- };
321
- if (options.refs) {
322
- const refs = mapValues(options.refs, (options2) => new Schema(options2));
323
- const getRef = (uid) => refs[uid];
324
- for (const key in refs) {
325
- const options2 = refs[key];
326
- options2.sKey = getRef(options2.sKey);
327
- options2.inner = getRef(options2.inner);
328
- options2.list = options2.list && options2.list.map(getRef);
329
- options2.dict = options2.dict && mapValues(options2.dict, getRef);
330
- }
331
- return refs[options.uid];
332
- }
333
- Object.assign(schema, options);
334
- if (typeof schema.callback === "string") try {
335
- schema.callback = new Function("return " + schema.callback)();
336
- } catch {
337
- }
338
- Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
339
- Object.setPrototypeOf(schema, Schema.prototype);
340
- schema.meta ||= {};
341
- schema.toString = schema.toString.bind(schema);
342
- return schema;
343
- };
344
- Schema.prototype = Object.create(Function.prototype);
345
- Schema.prototype[kSchema] = true;
346
- Object.defineProperty(Schema.prototype, "~standard", { get() {
347
- return {
348
- version: 1,
349
- vendor: "schemastery",
350
- validate: (value) => {
351
- try {
352
- return { value: Schema.resolve(value, this, {})[0] };
353
- } catch (error) {
354
- if (ValidationError.is(error)) return { issues: [{
355
- message: error.message,
356
- path: error.options.path
357
- }] };
358
- throw error;
359
- }
360
- }
361
- };
362
- } });
363
- Schema.ValidationError = ValidationError;
364
- Schema.prototype.toJSON = function toJSON() {
365
- if (globalThis.__schemastery_refs__) {
366
- globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
367
- return this.uid;
368
- }
369
- globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
370
- globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
371
- const result = {
372
- uid: this.uid,
373
- refs: globalThis.__schemastery_refs__
374
- };
375
- globalThis.__schemastery_refs__ = void 0;
376
- return result;
377
- };
378
- Schema.prototype.set = function set(key, value) {
379
- this.dict[key] = value;
380
- return this;
381
- };
382
- Schema.prototype.push = function push(value) {
383
- this.list.push(value);
384
- return this;
385
- };
386
- function mergeDesc(original, messages) {
387
- const result = typeof original === "string" ? { "": original } : { ...original };
388
- for (const locale in messages) {
389
- const value = messages[locale];
390
- if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
391
- else if (typeof value === "string") result[locale] = value;
392
- }
393
- return result;
394
- }
395
- function getInner(value) {
396
- return value?.$value ?? value?.$inner;
397
- }
398
- function extractKeys(data) {
399
- return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
400
- }
401
- Schema.prototype.i18n = function i18n(messages) {
402
- const schema = Schema(this);
403
- const desc = mergeDesc(schema.meta.description, messages);
404
- if (Object.keys(desc).length) schema.meta.description = desc;
405
- if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
406
- return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
407
- });
408
- if (schema.list) schema.list = schema.list.map((inner, index) => {
409
- return inner.i18n(mapValues(messages, (data = {}) => {
410
- if (Array.isArray(getInner(data))) return getInner(data)[index];
411
- if (Array.isArray(data)) return data[index];
412
- return extractKeys(data);
413
- }));
414
- });
415
- if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
416
- if (getInner(data)) return getInner(data);
417
- return extractKeys(data);
418
- }));
419
- if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
420
- return schema;
421
- };
422
- Schema.prototype.extra = function extra(key, value) {
423
- const schema = Schema(this);
424
- schema.meta = {
425
- ...schema.meta,
426
- [key]: value
427
- };
428
- return schema;
429
- };
430
- for (const key of [
431
- "required",
432
- "disabled",
433
- "collapse",
434
- "hidden",
435
- "loose"
436
- ]) Object.assign(Schema.prototype, { [key](value = true) {
437
- const schema = Schema(this);
438
- schema.meta = {
439
- ...schema.meta,
440
- [key]: value
441
- };
442
- return schema;
443
- } });
444
- Schema.prototype.deprecated = function deprecated() {
445
- const schema = Schema(this);
446
- schema.meta.badges ||= [];
447
- schema.meta.badges.push({
448
- text: "deprecated",
449
- type: "danger"
450
- });
451
- return schema;
452
- };
453
- Schema.prototype.experimental = function experimental() {
454
- const schema = Schema(this);
455
- schema.meta.badges ||= [];
456
- schema.meta.badges.push({
457
- text: "experimental",
458
- type: "warning"
459
- });
460
- return schema;
461
- };
462
- Schema.prototype.pattern = function pattern(regexp) {
463
- const schema = Schema(this);
464
- const pattern2 = pick(regexp, ["source", "flags"]);
465
- schema.meta = {
466
- ...schema.meta,
467
- pattern: pattern2
468
- };
469
- return schema;
470
- };
471
- Schema.prototype.simplify = function simplify(value) {
472
- if (isVolatile(value)) value = value.get();
473
- if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
474
- if (isNullable(value)) return value;
475
- if (this.type === "object" || this.type === "dict") {
476
- const result = {};
477
- for (const key in value) {
478
- const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
479
- if (this.type === "dict" || !isNullable(item)) result[key] = item;
480
- }
481
- if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
482
- return result;
483
- } else if (this.type === "array" || this.type === "tuple") {
484
- const result = [];
485
- value.forEach((value2, index) => {
486
- const schema = this.type === "array" ? this.inner : this.list[index];
487
- const item = schema ? schema.simplify(value2) : value2;
488
- result.push(item);
489
- });
490
- return result;
491
- } else if (this.type === "intersect") {
492
- const result = {};
493
- for (const item of this.list) Object.assign(result, item.simplify(value));
494
- return result;
495
- } else if (this.type === "union") for (const schema of this.list) try {
496
- Schema.resolve(value, schema, {});
497
- return schema.simplify(value);
498
- } catch {
499
- }
500
- return value;
501
- };
502
- Schema.prototype.toString = function toString(inline) {
503
- return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
504
- };
505
- Schema.prototype.role = function role(role, extra2) {
506
- const schema = Schema(this);
507
- schema.meta = {
508
- ...schema.meta,
509
- role,
510
- extra: extra2
511
- };
512
- return schema;
513
- };
514
- for (const key of [
515
- "default",
516
- "link",
517
- "comment",
518
- "description",
519
- "max",
520
- "min",
521
- "step"
522
- ]) Object.assign(Schema.prototype, { [key](value) {
523
- const schema = Schema(this);
524
- schema.meta = {
525
- ...schema.meta,
526
- [key]: value
527
- };
528
- return schema;
529
- } });
530
- Schema.prototype.volatile = function volatile() {
531
- if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
532
- return this.extra("volatile", true);
533
- };
534
- var resolvers = {};
535
- var checkedVolatile = /* @__PURE__ */ Symbol("checked-volatile-schema");
536
- function validateVolatileSchema(schema, path5 = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
537
- const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
538
- if (states.has(blocked)) return;
539
- states.add(blocked);
540
- seen.set(schema, states);
541
- if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path: path5 });
542
- const nested = blocked || !!schema.meta?.volatile;
543
- if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path5, key], nested, seen);
544
- if (schema.sKey) validateVolatileSchema(schema.sKey, [...path5, "<key>"], true, seen);
545
- if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path5, "*"], true, seen);
546
- if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path5, String(index)], true, seen);
547
- }
548
- Schema.extend = function extend(type, resolve2) {
549
- resolvers[type] = resolve2;
550
- };
551
- Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
552
- if (!schema) return [data];
553
- if (!options[checkedVolatile]) {
554
- validateVolatileSchema(schema, options.path);
555
- options = {
556
- ...options,
557
- [checkedVolatile]: true
558
- };
559
- }
560
- if (schema.meta?.volatile) {
561
- const inner = Schema(schema);
562
- inner.meta = {
563
- ...schema.meta,
564
- volatile: false
565
- };
566
- const [value, adapted] = Schema.resolve(data, inner, options, strict);
567
- try {
568
- return [createVolatile(value), adapted];
569
- } catch (error) {
570
- throw new ValidationError(error instanceof Error ? error.message : String(error), options);
571
- }
572
- }
573
- if (options.ignore?.(data, schema)) return [data];
574
- if (isNullable(data) && schema.type !== "lazy") {
575
- if (schema.meta.required) throw new ValidationError(`missing required value`, options);
576
- let current = schema;
577
- let fallback = schema.meta.default;
578
- while (current?.type === "intersect" && isNullable(fallback)) {
579
- current = current.list[0];
580
- fallback = current?.meta.default;
581
- }
582
- if (isNullable(fallback)) return [data];
583
- data = clone(fallback);
584
- }
585
- const callback = resolvers[schema.type];
586
- if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
587
- try {
588
- return callback(data, schema, options, strict);
589
- } catch (error) {
590
- if (!schema.meta.loose) throw error;
591
- return [schema.meta.default];
592
- }
593
- };
594
- Schema.from = function from(source) {
595
- if (isNullable(source)) return Schema.any();
596
- else if ([
597
- "string",
598
- "number",
599
- "boolean"
600
- ].includes(typeof source)) return Schema.const(source).required();
601
- else if (source[kSchema]) return source;
602
- else if (typeof source === "function") switch (source) {
603
- case String:
604
- return Schema.string().required();
605
- case Number:
606
- return Schema.number().required();
607
- case Boolean:
608
- return Schema.boolean().required();
609
- case Function:
610
- return Schema.function().required();
611
- default:
612
- return Schema.is(source).required();
613
- }
614
- else throw new TypeError(`cannot infer schema from ${source}`);
615
- };
616
- Schema.lazy = function lazy(builder) {
617
- const toJSON2 = () => {
618
- if (!schema.inner[kSchema]) {
619
- schema.inner = schema.builder();
620
- schema.inner.meta = {
621
- ...schema.meta,
622
- ...schema.inner.meta
623
- };
624
- }
625
- return schema.inner.toJSON();
626
- };
627
- const schema = new Schema({
628
- type: "lazy",
629
- builder,
630
- inner: { toJSON: toJSON2 }
631
- });
632
- return schema;
633
- };
634
- Schema.natural = function natural() {
635
- return Schema.number().step(1).min(0);
636
- };
637
- Schema.percent = function percent() {
638
- return Schema.number().step(0.01).min(0).max(1).role("slider");
639
- };
640
- Schema.date = function date() {
641
- return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
642
- const date2 = new Date(value);
643
- if (isNaN(+date2)) throw new ValidationError(`invalid date "${value}"`, options);
644
- return date2;
645
- }, true)]);
646
- };
647
- Schema.regExp = function regExp(flag = "") {
648
- return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
649
- try {
650
- return new RegExp(value, flag);
651
- } catch (e) {
652
- throw new ValidationError(e.message, options);
653
- }
654
- }, true)]);
655
- };
656
- Schema.arrayBuffer = function arrayBuffer(encoding) {
657
- return Schema.union([
658
- Schema.is(ArrayBuffer),
659
- Schema.is(SharedArrayBuffer),
660
- Schema.transform(Schema.any(), (value, options) => {
661
- if (Binary.isSource(value)) return Binary.fromSource(value);
662
- throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
663
- }, true),
664
- ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
665
- try {
666
- return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
667
- } catch (e) {
668
- throw new ValidationError(e.message, options);
669
- }
670
- }, true)] : []
671
- ]);
672
- };
673
- Schema.extend("lazy", (data, schema, options, strict) => {
674
- if (!schema.inner[kSchema]) {
675
- schema.inner = schema.builder();
676
- schema.inner.meta = {
677
- ...schema.meta,
678
- ...schema.inner.meta
679
- };
680
- validateVolatileSchema(schema.inner, options.path, true);
681
- }
682
- return Schema.resolve(data, schema.inner, options, strict);
683
- });
684
- Schema.extend("any", (data) => {
685
- return [data];
686
- });
687
- Schema.extend("never", (data, _, options) => {
688
- throw new ValidationError(`expected nullable but got ${data}`, options);
689
- });
690
- Schema.extend("const", (data, { value }, options) => {
691
- if (deepEqual(data, value)) return [value];
692
- throw new ValidationError(`expected ${value} but got ${data}`, options);
693
- });
694
- function checkWithinRange(data, meta, description, options, skipMin = false) {
695
- const { max = Infinity, min = -Infinity } = meta;
696
- if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
697
- if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
698
- }
699
- Schema.extend("string", (data, { meta }, options) => {
700
- if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
701
- if (meta.pattern) {
702
- const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
703
- if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
704
- }
705
- checkWithinRange(data.length, meta, "string length", options);
706
- return [data];
707
- });
708
- function decimalShift(data, digits) {
709
- const str = data.toString();
710
- if (str.includes("e")) return data * Math.pow(10, digits);
711
- const index = str.indexOf(".");
712
- if (index === -1) return data * Math.pow(10, digits);
713
- const frac = str.slice(index + 1);
714
- const integer = str.slice(0, index);
715
- if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
716
- return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
717
- }
718
- function isMultipleOf(data, min, step) {
719
- step = Math.abs(step);
720
- if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
721
- const index = step.toString().indexOf(".");
722
- const digits = step.toString().slice(index + 1).length;
723
- return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
724
- }
725
- Schema.extend("number", (data, { meta }, options) => {
726
- if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
727
- checkWithinRange(data, meta, "number", options);
728
- const { step } = meta;
729
- if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
730
- return [data];
731
- });
732
- Schema.extend("boolean", (data, _, options) => {
733
- if (typeof data === "boolean") return [data];
734
- throw new ValidationError(`expected boolean but got ${data}`, options);
735
- });
736
- Schema.extend("bitset", (data, { bits, meta }, options) => {
737
- let value = 0, keys = [];
738
- if (typeof data === "number") {
739
- value = data;
740
- for (const key in bits) if (data & bits[key]) keys.push(key);
741
- } else if (Array.isArray(data)) {
742
- keys = data;
743
- for (const key of keys) {
744
- if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
745
- if (key in bits) value |= bits[key];
746
- }
747
- } else throw new ValidationError(`expected number or array but got ${data}`, options);
748
- if (value === meta.default) return [value];
749
- return [value, keys];
750
- });
751
- Schema.extend("function", (data, _, options) => {
752
- if (typeof data === "function") return [data];
753
- throw new ValidationError(`expected function but got ${data}`, options);
754
- });
755
- Schema.extend("is", (data, { constructor }, options) => {
756
- if (typeof constructor === "function") {
757
- if (data instanceof constructor) return [data];
758
- throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
759
- } else {
760
- if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
761
- let prototype = Object.getPrototypeOf(data);
762
- while (prototype) {
763
- if (prototype.constructor?.name === constructor) return [data];
764
- prototype = Object.getPrototypeOf(prototype);
765
- }
766
- throw new ValidationError(`expected ${constructor} but got ${data}`, options);
767
- }
768
- });
769
- function property(data, key, schema, options) {
770
- try {
771
- const [value, adapted] = Schema.resolve(data[key], schema, {
772
- ...options,
773
- path: [...options.path || [], key]
774
- });
775
- if (adapted !== void 0) data[key] = adapted;
776
- return value;
777
- } catch (e) {
778
- if (!options?.autofix) throw e;
779
- delete data[key];
780
- return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
781
- }
782
- }
783
- Schema.extend("array", (data, { inner, meta }, options) => {
784
- if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
785
- checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
786
- return [data.map((_, index) => property(data, index, inner, options))];
787
- });
788
- Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
789
- if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
790
- const result = {};
791
- for (const key in data) {
792
- let rKey;
793
- try {
794
- rKey = Schema.resolve(key, sKey, options)[0];
795
- } catch (error) {
796
- if (strict) continue;
797
- throw error;
798
- }
799
- result[rKey] = property(data, key, inner, options);
800
- data[rKey] = data[key];
801
- if (key !== rKey) delete data[key];
802
- }
803
- return [result];
804
- });
805
- Schema.extend("tuple", (data, { list }, options, strict) => {
806
- if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
807
- const result = list.map((inner, index) => property(data, index, inner, options));
808
- if (strict) return [result];
809
- result.push(...data.slice(list.length));
810
- return [result];
811
- });
812
- function merge(result, data) {
813
- for (const key in data) {
814
- if (key in result) continue;
815
- result[key] = data[key];
816
- }
817
- }
818
- Schema.extend("object", (data, { dict }, options, strict) => {
819
- if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
820
- const result = {};
821
- for (const key in dict) {
822
- const value = property(data, key, dict[key], options);
823
- if (!isNullable(value) || key in data) result[key] = value;
824
- }
825
- if (!strict) merge(result, data);
826
- return [result];
827
- });
828
- Schema.extend("union", (data, { list, toString: toString2 }, options, strict) => {
829
- const messages = [];
830
- for (const inner of list) try {
831
- return Schema.resolve(data, inner, options, strict);
832
- } catch (error) {
833
- messages.push(error);
834
- }
835
- throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
836
- });
837
- Schema.extend("intersect", (data, { list, toString: toString2 }, options, strict) => {
838
- if (!list.length) return [data];
839
- let result;
840
- for (const inner of list) {
841
- const value = Schema.resolve(data, inner, options, true)[0];
842
- if (isNullable(value)) continue;
843
- if (isNullable(result)) result = value;
844
- else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
845
- else if (typeof value === "object") merge(result ??= {}, value);
846
- else if (result !== value) throw new ValidationError(`expected ${toString2()} but got ${JSON.stringify(data)}`, options);
847
- }
848
- if (!strict && isPlainObject(data)) merge(result, data);
849
- return [result];
850
- });
851
- Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
852
- const [result, adapted = data] = Schema.resolve(data, inner, options, true);
853
- if (preserve) return [callback(result)];
854
- else return [callback(result), callback(adapted)];
855
- });
856
- var formatters = {};
857
- function defineMethod(name2, keys, format) {
858
- formatters[name2] = format;
859
- Object.assign(Schema, { [name2](...args) {
860
- const schema = new Schema({ type: name2 });
861
- keys.forEach((key, index) => {
862
- switch (key) {
863
- case "sKey":
864
- schema.sKey = args[index] ?? Schema.string();
865
- break;
866
- case "inner":
867
- schema.inner = Schema.from(args[index]);
868
- break;
869
- case "list":
870
- schema.list = args[index].map(Schema.from);
871
- break;
872
- case "dict":
873
- schema.dict = mapValues(args[index], Schema.from);
874
- break;
875
- case "bits":
876
- schema.bits = {};
877
- for (const key2 in args[index]) {
878
- if (typeof args[index][key2] !== "number") continue;
879
- schema.bits[key2] = args[index][key2];
880
- }
881
- break;
882
- case "callback": {
883
- const callback = schema.callback = args[index];
884
- callback["toJSON"] ||= () => callback.toString();
885
- break;
886
- }
887
- case "constructor": {
888
- const constructor = schema.constructor = args[index];
889
- if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
890
- break;
891
- }
892
- default:
893
- schema[key] = args[index];
894
- }
895
- });
896
- if (name2 === "object" || name2 === "dict") schema.meta.default = {};
897
- else if (name2 === "array" || name2 === "tuple") schema.meta.default = [];
898
- else if (name2 === "bitset") schema.meta.default = 0;
899
- return schema;
900
- } });
901
- }
902
- defineMethod("is", ["constructor"], ({ constructor }) => {
903
- if (typeof constructor === "function") return constructor.name;
904
- else return constructor;
905
- });
906
- defineMethod("any", [], () => "any");
907
- defineMethod("never", [], () => "never");
908
- defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
909
- defineMethod("string", [], () => "string");
910
- defineMethod("number", [], () => "number");
911
- defineMethod("boolean", [], () => "boolean");
912
- defineMethod("bitset", ["bits"], () => "bitset");
913
- defineMethod("function", [], () => "function");
914
- defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
915
- defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
916
- defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
917
- defineMethod("object", ["dict"], ({ dict }) => {
918
- if (Object.keys(dict).length === 0) return "{}";
919
- return `{ ${Object.entries(dict).map(([key, inner]) => {
920
- return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
921
- }).join(", ")} }`;
922
- });
923
- defineMethod("union", ["list"], ({ list }, inline) => {
924
- const result = list.map(({ toString: format }) => format()).join(" | ");
925
- return inline ? `(${result})` : result;
926
- });
927
- defineMethod("intersect", ["list"], ({ list }) => {
928
- return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
929
- });
930
- defineMethod("transform", [
931
- "inner",
932
- "callback",
933
- "preserve"
934
- ], ({ inner }, isInner) => inner.toString(isInner));
81
+ // src/index.ts
82
+ import z from "@deepseek-ai/schemastery";
935
83
 
936
84
  // src/config/ui-config.ts
937
85
  import fs from "fs";
@@ -979,7 +127,6 @@ function saveUiConfig(guard, settingsDir, patch) {
979
127
  // src/rpc.ts
980
128
  import { spawn } from "child_process";
981
129
  import fs4 from "fs";
982
- import os from "os";
983
130
  import path4 from "path";
984
131
 
985
132
  // src/browse/interests-edit.ts
@@ -1208,13 +355,12 @@ ${statusLine}`;
1208
355
 
1209
356
  // src/rpc.ts
1210
357
  var RPC_ROUTE_PATH = "/api/heartbeat";
1211
- var DESTRUCTIVE_ENDPOINTS = /* @__PURE__ */ new Set([
1212
- "seeds.delete",
1213
- "migrate.import",
1214
- "bindings.remove",
1215
- "config.set",
1216
- "profile.export",
1217
- "interests.remove"
358
+ var GATE_SAFE_ENDPOINTS = /* @__PURE__ */ new Set([
359
+ "status",
360
+ "config.get",
361
+ "sessions.list",
362
+ "bindings.get",
363
+ "weekly.list"
1218
364
  ]);
1219
365
  var ok = (value) => ({ ok: true, value });
1220
366
  var err = (code, message) => ({ ok: false, error: { code, message, details: {} } });
@@ -1255,7 +401,7 @@ function loadSessionTitles() {
1255
401
  if (row && typeof row.val === "string" && row.val && !titles[id]) titles[id] = row.val;
1256
402
  };
1257
403
  try {
1258
- const dir = path4.join(os.homedir(), ".dsh", "storages", "session_projcache", "sessions");
404
+ const dir = path4.join(dshHomeDir(), "storages", "session_projcache", "sessions");
1259
405
  for (const file of fs4.readdirSync(dir)) {
1260
406
  if (!file.endsWith(".json")) continue;
1261
407
  const id = file.slice(0, -".json".length);
@@ -1269,7 +415,7 @@ function loadSessionTitles() {
1269
415
  } catch {
1270
416
  }
1271
417
  try {
1272
- const raw = JSON.parse(fs4.readFileSync(path4.join(os.homedir(), ".dsh", "storages", "session_projcache.json"), "utf8"));
418
+ const raw = JSON.parse(fs4.readFileSync(path4.join(dshHomeDir(), "storages", "session_projcache.json"), "utf8"));
1273
419
  const walk = (node) => {
1274
420
  if (!node || typeof node !== "object") return;
1275
421
  for (const [key, value] of Object.entries(node)) {
@@ -1287,7 +433,7 @@ function loadSessionTitles() {
1287
433
  }
1288
434
  function loadVisibleSessionIds(registryFile) {
1289
435
  try {
1290
- const file = registryFile ?? path4.join(os.homedir(), ".dsh", "storages", "workspace.json");
436
+ const file = registryFile ?? path4.join(dshHomeDir(), "storages", "workspace.json");
1291
437
  const j = JSON.parse(fs4.readFileSync(file, "utf8"));
1292
438
  const archived = new Set(
1293
439
  (Array.isArray(j.global?.archivedSessionIds) ? j.global.archivedSessionIds : []).map((s) => String(s))
@@ -1347,7 +493,7 @@ function buildEndpoints(deps, isLive) {
1347
493
  });
1348
494
  },
1349
495
  "sessions.list"() {
1350
- const root = path4.join(os.homedir(), ".dsh", "sessions");
496
+ const root = path4.join(dshHomeDir(), "sessions");
1351
497
  const bindings = loadBindings(guard, paths.settingsDir).bindings;
1352
498
  const home = homeSessionId(guard, paths);
1353
499
  const titles = loadSessionTitles();
@@ -1500,6 +646,12 @@ function buildEndpoints(deps, isLive) {
1500
646
  spawn("cmd", ["/c", "start", "", f], { detached: true, stdio: "ignore" }).unref();
1501
647
  return ok({ path: f });
1502
648
  },
649
+ "excerpt.open"() {
650
+ const f = excerptFilePath(paths.dataDir);
651
+ if (!fs4.existsSync(guard.assert(f))) fs4.writeFileSync(f, EXCERPT_HEADER, "utf8");
652
+ spawn("cmd", ["/c", "start", "", f], { detached: true, stdio: "ignore" }).unref();
653
+ return ok({ path: f });
654
+ },
1503
655
  "weekly.list": () => ok({ reports: listWeeklyReports(guard, paths.dataDir, policy.weekly.keepReports) }),
1504
656
  "weekly.get"(p) {
1505
657
  const file = String(p.file ?? "");
@@ -1510,7 +662,7 @@ function buildEndpoints(deps, isLive) {
1510
662
  async "migrate.export"(p) {
1511
663
  const passphrase = String(p.passphrase ?? "");
1512
664
  if (!passphrase) return err("bad-request", "\u9700\u8981\u8BBE\u7F6E\u53E3\u4EE4");
1513
- const { collectMigrationEntries, encryptContainer } = await import("./migrate-D4VKAKYT.js");
665
+ const { collectMigrationEntries, encryptContainer } = await import("./migrate-TQ5PB2DI.js");
1514
666
  const { entries } = collectMigrationEntries(guard, paths);
1515
667
  if (entries.length === 0) return err("bad-request", "\u6CA1\u6709\u53EF\u6253\u5305\u7684\u8BB0\u5FC6\u6587\u4EF6\uFF08data/ \u662F\u7A7A\u7684\uFF09");
1516
668
  const out = path4.join(paths.exportsDir, `heartbeat-memory-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.hbmig`);
@@ -1522,7 +674,7 @@ function buildEndpoints(deps, isLive) {
1522
674
  const passphrase = String(p.passphrase ?? "");
1523
675
  const file = String(p.file ?? "");
1524
676
  if (!passphrase || !file) return err("bad-request", "\u9700\u8981\u5BB9\u5668\u8DEF\u5F84\u4E0E\u53E3\u4EE4");
1525
- const { decryptContainer, applyMigrationEntries } = await import("./migrate-D4VKAKYT.js");
677
+ const { decryptContainer, applyMigrationEntries } = await import("./migrate-TQ5PB2DI.js");
1526
678
  let text;
1527
679
  try {
1528
680
  text = fs4.readFileSync(file, "utf8");
@@ -1544,6 +696,7 @@ function buildEndpoints(deps, isLive) {
1544
696
  rolledBack: result.rolledBack?.length ?? 0,
1545
697
  error: result.error ?? null
1546
698
  });
699
+ if (result.error) return err("migrate-failed", result.error);
1547
700
  return ok(result);
1548
701
  }
1549
702
  };
@@ -1558,25 +711,25 @@ function installHeartbeatRpc(ctx, deps) {
1558
711
  return false;
1559
712
  }
1560
713
  };
1561
- const endpoints = buildEndpoints(deps, isLive);
714
+ const endpoints = new Map(Object.entries(buildEndpoints(deps, isLive)));
1562
715
  const gate = remoteCtx.connection;
1563
716
  const hostGuarded = typeof gate.admit === "function" || typeof gate.requestRejection === "function";
1564
717
  if (!hostGuarded) {
1565
718
  try {
1566
719
  appendAuditLine(deps.guard.assert(deps.paths.logsDir + "/heartbeat.jsonl"), {
1567
720
  event: "rpc_host_gate_missing",
1568
- detail: "connection.admit/requestRejection absent; destructive endpoints disabled",
1569
- destructive: [...DESTRUCTIVE_ENDPOINTS]
721
+ detail: "connection.admit/requestRejection absent; all but the low-sensitivity read-only verbs are refused (\u2466A)",
722
+ allowed: [...GATE_SAFE_ENDPOINTS]
1570
723
  });
1571
724
  } catch {
1572
725
  }
1573
726
  }
1574
727
  const handler = async (endpoint, payload) => {
1575
728
  const p = payload ?? {};
1576
- const fn = typeof endpoint === "string" ? endpoints[endpoint] : void 0;
729
+ const fn = typeof endpoint === "string" ? endpoints.get(endpoint) : void 0;
1577
730
  if (!fn) return err("bad-request", `unknown endpoint ${JSON.stringify(endpoint)}`);
1578
- if (!hostGuarded && DESTRUCTIVE_ENDPOINTS.has(endpoint)) {
1579
- return err("forbidden", `host gate unavailable; ${endpoint} is refused (H-41)`);
731
+ if (!hostGuarded && !GATE_SAFE_ENDPOINTS.has(endpoint)) {
732
+ return err("forbidden", `host gate unavailable; ${endpoint} is refused (H-41, \u2466A)`);
1580
733
  }
1581
734
  try {
1582
735
  return await fn(p);
@@ -1623,9 +776,9 @@ function supportsInHistory(session) {
1623
776
  const len = sessionEventCount(session);
1624
777
  const hit = capabilityCache.get(key);
1625
778
  if (hit && hit.scannedUpTo === len) return hit.supported;
1626
- const from2 = hit && len >= hit.scannedUpTo ? hit.scannedUpTo : 0;
779
+ const from = hit && len >= hit.scannedUpTo ? hit.scannedUpTo : 0;
1627
780
  let supported = false;
1628
- if (from2 !== 0 && hit) supported = hit.supported;
781
+ if (from !== 0 && hit) supported = hit.supported;
1629
782
  const readTail = (fromSeq) => {
1630
783
  if (typeof session.snapshotEvents === "function") {
1631
784
  try {
@@ -1636,7 +789,7 @@ function supportsInHistory(session) {
1636
789
  }
1637
790
  return sessionEvents(session).slice(fromSeq);
1638
791
  };
1639
- for (const e of readTail(from2)) {
792
+ for (const e of readTail(from)) {
1640
793
  if (e.type === "request/context") {
1641
794
  supported = e.data?.systemPromptUpdate === "in-history";
1642
795
  }
@@ -1741,8 +894,8 @@ async function registerHeartbeatPreset(service, id = "heartbeat", enabled = true
1741
894
  return { action: "skipped-no-api", id };
1742
895
  }
1743
896
  try {
1744
- await registrar.register(heartbeatPresetDefinition(id));
1745
- return { action: "registered", id };
897
+ const disposer = await registrar.register(heartbeatPresetDefinition(id));
898
+ return typeof disposer === "function" ? { action: "registered", id, disposer } : { action: "registered", id };
1746
899
  } catch (e) {
1747
900
  return { action: "error", id, detail: String(e).slice(0, 200) };
1748
901
  }
@@ -1815,44 +968,207 @@ ${items.join("\n")}` : "\u8D26\u672C\u91CC\u6CA1\u6709\u672A\u5B8C\u6210\u4E8B\u
1815
968
  };
1816
969
  }
1817
970
 
971
+ // src/notepad/tool.ts
972
+ var MAX_NOTE_CHARS = 160;
973
+ function clean2(v) {
974
+ return String(v ?? "").replace(/\s+/g, " ").trim().slice(0, MAX_NOTE_CHARS);
975
+ }
976
+ function fmtMinutes(m) {
977
+ if (m < 1) return "\u4E0D\u5230 1 \u5206\u949F";
978
+ if (m < 60) return `${m} \u5206\u949F`;
979
+ const h = Math.floor(m / 60);
980
+ const rest = m % 60;
981
+ return rest > 0 ? `${h} \u5C0F\u65F6 ${rest} \u5206` : `${h} \u5C0F\u65F6`;
982
+ }
983
+ function fmtView(v) {
984
+ const beats = v.beatsAgo === 0 ? "\u672C\u8DF3" : `${v.beatsAgo} \u8DF3\u524D`;
985
+ const wakes = v.wakesAgo === 0 ? "\u8FD8\u6CA1\u88AB\u53EB\u9192\u8FC7" : `\u671F\u95F4\u88AB\u53EB\u9192\u8FC7 ${v.wakesAgo} \u6B21`;
986
+ return `\u5FC3\u4E8B\u5323\u91CC\u73B0\u5728\u6709\uFF1A${v.text}
987
+ \uFF08\u7559\u4E8E${beats}\uFF0C\u5DF2\u6401 ${fmtMinutes(v.sinceMinutes)}\uFF0C${wakes}\uFF09`;
988
+ }
989
+ function buildNotepadTool(guard, file) {
990
+ return {
991
+ name: "notepad",
992
+ description: '\u5FC3\u4E8B\u5323\uFF08\u5FC3\u8DF3\u63D2\u4EF6\u7684"\u7559\u7ED9\u4E0B\u4E00\u8DF3\u7684\u81EA\u5DF1"\u4FBF\u7B7E\uFF09\u3002\u53EA\u6709\u4E00\u683C\uFF1A\u5199\u4E0B\u65B0\u7684\u5C31\u76D6\u6389\u65E7\u7684\u3002\u5F53\u4F60\u6709\u8BDD\u60F3\u7559\u5230\u4E0B\u6B21\u5FC3\u8DF3\u518D\u8BF4\u3001\u6216\u8005\u6709\u4E00\u4EF6\u653E\u4E0D\u4E0B\u7684\u4E8B\u65F6\uFF0C\u7528 action=write \u7559\u4E0B\u4E00\u53E5\u5F15\u5B50\u2014\u2014\u4E0D\u8981\u5199\u6574\u6BB5\uFF0C\u4E0B\u6B21\u8DF3\u7531\u90A3\u65F6\u7684\u4F60\u91CD\u65B0\u5C55\u5F00\u3002\u60F3\u7559\u4F4F\u539F\u6765\u7684\u5C31\u7167\u539F\u6837\u518D\u5199\u4E00\u904D\uFF08\u5B57\u6837\u4E00\u81F4\u7B97\u4FDD\u7559\uFF0C\u5B83\u7684\u5E74\u9F84\u4E0D\u4F1A\u91CD\u7B97\uFF09\uFF1B\u5199\u522B\u7684\u5C31\u662F\u6362\u6389\u5B83\u3002action=read \u770B\u73B0\u5728\u683C\u5B50\u91CC\u662F\u4EC0\u4E48\uFF1Baction=clear \u4E3B\u52A8\u653E\u6389\u3002\u6295\u9012\u5305\u8BFB\u8FC7\u4E4B\u540E\uFF0C\u4EC0\u4E48\u90FD\u4E0D\u505A\u5B83\u5C31\u4E0B\u4E00\u8DF3\u6CA1\u4E86\u3002\u7559\u4E0D\u7559\u90FD\u884C\uFF0C\u6CA1\u8BDD\u5C31\u7A7A\u7740\u3002',
993
+ parameters: {
994
+ type: "object",
995
+ properties: {
996
+ action: {
997
+ type: "string",
998
+ enum: ["write", "read", "clear"],
999
+ description: "write=\u7559\u4E00\u53E5\uFF08\u76D6\u6389\u65E7\u7684\uFF09\uFF0Cread=\u770B\u73B0\u5728\u662F\u4EC0\u4E48\uFF0Cclear=\u4E3B\u52A8\u653E\u6389"
1000
+ },
1001
+ text: {
1002
+ type: "string",
1003
+ description: "action=write \u65F6\u5FC5\u586B\uFF1A\u4E00\u53E5\u5F15\u5B50\uFF08\u4E0D\u662F\u6574\u6BB5\u5FC3\u4E8B\uFF0C\u4E0B\u6B21\u8DF3\u4F60\u81EA\u5DF1\u91CD\u65B0\u5C55\u5F00\uFF09"
1004
+ }
1005
+ },
1006
+ required: ["action"],
1007
+ additionalProperties: false
1008
+ },
1009
+ output: {
1010
+ schema: {
1011
+ type: "object",
1012
+ properties: {
1013
+ ok: { type: "boolean" },
1014
+ message: { type: "string" }
1015
+ },
1016
+ required: ["ok", "message"],
1017
+ additionalProperties: false
1018
+ },
1019
+ render: (_args, value) => {
1020
+ const v = value;
1021
+ return [{ type: "text", text: String(v.message ?? "") }];
1022
+ }
1023
+ },
1024
+ timeoutMs: 5e3,
1025
+ // Read-modify-write on one file, and the note's lifecycle depends on it.
1026
+ isConcurrencySafe: () => false,
1027
+ async execute(args) {
1028
+ const a = args ?? {};
1029
+ const action = String(a.action ?? "");
1030
+ try {
1031
+ if (action === "write") {
1032
+ const text = clean2(a.text);
1033
+ if (!text) return { ok: false, message: "write \u9700\u8981\u975E\u7A7A text\uFF08\u4E00\u53E5\u5F15\u5B50\uFF09" };
1034
+ const { note, kept } = writeNote(guard, file, text);
1035
+ return {
1036
+ ok: true,
1037
+ message: kept ? `\u8FD8\u60E6\u8BB0\u7740\uFF1A${note.text}\uFF08\u5E74\u9F84\u4E0D\u53D8\uFF09` : `\u5DF2\u7559\u4E0B\u5FC3\u4E8B\uFF1A${note.text}`
1038
+ };
1039
+ }
1040
+ if (action === "read") {
1041
+ const v = notepadView(readNotepad(guard, file));
1042
+ return { ok: true, message: v ? fmtView(v) : "\u5FC3\u4E8B\u5323\u662F\u7A7A\u7684" };
1043
+ }
1044
+ if (action === "clear") {
1045
+ const prev = clearNote(guard, file);
1046
+ return prev ? { ok: true, message: `\u5DF2\u653E\u6389\uFF1A${prev.text}` } : { ok: true, message: "\u5FC3\u4E8B\u5323\u672C\u6765\u5C31\u662F\u7A7A\u7684" };
1047
+ }
1048
+ return { ok: false, message: `\u672A\u77E5 action\uFF08${action || "\u7A7A"}\uFF09\uFF0C\u53EA\u8BA4 write / read / clear` };
1049
+ } catch (e) {
1050
+ return { ok: false, message: `\u5FC3\u4E8B\u5323\u8BFB\u5199\u5931\u8D25\uFF1A${String(e).slice(0, 120)}` };
1051
+ }
1052
+ }
1053
+ };
1054
+ }
1055
+
1056
+ // src/excerpt/tool.ts
1057
+ var MAX_TEXT2 = 300;
1058
+ var LIST_LIMIT = 10;
1059
+ function clean3(v) {
1060
+ return String(v ?? "").replace(/\s+/g, " ").trim();
1061
+ }
1062
+ function fmtEntry2(e) {
1063
+ return `#${e.id} ${e.date} ${e.time} ${e.text}`;
1064
+ }
1065
+ function buildExcerptTool(guard, file) {
1066
+ return {
1067
+ name: "excerpt",
1068
+ description: '\u4F60\u81EA\u5DF1\u7684\u6458\u6284\u672C\uFF1A\u7559\u53E5\u5B50\u548C\u5C0F\u4E8B\u7684\u5730\u65B9\u3002\u60F3\u8BF4"\u8FD9\u53E5\u6211\u8981\u8BB0\u4E0B\u6765"\u7684\u65F6\u5019\u7528\u2014\u2014\u4ED6\u8BF4\u8FC7\u7684\u8BDD\u3001\u770B\u5230\u7684\u53E5\u5B50\u3001\u5FC3\u91CC\u8FC7\u4E86\u4E00\u4E0B\u7684\u5C0F\u4E8B\u3002\u5B83\u548C\u8D26\u672C\u3001\u5FC3\u4E8B\u5323\u90FD\u4E0D\u4E00\u6837\uFF1A\u8D26\u672C\u8BB0\u7684\u662F\u5F85\u529E\u548C\u627F\u8BFA\uFF08\u4F1A\u52FE\u6389\uFF09\uFF0C\u5FC3\u4E8B\u5323\u662F\u7559\u7ED9\u4E0B\u4E00\u8DF3\u7684\u4E00\u53E5\u5F15\u5B50\uFF08\u53EA\u6709\u4E00\u683C\u3001\u4F1A\u88AB\u76D6\u6389\uFF09\uFF0C\u6458\u6284\u672C\u53EA\u589E\u4E0D\u51CF\uFF0C\u9664\u975E\u4F60\u4E3B\u52A8 remove\u3002\u5199\u7684\u65F6\u5019\u628A\u8BDD\u539F\u6837\u7559\u4E0B\uFF0C\u4E0D\u7528\u89E3\u91CA\u3002action=add \u6284\u4E00\u6761\uFF08text \u5FC5\u586B\uFF09\uFF1Baction=list \u7FFB\u6700\u8FD1\u5341\u6761\uFF1Baction=remove \u62B9\u6389\u4E00\u6761\uFF08key \u4E3A #id \u6216\u6B63\u6587\u91CC\u7684\u552F\u4E00\u5B50\u4E32\uFF09\u3002',
1069
+ parameters: {
1070
+ type: "object",
1071
+ properties: {
1072
+ action: { type: "string", enum: ["add", "list", "remove"], description: "add=\u6284\u4E00\u6761\uFF0Clist=\u7FFB\u6700\u8FD1\u5341\u6761\uFF0Cremove=\u62B9\u6389\u4E00\u6761" },
1073
+ text: { type: "string", description: "action=add \u65F6\u5FC5\u586B\uFF1A\u8981\u7559\u4E0B\u7684\u90A3\u53E5\u8BDD\u6216\u90A3\u4EF6\u5C0F\u4E8B" },
1074
+ key: { type: "string", description: "action=remove \u65F6\u5FC5\u586B\uFF1A#id \u6216\u6B63\u6587\u91CC\u7684\u552F\u4E00\u5B50\u4E32" }
1075
+ },
1076
+ required: ["action"],
1077
+ additionalProperties: false
1078
+ },
1079
+ output: {
1080
+ schema: {
1081
+ type: "object",
1082
+ properties: {
1083
+ ok: { type: "boolean" },
1084
+ message: { type: "string" }
1085
+ },
1086
+ required: ["ok", "message"],
1087
+ additionalProperties: false
1088
+ },
1089
+ render: (_args, value) => {
1090
+ const v = value;
1091
+ return [{ type: "text", text: String(v.message ?? "") }];
1092
+ }
1093
+ },
1094
+ timeoutMs: 5e3,
1095
+ // Read-modify-write on one file; never parallel.
1096
+ isConcurrencySafe: () => false,
1097
+ async execute(args) {
1098
+ const a = args ?? {};
1099
+ const action = String(a.action ?? "");
1100
+ if (action === "add") {
1101
+ const text = clean3(a.text).slice(0, MAX_TEXT2);
1102
+ if (!text) return { ok: false, message: "add \u9700\u8981\u975E\u7A7A text" };
1103
+ const e = appendExcerpt(guard, file, text);
1104
+ return { ok: true, message: `\u5DF2\u6284\u4E0B ${fmtEntry2(e)}` };
1105
+ }
1106
+ if (action === "remove") {
1107
+ const key = clean3(a.key);
1108
+ if (!key) return { ok: false, message: "remove \u9700\u8981 key\uFF08#id \u6216\u6B63\u6587\u91CC\u7684\u552F\u4E00\u5B50\u4E32\uFF09" };
1109
+ const e = removeExcerpt(guard, file, key);
1110
+ if (!e) return { ok: false, message: `\u6458\u6284\u672C\u91CC\u6CA1\u6709\u5339\u914D\u300C${key}\u300D\u7684\u4E00\u6761\uFF08\u5148\u7528 list \u7FFB\uFF09` };
1111
+ return { ok: true, message: `\u5DF2\u62B9\u6389 ${fmtEntry2(e)}` };
1112
+ }
1113
+ if (action === "list") {
1114
+ const total2 = readExcerpts(guard, file).entries.length;
1115
+ if (total2 === 0) return { ok: true, message: "\u6458\u6284\u672C\u8FD8\u662F\u7A7A\u7684" };
1116
+ const items = recentExcerpts(guard, file, LIST_LIMIT).map(fmtEntry2);
1117
+ return { ok: true, message: `\u6458\u6284\u672C\u5171 ${total2} \u6761\uFF0C\u6700\u8FD1 ${items.length} \u6761\uFF1A
1118
+ ${items.join("\n")}` };
1119
+ }
1120
+ const total = readExcerpts(guard, file).entries.length;
1121
+ return { ok: false, message: `\u672A\u77E5 action\uFF0C\u6458\u6284\u672C\u5171 ${total} \u6761` };
1122
+ }
1123
+ };
1124
+ }
1125
+
1818
1126
  // src/index.ts
1819
1127
  var name = "heartbeat";
1820
1128
  var inject = ["agents", "settings"];
1821
- var Config = Schema.object({
1129
+ var Config = z.object({
1822
1130
  /** Override the runtime data dir (workspace guard boundary). Empty = default (<packageRoot>/data). */
1823
- dataDir: Schema.string().default(""),
1131
+ dataDir: z.string().default(""),
1824
1132
  /** UI-editable: heartbeat interval in minutes. 0 = use policy file / factory. */
1825
- intervalMin: Schema.number().default(0),
1133
+ intervalMin: z.number().default(0),
1826
1134
  /** UI-editable: daily expression cap. 0 = use policy file / factory. */
1827
- maxDailySend: Schema.number().default(0),
1135
+ maxDailySend: z.number().default(0),
1828
1136
  /**
1829
1137
  * Agent preset the heartbeat agent joins (`<dshHome>/.agent-presets/<id>/`).
1830
1138
  * Without a preset the agent is a BARE agent: tools/prompt sections resolve
1831
1139
  * against the empty global layer, so it cannot even see `web_search`.
1832
1140
  */
1833
- agentPreset: Schema.string().default("heartbeat"),
1141
+ agentPreset: z.string().default("heartbeat"),
1834
1142
  /**
1835
1143
  * Install the bundled preset (see `agentPreset`) into the roster's user root
1836
1144
  * on first run, so setup needs no manual file copy. An existing preset is
1837
1145
  * never overwritten; set false to manage the preset entirely by hand.
1838
1146
  */
1839
- installPreset: Schema.boolean().default(true),
1840
- /** Self-built time injection interval (D20, §17.6). 0 disables injection. */
1841
- timeInjectMin: Schema.number().default(25),
1147
+ installPreset: z.boolean().default(true),
1148
+ /** Self-built time injection interval (D20, §17.6). 0 disables injection.
1149
+ * Left OPTIONAL on purpose (2026-10-17): a schema default here is
1150
+ * indistinguishable from an explicit choice, and `applySettingsOverrides`
1151
+ * applies this value over ui.json — so a default would silently undo the
1152
+ * card on every reload. Unset falls back at the refs below. */
1153
+ timeInjectMin: z.number(),
1842
1154
  /** IANA timezone for the injected clock; empty = process zone. */
1843
- timeZone: Schema.string().default(""),
1155
+ timeZone: z.string().default(""),
1844
1156
  /** Statusbar master switch (D19). Off = no section/pre-step status; time injection unaffected. */
1845
- statusbar: Schema.boolean().default(false),
1157
+ statusbar: z.boolean(),
1846
1158
  /** v1.6.3 闲着模式:素材池为空时用画像话题兜底主动搭话(默认关)。 */
1847
- idleMode: Schema.boolean().default(false),
1159
+ idleMode: z.boolean(),
1848
1160
  /** v1.7.0 节省 token 模式:用户离开(闲置 ≥30 分钟)或锁屏时整跳暂停(默认关)。 */
1849
- tokenSaver: Schema.boolean().default(false),
1161
+ tokenSaver: z.boolean(),
1850
1162
  /** v1.8.0 账本工具:向所有日常会话 agent 注册共享账本工具(默认开)。 */
1851
- ledgerTool: Schema.boolean().default(true),
1163
+ ledgerTool: z.boolean().default(true),
1852
1164
  /** v1.9.0 素材报账工具:投递后由陪伴 agent 主动报账(默认开)。 */
1853
- seedReportTool: Schema.boolean().default(true),
1165
+ seedReportTool: z.boolean().default(true),
1166
+ /** v2.0.0 心事匣工具:留给下一跳的一句便签(默认开)。 */
1167
+ notepadTool: z.boolean().default(true),
1168
+ /** v2.0.0 摘抄本工具:留句子和小事的地方(默认开)。 */
1169
+ excerptTool: z.boolean().default(true),
1854
1170
  /** v1.8.0 引擎室追加工具:逗号分隔的全局工具名,存在才加入白名单(bili 压缩工具自动探测,无需手填)。 */
1855
- extraTools: Schema.string().default("")
1171
+ extraTools: z.string().default("")
1856
1172
  });
1857
1173
  function apply(ctx, config = {}) {
1858
1174
  const paths = initWorkspace(config.dataDir ? { dataDir: config.dataDir } : {});
@@ -1892,6 +1208,8 @@ function apply(ctx, config = {}) {
1892
1208
  }
1893
1209
  });
1894
1210
  let presetRegistration;
1211
+ let presetDisposer;
1212
+ let presetDisposed = false;
1895
1213
  ctx.inject(["agentPresets"], (presetCtx) => {
1896
1214
  const service = presetCtx.agentPresets;
1897
1215
  const presetId = config.agentPreset || "heartbeat";
@@ -1905,6 +1223,15 @@ function apply(ctx, config = {}) {
1905
1223
  };
1906
1224
  presetRegistration = registerHeartbeatPreset(service, presetId, installEnabled).then((result2) => {
1907
1225
  audit({ event: "preset_register", ...result2 });
1226
+ if (typeof result2.disposer === "function") {
1227
+ if (presetDisposed) {
1228
+ void Promise.resolve(result2.disposer()).catch((e) => {
1229
+ ctx.logger.warn("heartbeat: preset dispose failed (%s)", String(e).slice(0, 120));
1230
+ });
1231
+ } else {
1232
+ presetDisposer = result2.disposer;
1233
+ }
1234
+ }
1908
1235
  if (result2.action === "error") {
1909
1236
  ctx.logger.warn("heartbeat: preset register failed (%s) \u2014 the engine room runs without it", result2.detail ?? "");
1910
1237
  } else if (result2.action === "registered") {
@@ -1930,7 +1257,7 @@ function apply(ctx, config = {}) {
1930
1257
  });
1931
1258
  let sectionSource = null;
1932
1259
  let timeInjectMinRef = ui.timeInjectMin ?? (config.timeInjectMin ?? 25);
1933
- let statusbarEnabledRef = ui.statusbar ?? config.statusbar !== false;
1260
+ let statusbarEnabledRef = ui.statusbar ?? config.statusbar === true;
1934
1261
  let idleModeRef = ui.idleMode ?? config.idleMode === true;
1935
1262
  let tokenSaverRef = ui.tokenSaver ?? config.tokenSaver === true;
1936
1263
  const applyLiveSettings = (v) => {
@@ -2070,6 +1397,12 @@ function apply(ctx, config = {}) {
2070
1397
  if (config.seedReportTool !== false) {
2071
1398
  registerGlobalTool("seed_report", () => buildSeedReportTool(guard, reportFilePath(paths.dataDir)));
2072
1399
  }
1400
+ if (config.notepadTool !== false) {
1401
+ registerGlobalTool("notepad", () => buildNotepadTool(guard, notepadFilePath(paths.dataDir)));
1402
+ }
1403
+ if (config.excerptTool !== false) {
1404
+ registerGlobalTool("excerpt", () => buildExcerptTool(guard, excerptFilePath(paths.dataDir)));
1405
+ }
2073
1406
  startOrchestrator(deps);
2074
1407
  const statusReader = new StatusReader();
2075
1408
  registerStatusbarSection(ctx, guard, paths, {
@@ -2100,6 +1433,14 @@ function apply(ctx, config = {}) {
2100
1433
  }, "heartbeat: time injection");
2101
1434
  ctx.effect(() => {
2102
1435
  return () => {
1436
+ presetDisposed = true;
1437
+ const undoPreset = presetDisposer;
1438
+ presetDisposer = void 0;
1439
+ if (typeof undoPreset === "function") {
1440
+ void Promise.resolve(undoPreset()).catch((e) => {
1441
+ ctx.logger.warn("heartbeat: preset dispose failed (%s)", String(e).slice(0, 120));
1442
+ });
1443
+ }
2103
1444
  ctx.logger.info("heartbeat: disposed, timers cleaned up");
2104
1445
  };
2105
1446
  }, "heartbeat: lifecycle");