@kanadego/dsh-heartbeat 2.2.1 → 2.4.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 (69) hide show
  1. package/README.md +105 -311
  2. package/USAGE-GUIDE.md +357 -0
  3. package/client.js +186 -24
  4. package/dist/{bili-login-XQVEE4M6.js → bili-login-KDDU63Z2.js} +4 -4
  5. package/dist/{bindings-U2M3CO2D.js → bindings-LTSGGNIH.js} +3 -3
  6. package/dist/{chunk-LQKOYTRL.js → chunk-4OQXAHU5.js} +2 -2
  7. package/dist/{chunk-3QJJRXIR.js → chunk-5CVAW5AS.js} +11 -2
  8. package/dist/chunk-5CVAW5AS.js.map +1 -0
  9. package/dist/{chunk-IBBAISSW.js → chunk-66IUDHCY.js} +50 -1
  10. package/dist/chunk-66IUDHCY.js.map +1 -0
  11. package/dist/{chunk-3DNGY4DS.js → chunk-77UYDI2A.js} +2 -2
  12. package/dist/{chunk-AT32XCCI.js → chunk-AJ5JAQVB.js} +20 -3
  13. package/dist/chunk-AJ5JAQVB.js.map +1 -0
  14. package/dist/chunk-CRRN6UD3.js +389 -0
  15. package/dist/chunk-CRRN6UD3.js.map +1 -0
  16. package/dist/{chunk-ECXYNTEV.js → chunk-ERRPMYKB.js} +164 -152
  17. package/dist/chunk-ERRPMYKB.js.map +1 -0
  18. package/dist/{chunk-M72T5MZU.js → chunk-GOLMRQRW.js} +3 -2
  19. package/dist/{chunk-KZLVR4J7.js → chunk-IPTNSXOY.js} +2 -2
  20. package/dist/chunk-L54R23O2.js +262 -0
  21. package/dist/chunk-L54R23O2.js.map +1 -0
  22. package/dist/chunk-MHRAPKES.js +1081 -0
  23. package/dist/chunk-MHRAPKES.js.map +1 -0
  24. package/dist/{chunk-SIY3YHFY.js → chunk-MMI6OBEC.js} +2 -2
  25. package/dist/{chunk-CJK6RTMH.js → chunk-RPWQZYNW.js} +1485 -310
  26. package/dist/chunk-RPWQZYNW.js.map +1 -0
  27. package/dist/cli/index.js +244 -36
  28. package/dist/cli/index.js.map +1 -1
  29. package/dist/{focus-store-RNHBAFYS.js → focus-store-XGTPIVF6.js} +3 -3
  30. package/dist/{inbox-ZLX2MH7A.js → inbox-7GGEMBUD.js} +4 -4
  31. package/dist/index.d.ts +66 -1
  32. package/dist/index.js +556 -167
  33. package/dist/index.js.map +1 -1
  34. package/dist/{migrate-XFZU5EBE.js → migrate-25F53XIC.js} +6 -4
  35. package/dist/{orchestrator-5BHYQ77Y.js → orchestrator-4PJD7QYO.js} +25 -11
  36. package/dist/runtime-RGZKOFP3.js +15 -0
  37. package/dist/snapshot-J6LKNY57.js +27 -0
  38. package/dist/store-HM6ZMFKS.js +45 -0
  39. package/package.json +6 -3
  40. package/dist/chunk-3QJJRXIR.js.map +0 -1
  41. package/dist/chunk-AT32XCCI.js.map +0 -1
  42. package/dist/chunk-CJK6RTMH.js.map +0 -1
  43. package/dist/chunk-DLOYERAK.js +0 -87
  44. package/dist/chunk-DLOYERAK.js.map +0 -1
  45. package/dist/chunk-ECXYNTEV.js.map +0 -1
  46. package/dist/chunk-F2XVKX55.js +0 -413
  47. package/dist/chunk-F2XVKX55.js.map +0 -1
  48. package/dist/chunk-IBBAISSW.js.map +0 -1
  49. package/dist/chunk-N6SMIGYJ.js +0 -393
  50. package/dist/chunk-N6SMIGYJ.js.map +0 -1
  51. package/dist/chunk-XYBII5PR.js +0 -602
  52. package/dist/chunk-XYBII5PR.js.map +0 -1
  53. package/dist/pool-76VLAZER.js +0 -49
  54. package/dist/runtime-W2OWJIHY.js +0 -11
  55. package/dist/snapshot-SU2VGM4C.js +0 -16
  56. /package/dist/{bili-login-XQVEE4M6.js.map → bili-login-KDDU63Z2.js.map} +0 -0
  57. /package/dist/{bindings-U2M3CO2D.js.map → bindings-LTSGGNIH.js.map} +0 -0
  58. /package/dist/{chunk-LQKOYTRL.js.map → chunk-4OQXAHU5.js.map} +0 -0
  59. /package/dist/{chunk-3DNGY4DS.js.map → chunk-77UYDI2A.js.map} +0 -0
  60. /package/dist/{chunk-M72T5MZU.js.map → chunk-GOLMRQRW.js.map} +0 -0
  61. /package/dist/{chunk-KZLVR4J7.js.map → chunk-IPTNSXOY.js.map} +0 -0
  62. /package/dist/{chunk-SIY3YHFY.js.map → chunk-MMI6OBEC.js.map} +0 -0
  63. /package/dist/{focus-store-RNHBAFYS.js.map → focus-store-XGTPIVF6.js.map} +0 -0
  64. /package/dist/{inbox-ZLX2MH7A.js.map → inbox-7GGEMBUD.js.map} +0 -0
  65. /package/dist/{migrate-XFZU5EBE.js.map → migrate-25F53XIC.js.map} +0 -0
  66. /package/dist/{orchestrator-5BHYQ77Y.js.map → orchestrator-4PJD7QYO.js.map} +0 -0
  67. /package/dist/{pool-76VLAZER.js.map → runtime-RGZKOFP3.js.map} +0 -0
  68. /package/dist/{runtime-W2OWJIHY.js.map → snapshot-J6LKNY57.js.map} +0 -0
  69. /package/dist/{snapshot-SU2VGM4C.js.map → store-HM6ZMFKS.js.map} +0 -0
package/dist/index.js CHANGED
@@ -3,13 +3,17 @@ import {
3
3
  applyHeartbeatInterval,
4
4
  buildDigest,
5
5
  buildSeedReportTool,
6
+ checkDeliverySession,
6
7
  clearNote,
8
+ createProfileTools,
9
+ detachEngineRoomPersonTools,
7
10
  formatFocusClock,
8
11
  getFocusUntil,
9
12
  getLastBeat,
10
13
  homeSessionId,
11
14
  inQuietHours,
12
15
  isArchivedSession,
16
+ isSubagentSession,
13
17
  notepadFilePath,
14
18
  notepadView,
15
19
  parseArchivedSessionIds,
@@ -24,82 +28,94 @@ import {
24
28
  sessionEvents,
25
29
  startOrchestrator,
26
30
  writeNote
27
- } from "./chunk-CJK6RTMH.js";
31
+ } from "./chunk-RPWQZYNW.js";
28
32
  import {
29
33
  bilibiliSessionFilePath,
30
34
  createBiliLoginService,
31
35
  saveBiliSession
32
- } from "./chunk-SIY3YHFY.js";
36
+ } from "./chunk-MMI6OBEC.js";
33
37
  import {
34
38
  EXCERPT_HEADER,
35
39
  appendExcerpt,
36
40
  createPathGuard,
37
- deepMerge,
38
41
  describeInstall,
39
42
  excerptFilePath,
40
43
  installBundledPreset,
41
- loadPolicy,
42
44
  readExcerpts,
43
45
  recentExcerpts,
44
46
  removeExcerpt,
45
- updateUserPolicy,
46
47
  userPresetRoot
47
- } from "./chunk-F2XVKX55.js";
48
+ } from "./chunk-L54R23O2.js";
48
49
  import {
50
+ CORRECTIONS_DONE_HEADER,
51
+ CORRECTIONS_HEADER,
52
+ LEDGER_DONE_HEADER,
53
+ LEDGER_HEADER,
54
+ activeSeeds,
55
+ addSeed,
56
+ appendArchiveLines,
49
57
  appendEntry,
58
+ archiveSeedById,
59
+ archivedSeeds,
60
+ correctionsDoneFilePath,
61
+ correctionsFilePath,
62
+ deleteSeed,
63
+ ledgerDoneFilePath,
50
64
  ledgerFilePath,
51
65
  listWeeklyReports,
52
- localDayKey,
66
+ loadPool,
53
67
  markDone,
68
+ parseLedgerLine,
54
69
  readLedger,
55
70
  readWeeklyReport,
56
- scanPending
57
- } from "./chunk-XYBII5PR.js";
71
+ restoreSeed,
72
+ scanPending,
73
+ seedBookFile,
74
+ seedsFilePath
75
+ } from "./chunk-MHRAPKES.js";
58
76
  import {
59
77
  openPath
60
78
  } from "./chunk-OCBE2AKW.js";
