@kanadego/dsh-heartbeat 2.1.2 → 2.2.1

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.
@@ -0,0 +1,32 @@
1
+ import {
2
+ BILI_SESSION_FILE_NAME,
3
+ GENERATE_URL,
4
+ POLL_URL,
5
+ bilibiliSessionFilePath,
6
+ createBiliLoginService,
7
+ openImageProduction,
8
+ renderQrPngProduction,
9
+ runBiliLogin,
10
+ saveBiliSession,
11
+ sessdataFromCookies,
12
+ sessdataFromUrl,
13
+ tryOpenImage
14
+ } from "./chunk-SIY3YHFY.js";
15
+ import "./chunk-OCBE2AKW.js";
16
+ import "./chunk-M72T5MZU.js";
17
+ import "./chunk-IBBAISSW.js";
18
+ export {
19
+ BILI_SESSION_FILE_NAME,
20
+ GENERATE_URL,
21
+ POLL_URL,
22
+ bilibiliSessionFilePath,
23
+ createBiliLoginService,
24
+ openImageProduction,
25
+ renderQrPngProduction,
26
+ runBiliLogin,
27
+ saveBiliSession,
28
+ sessdataFromCookies,
29
+ sessdataFromUrl,
30
+ tryOpenImage
31
+ };
32
+ //# sourceMappingURL=bili-login-XQVEE4M6.js.map
@@ -22,7 +22,7 @@ import {
22
22
  sendNewMessageHint,
23
23
  sendWeeklyReadyHint,
24
24
  weeklyDue
25
- } from "./chunk-LPPRI53J.js";
25
+ } from "./chunk-XYBII5PR.js";
26
26
  import {
27
27
  getRuntime
28
28
  } from "./chunk-3QJJRXIR.js";
@@ -33,7 +33,7 @@ import {
33
33
  loadPool,
34
34
  seedsFilePath,
35
35
  surfaceSeed
36
- } from "./chunk-63E5OYSI.js";
36
+ } from "./chunk-N6SMIGYJ.js";
37
37
  import {
38
38
  resolveFocusUntil
39
39
  } from "./chunk-LQKOYTRL.js";
@@ -63,6 +63,7 @@ import {
63
63
  } from "./chunk-ECXYNTEV.js";