61
79
  import {
80
+ getCurrentDeliveryId,
62
81
  getRuntime,
63
82
  setRuntime
64
- } from "./chunk-3QJJRXIR.js";
83
+ } from "./chunk-5CVAW5AS.js";
65
84
  import {
66
- activeSeeds,
67
- addSeed,
68
- archiveSeedById,
69
- archivedSeeds,
70
- deleteSeed,
71
- loadPool,
72
- restoreSeed,
73
- seedsFilePath
74
- } from "./chunk-N6SMIGYJ.js";
85
+ addBinding,
86
+ loadBindings,
87
+ removeBinding
88
+ } from "./chunk-77UYDI2A.js";
75
89
  import {
76
90
  clearFocusState,
77
91
  readFocusState,
78
92
  writeFocusState
79
- } from "./chunk-LQKOYTRL.js";
80
- import "./chunk-KZLVR4J7.js";
81
- import "./chunk-DLOYERAK.js";
93
+ } from "./chunk-4OQXAHU5.js";
94
+ import "./chunk-IPTNSXOY.js";
82
95
  import {
83
96
  appendAuditLine,
97
+ deepMerge,
98
+ loadPolicy,
99
+ localDayKey,
100
+ updateUserPolicy
101
+ } from "./chunk-CRRN6UD3.js";
102
+ import {
84
103
  loadProfile,
85
104
  profileFilePath
86
- } from "./chunk-ECXYNTEV.js";
105
+ } from "./chunk-ERRPMYKB.js";
87
106
  import {
88
107
  dshHomeDir,
89
108
  initWorkspace,
90
109
  loadJson,
110
+ readText,
91
111
  saveJson,
112
+ withFileLock,
92
113
  writeText
93
- } from "./chunk-M72T5MZU.js";
94
- import {
95
- addBinding,
96
- loadBindings,
97
- removeBinding
98
- } from "./chunk-3DNGY4DS.js";
114
+ } from "./chunk-GOLMRQRW.js";
99
115
  import {
100
116
  atomicWriteFileSync,
101
117
  atomicWriteJsonSync
102
- } from "./chunk-IBBAISSW.js";
118
+ } from "./chunk-66IUDHCY.js";
103
119
 
104
120
  // src/index.ts
105
121
  import z from "@deepseek-ai/schemastery";
@@ -126,6 +142,10 @@ function sanitize(raw) {
126
142
  if (typeof r.statusbar === "boolean") out.statusbar = r.statusbar;
127
143
  if (typeof r.idleMode === "boolean") out.idleMode = r.idleMode;
128
144
  if (typeof r.tokenSaver === "boolean") out.tokenSaver = r.tokenSaver;
145
+ if (r.visionEngine === "" || r.visionEngine === "auto" || r.visionEngine === "native" || r.visionEngine === "modlens") {
146
+ out.visionEngine = r.visionEngine;
147
+ }
148
+ if (typeof r.concludeSilentTurn === "boolean") out.concludeSilentTurn = r.concludeSilentTurn;
129
149
  return out;
130
150
  }
131
151
  function uiConfigPath(settingsDir) {
@@ -270,6 +290,120 @@ function setWanderWindows(guard, paths, rawWindows) {
270
290
  // src/statusbar/time-inject.ts
271
291
  import fs3 from "fs";
272
292
  import path3 from "path";
293
+
294
+ // src/statusbar/track.ts
295
+ var capabilityCache = /* @__PURE__ */ new Map();
296
+ function supportsInHistory(session) {
297
+ const key = session.id;
298
+ const len = sessionEventCount(session);
299
+ const hit = capabilityCache.get(key);
300
+ if (hit && hit.scannedUpTo === len) return hit.supported;
301
+ const from = hit && len >= hit.scannedUpTo ? hit.scannedUpTo : 0;
302
+ let supported = false;
303
+ if (from !== 0 && hit) supported = hit.supported;
304
+ const readTail = (fromSeq) => {
305
+ if (typeof session.snapshotEvents === "function") {
306
+ try {
307
+ const slice = session.snapshotEvents(fromSeq);
308
+ if (Array.isArray(slice)) return slice;
309
+ } catch {
310
+ }
311
+ }
312
+ return sessionEvents(session).slice(fromSeq);
313
+ };
314
+ for (const e of readTail(from)) {
315
+ if (e.type === "request/context") {
316
+ supported = e.data?.systemPromptUpdate === "in-history";
317
+ }
318
+ }
319
+ capabilityCache.set(key, { scannedUpTo: len, supported });
320
+ return supported;
321
+ }
322
+ var SCENE_LABELS = {
323
+ "quiet-hours": "\u9759\u9ED8\u65F6\u6BB5\uFF0C\u4E16\u754C\u7761\u4E86",
324
+ "just-spoke": "\u521A\u53BB\u548C\u4F60\u8BF4\u8FC7\u8BDD",
325
+ wandering: "\u6B63\u5728\u95F2\u901B\u770B\u65B0\u4E1C\u897F",
326
+ busy: "\u770B\u5230\u4F60\u5728\u5FD9\uFF0C\u4E0D\u53BB\u6253\u6270",
327
+ present: "\u5728\u573A\u5F85\u7740",
328
+ away: "\u4F60\u4E0D\u5728\uFF0C\u81EA\u5DF1\u5F85\u7740"
329
+ };
330
+ function renderStatusText(status, opts) {
331
+ if (!status) return "";
332
+ const label = SCENE_LABELS[status.scene] ?? "\u5728\u573A";
333
+ const note = opts?.withNote === false ? "" : status.note ? `\u2014\u2014${status.note}` : "";
334
+ return `\u5FC3\u8DF3\u6B64\u523B\uFF1A${label}${note}\u3002`;
335
+ }
336
+ var pinnedTrack = /* @__PURE__ */ new Map();
337
+ function pinTrack(sessionId, session) {
338
+ const track = trackFor(session);
339
+ pinnedTrack.set(sessionId, track);
340
+ return track;
341
+ }
342
+ function pinnedTrackFor(sessionId, session) {
343
+ return pinnedTrack.get(sessionId) ?? trackFor(session);
344
+ }
345
+ var lastTrack = /* @__PURE__ */ new Map();
346
+ function noteTrack(auditFile, sessionId, track) {
347
+ if (lastTrack.get(sessionId) === track) return;
348
+ lastTrack.set(sessionId, track);
349
+ try {
350
+ appendAuditLine(auditFile, { event: "statusbar_track", sessionId, track });
351
+ } catch {
352
+ }
353
+ }
354
+ var lastSkip = /* @__PURE__ */ new Map();
355
+ function noteStatusbarSkip(auditFile, sessionId, reason) {
356
+ if (reason === null) {
357
+ lastSkip.delete(sessionId);
358
+ return;
359
+ }
360
+ if (lastSkip.get(sessionId) === reason) return;
361
+ lastSkip.set(sessionId, reason);
362
+ try {
363
+ appendAuditLine(auditFile, { event: "statusbar_skipped", sessionId, reason });
364
+ } catch {
365
+ }
366
+ }
367
+ function trackFor(session) {
368
+ return supportsInHistory(session) ? "system-prompt" : "pre-step";
369
+ }
370
+ function registerStatusbarSection(ctx, guard, paths, opts) {
371
+ ctx.inject(["systemPrompt"], (scoped) => {
372
+ const spCtx = scoped;
373
+ const section = spCtx.systemPrompt?.section;
374
+ if (typeof section !== "function") {
375
+ spCtx.logger?.warn("heartbeat: systemPrompt service has no section API, statusbar Track A unavailable");
376
+ return;
377
+ }
378
+ spCtx.effect(() => section.call(spCtx.systemPrompt, {
379
+ name: "heartbeat:status",
380
+ order: 5e3,
381
+ // between the persona prefix (0) and the harness block (10000)
382
+ text: (context) => {
383
+ if (!opts.enabled()) {
384
+ noteTrack(paths.logsDir + "/heartbeat.jsonl", context.agent?.session.id ?? "(none)", "off");
385
+ return "";
386
+ }
387
+ const agent = context.agent;
388
+ if (!agent?.session) return "";
389
+ if (opts.isDeliverSession) {
390
+ const delivery = opts.isDeliverSession(agent.session);
391
+ if (!delivery.allowed) {
392
+ noteStatusbarSkip(paths.logsDir + "/heartbeat.jsonl", agent.session.id, delivery.reason ?? "not-deliver");
393
+ return "";
394
+ }
395
+ noteStatusbarSkip(paths.logsDir + "/heartbeat.jsonl", agent.session.id, null);
396
+ }
397
+ const track = pinnedTrackFor(agent.session.id, agent.session);
398
+ noteTrack(paths.logsDir + "/heartbeat.jsonl", agent.session.id, track);
399
+ if (track !== "system-prompt") return "";
400
+ return renderStatusText(opts.reader.read(guard, paths), { withNote: false });
401
+ }
402
+ }), "heartbeat: statusbar section");
403
+ });
404
+ }
405
+
406
+ // src/statusbar/time-inject.ts
273
407
  function shouldInjectTime(input) {
274
408
  if (input.step !== 1) return false;
275
409
  if (!input.originIsUserSplice) return false;
@@ -293,13 +427,6 @@ function turnOriginIsUserSplice(session) {
293
427
  }
294
428
  return false;
295
429
  }
296
- function isSubagentSession(session) {
297
- if (!session) return false;
298
- const header = session.header;
299
- if (header?.origin === "subagent") return true;
300
- if (typeof header?.delegationDepth === "number" && header.delegationDepth > 0) return true;
301
- return sessionEvents(session).slice(0, 8).some((e) => e?.type === "subagent/descriptor");
302
- }
303
430
  function formatElapsed(ms) {
304
431
  const minutes = Math.max(1, Math.round(ms / 6e4));
305
432
  if (minutes < 60) return `${minutes} \u5206\u949F`;
@@ -388,9 +515,15 @@ function registerTimeInjection(ctx, guard, dataDir, opts) {
388
515
  lastMessageTime: lastMessageTime(payload.agent.session)
389
516
  });
390
517
  if (opts.getStatusLine && track) {
391
- const statusLine = opts.getStatusLine(payload.agent.session, track);
392
- if (statusLine) text += `
518
+ const delivery = opts.isDeliverSession?.(payload.agent.session);
519
+ if (delivery && !delivery.allowed) {
520
+ noteStatusbarSkip(opts.paths.logsDir + "/heartbeat.jsonl", sessionId, delivery.reason ?? "not-deliver");
521
+ } else {
522
+ if (delivery) noteStatusbarSkip(opts.paths.logsDir + "/heartbeat.jsonl", sessionId, null);
523
+ const statusLine = opts.getStatusLine(payload.agent.session, track);
524
+ if (statusLine) text += `
393
525
  ${statusLine}`;
526
+ }
394
527
  }
395
528
  const message = createUserMessage({
396
529
  content: [{ type: "text", text }],
@@ -535,7 +668,7 @@ function buildEndpoints(deps, isLive) {
535
668
  }
536
669
  let flags = { statusbarEnabled: true, timeInjectMin: 25, idleMode: false };
537
670
  try {
538
- const { getRuntime: getRuntime2 } = await import("./runtime-W2OWJIHY.js");
671
+ const { getRuntime: getRuntime2 } = await import("./runtime-RGZKOFP3.js");
539
672
  const f = getRuntime2().flags;
540
673
  flags = { statusbarEnabled: f.statusbarEnabled(), timeInjectMin: f.timeInjectMin(), idleMode: f.idleMode() };
541
674
  } catch {
@@ -712,7 +845,7 @@ function buildEndpoints(deps, isLive) {
712
845
  return err("bad-request", "config.set needs a patch object");
713
846
  }
714
847
  const keys = Object.keys(patch).filter(
715
- (k) => ["intervalMin", "maxDailySend", "timeInjectMin", "statusbar", "idleMode", "tokenSaver", "psyEnabled", "quietStart", "quietEnd"].includes(k)
848
+ (k) => ["intervalMin", "maxDailySend", "timeInjectMin", "statusbar", "idleMode", "tokenSaver", "visionEngine", "concludeSilentTurn", "psyEnabled", "quietStart", "quietEnd"].includes(k)
716
849
  );
717
850
  if (keys.length === 0) return err("bad-request", "config.set has no recognized field");
718
851
  try {
@@ -775,7 +908,29 @@ function buildEndpoints(deps, isLive) {
775
908
  },
776
909
  "ledger.open"() {
777
910
  const f = ledgerFilePath(paths.dataDir);
778
- if (!fs4.existsSync(guard.assert(f))) fs4.writeFileSync(f, "# \u8D26\u672C\n", "utf8");
911
+ seedBookFile(guard, f, LEDGER_HEADER);
912
+ openPath(f);
913
+ return ok({ path: f });
914
+ },
915
+ // 2.3.0: the live book only shows open rows; the archive is a read-only
916
+ // companion (same button row in the card). Missing archive = empty file.
917
+ "ledger.openDone"() {
918
+ const f = ledgerDoneFilePath(paths.dataDir);
919
+ seedBookFile(guard, f, LEDGER_DONE_HEADER);
920
+ openPath(f);
921
+ return ok({ path: f });
922
+ },
923
+ // 错题本 (v2.3.0): same two-button semantics as the ledger; `pending` is
924
+ // the count of unreviewed rows in the live book.
925
+ "corrections.open"() {
926
+ const f = correctionsFilePath(paths.dataDir);
927
+ seedBookFile(guard, f, CORRECTIONS_HEADER);
928
+ openPath(f);
929
+ return ok({ path: f, pending: scanPending(guard, f).length });
930
+ },
931
+ "corrections.openDone"() {
932
+ const f = correctionsDoneFilePath(paths.dataDir);
933
+ seedBookFile(guard, f, CORRECTIONS_DONE_HEADER);
779
934
  openPath(f);
780
935
  return ok({ path: f });
781
936
  },
@@ -795,7 +950,7 @@ function buildEndpoints(deps, isLive) {
795
950
  async "migrate.export"(p) {
796
951
  const passphrase = String(p.passphrase ?? "");
797
952
  if (!passphrase) return err("bad-request", "\u9700\u8981\u8BBE\u7F6E\u53E3\u4EE4");
798
- const { collectMigrationEntries, encryptContainer } = await import("./migrate-XFZU5EBE.js");
953
+ const { collectMigrationEntries, encryptContainer } = await import("./migrate-25F53XIC.js");
799
954
  const { entries } = collectMigrationEntries(guard, paths);
800
955
  if (entries.length === 0) return err("bad-request", "\u6CA1\u6709\u53EF\u6253\u5305\u7684\u8BB0\u5FC6\u6587\u4EF6\uFF08data/ \u662F\u7A7A\u7684\uFF09");
801
956
  const out = path4.join(paths.exportsDir, `heartbeat-memory-${localDayKey()}.hbmig`);
@@ -807,7 +962,7 @@ function buildEndpoints(deps, isLive) {
807
962
  const passphrase = String(p.passphrase ?? "");
808
963
  const file = String(p.file ?? "");
809
964
  if (!passphrase || !file) return err("bad-request", "\u9700\u8981\u5BB9\u5668\u8DEF\u5F84\u4E0E\u53E3\u4EE4");
810
- const { decryptContainer, applyMigrationEntries } = await import("./migrate-XFZU5EBE.js");
965
+ const { decryptContainer, applyMigrationEntries } = await import("./migrate-25F53XIC.js");
811
966
  let text;
812
967
  try {
813
968
  text = fs4.readFileSync(file, "utf8");
@@ -902,97 +1057,6 @@ function installHeartbeatRpc(ctx, deps) {
902
1057
  });
903
1058
  }
904
1059
 
905
- // src/statusbar/track.ts
906
- var capabilityCache = /* @__PURE__ */ new Map();
907
- function supportsInHistory(session) {
908
- const key = session.id;
909
- const len = sessionEventCount(session);
910
- const hit = capabilityCache.get(key);
911
- if (hit && hit.scannedUpTo === len) return hit.supported;
912
- const from = hit && len >= hit.scannedUpTo ? hit.scannedUpTo : 0;
913
- let supported = false;
914
- if (from !== 0 && hit) supported = hit.supported;
915
- const readTail = (fromSeq) => {
916
- if (typeof session.snapshotEvents === "function") {
917
- try {
918
- const slice = session.snapshotEvents(fromSeq);
919
- if (Array.isArray(slice)) return slice;
920
- } catch {
921
- }
922
- }
923
- return sessionEvents(session).slice(fromSeq);
924
- };
925
- for (const e of readTail(from)) {
926
- if (e.type === "request/context") {
927
- supported = e.data?.systemPromptUpdate === "in-history";
928
- }
929
- }
930
- capabilityCache.set(key, { scannedUpTo: len, supported });
931
- return supported;
932
- }
933
- var SCENE_LABELS = {
934
- "quiet-hours": "\u9759\u9ED8\u65F6\u6BB5\uFF0C\u4E16\u754C\u7761\u4E86",
935
- "just-spoke": "\u521A\u53BB\u548C\u4F60\u8BF4\u8FC7\u8BDD",
936
- wandering: "\u6B63\u5728\u95F2\u901B\u770B\u65B0\u4E1C\u897F",
937
- busy: "\u770B\u5230\u4F60\u5728\u5FD9\uFF0C\u4E0D\u53BB\u6253\u6270",
938
- present: "\u5728\u573A\u5F85\u7740",
939
- away: "\u4F60\u4E0D\u5728\uFF0C\u81EA\u5DF1\u5F85\u7740"
940
- };
941
- function renderStatusText(status, opts) {
942
- if (!status) return "";
943
- const label = SCENE_LABELS[status.scene] ?? "\u5728\u573A";
944
- const note = opts?.withNote === false ? "" : status.note ? `\u2014\u2014${status.note}` : "";
945
- return `\u5FC3\u8DF3\u6B64\u523B\uFF1A${label}${note}\u3002`;
946
- }
947
- var pinnedTrack = /* @__PURE__ */ new Map();
948
- function pinTrack(sessionId, session) {
949
- const track = trackFor(session);
950
- pinnedTrack.set(sessionId, track);
951
- return track;
952
- }
953
- function pinnedTrackFor(sessionId, session) {
954
- return pinnedTrack.get(sessionId) ?? trackFor(session);
955
- }
956
- var lastTrack = /* @__PURE__ */ new Map();
957
- function noteTrack(auditFile, sessionId, track) {
958
- if (lastTrack.get(sessionId) === track) return;
959
- lastTrack.set(sessionId, track);
960
- try {
961
- appendAuditLine(auditFile, { event: "statusbar_track", sessionId, track });
962
- } catch {
963
- }
964
- }
965
- function trackFor(session) {
966
- return supportsInHistory(session) ? "system-prompt" : "pre-step";
967
- }
968
- function registerStatusbarSection(ctx, guard, paths, opts) {
969
- ctx.inject(["systemPrompt"], (scoped) => {
970
- const spCtx = scoped;
971
- const section = spCtx.systemPrompt?.section;
972
- if (typeof section !== "function") {
973
- spCtx.logger?.warn("heartbeat: systemPrompt service has no section API, statusbar Track A unavailable");
974
- return;
975
- }
976
- spCtx.effect(() => section.call(spCtx.systemPrompt, {
977
- name: "heartbeat:status",
978
- order: 5e3,
979
- // between the persona prefix (0) and the harness block (10000)
980
- text: (context) => {
981
- if (!opts.enabled()) {
982
- noteTrack(paths.logsDir + "/heartbeat.jsonl", context.agent?.session.id ?? "(none)", "off");
983
- return "";
984
- }
985
- const agent = context.agent;
986
- if (!agent?.session) return "";
987
- const track = pinnedTrackFor(agent.session.id, agent.session);
988
- noteTrack(paths.logsDir + "/heartbeat.jsonl", agent.session.id, track);
989
- if (track !== "system-prompt") return "";
990
- return renderStatusText(opts.reader.read(guard, paths), { withNote: false });
991
- }
992
- }), "heartbeat: statusbar section");
993
- });
994
- }
995
-
996
1060
  // src/core/preset-definition.ts
997
1061
  function heartbeatPresetDefinition(id = "heartbeat") {
998
1062
  return {
@@ -1056,16 +1120,16 @@ function clean(v) {
1056
1120
  function fmtEntry(e) {
1057
1121
  return `#${e.id} [${e.status}] ${e.date} ${e.text}`;
1058
1122
  }
1059
- function buildLedgerTool(guard, file) {
1123
+ function buildBookTool(guard, file, labels, audit) {
1060
1124
  return {
1061
- name: "ledger",
1062
- description: '\u5171\u4EAB\u8D26\u672C\u5DE5\u5177\uFF08\u5FC3\u8DF3\u63D2\u4EF6\u7684\u5F85\u529E\u4E0E\u4E8B\u9879\u8BB0\u5F55\uFF09\u3002\u5F53\u7528\u6237\u63D0\u5230\u8BA1\u5212\u3001\u5F85\u529E\u3001\u627F\u8BFA\u3001\u60F3\u505A\u7684\u4E8B\uFF0C\u6216\u8005\u67D0\u4EF6\u4E8B\u5DF2\u7ECF\u5B8C\u6210\u65F6\uFF0C\u4E3B\u52A8\u8C03\u7528\u672C\u5DE5\u5177\u767B\u8BB0\u6216\u52FE\u6389\u2014\u2014\u4E0D\u9700\u8981\u7B49\u7528\u6237\u660E\u786E\u8BF4"\u8BB0\u4E00\u4E0B"\u3002action=add \u767B\u8BB0\u65B0\u4E8B\u9879\uFF08text \u5FC5\u586B\uFF09\uFF1Baction=list \u67E5\u770B\u5F53\u524D\u672A\u5B8C\u6210\u4E8B\u9879\uFF1Baction=done \u52FE\u6389\u4E00\u6761\uFF08key \u4E3A #id \u6216\u6587\u672C\u5B50\u4E32\uFF09\u3002',
1125
+ name: labels.name,
1126
+ description: labels.description,
1063
1127
  parameters: {
1064
1128
  type: "object",
1065
1129
  properties: {
1066
1130
  action: { type: "string", enum: ["add", "list", "done"], description: "add=\u767B\u8BB0\uFF0Clist=\u67E5\u672A\u5B8C\u6210\uFF0Cdone=\u52FE\u6389" },
1067
- text: { type: "string", description: "action=add \u65F6\u5FC5\u586B\uFF1A\u4E8B\u9879\u5185\u5BB9\uFF08\u4E00\u53E5\u8BDD\uFF09" },
1068
- key: { type: "string", description: "action=done \u65F6\u5FC5\u586B\uFF1A#id \u6216\u4E8B\u9879\u6587\u672C\u7684\u552F\u4E00\u5B50\u4E32" }
1131
+ text: { type: "string", description: labels.textHint },
1132
+ key: { type: "string", description: labels.keyHint }
1069
1133
  },
1070
1134
  required: ["action"],
1071
1135
  additionalProperties: false
@@ -1086,7 +1150,7 @@ function buildLedgerTool(guard, file) {
1086
1150
  }
1087
1151
  },
1088
1152
  timeoutMs: 5e3,
1089
- // Ledger writes go through read-modify-write on one file; never parallel.
1153
+ // Both books write through read-modify-write on one file; never parallel.
1090
1154
  isConcurrencySafe: () => false,
1091
1155
  async execute(args) {
1092
1156
  const a = args ?? {};
@@ -1094,26 +1158,142 @@ function buildLedgerTool(guard, file) {
1094
1158
  if (action === "add") {
1095
1159
  const text = clean(a.text);
1096
1160
  if (!text) return { ok: false, message: "add \u9700\u8981\u975E\u7A7A text" };
1097
- const e = appendEntry(guard, file, text);
1098
- return { ok: true, message: `\u5DF2\u767B\u8BB0 ${fmtEntry(e)}` };
1161
+ const e = appendEntry(guard, file, text, Date.now(), labels.header);
1162
+ return { ok: true, message: `${labels.addedVerb} ${fmtEntry(e)}` };
1099
1163
  }
1100
1164
  if (action === "done") {
1101
1165
  const key = clean(a.key);
1102
- if (!key) return { ok: false, message: "done \u9700\u8981 key\uFF08#id \u6216\u6587\u672C\u5B50\u4E32\uFF09" };
1103
- const e = markDone(guard, file, key);
1104
- if (!e) return { ok: false, message: `\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C${key}\u300D\u7684\u672A\u5B8C\u6210\u4E8B\u9879\uFF08\u5148\u7528 list \u67E5\uFF09` };
1105
- return { ok: true, message: `\u5DF2\u5B8C\u6210 ${fmtEntry(e)}` };
1166
+ if (!key) return { ok: false, message: `done \u9700\u8981 key\uFF08#id \u6216\u6587\u672C\u5B50\u4E32\uFF09` };
1167
+ const e = markDone(guard, file, key, Date.now(), void 0, void 0, audit);
1168
+ if (!e) return { ok: false, message: `\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C${key}\u300D\u7684${labels.listNoun}\uFF08\u5148\u7528 list \u67E5\uFF09` };
1169
+ return { ok: true, message: `${labels.doneVerb} ${fmtEntry(e)}` };
1106
1170
  }
1107
1171
  if (action === "list") {
1108
1172
  const items = scanPending(guard, file).map(fmtEntry);
1109
- return { ok: true, message: items.length > 0 ? `\u5F53\u524D\u672A\u5B8C\u6210 ${items.length} \u9879\uFF1A
1110
- ${items.join("\n")}` : "\u8D26\u672C\u91CC\u6CA1\u6709\u672A\u5B8C\u6210\u4E8B\u9879" };
1173
+ return {
1174
+ ok: true,
1175
+ message: items.length > 0 ? `${labels.listTitle} ${items.length} \u9879\uFF1A
1176
+ ${items.join("\n")}` : `${labels.bookName}\u91CC\u6CA1\u6709${labels.listNoun}`
1177
+ };
1111
1178
  }
1112
1179
  const total = readLedger(guard, file).entries.length;
1113
- return { ok: false, message: `\u672A\u77E5 action\uFF0C\u8D26\u672C\u5171 ${total} \u6761` };
1180
+ return { ok: false, message: `\u672A\u77E5 action\uFF0C${labels.bookName}\u5171 ${total} \u6761` };
1114
1181
  }
1115
1182
  };
1116
1183
  }
1184
+ var LEDGER_LABELS = {
1185
+ name: "ledger",
1186
+ header: LEDGER_HEADER,
1187
+ description: '\u5171\u4EAB\u8D26\u672C\u5DE5\u5177\uFF08\u5FC3\u8DF3\u63D2\u4EF6\u7684\u5F85\u529E\u4E0E\u4E8B\u9879\u8BB0\u5F55\uFF09\u3002\u5F53\u7528\u6237\u63D0\u5230\u8BA1\u5212\u3001\u5F85\u529E\u3001\u627F\u8BFA\u3001\u60F3\u505A\u7684\u4E8B\uFF0C\u6216\u8005\u67D0\u4EF6\u4E8B\u5DF2\u7ECF\u5B8C\u6210\u65F6\uFF0C\u4E3B\u52A8\u8C03\u7528\u672C\u5DE5\u5177\u767B\u8BB0\u6216\u52FE\u6389\u2014\u2014\u4E0D\u9700\u8981\u7B49\u7528\u6237\u660E\u786E\u8BF4"\u8BB0\u4E00\u4E0B"\u3002action=add \u767B\u8BB0\u65B0\u4E8B\u9879\uFF08text \u5FC5\u586B\uFF09\uFF1Baction=list \u67E5\u770B\u5F53\u524D\u672A\u5B8C\u6210\u4E8B\u9879\uFF1Baction=done \u52FE\u6389\u4E00\u6761\uFF08key \u4E3A #id \u6216\u6587\u672C\u5B50\u4E32\uFF09\u3002',
1188
+ addedVerb: "\u5DF2\u767B\u8BB0",
1189
+ doneVerb: "\u5DF2\u5B8C\u6210",
1190
+ listTitle: "\u5F53\u524D\u672A\u5B8C\u6210",
1191
+ listNoun: "\u672A\u5B8C\u6210\u4E8B\u9879",
1192
+ bookName: "\u8D26\u672C",
1193
+ textHint: "action=add \u65F6\u5FC5\u586B\uFF1A\u4E8B\u9879\u5185\u5BB9\uFF08\u4E00\u53E5\u8BDD\uFF09",
1194
+ keyHint: "action=done \u65F6\u5FC5\u586B\uFF1A#id \u6216\u4E8B\u9879\u6587\u672C\u7684\u552F\u4E00\u5B50\u4E32"
1195
+ };
1196
+ var CORRECTIONS_LABELS = {
1197
+ name: "corrections",
1198
+ header: CORRECTIONS_HEADER,
1199
+ description: '\u9519\u9898\u672C\u5DE5\u5177\uFF08\u8BB0\u5F55\u7528\u6237\u5BF9\u4F60\u7684\u7EA0\u6B63\uFF09\u3002\u5F53\u7528\u6237\u6307\u51FA\u4F60\u8BF4\u9519\u4E86\u3001\u505A\u9519\u4E86\u3001\u8BB0\u9519\u4E86\uFF0C\u6216\u8005\u7EA0\u6B63\u4F60\u7684\u8BF4\u6CD5\u4E0E\u505A\u6CD5\u65F6\uFF0C\u4E3B\u52A8\u8C03\u7528\u672C\u5DE5\u5177\u8BB0\u4E00\u6761\u2014\u2014\u4E0D\u9700\u8981\u7B49\u7528\u6237\u8BF4"\u8BB0\u4E00\u4E0B"\u3002action=add \u8BB0\u4E00\u6761\u7EA0\u6B63\uFF08text \u5FC5\u586B\uFF0C\u4E00\u53E5\u8BDD\u5199\u6E05\u7528\u6237\u7EA0\u6B63\u4E86\u4EC0\u4E48\uFF09\uFF1Baction=list \u67E5\u770B\u8FD8\u6CA1\u590D\u76D8\u7684\u6761\u76EE\uFF1Baction=done \u52FE\u6389\u4E00\u6761\uFF08key \u4E3A #id \u6216\u6587\u672C\u5B50\u4E32\uFF09\u2014\u2014\u52FE\u6389\u8868\u793A\u8FD9\u6761\u6559\u8BAD\u5DF2\u7ECF\u5199\u8FDB\u4EBA\u8BBE\u5361\u6216\u957F\u671F\u8BB0\u5FC6\u3002',
1200
+ addedVerb: "\u5DF2\u8BB0\u4E0B",
1201
+ doneVerb: "\u5DF2\u590D\u76D8",
1202
+ listTitle: "\u5F85\u590D\u76D8",
1203
+ listNoun: "\u5F85\u590D\u76D8\u6761\u76EE",
1204
+ bookName: "\u9519\u9898\u672C",
1205
+ textHint: "action=add \u65F6\u5FC5\u586B\uFF1A\u7528\u6237\u7EA0\u6B63\u4E86\u4EC0\u4E48\uFF08\u4E00\u53E5\u8BDD\uFF09",
1206
+ keyHint: "action=done \u65F6\u5FC5\u586B\uFF1A#id \u6216\u7EA0\u6B63\u6587\u672C\u7684\u552F\u4E00\u5B50\u4E32"
1207
+ };
1208
+ function buildLedgerTool(guard, file, audit) {
1209
+ return buildBookTool(guard, file, LEDGER_LABELS, audit);
1210
+ }
1211
+ function buildCorrectionsTool(guard, file, audit) {
1212
+ return buildBookTool(guard, file, CORRECTIONS_LABELS, audit);
1213
+ }
1214
+
1215
+ // src/ledger/archive.ts
1216
+ import fs5 from "fs";
1217
+ import path5 from "path";
1218
+ var STATE_FILE = "state.json";
1219
+ function stateFilePath(settingsDir) {
1220
+ return path5.join(settingsDir, STATE_FILE);
1221
+ }
1222
+ function readState(guard, settingsDir) {
1223
+ try {
1224
+ const raw = readText(guard, stateFilePath(settingsDir), "");
1225
+ if (!raw.trim()) return {};
1226
+ const parsed = JSON.parse(raw);
1227
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1228
+ } catch {
1229
+ return {};
1230
+ }
1231
+ }
1232
+ function writeState(guard, settingsDir, state) {
1233
+ writeText(guard, stateFilePath(settingsDir), JSON.stringify(state, null, 2) + "\n");
1234
+ }
1235
+ function bookSpecs(dataDir) {
1236
+ return [
1237
+ {
1238
+ label: "ledger",
1239
+ marker: "ledgerDoneMigrated",
1240
+ mainFile: ledgerFilePath(dataDir),
1241
+ doneFile: ledgerDoneFilePath(dataDir),
1242
+ mainHeader: LEDGER_HEADER,
1243
+ doneHeader: LEDGER_DONE_HEADER
1244
+ },
1245
+ {
1246
+ label: "corrections",
1247
+ marker: "correctionsDoneMigrated",
1248
+ mainFile: correctionsFilePath(dataDir),
1249
+ doneFile: correctionsDoneFilePath(dataDir),
1250
+ mainHeader: CORRECTIONS_HEADER,
1251
+ doneHeader: CORRECTIONS_DONE_HEADER
1252
+ }
1253
+ ];
1254
+ }
1255
+ function pad2(n) {
1256
+ return String(n).padStart(2, "0");
1257
+ }
1258
+ function backupPathFor(guard, file, now) {
1259
+ const d = new Date(now);
1260
+ const stamp = `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}-${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}`;
1261
+ const base = `${file}.bak-${stamp}`;
1262
+ let out = base;
1263
+ for (let i = 1; fs5.existsSync(guard.assert(out)); i += 1) out = `${base}-${i}`;
1264
+ return out;
1265
+ }
1266
+ function migrateBookDone(guard, spec, settingsDir, audit, now = Date.now()) {
1267
+ return withFileLock(spec.mainFile, () => {
1268
+ const state = readState(guard, settingsDir);
1269
+ if (state[spec.marker] === true) return { skipped: true, count: 0, backup: null };
1270
+ const doneLines = [];
1271
+ const keptLines = [];
1272
+ const exists = fs5.existsSync(guard.assert(spec.mainFile));
1273
+ if (exists) {
1274
+ for (const line of readText(guard, spec.mainFile, spec.mainHeader).split("\n")) {
1275
+ const entry = parseLedgerLine(line);
1276
+ if (entry && entry.status === "done") doneLines.push(line);
1277
+ else keptLines.push(line);
1278
+ }
1279
+ }
1280
+ let backup = null;
1281
+ let appended = 0;
1282
+ if (doneLines.length > 0) {
1283
+ backup = backupPathFor(guard, spec.mainFile, now);
1284
+ fs5.copyFileSync(guard.assert(spec.mainFile), guard.assert(backup));
1285
+ appended = appendArchiveLines(guard, spec.doneFile, spec.doneHeader, doneLines, now);
1286
+ writeText(guard, spec.mainFile, keptLines.join("\n").replace(/\n*$/, "\n"));
1287
+ }
1288
+ state[spec.marker] = true;
1289
+ writeState(guard, settingsDir, state);
1290
+ audit({ event: `${spec.label}_done_migrated`, count: appended, found: doneLines.length });
1291
+ return { skipped: false, count: appended, backup };
1292
+ });
1293
+ }
1294
+ function runBookDoneMigrations(guard, dataDir, settingsDir, audit, now = Date.now()) {
1295
+ return bookSpecs(dataDir).map((spec) => migrateBookDone(guard, spec, settingsDir, audit, now));
1296
+ }
1117
1297
 
1118
1298
  // src/notepad/tool.ts
1119
1299
  var MAX_NOTE_CHARS = 160;
@@ -1133,7 +1313,7 @@ function fmtView(v) {
1133
1313
  return `\u5FC3\u4E8B\u5323\u91CC\u73B0\u5728\u6709\uFF1A${v.text}
1134
1314
  \uFF08\u7559\u4E8E${beats}\uFF0C\u5DF2\u6401 ${fmtMinutes(v.sinceMinutes)}\uFF0C${wakes}\uFF09`;
1135
1315
  }
1136
- function buildNotepadTool(guard, file) {
1316
+ function buildNotepadTool(guard, file, gate = {}) {
1137
1317
  return {
1138
1318
  name: "notepad",
1139
1319
  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',
@@ -1171,7 +1351,15 @@ function buildNotepadTool(guard, file) {
1171
1351
  timeoutMs: 5e3,
1172
1352
  // Read-modify-write on one file, and the note's lifecycle depends on it.
1173
1353
  isConcurrencySafe: () => false,
1174
- async execute(args) {
1354
+ async execute(args, exec) {
1355
+ const session = exec?.agent?.session;
1356
+ if (gate.isDeliverySession && session?.id && !gate.isDeliverySession(session)) {
1357
+ try {
1358
+ gate.onBlocked?.(session.id);
1359
+ } catch {
1360
+ }
1361
+ return { ok: false, message: "\u5FC3\u4E8B\u5323\u53EA\u5728\u6295\u9012\u5BF9\u8BDD\u91CC\u7528" };
1362
+ }
1175
1363
  const a = args ?? {};
1176
1364
  const action = String(a.action ?? "");
1177
1365
  try {
@@ -1200,6 +1388,27 @@ function buildNotepadTool(guard, file) {
1200
1388
  };
1201
1389
  }
1202
1390
 
1391
+ // src/profile/fallback-guard.ts
1392
+ function createPersonFallbackGuard(deps) {
1393
+ let registered = false;
1394
+ return {
1395
+ register(why) {
1396
+ if (registered) {
1397
+ try {
1398
+ deps.audit({ event: "person_tool_fallback_already", reason: why });
1399
+ } catch {
1400
+ }
1401
+ return;
1402
+ }
1403
+ registered = true;
1404
+ deps.performRegister(why);
1405
+ },
1406
+ reset() {
1407
+ registered = false;
1408
+ }
1409
+ };
1410
+ }
1411
+
1203
1412
  // src/excerpt/tool.ts
1204
1413
  var MAX_TEXT2 = 300;
1205
1414
  var LIST_LIMIT = 10;
@@ -1271,8 +1480,8 @@ ${items.join("\n")}` };
1271
1480
  }
1272
1481
 
1273
1482
  // src/sources/bilibili.ts
1274
- import fs5 from "fs";
1275
- import path5 from "path";
1483
+ import fs6 from "fs";
1484
+ import path6 from "path";
1276
1485
  var BILI_HISTORY_URL = "https://api.bilibili.com/x/web-interface/history/cursor?ps=8";
1277
1486
  var BILI_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36";
1278
1487
  var BILI_SESSION_FILE = "bilibili-session.json";
@@ -1295,7 +1504,7 @@ function readVaultSessdata(guard, dataDir) {
1295
1504
  try {
1296
1505
  const session = loadJson(
1297
1506
  guard,
1298
- path5.join(dataDir, BILI_SESSION_FILE)
1507
+ path6.join(dataDir, BILI_SESSION_FILE)
1299
1508
  );
1300
1509
  const field = session?.sessdata;
1301
1510
  if (typeof field !== "string") return null;
@@ -1310,7 +1519,7 @@ function readVaultSessdata(guard, dataDir) {
1310
1519
  function readCookieFileSessdata(file) {
1311
1520
  if (!file) return null;
1312
1521
  try {
1313
- const raw = fs5.readFileSync(file, "utf8");
1522
+ const raw = fs6.readFileSync(file, "utf8");
1314
1523
  if (!raw) return null;
1315
1524
  const v = parseSessdata(raw);
1316
1525
  return v || null;
@@ -1360,7 +1569,7 @@ function emptyBiliState() {
1360
1569
  return { lastFetchAt: 0, bvids: [] };
1361
1570
  }
1362
1571
  function bilibiliStatePath(dataDir) {
1363
- return path5.join(dataDir, BILI_STATE_FILE);
1572
+ return path6.join(dataDir, BILI_STATE_FILE);
1364
1573
  }
1365
1574
  function normalizeBiliState(raw) {
1366
1575
  const out = emptyBiliState();
@@ -1514,6 +1723,29 @@ function stopBilibiliSource() {
1514
1723
 
1515
1724
  // src/index.ts
1516
1725
  var name = "heartbeat";
1726
+ var VISION_ENGINE_LITERALS = ["native", "modlens", "auto"];
1727
+ function auditInvalidVisionEngines(invalid, alreadyAudited, write) {
1728
+ for (const bad of invalid) {
1729
+ const key = `${bad.source}:${bad.value}`;
1730
+ if (alreadyAudited.has(key)) continue;
1731
+ try {
1732
+ const ok2 = write({ event: "vision_engine_invalid", source: bad.source, value: bad.value });
1733
+ if (ok2 !== false) alreadyAudited.add(key);
1734
+ } catch {
1735
+ }
1736
+ }
1737
+ }
1738
+ function resolveVisionEngineSetting(configured, card) {
1739
+ const invalid = [];
1740
+ const pick = (raw, source) => {
1741
+ const v = raw.trim();
1742
+ if (!v) return "";
1743
+ if (VISION_ENGINE_LITERALS.includes(v)) return v;
1744
+ invalid.push({ source, value: v });
1745
+ return "";
1746
+ };
1747
+ return { value: pick(configured, "config") || pick(card, "card"), invalid };
1748
+ }
1517
1749
  var inject = ["agents"];
1518
1750
  var Config = z.object({
1519
1751
  /** Override the runtime data dir (workspace guard boundary). Empty = default (<packageRoot>/data). */
@@ -1557,11 +1789,34 @@ var Config = z.object({
1557
1789
  /** v2.0.0 摘抄本工具:留句子和小事的地方(默认开)。 */
1558
1790
  excerptTool: z.boolean().default(true),
1559
1791
  /** v1.8.0 引擎室追加工具:逗号分隔的全局工具名,存在才加入白名单(bili 压缩工具自动探测,无需手填)。 */
1560
- extraTools: z.string().default("")
1792
+ extraTools: z.string().default(""),
1793
+ /**
1794
+ * 视觉识别引擎(v2.2.1-native.1):`auto` / `native` / `modlens`。
1795
+ * 留空 = 跟随 `data/settings/vision.json` 的 engine,再回落到内置默认 auto。
1796
+ * 这里给一个正式设置项,是为了让"默认走哪条路"可以不改代码就调——
1797
+ * 例如想保守地维持 v2.2.1 行为(只用 ModLens)就填 `modlens`。
1798
+ */
1799
+ visionEngine: z.string().default("")
1561
1800
  });
1562
1801
  function apply(ctx, config = {}) {
1563
1802
  const paths = initWorkspace(config.dataDir ? { dataDir: config.dataDir } : {});
1564
1803
  const guard = createPathGuard(paths.dataDir);
1804
+ try {
1805
+ runBookDoneMigrations(guard, paths.dataDir, paths.settingsDir, (entry) => {
1806
+ try {
1807
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), entry);
1808
+ } catch {
1809
+ }
1810
+ });
1811
+ } catch (e) {
1812
+ try {
1813
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), {
1814
+ event: "book_done_migration_failed",
1815
+ error: String(e).slice(0, 160)
1816
+ });
1817
+ } catch {
1818
+ }
1819
+ }
1565
1820
  let policy = loadPolicy(guard, paths.configDir, paths.settingsDir);
1566
1821
  const ui = loadUiConfig(guard, paths.settingsDir);
1567
1822
  if (ui.intervalMin && ui.intervalMin >= 1) {
@@ -1585,6 +1840,58 @@ function apply(ctx, config = {}) {
1585
1840
  extraTools: (config.extraTools ?? "").split(",").map((s) => s.trim()).filter(Boolean),
1586
1841
  presetRegistration: () => presetRegistration ?? Promise.resolve()
1587
1842
  };
1843
+ const performPersonFallbackRegister = (why) => {
1844
+ ctx.inject(["tools"], (scoped) => {
1845
+ const audit = (entry) => {
1846
+ try {
1847
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), entry);
1848
+ } catch {
1849
+ }
1850
+ };
1851
+ try {
1852
+ const tools = scoped.tools;
1853
+ if (!tools || typeof tools.register !== "function") throw new Error("ToolRuntime.register unavailable on this host");
1854
+ const homeOnly = (context) => context.agent?.session?.id === homeSessionId(guard, paths);
1855
+ const gate = {
1856
+ isHomeSession: (session) => homeOnly({ agent: { session } }),
1857
+ onBlocked: (sessionId) => {
1858
+ try {
1859
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), { event: "person_blocked", sessionId });
1860
+ } catch {
1861
+ }
1862
+ }
1863
+ };
1864
+ const defs = createProfileTools({ guard, dataDir: paths.dataDir, policy, getNow: () => Date.now(), ...gate });
1865
+ let whenUsed = true;
1866
+ for (const def of defs) {
1867
+ const name2 = def.name ?? "person";
1868
+ try {
1869
+ tools.register(def, { when: homeOnly });
1870
+ } catch {
1871
+ whenUsed = false;
1872
+ try {
1873
+ tools.register(def);
1874
+ audit({ event: "person_tool_when_unsupported", tool: name2, reason: why });
1875
+ } catch (e2) {
1876
+ audit({ event: "person_tool_register_failed", tool: name2, error: String(e2).slice(0, 160) });
1877
+ }
1878
+ }
1879
+ }
1880
+ audit({ event: "person_tool_registered", mode: whenUsed ? "global-when" : "global-gate", registered: true, reason: why });
1881
+ } catch (e) {
1882
+ audit({ event: "person_tool_register_failed", error: String(e).slice(0, 160) });
1883
+ }
1884
+ });
1885
+ };
1886
+ const personFallback = createPersonFallbackGuard({
1887
+ audit: (entry) => {
1888
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), entry);
1889
+ },
1890
+ performRegister: performPersonFallbackRegister
1891
+ });
1892
+ deps.personToolsFallback = (why) => {
1893
+ personFallback.register(why);
1894
+ };
1588
1895
  setRuntime({
1589
1896
  paths,
1590
1897
  guard,
@@ -1593,7 +1900,13 @@ function apply(ctx, config = {}) {
1593
1900
  statusbarEnabled: () => statusbarEnabledRef,
1594
1901
  timeInjectMin: () => timeInjectMinRef,
1595
1902
  idleMode: () => idleModeRef,
1596
- tokenSaver: () => tokenSaverRef
1903
+ tokenSaver: () => tokenSaverRef,
1904
+ // v2.2.1-native.1: card / composition engine choice ('' = vision.json).
1905
+ // Lazy on purpose: the refs below are declared after this call.
1906
+ visionEngine: () => effectiveVisionEngine(),
1907
+ // 2.3.0 experimental (default off): silent report concludes the turn.
1908
+ // Same lazy pattern as the refs above.
1909
+ concludeSilentTurn: () => concludeSilentTurnRef
1597
1910
  }
1598
1911
  });
1599
1912
  let presetRegistration;
@@ -1651,6 +1964,19 @@ function apply(ctx, config = {}) {
1651
1964
  let statusbarEnabledRef = ui.statusbar ?? config.statusbar === true;
1652
1965
  let idleModeRef = ui.idleMode ?? config.idleMode === true;
1653
1966
  let tokenSaverRef = ui.tokenSaver ?? config.tokenSaver === true;
1967
+ let visionEngineConfigRef = config.visionEngine ?? "";
1968
+ let visionEngineUiRef = ui.visionEngine ?? "";
1969
+ const invalidEnginesAudited = /* @__PURE__ */ new Set();
1970
+ let concludeSilentTurnRef = ui.concludeSilentTurn === true;
1971
+ const effectiveVisionEngine = () => {
1972
+ const resolved = resolveVisionEngineSetting(visionEngineConfigRef, visionEngineUiRef);
1973
+ auditInvalidVisionEngines(resolved.invalid, invalidEnginesAudited, (entry) => (
1974
+ // a3 中3: forward the success verdict — `false` means the line did NOT
1975
+ // land and the typo must stay unconsumed for the next beat's retry.
1976
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), entry)
1977
+ ));
1978
+ return resolved.value;
1979
+ };
1654
1980
  const applyLiveSettings = (v) => {
1655
1981
  if (v.intervalMin && v.intervalMin >= 1) applyHeartbeatInterval(deps, v.intervalMin);
1656
1982
  if (v.maxDailySend && v.maxDailySend >= 1) getRuntime().policy.gate.maxDailySend = v.maxDailySend;
@@ -1667,6 +1993,7 @@ function apply(ctx, config = {}) {
1667
1993
  const v = sectionSource?.();
1668
1994
  if (!v) return;
1669
1995
  applyLiveSettings(v);
1996
+ visionEngineConfigRef = typeof v.visionEngine === "string" ? v.visionEngine : "";
1670
1997
  ctx.logger.info("heartbeat: settings overrides live (interval %s, cap %s, timeInject %s)", v.intervalMin ?? "-", v.maxDailySend ?? "-", v.timeInjectMin ?? "-");
1671
1998
  } catch (e) {
1672
1999
  ctx.logger.warn("heartbeat: settings override failed (%s)", String(e).slice(0, 120));
@@ -1726,6 +2053,10 @@ function apply(ctx, config = {}) {
1726
2053
  statusbar: statusbarEnabledRef,
1727
2054
  idleMode: idleModeRef,
1728
2055
  tokenSaver: tokenSaverRef,
2056
+ // card-stored choice ('' = follow vision.json); the effective engine also
2057
+ // honours a composition-level config pin (see effectiveVisionEngine).
2058
+ visionEngine: visionEngineUiRef,
2059
+ concludeSilentTurn: concludeSilentTurnRef,
1729
2060
  psyEnabled: getRuntime().policy.profile.psyEnabled,
1730
2061
  quietStart: getRuntime().policy.gate.quietHours.start,
1731
2062
  quietEnd: getRuntime().policy.gate.quietHours.end
@@ -1744,10 +2075,13 @@ function apply(ctx, config = {}) {
1744
2075
  q.end = next.end;
1745
2076
  }
1746
2077
  const merged = saveUiConfig(guard, paths.settingsDir, patch);
2078
+ visionEngineUiRef = merged.visionEngine ?? "";
2079
+ concludeSilentTurnRef = merged.concludeSilentTurn === true;
1747
2080
  applyLiveSettings(merged);
1748
2081
  };
1749
2082
  installHeartbeatRpc(ctx, { paths, guard, policy, ui: { get: uiGet, set: uiSet } });
1750
- const registerGlobalTool = (name2, build) => {
2083
+ const deliverySessionVerdict = (session) => checkDeliverySession({ sessionId: session.id, session, guard, settingsDir: paths.settingsDir });
2084
+ const registerGlobalTool = (name2, build, when) => {
1751
2085
  ctx.inject(["tools"], (scoped) => {
1752
2086
  const audit = (entry) => {
1753
2087
  try {
@@ -1758,7 +2092,16 @@ function apply(ctx, config = {}) {
1758
2092
  try {
1759
2093
  const tools = scoped.tools;
1760
2094
  if (!tools || typeof tools.register !== "function") throw new Error("ToolRuntime.register unavailable on this host");
1761
- tools.register(build());
2095
+ if (when) {
2096
+ try {
2097
+ tools.register(build(), { when });
2098
+ } catch {
2099
+ tools.register(build());
2100
+ audit({ event: `${name2}_tool_when_unsupported` });
2101
+ }
2102
+ } else {
2103
+ tools.register(build());
2104
+ }
1762
2105
  audit({ event: `${name2}_tool_registered` });
1763
2106
  } catch (e) {
1764
2107
  audit({ event: `${name2}_tool_register_failed`, error: String(e).slice(0, 160) });
@@ -1766,13 +2109,53 @@ function apply(ctx, config = {}) {
1766
2109
  });
1767
2110
  };
1768
2111
  if (config.ledgerTool !== false) {
1769
- registerGlobalTool("ledger", () => buildLedgerTool(guard, ledgerFilePath(paths.dataDir)));
2112
+ const auditBookLine = (entry) => {
2113
+ try {
2114
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), entry);
2115
+ } catch {
2116
+ }
2117
+ };
2118
+ registerGlobalTool("ledger", () => buildLedgerTool(guard, ledgerFilePath(paths.dataDir), auditBookLine));
2119
+ registerGlobalTool("corrections", () => buildCorrectionsTool(guard, correctionsFilePath(paths.dataDir), auditBookLine));
1770
2120
  }
1771
2121
  if (config.seedReportTool !== false) {
1772
- registerGlobalTool("seed_report", () => buildSeedReportTool(guard, reportFilePath(paths.dataDir)));
2122
+ const auditReportLine = (entry) => {
2123
+ try {
2124
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), entry);
2125
+ } catch {
2126
+ }
2127
+ };
2128
+ registerGlobalTool("seed_report", () => buildSeedReportTool(
2129
+ guard,
2130
+ reportFilePath(paths.dataDir),
2131
+ () => concludeSilentTurnRef,
2132
+ auditReportLine,
2133
+ () => getCurrentDeliveryId(),
2134
+ // P1-1 (2.3.0, 账本 #d891e0): the lock is unconditional inside the
2135
+ // tool — a self-invented or repeated delivery id is always rejected;
2136
+ // this wiring only supplies the live-id getter and the audit sink.
2137
+ { onRejected: auditReportLine }
2138
+ ));
1773
2139
  }
1774
2140
  if (config.notepadTool !== false) {
1775
- registerGlobalTool("notepad", () => buildNotepadTool(guard, notepadFilePath(paths.dataDir)));
2141
+ const notepadAuditFile = paths.logsDir + "/heartbeat.jsonl";
2142
+ const notepadAllowed = (session) => {
2143
+ if (!session?.id) return false;
2144
+ return deliverySessionVerdict(session).allowed;
2145
+ };
2146
+ registerGlobalTool(
2147
+ "notepad",
2148
+ () => buildNotepadTool(guard, notepadFilePath(paths.dataDir), {
2149
+ isDeliverySession: (session) => notepadAllowed(session),
2150
+ onBlocked: (sessionId) => {
2151
+ try {
2152
+ appendAuditLine(guard.assert(notepadAuditFile), { event: "notepad_blocked", sessionId });
2153
+ } catch {
2154
+ }
2155
+ }
2156
+ }),
2157
+ (context) => notepadAllowed(context.agent?.session)
2158
+ );
1776
2159
  }
1777
2160
  if (config.excerptTool !== false) {
1778
2161
  registerGlobalTool("excerpt", () => buildExcerptTool(guard, excerptFilePath(paths.dataDir)));
@@ -1796,7 +2179,8 @@ function apply(ctx, config = {}) {
1796
2179
  const statusReader = new StatusReader();
1797
2180
  registerStatusbarSection(ctx, guard, paths, {
1798
2181
  enabled: () => statusbarEnabledRef,
1799
- reader: statusReader
2182
+ reader: statusReader,
2183
+ isDeliverSession: deliverySessionVerdict
1800
2184
  });
1801
2185
  ctx.effect(() => {
1802
2186
  registerTimeInjection(ctx, guard, paths.dataDir, {
@@ -1816,13 +2200,16 @@ function apply(ctx, config = {}) {
1816
2200
  return "";
1817
2201
  }
1818
2202
  return track === "pre-step" ? renderStatusText(statusReader.read(guard, paths)) : "";
1819
- }
2203
+ },
2204
+ isDeliverSession: deliverySessionVerdict
1820
2205
  });
1821
2206
  return void 0;
1822
2207
  }, "heartbeat: time injection");
1823
2208
  ctx.effect(() => {
1824
2209
  return () => {
1825
2210
  presetDisposed = true;
2211
+ detachEngineRoomPersonTools();
2212
+ personFallback.reset();
1826
2213
  const undoPreset = presetDisposer;
1827
2214
  presetDisposer = void 0;
1828
2215
  if (typeof undoPreset === "function") {
@@ -1837,8 +2224,10 @@ function apply(ctx, config = {}) {
1837
2224
  export {
1838
2225
  Config,
1839
2226
  apply,
2227
+ auditInvalidVisionEngines,
1840
2228
  deepMerge,
1841
2229
  inject,
1842
- name
2230
+ name,
2231
+ resolveVisionEngineSetting
1843
2232
  };
1844
2233
  //# sourceMappingURL=index.js.map