64
64
  import {
65
65
  decryptFile,
66
+ dshHomeDir,
66
67
  encryptFile,
67
68
  loadEncryptedText,
68
69
  loadJson,
@@ -79,8 +80,8 @@ import {
79
80
 
80
81
  // src/core/orchestrator.ts
81
82
  import { randomUUID as randomUUID2 } from "crypto";
82
- import fs8 from "fs";
83
- import path10 from "path";
83
+ import fs9 from "fs";
84
+ import path11 from "path";
84
85
 
85
86
  // src/env/envpulse.ts
86
87
  import fs2 from "fs";
@@ -244,47 +245,81 @@ function readPulse(guard, paths) {
244
245
  }
245
246
  }
246
247
 
247
- // src/screen/screenpulse.ts
248
+ // src/core/archived-sessions.ts
248
249
  import fs3 from "fs";
249
250
  import path3 from "path";
251
+ function parseArchivedSessionIds(text) {
252
+ try {
253
+ const j = JSON.parse(text);
254
+ const raw = j.global?.archivedSessionIds;
255
+ if (!Array.isArray(raw)) return /* @__PURE__ */ new Set();
256
+ return new Set(raw.map((s) => String(s)));
257
+ } catch {
258
+ return /* @__PURE__ */ new Set();
259
+ }
260
+ }
261
+ function loadArchivedSessionIds(registryFile) {
262
+ const file = registryFile ?? path3.join(dshHomeDir(), "storages", "workspace.json");
263
+ try {
264
+ return parseArchivedSessionIds(fs3.readFileSync(file, "utf8"));
265
+ } catch {
266
+ return /* @__PURE__ */ new Set();
267
+ }
268
+ }
269
+ function isArchivedSession(archived, id) {
270
+ return archived.has(id) || archived.has(id.replace(/^session-/, ""));
271
+ }
272
+ function splitDeliverTargets(all, archived) {
273
+ const usable = [];
274
+ const skipped = [];
275
+ for (const t of all) {
276
+ if (isArchivedSession(archived, t.sessionId)) skipped.push(t);
277
+ else usable.push(t);
278
+ }
279
+ return { usable, skipped };
280
+ }
281
+
282
+ // src/screen/screenpulse.ts
283
+ import fs4 from "fs";
284
+ import path4 from "path";
250
285
  var SCREEN_JSON = "screen.json";
251
286
  var SCREEN_JPG = "screen.jpg";
252
287
  function screenJsonPath(paths) {
253
- return path3.join(paths.dataDir, SCREEN_JSON);
288
+ return path4.join(paths.dataDir, SCREEN_JSON);
254
289
  }
255
290
  function screenJpgPath(paths) {
256
- return path3.join(paths.dataDir, SCREEN_JPG);
291
+ return path4.join(paths.dataDir, SCREEN_JPG);
257
292
  }
258
293
  var SCREEN_STAMP = "screen.capture";
259
294
  function screenStampPath(paths) {
260
- return path3.join(paths.dataDir, SCREEN_STAMP);
295
+ return path4.join(paths.dataDir, SCREEN_STAMP);
261
296
  }
262
297
  function readScreenStamp(paths) {
263
298
  try {
264
- return fs3.readFileSync(screenStampPath(paths), "utf8").trim();
299
+ return fs4.readFileSync(screenStampPath(paths), "utf8").trim();
265
300
  } catch {
266
301
  return "";
267
302
  }
268
303
  }
269
304
  function shotIsCurrent(guard, paths) {
270
305
  const f = screenJpgPath(paths);
271
- if (!fs3.existsSync(guard.assert(f))) return false;
306
+ if (!fs4.existsSync(guard.assert(f))) return false;
272
307
  const stamp = readScreenStamp(paths);
273
308
  const capturedAt = readScreenJson(guard, paths)?.captured_at ?? "";
274
309
  return Boolean(stamp) && stamp === capturedAt;
275
310
  }
276
311
  function dropStaleShot(guard, paths) {
277
312
  burnFileSync(guard.assert(screenJpgPath(paths)));
278
- fs3.rmSync(screenStampPath(paths), { force: true });
313
+ fs4.rmSync(screenStampPath(paths), { force: true });
279
314
  }
280
315
  async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, signal) {
281
- const rawJson = path3.join(paths.tmpDir, "screen.raw.json");
282
- const rawJpg = path3.join(paths.tmpDir, "screen.raw.jpg");
316
+ const rawJson = path4.join(paths.tmpDir, "screen.raw.json");
317
+ const rawJpg = path4.join(paths.tmpDir, "screen.raw.jpg");
283
318
  let encJson = "";
284
319
  let shotThisBeat = false;
285
320
  try {
286
321
  const r = await runPowerShellFile(
287
- path3.join(paths.assetsDir, "screenpulse.ps1"),
322
+ path4.join(paths.assetsDir, "screenpulse.ps1"),
288
323
  ["-outdir", paths.tmpDir, "-cap", String(windowCap)],
289
324
  45e3,
290
325
  signal
@@ -296,12 +331,12 @@ async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, sig
296
331
  dropStaleShot(guard, paths);
297
332
  return { ok: false, capturedAt: null, hasShot: false, visibleCount: 0, error: `collector exit ${r.status}` };
298
333
  }
299
- const raw = fs3.readFileSync(rawJson, "utf8");
334
+ const raw = fs4.readFileSync(rawJson, "utf8");
300
335
  const meta = JSON.parse(raw);
301
- if (meta.shot_path && fs3.existsSync(meta.shot_path)) {
336
+ if (meta.shot_path && fs4.existsSync(meta.shot_path)) {
302
337
  try {
303
338
  encryptFile(guard, meta.shot_path, screenJpgPath(paths));
304
- fs3.writeFileSync(
339
+ fs4.writeFileSync(
305
340
  screenStampPath(paths),
306
341
  String(meta.captured_at ?? new Date(now).toISOString()),
307
342
  "utf8"
@@ -313,8 +348,8 @@ async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, sig
313
348
  if (!shotThisBeat) dropStaleShot(guard, paths);
314
349
  const { shot_path: _drop, ...clean } = meta;
315
350
  void _drop;
316
- encJson = path3.join(paths.tmpDir, `screen.enc.${now}.json`);
317
- fs3.writeFileSync(encJson, JSON.stringify(clean, null, 1), "utf8");
351
+ encJson = path4.join(paths.tmpDir, `screen.enc.${now}.json`);
352
+ fs4.writeFileSync(encJson, JSON.stringify(clean, null, 1), "utf8");
318
353
  encryptFile(guard, encJson, screenJsonPath(paths));
319
354
  return {
320
355
  ok: true,
@@ -327,17 +362,17 @@ async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, sig
327
362
  return { ok: false, capturedAt: null, hasShot: false, visibleCount: 0, error: String(e) };
328
363
  } finally {
329
364
  for (const leftover of [rawJson, rawJpg, encJson]) {
330
- fs3.rmSync(leftover, { force: true });
365
+ fs4.rmSync(leftover, { force: true });
331
366
  }
332
367
  }
333
368
  }
334
369
  function readScreenJson(guard, paths) {
335
370
  const f = screenJsonPath(paths);
336
- if (!fs3.existsSync(guard.assert(f))) return null;
337
- const tmp = path3.join(paths.tmpDir, `screen.read.${Date.now()}.json`);
371
+ if (!fs4.existsSync(guard.assert(f))) return null;
372
+ const tmp = path4.join(paths.tmpDir, `screen.read.${Date.now()}.json`);
338
373
  try {
339
374
  decryptFile(guard, f, guard.assert(tmp));
340
- return JSON.parse(fs3.readFileSync(tmp, "utf8"));
375
+ return JSON.parse(fs4.readFileSync(tmp, "utf8"));
341
376
  } catch {
342
377
  return null;
343
378
  } finally {
@@ -347,7 +382,7 @@ function readScreenJson(guard, paths) {
347
382
  function unlockShot(guard, paths) {
348
383
  const f = screenJpgPath(paths);
349
384
  if (!shotIsCurrent(guard, paths)) return null;
350
- const tmp = path3.join(paths.tmpDir, `screen.view.${Date.now()}.jpg`);
385
+ const tmp = path4.join(paths.tmpDir, `screen.view.${Date.now()}.jpg`);
351
386
  try {
352
387
  decryptFile(guard, f, guard.assert(tmp));
353
388
  } catch (e) {
@@ -362,8 +397,8 @@ function burnUnlocked(guard, tmpPath) {
362
397
 
363
398
  // src/screen/vision.ts
364
399
  import { createRequire } from "module";
365
- import fs4 from "fs";
366
- import path4 from "path";
400
+ import fs5 from "fs";
401
+ import path5 from "path";
367
402
  import { spawn } from "child_process";
368
403
  var VISION_TIMEOUT_MS = 12e4;
369
404
  var VISION_MAX_SUMMARY = 300;
@@ -371,8 +406,8 @@ function resolveModlensMain(fromUrl) {
371
406
  try {
372
407
  const req = createRequire(fromUrl);
373
408
  const pkgJson = req.resolve("@liustack/modlens/package.json");
374
- const main = path4.join(path4.dirname(pkgJson), "dist", "main.js");
375
- return fs4.existsSync(main) ? main : null;
409
+ const main = path5.join(path5.dirname(pkgJson), "dist", "main.js");
410
+ return fs5.existsSync(main) ? main : null;
376
411
  } catch {
377
412
  return null;
378
413
  }
@@ -410,7 +445,7 @@ function extractSummary(raw) {
410
445
  var DEFAULT_VISION_PROVIDER = "openai";
411
446
  function readVisionSettings(guard, paths) {
412
447
  try {
413
- const raw = fs4.readFileSync(guard.assert(path4.join(paths.settingsDir, "vision.json")), "utf8");
448
+ const raw = fs5.readFileSync(guard.assert(path5.join(paths.settingsDir, "vision.json")), "utf8");
414
449
  const obj = JSON.parse(raw);
415
450
  return {
416
451
  ...typeof obj.provider === "string" && obj.provider.trim() ? { provider: obj.provider.trim() } : {},
@@ -423,7 +458,7 @@ function readVisionSettings(guard, paths) {
423
458
  async function describeScreenShot(guard, paths, opts) {
424
459
  const mainJs = opts.mainPath ?? resolveModlensMain(opts.moduleUrl);
425
460
  if (!mainJs) return { ok: false, summary: null, error: "modlens not installed" };
426
- const outJson = path4.join(paths.tmpDir, `screen.vision.${Date.now()}.json`);
461
+ const outJson = path5.join(paths.tmpDir, `screen.vision.${Date.now()}.json`);
427
462
  const spawnCli = opts.spawnCli ?? defaultSpawn;
428
463
  const timeoutMs = opts.timeoutMs ?? VISION_TIMEOUT_MS;
429
464
  const settings = opts.settings ?? readVisionSettings(guard, paths);
@@ -451,7 +486,7 @@ async function describeScreenShot(guard, paths, opts) {
451
486
  if (code !== 0) {
452
487
  return { ok: false, summary: null, error: `modlens exit ${code}${stderr ? `: ${stderr.slice(0, 140)}` : ""}` };
453
488
  }
454
- const raw = fs4.existsSync(outJson) ? fs4.readFileSync(outJson, "utf8") : "";
489
+ const raw = fs5.existsSync(outJson) ? fs5.readFileSync(outJson, "utf8") : "";
455
490
  const summary = extractSummary(raw);
456
491
  if (!summary) return { ok: false, summary: null, error: "modlens produced no summary" };
457
492
  return { ok: true, summary };
@@ -459,16 +494,16 @@ async function describeScreenShot(guard, paths, opts) {
459
494
  return { ok: false, summary: null, error: String(e).slice(0, 160) };
460
495
  } finally {
461
496
  if (shot) burnUnlocked(guard, shot);
462
- fs4.rmSync(outJson, { force: true });
497
+ fs5.rmSync(outJson, { force: true });
463
498
  }
464
499
  }
465
500
 
466
501
  // src/gate/gate.ts
467
- import path5 from "path";
468
- import fs5 from "fs";
502
+ import path6 from "path";
503
+ import fs6 from "fs";
469
504
  var STABLE_WINDOW_MS = 15e3;
470
505
  function sentFilePath(paths) {
471
- return path5.join(paths.dataDir, "sent.json");
506
+ return path6.join(paths.dataDir, "sent.json");
472
507
  }
473
508
  function localDay(now) {
474
509
  const d = new Date(now);
@@ -511,16 +546,16 @@ function evaluateGate(input) {
511
546
  };
512
547
  }
513
548
  async function probeFrontWindowLive(guard, paths, signal) {
514
- const tmp = path5.join(paths.tmpDir, `frontwin.${Date.now()}.json`);
549
+ const tmp = path6.join(paths.tmpDir, `frontwin.${Date.now()}.json`);
515
550
  try {
516
551
  const out = guard.assert(tmp);
517
- const r = await runPowerShellFile(path5.join(paths.assetsDir, "frontwin.ps1"), ["-out", out], 1e4, signal);
518
- if (r.status !== 0 || !fs5.existsSync(out)) return null;
519
- return JSON.parse(fs5.readFileSync(out, "utf8"));
552
+ const r = await runPowerShellFile(path6.join(paths.assetsDir, "frontwin.ps1"), ["-out", out], 1e4, signal);
553
+ if (r.status !== 0 || !fs6.existsSync(out)) return null;
554
+ return JSON.parse(fs6.readFileSync(out, "utf8"));
520
555
  } catch {
521
556
  return null;
522
557
  } finally {
523
- fs5.rmSync(tmp, { force: true });
558
+ fs6.rmSync(tmp, { force: true });
524
559
  }
525
560
  }
526
561
  function probeFrontWindowSnapshot(guard, paths, rules) {
@@ -610,10 +645,23 @@ function shuffle(items, rand) {
610
645
  }
611
646
  return out;
612
647
  }
648
+ var BILI_TOPIC_SOFT_CAP = 2;
613
649
  function assembleCandidates(seeds, opts = {}) {
614
650
  const rand = opts.rand ?? Math.random;
615
651
  const cat = (s) => s.category ?? "topic";
616
- const topicPool = shuffle(seeds.filter((s) => cat(s) === "topic"), rand);
652
+ const isBili = (s) => s.source === "bilibili";
653
+ const shuffled = shuffle(seeds.filter((s) => cat(s) === "topic"), rand);
654
+ const head = [];
655
+ const tail = [];
656
+ let biliSeen = 0;
657
+ for (const s of shuffled) {
658
+ if (isBili(s) && biliSeen >= BILI_TOPIC_SOFT_CAP) tail.push(s);
659
+ else {
660
+ if (isBili(s)) biliSeen += 1;
661
+ head.push(s);
662
+ }
663
+ }
664
+ const topicPool = [...head, ...tail];
617
665
  const chatPool = seeds.filter((s) => cat(s) === "chat").sort((a, b) => Date.parse(b.lastEvidenceAt) - Date.parse(a.lastEvidenceAt));
618
666
  const topic = topicPool.slice(0, 4);
619
667
  const chat = chatPool.slice(0, 2);
@@ -712,12 +760,12 @@ function reconcileDelivery(materials, report, decisionIds, spokeText) {
712
760
  function buildRuminationPrompt(input) {
713
761
  const max = input.max ?? 3;
714
762
  const lines = [
715
- "\u8FD9\u662F\u5FC3\u8DF3\u8F6E\u6B21\u7684\u53CD\u520D\u5907\u6599\u73AF\u8282:\u4ECE\u5019\u9009\u7D20\u6750\u91CC\u6311(\u6700\u591A " + max + " \u6761),\u628A\u6BCF\u6761\u538B\u7F29\u6210\u4E00\u53E5\u8BDD\u3002",
763
+ "\u8FD9\u662F\u5FC3\u8DF3\u8F6E\u6B21\u7684\u53CD\u520D\u5907\u6599\u73AF\u8282:\u4ECE\u5019\u9009\u7D20\u6750\u91CC\u6311(\u6700\u591A " + max + " \u6761),\u9009\u51FA\u6700\u60F3\u8BF4\u7684\u51E0\u6761\u3002",
716
764
  "\u7D20\u6750\u53EA\u4ECE\u4E0B\u9762\u7ED9\u7684\u5019\u9009\u91CC\u6311,\u4E0D\u8981\u81EA\u5DF1\u7F16;\u6CA1\u5408\u9002\u7684\u5C31\u5C11\u6311,\u751A\u81F3\u53EF\u4EE5\u4E0D\u6311\u3002",
717
765
  "\u4E0D\u8981\u4F7F\u7528\u4EFB\u4F55\u5DE5\u5177\u3002\u53EA\u8F93\u51FA\u4E00\u4E2A JSON \u5BF9\u8C61:",
718
- '- \u6709\u60F3\u9012\u7684:{"speak":true,"text":"\u7B2C1\u6761\u7D20\u6750\n\u7B2C2\u6761\u7D20\u6750...","seed_ids":["s1","s2"],"doing":"\u4ED6\u6B64\u523B\u5728\u5E72\u4EC0\u4E48(\u4E00\u53E5\u8BDD)"}',
719
- '- \u4E00\u6761\u90FD\u4E0D\u5408\u9002:{"speak":false,"seed_ids":[],"doing":"\u4ED6\u6B64\u523B\u5728\u5E72\u4EC0\u4E48(\u4E00\u53E5\u8BDD)"}',
720
- "- text = \u6311\u51FA\u7684\u7D20\u6750,\u6BCF\u6761\u7D20\u6750\u5355\u72EC\u4E00\u884C;seed_ids = \u5BF9\u5E94\u7684\u7D20\u6750 id\u3002",
766
+ '- \u6709\u60F3\u9012\u7684:{"seed_ids":["s1","s2"],"doing":"\u4ED6\u6B64\u523B\u5728\u5E72\u4EC0\u4E48(\u4E00\u53E5\u8BDD)"}',
767
+ '- \u4E00\u6761\u90FD\u4E0D\u5408\u9002:{"seed_ids":[],"doing":"\u4ED6\u6B64\u523B\u5728\u5E72\u4EC0\u4E48(\u4E00\u53E5\u8BDD)"}',
768
+ "- seed_ids = \u5BF9\u5E94\u7684\u7D20\u6750 id\u3002",
721
769
  "",
722
770
  "## \u6B64\u523B\u5904\u5883",
723
771
  input.digestTact,
@@ -749,10 +797,10 @@ function buildRuminationPrompt(input) {
749
797
  }
750
798
 
751
799
  // src/seeds/report.ts
752
- import path6 from "path";
800
+ import path7 from "path";
753
801
  var REPORT_REASONS = ["\u4E0D\u60F3\u8BF4\u8BDD", "\u7D20\u6750\u4E0D\u642D", "\u5728\u5FD9\u6216\u521A\u804A\u8FC7"];
754
802
  function reportFilePath(dataDir) {
755
- return path6.join(dataDir, "seed_report.jsonl");
803
+ return path7.join(dataDir, "seed_report.jsonl");
756
804
  }
757
805
  var REPORT_KEEP = 400;
758
806
  function parseEntry(obj) {
@@ -868,9 +916,9 @@ function buildSeedReportTool(guard, file) {
868
916
  }
869
917
 
870
918
  // src/notepad/store.ts
871
- import path7 from "path";
919
+ import path8 from "path";
872
920
  function notepadFilePath(dataDir) {
873
- return path7.join(dataDir, "notepad.json");
921
+ return path8.join(dataDir, "notepad.json");
874
922
  }
875
923
  function emptyState() {
876
924
  return { note: null, counters: { beats: 0, delivers: 0 } };
@@ -968,8 +1016,8 @@ function notepadView(st, now = Date.now()) {
968
1016
  }
969
1017
 
970
1018
  // src/statusbar/store.ts
971
- import fs6 from "fs";
972
- import path8 from "path";
1019
+ import fs7 from "fs";
1020
+ import path9 from "path";
973
1021
  function deriveScene(input) {
974
1022
  if (input.quietHours) return "quiet-hours";
975
1023
  if (input.spokeThisBeat) return "just-spoke";
@@ -984,14 +1032,14 @@ function clampNote(note) {
984
1032
  return t.length <= 30 ? t : t.slice(0, 30);
985
1033
  }
986
1034
  function statusFilePath(dataDir) {
987
- return path8.join(dataDir, "settings", "status.json");
1035
+ return path9.join(dataDir, "settings", "status.json");
988
1036
  }
989
1037
  function writeStatus(guard, paths, state) {
990
1038
  atomicWriteJsonSync(guard.assert(statusFilePath(paths.dataDir)), state);
991
1039
  }
992
1040
  function readStatus(guard, paths) {
993
1041
  try {
994
- const raw = fs6.readFileSync(guard.assert(statusFilePath(paths.dataDir)), "utf8");
1042
+ const raw = fs7.readFileSync(guard.assert(statusFilePath(paths.dataDir)), "utf8");
995
1043
  const parsed = JSON.parse(raw);
996
1044
  if (typeof parsed?.at !== "string" || typeof parsed?.scene !== "string") return null;
997
1045
  return parsed;
@@ -1007,7 +1055,7 @@ var StatusReader = class {
1007
1055
  const file = statusFilePath(paths.dataDir);
1008
1056
  let st;
1009
1057
  try {
1010
- st = fs6.statSync(guard.assert(file));
1058
+ st = fs7.statSync(guard.assert(file));
1011
1059
  } catch {
1012
1060
  this.mtimeMs = -1;
1013
1061
  this.cached = null;
@@ -1218,7 +1266,7 @@ async function runConsolidation(guard, paths, policy, llm, now = Date.now()) {
1218
1266
  rejected,
1219
1267
  entries: [...report.entries ?? [], ...aged.entries]
1220
1268
  });
1221
- const { addSeed: addSeed2, seedsFilePath: seedsFilePath2 } = await import("./pool-MAABBHC4.js");
1269
+ const { addSeed: addSeed2, seedsFilePath: seedsFilePath2 } = await import("./pool-76VLAZER.js");
1222
1270
  const seedAudit = (entry) => {
1223
1271
  try {
1224
1272
  appendAuditLine(paths.dataDir + "/logs/heartbeat.jsonl", entry);
@@ -1272,19 +1320,19 @@ async function runConsolidation(guard, paths, policy, llm, now = Date.now()) {
1272
1320
  }
1273
1321
 
1274
1322
  // src/rhythm/rhythm.ts
1275
- import fs7 from "fs";
1276
- import path9 from "path";
1323
+ import fs8 from "fs";
1324
+ import path10 from "path";
1277
1325
  var DAY_MS = 864e5;
1278
1326
  var TAU_DAYS = 10;
1279
1327
  var CELL_EPSILON = 1e-3;
1280
1328
  var PEAK_MIN_ACTIVE = 0.25;
1281
1329
  var PEAK_MIN_SHARE = 0.05;
1282
1330
  function rhythmFilePath(paths) {
1283
- return path9.join(paths.dataDir, "profile_rhythm.json");
1331
+ return path10.join(paths.dataDir, "profile_rhythm.json");
1284
1332
  }
1285
1333
  function loadRhythm(paths) {
1286
1334
  try {
1287
- return JSON.parse(fs7.readFileSync(rhythmFilePath(paths), "utf8"));
1335
+ return JSON.parse(fs8.readFileSync(rhythmFilePath(paths), "utf8"));
1288
1336
  } catch {
1289
1337
  return { histogram: {}, days: [], lastDecayAt: (/* @__PURE__ */ new Date()).toISOString() };
1290
1338
  }
@@ -1659,7 +1707,7 @@ function noteBeat(verdict, detail) {
1659
1707
  lastBeat = { at: (/* @__PURE__ */ new Date()).toISOString(), verdict, ...detail };
1660
1708
  }
1661
1709
  function gateFilePath(paths) {
1662
- return path10.join(paths.dataDir, "gate.json");
1710
+ return path11.join(paths.dataDir, "gate.json");
1663
1711
  }
1664
1712
  function readBeatState(guard, paths) {
1665
1713
  try {
@@ -1677,7 +1725,7 @@ function homeSessionId(guard, paths) {
1677
1725
  function resetHomeSession(guard, paths, id) {
1678
1726
  if (homeSessionId(guard, paths) !== id) return false;
1679
1727
  try {
1680
- fs8.rmSync(guard.assert(gateFilePath(paths)), { force: true });
1728
+ fs9.rmSync(guard.assert(gateFilePath(paths)), { force: true });
1681
1729
  } catch {
1682
1730
  }
1683
1731
  appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "home_reset", oldSessionId: id });
@@ -1746,6 +1794,30 @@ function pinEngineRoomTools(deps, agentCtx, notes) {
1746
1794
  }
1747
1795
  }
1748
1796
  }
1797
+ async function waitForVisibleTool(getSchemas, name, opts) {
1798
+ const timeoutMs = opts?.timeoutMs ?? 2e3;
1799
+ const pollMs = opts?.pollMs ?? 50;
1800
+ const now = opts?.now ?? (() => Date.now());
1801
+ const sleep = opts?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1802
+ const startedAt = now();
1803
+ let sawNames = [];
1804
+ for (; ; ) {
1805
+ let schemas = [];
1806
+ try {
1807
+ schemas = getSchemas() ?? [];
1808
+ } catch {
1809
+ }
1810
+ sawNames = schemas.map((s) => String(s?.name ?? ""));
1811
+ if (sawNames.includes(name)) {
1812
+ return { ready: true, waitedMs: now() - startedAt, sawNames };
1813
+ }
1814
+ const elapsed = now() - startedAt;
1815
+ if (elapsed >= timeoutMs) {
1816
+ return { ready: false, waitedMs: elapsed, sawNames };
1817
+ }
1818
+ await sleep(Math.min(pollMs, timeoutMs - elapsed));
1819
+ }
1820
+ }
1749
1821
  function makeHomeSetup(deps) {
1750
1822
  const { ctx, paths } = deps;
1751
1823
  return async (agentCtx) => {
@@ -1756,6 +1828,7 @@ function makeHomeSetup(deps) {
1756
1828
  } catch (e) {
1757
1829
  notes.push(`preset-register=threw(${String(e).slice(0, 120)})`);
1758
1830
  }
1831
+ let presetMounted = false;
1759
1832
  try {
1760
1833
  const presets = agentCtx.get("agentPresets");
1761
1834
  if (typeof presets?.mount !== "function") {
@@ -1764,10 +1837,26 @@ function makeHomeSetup(deps) {
1764
1837
  const preset = await presets.mount(agentCtx, presetId);
1765
1838
  const joined = preset?.id;
1766
1839
  notes.push(`preset=mounted(${joined ?? presetId})`);
1840
+ presetMounted = true;
1767
1841
  }
1768
1842
  } catch (e) {
1769
1843
  notes.push(`preset=threw(${String(e).slice(0, 200)})`);
1770
1844
  }
1845
+ if (presetMounted) {
1846
+ const tools = agentCtx.get("tools");
1847
+ if (typeof tools?.schemas !== "function") {
1848
+ notes.push("toolsReady=no-api");
1849
+ } else {
1850
+ try {
1851
+ const wait = await waitForVisibleTool(() => tools.schemas(agentCtx) ?? [], "web_search");
1852
+ notes.push(
1853
+ wait.ready ? `toolsReady=ok(${wait.waitedMs}ms)` : `toolsReady=timeout(${wait.waitedMs}ms saw=${wait.sawNames.slice(0, 5).join(",") || "(empty)"})`
1854
+ );
1855
+ } catch (e) {
1856
+ notes.push(`toolsReady=threw(${String(e).slice(0, 120)})`);
1857
+ }
1858
+ }
1859
+ }
1771
1860
  pinEngineRoomTools(deps, agentCtx, notes);
1772
1861
  ctx.logger.info("heartbeat: tool policy %s", notes.join(" "));
1773
1862
  appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "tool_policy", policy: notes.join(" ") });
@@ -2131,7 +2220,7 @@ async function collectPhase(bc) {
2131
2220
  }
2132
2221
  function loadCursors(file) {
2133
2222
  try {
2134
- const raw = JSON.parse(fs8.readFileSync(file, "utf8"));
2223
+ const raw = JSON.parse(fs9.readFileSync(file, "utf8"));
2135
2224
  if (raw?.version === 2 && raw.sessions && typeof raw.sessions === "object") {
2136
2225
  const sessions = {};
2137
2226
  for (const [id, v] of Object.entries(raw.sessions)) {
@@ -2162,6 +2251,20 @@ function spokeTextSince(session, fromSeq) {
2162
2251
  }
2163
2252
  return null;
2164
2253
  }
2254
+ function turnEndKindSince(session, fromSeq) {
2255
+ let kind = null;
2256
+ for (const e of sessionEvents(session, fromSeq)) {
2257
+ if (e.type !== "turn/end") continue;
2258
+ const d = e.data;
2259
+ if (typeof d?.reason?.kind === "string") kind = d.reason.kind;
2260
+ }
2261
+ return kind;
2262
+ }
2263
+ function classifySilentReason(raw, turnEndKind) {
2264
+ if (turnEndKind === "blocked") return "target turn blocked";
2265
+ if (!raw.trim()) return "empty model output";
2266
+ return "non-Chinese output discarded";
2267
+ }
2165
2268
  async function observeBoundSessions(bc) {
2166
2269
  throwIfAborted(bc.signal, "observe");
2167
2270
  const { deps, now } = bc;
@@ -2171,7 +2274,7 @@ async function observeBoundSessions(bc) {
2171
2274
  const data = loadBindings(guard, paths.settingsDir);
2172
2275
  const targets = observeTargets(data);
2173
2276
  if (targets.length === 0) return;
2174
- const cursorFile = path10.join(paths.dataDir, "cursors.json");
2277
+ const cursorFile = path11.join(paths.dataDir, "cursors.json");
2175
2278
  const loaded = loadCursors(cursorFile);
2176
2279
  const cursors = loaded.sessions;
2177
2280
  if (loaded.discardedLegacy) {
@@ -2458,7 +2561,24 @@ async function deliverPackage(bc, materials, opts) {
2458
2561
  const homeId = bc.agent?.session?.id ?? null;
2459
2562
  const { loadBindings, deliverTargets } = await import("./bindings-U2M3CO2D.js");
2460
2563
  const data = loadBindings(guard, paths.settingsDir);
2461
- const targets = deliverTargets(data).filter((b) => b.sessionId !== homeId);
2564
+ const archived = loadArchivedSessionIds();
2565
+ const all = deliverTargets(data).filter((b) => b.sessionId !== homeId);
2566
+ const { usable: targets, skipped } = splitDeliverTargets(all, archived);
2567
+ if (skipped.length > 0) {
2568
+ appendAuditLine(paths.logsDir + "/heartbeat.jsonl", {
2569
+ event: "deliver_target_skipped",
2570
+ reason: "archived",
2571
+ targets: skipped.map((t) => t.sessionId).join(",")
2572
+ });
2573
+ }
2574
+ if (targets.length === 0 && all.length > 0) {
2575
+ appendAuditLine(paths.logsDir + "/heartbeat.jsonl", {
2576
+ event: "spoke_failed",
2577
+ reason: "all deliver targets archived"
2578
+ });
2579
+ noteBeat("spoke_failed", { reason: "all deliver targets archived" });
2580
+ return;
2581
+ }
2462
2582
  let liveTarget = null;
2463
2583
  for (const b of targets) {
2464
2584
  const acquired = await acquireTargetAgent(deps, b.sessionId);
@@ -2544,8 +2664,9 @@ async function deliverPackage(bc, materials, opts) {
2544
2664
  appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "preference_record_failed", error: String(e).slice(0, 120) });
2545
2665
  }
2546
2666
  } else {
2547
- appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "spoke_failed", reason: "non-Chinese output discarded" });
2548
- noteBeat("spoke_failed", { reason: "non-Chinese output discarded" });
2667
+ const silentReason = classifySilentReason(spokenRaw, turnEndKindSince(voiceAgent.session, beforeSeq));
2668
+ appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "spoke_failed", reason: silentReason });
2669
+ noteBeat("spoke_failed", { reason: silentReason });
2549
2670
  }
2550
2671
  return;
2551
2672
  }
@@ -2677,8 +2798,7 @@ async function expressionPhases(bc) {
2677
2798
  if (!Array.isArray(parsed.seed_ids) || parsed.seed_ids.length === 0) {
2678
2799
  appendAuditLine(paths.logsDir + "/heartbeat.jsonl", {
2679
2800
  event: "expression_dropped",
2680
- why: "no seed_ids from the decision turn",
2681
- speak_flag: typeof parsed.speak === "boolean" ? parsed.speak : null
2801
+ why: "no seed_ids from the decision turn"
2682
2802
  });
2683
2803
  noteDroppedStreak(paths.logsDir + "/heartbeat.jsonl", "no seed_ids from the decision turn");
2684
2804
  noteBeat("silent", { reason: "no material" });
@@ -2798,7 +2918,7 @@ async function userActiveInBoundSessions(deps) {
2798
2918
  const { loadBindings, observeTargets } = await import("./bindings-U2M3CO2D.js");
2799
2919
  const targets = observeTargets(loadBindings(deps.guard, deps.paths.settingsDir));
2800
2920
  if (targets.length === 0) return false;
2801
- const cursors = loadCursors(path10.join(deps.paths.dataDir, "cursors.json")).sessions;
2921
+ const cursors = loadCursors(path11.join(deps.paths.dataDir, "cursors.json")).sessions;
2802
2922
  for (const b of targets) {
2803
2923
  const agent = ctx_getAgent(deps, b.sessionId);
2804
2924
  if (!agent) continue;
@@ -2878,6 +2998,12 @@ async function beat(deps, trigger = "interval") {
2878
2998
  if (agent && homeRotatePending === null && shouldRotateHome({ eventCount: sessionEventCount(agent.session) })) {
2879
2999
  homeRotatePending = `size threshold (${sessionEventCount(agent.session)} events \u2265 ${HOME_ROTATE_EVENT_COUNT})`;
2880
3000
  }
3001
+ if (agent && homeRotatePending === null) {
3002
+ const homeId = agent.session?.id;
3003
+ if (homeId && isArchivedSession(loadArchivedSessionIds(), homeId)) {
3004
+ homeRotatePending = `home session archived (${homeId})`;
3005
+ }
3006
+ }
2881
3007
  if (agent && homeRotatePending !== null) {
2882
3008
  try {
2883
3009
  await rotateHome(deps, homeRotatePending);
@@ -3050,6 +3176,8 @@ function startOrchestrator(deps) {
3050
3176
  }
3051
3177
 
3052
3178
  export {
3179
+ parseArchivedSessionIds,
3180
+ isArchivedSession,
3053
3181
  readSentState,
3054
3182
  inQuietHours,
3055
3183
  reportFilePath,
@@ -3087,6 +3215,8 @@ export {
3087
3215
  ENGINE_ROOM_EXTRA_TOOLS,
3088
3216
  buildEngineRoomAllowList,
3089
3217
  pinEngineRoomTools,
3218
+ waitForVisibleTool,
3219
+ makeHomeSetup,
3090
3220
  shouldArchiveRotatedHome,
3091
3221
  agentLooksAlive,
3092
3222
  agentTurn,
@@ -3095,6 +3225,8 @@ export {
3095
3225
  loadCursors,
3096
3226
  pickSpokenLine,
3097
3227
  spokeTextSince,
3228
+ turnEndKindSince,
3229
+ classifySilentReason,
3098
3230
  TOKEN_SAVER_IDLE_SECONDS,
3099
3231
  TOKEN_SAVER_WAKE_MS,
3100
3232
  userActiveInBoundSessions,
@@ -3104,4 +3236,4 @@ export {
3104
3236
  jitteredIntervalMs,
3105
3237
  startOrchestrator
3106
3238
  };
3107
- //# sourceMappingURL=chunk-XCMGPIUQ.js.map
3239
+ //# sourceMappingURL=chunk-CJK6RTMH.js.map