@kanadego/dsh-heartbeat 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,8 +9,10 @@ import {
9
9
  getLastBeat,
10
10
  homeSessionId,
11
11
  inQuietHours,
12
+ isArchivedSession,
12
13
  notepadFilePath,
13
14
  notepadView,
15
+ parseArchivedSessionIds,
14
16
  pauseFocus,
15
17
  readNotepad,
16
18
  readSentState,
@@ -22,7 +24,12 @@ import {
22
24
  sessionEvents,
23
25
  startOrchestrator,
24
26
  writeNote
25
- } from "./chunk-XCMGPIUQ.js";
27
+ } from "./chunk-WF7ZBW5C.js";
28
+ import {
29
+ bilibiliSessionFilePath,
30
+ createBiliLoginService,
31
+ saveBiliSession
32
+ } from "./chunk-SIY3YHFY.js";
26
33
  import {
27
34
  EXCERPT_HEADER,
28
35
  appendExcerpt,
@@ -37,7 +44,7 @@ import {
37
44
  removeExcerpt,
38
45
  updateUserPolicy,
39
46
  userPresetRoot
40
- } from "./chunk-HE6IF6OU.js";
47
+ } from "./chunk-F2XVKX55.js";
41
48
  import {
42
49
  appendEntry,
43
50
  ledgerFilePath,
@@ -47,20 +54,24 @@ import {
47
54
  readLedger,
48
55
  readWeeklyReport,
49
56
  scanPending
50
- } from "./chunk-LPPRI53J.js";
57
+ } from "./chunk-XYBII5PR.js";
58
+ import {
59
+ openPath
60
+ } from "./chunk-OCBE2AKW.js";
51
61
  import {
52
62
  getRuntime,
53
63
  setRuntime
54
64
  } from "./chunk-3QJJRXIR.js";
55
65
  import {
56
66
  activeSeeds,
67
+ addSeed,
57
68
  archiveSeedById,
58
69
  archivedSeeds,
59
70
  deleteSeed,
60
71
  loadPool,
61
72
  restoreSeed,
62
73
  seedsFilePath
63
- } from "./chunk-63E5OYSI.js";
74
+ } from "./chunk-N6SMIGYJ.js";
64
75
  import {
65
76
  clearFocusState,
66
77
  readFocusState,
@@ -76,6 +87,8 @@ import {
76
87
  import {
77
88
  dshHomeDir,
78
89
  initWorkspace,
90
+ loadJson,
91
+ saveJson,
79
92
  writeText
80
93
  } from "./chunk-M72T5MZU.js";
81
94
  import {
@@ -134,8 +147,24 @@ function saveUiConfig(guard, settingsDir, patch) {
134
147
  return merged;
135
148
  }
136
149
 
150
+ // src/config/quiet-hours.ts
151
+ var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
152
+ function normalizeHhMm(v) {
153
+ return typeof v === "string" && HHMM.test(v) ? v : null;
154
+ }
155
+ function resolveQuietHours(startRaw, endRaw, current) {
156
+ const given = (v) => v !== void 0 && v !== null;
157
+ if (!given(startRaw) && !given(endRaw)) return { start: current.start, end: current.end };
158
+ const start = normalizeHhMm(startRaw);
159
+ const end = normalizeHhMm(endRaw);
160
+ if (given(startRaw) && !start || given(endRaw) && !end) return null;
161
+ return {
162
+ start: start ?? current.start,
163
+ end: end ?? current.end
164
+ };
165
+ }
166
+
137
167
  // src/rpc.ts
138
- import { spawn } from "child_process";
139
168
  import fs4 from "fs";
140
169
  import path4 from "path";
141
170
 
@@ -145,7 +174,7 @@ import path2 from "path";
145
174
  var MAX_INTERESTS = 32;
146
175
  var MAX_INTEREST_LEN = 60;
147
176
  var MAX_WINDOWS = 6;
148
- var HHMM = /^([01]\d|2[0-3]):([0-5]\d)$/;
177
+ var HHMM2 = /^([01]\d|2[0-3]):([0-5]\d)$/;
149
178
  function userInterestsPath(paths) {
150
179
  return path2.join(paths.settingsDir, "interests.json");
151
180
  }
@@ -210,8 +239,8 @@ function removeInterest(guard, paths, rawText) {
210
239
  function parseWindow(w) {
211
240
  if (typeof w !== "object" || w === null) return { ok: false, reason: "not-an-object" };
212
241
  const { id, start, end } = w;
213
- if (typeof start !== "string" || !HHMM.test(start)) return { ok: false, reason: `bad start ${JSON.stringify(start)}` };
214
- if (typeof end !== "string" || !HHMM.test(end)) return { ok: false, reason: `bad end ${JSON.stringify(end)}` };
242
+ if (typeof start !== "string" || !HHMM2.test(start)) return { ok: false, reason: `bad start ${JSON.stringify(start)}` };
243
+ if (typeof end !== "string" || !HHMM2.test(end)) return { ok: false, reason: `bad end ${JSON.stringify(end)}` };
215
244
  if (start >= end) return { ok: false, reason: `start ${start} must be before end ${end}` };
216
245
  return { ok: true, window: { id: typeof id === "string" && id ? id : `${start}-${end}`, start, end } };
217
246
  }
@@ -243,21 +272,26 @@ import fs3 from "fs";
243
272
  import path3 from "path";
244
273
  function shouldInjectTime(input) {
245
274
  if (input.step !== 1) return false;
246
- if (!input.originIsInboxSplice) return false;
275
+ if (!input.originIsUserSplice) return false;
247
276
  if (input.intervalMs <= 0) return false;
248
277
  return input.now - input.lastInjectAt >= input.intervalMs;
249
278
  }
250
- function turnOriginIsInboxSplice(session) {
279
+ function turnOriginIsUserSplice(session) {
251
280
  const events = sessionEvents(session);
252
- let splicedIdx = -1;
253
- let turnEndIdx = -1;
254
- for (let i = events.length - 1; i >= 0 && (splicedIdx < 0 || turnEndIdx < 0); i--) {
255
- const t = events[i].type;
256
- if (t === "agent/inbox/spliced" && splicedIdx < 0) splicedIdx = i;
257
- else if (t === "turn/end" && turnEndIdx < 0) turnEndIdx = i;
281
+ let start = 0;
282
+ for (let i = events.length - 1; i >= 0; i--) {
283
+ if (events[i].type === "turn/end") {
284
+ start = i + 1;
285
+ break;
286
+ }
258
287
  }
259
- if (splicedIdx < 0) return false;
260
- return splicedIdx > turnEndIdx;
288
+ for (let i = start; i < events.length; i++) {
289
+ if (events[i].type !== "agent/inbox/spliced") continue;
290
+ const inserted = events[i].data?.inserted;
291
+ if (!Array.isArray(inserted)) return false;
292
+ return inserted.some((m) => m?.source?.kind === "user");
293
+ }
294
+ return false;
261
295
  }
262
296
  function isSubagentSession(session) {
263
297
  if (!session) return false;
@@ -333,7 +367,7 @@ function registerTimeInjection(ctx, guard, dataDir, opts) {
333
367
  const intervalMs = Math.max(0, opts.getTimeInjectMin()) * 6e4;
334
368
  if (!shouldInjectTime({
335
369
  step: payload.step,
336
- originIsInboxSplice: payload.step === 1 ? turnOriginIsInboxSplice(payload.agent.session) : false,
370
+ originIsUserSplice: payload.step === 1 ? turnOriginIsUserSplice(payload.agent.session) : false,
337
371
  lastInjectAt: state[sessionId] ?? 0,
338
372
  now,
339
373
  intervalMs
@@ -459,17 +493,15 @@ function loadSessionTitles() {
459
493
  function loadVisibleSessionIds(registryFile) {
460
494
  try {
461
495
  const file = registryFile ?? path4.join(dshHomeDir(), "storages", "workspace.json");
462
- const j = JSON.parse(fs4.readFileSync(file, "utf8"));
463
- const archived = new Set(
464
- (Array.isArray(j.global?.archivedSessionIds) ? j.global.archivedSessionIds : []).map((s) => String(s))
465
- );
466
- const isArchived = (id) => archived.has(id) || archived.has(id.replace(/^session-/, ""));
496
+ const text = fs4.readFileSync(file, "utf8");
497
+ const archived = parseArchivedSessionIds(text);
498
+ const j = JSON.parse(text);
467
499
  const visible = /* @__PURE__ */ new Set();
468
500
  for (const ws of Object.values(j.tables?.workspaces ?? {})) {
469
501
  const ids = Array.isArray(ws?.sessionIds) ? ws.sessionIds : [];
470
502
  for (const raw of ids) {
471
503
  const id = String(raw);
472
- if (!isArchived(id)) visible.add(id);
504
+ if (!isArchivedSession(archived, id)) visible.add(id);
473
505
  }
474
506
  }
475
507
  return { visible, registryFound: true };
@@ -479,6 +511,15 @@ function loadVisibleSessionIds(registryFile) {
479
511
  }
480
512
  function buildEndpoints(deps, isLive) {
481
513
  const { guard, paths, policy } = deps;
514
+ const biliLogin = createBiliLoginService({
515
+ fetchImpl: fetch,
516
+ renderQrDataUrl: async (url) => {
517
+ const { default: QRCode } = await import("qrcode");
518
+ return QRCode.toDataURL(url, { type: "image/png", width: 400, margin: 2 });
519
+ },
520
+ now: () => Date.now(),
521
+ saveCredential: (value) => saveBiliSession(guard, paths, value)
522
+ });
482
523
  return {
483
524
  async status() {
484
525
  const now = Date.now();
@@ -616,6 +657,37 @@ function buildEndpoints(deps, isLive) {
616
657
  "seeds.delete"(p) {
617
658
  return ok({ deleted: deleteSeed(guard, seedsFilePath(paths.dataDir), String(p.id ?? ""), seedAuditSink(paths)) });
618
659
  },
660
+ // ── Bilibili QR login (v2.3.0): the panel's entry to the same login the
661
+ // CLI drives. Failures come back as err(...) envelopes — nothing throws
662
+ // at the card; the card maps poll states onto its own i18n texts.
663
+ "bili.status"() {
664
+ try {
665
+ const rec = loadJson(guard, bilibiliSessionFilePath(paths));
666
+ const loggedIn = typeof rec?.sessdata === "string" && rec.sessdata.length > 0;
667
+ return ok({
668
+ loggedIn,
669
+ savedAt: loggedIn && typeof rec.savedAt === "number" ? rec.savedAt : null
670
+ });
671
+ } catch {
672
+ return ok({ loggedIn: false, savedAt: null });
673
+ }
674
+ },
675
+ async "bili.login.start"() {
676
+ try {
677
+ return ok(await biliLogin.startBiliLogin());
678
+ } catch (e) {
679
+ return err("bili-login-failed", String(e instanceof Error ? e.message : e).slice(0, 200));
680
+ }
681
+ },
682
+ async "bili.login.poll"(p) {
683
+ const sessionId = String(p.sessionId ?? "");
684
+ if (!sessionId) return err("bad-request", "sessionId is required");
685
+ try {
686
+ return ok(await biliLogin.pollBiliLogin(sessionId));
687
+ } catch (e) {
688
+ return err("bili-login-failed", String(e instanceof Error ? e.message : e).slice(0, 200));
689
+ }
690
+ },
619
691
  // ── 兴趣范围 / 浏览时段(v1.4.0;首编继承出厂,见 interests-edit.ts)──
620
692
  "interests.list": () => ok(readEffective(paths)),
621
693
  "interests.add"(p) {
@@ -640,7 +712,7 @@ function buildEndpoints(deps, isLive) {
640
712
  return err("bad-request", "config.set needs a patch object");
641
713
  }
642
714
  const keys = Object.keys(patch).filter(
643
- (k) => ["intervalMin", "maxDailySend", "timeInjectMin", "statusbar", "idleMode", "tokenSaver", "psyEnabled"].includes(k)
715
+ (k) => ["intervalMin", "maxDailySend", "timeInjectMin", "statusbar", "idleMode", "tokenSaver", "psyEnabled", "quietStart", "quietEnd"].includes(k)
644
716
  );
645
717
  if (keys.length === 0) return err("bad-request", "config.set has no recognized field");
646
718
  try {
@@ -704,13 +776,13 @@ function buildEndpoints(deps, isLive) {
704
776
  "ledger.open"() {
705
777
  const f = ledgerFilePath(paths.dataDir);
706
778
  if (!fs4.existsSync(guard.assert(f))) fs4.writeFileSync(f, "# \u8D26\u672C\n", "utf8");
707
- spawn("cmd", ["/c", "start", "", f], { detached: true, stdio: "ignore" }).unref();
779
+ openPath(f);
708
780
  return ok({ path: f });
709
781
  },
710
782
  "excerpt.open"() {
711
783
  const f = excerptFilePath(paths.dataDir);
712
784
  if (!fs4.existsSync(guard.assert(f))) fs4.writeFileSync(f, EXCERPT_HEADER, "utf8");
713
- spawn("cmd", ["/c", "start", "", f], { detached: true, stdio: "ignore" }).unref();
785
+ openPath(f);
714
786
  return ok({ path: f });
715
787
  },
716
788
  "weekly.list": () => ok({ reports: listWeeklyReports(guard, paths.dataDir, policy.weekly.keepReports) }),
@@ -1198,6 +1270,248 @@ ${items.join("\n")}` };
1198
1270
  };
1199
1271
  }
1200
1272
 
1273
+ // src/sources/bilibili.ts
1274
+ import fs5 from "fs";
1275
+ import path5 from "path";
1276
+ var BILI_HISTORY_URL = "https://api.bilibili.com/x/web-interface/history/cursor?ps=8";
1277
+ 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
+ var BILI_SESSION_FILE = "bilibili-session.json";
1279
+ var BILI_STATE_FILE = "bilibili-source.json";
1280
+ var BILI_MIN_DURATION_SEC = 90;
1281
+ var BILI_MIN_WATCH_RATIO = 0.1;
1282
+ var BILI_FINISHED_RATIO = 0.9;
1283
+ var BILI_TEXT_MAX_CHARS = 100;
1284
+ var BILI_DEDUPE_WINDOW_MS = 24 * 60 * 6e4;
1285
+ var BILI_SEED_TTL_DAYS = 2;
1286
+ var BILI_FETCH_INTERVAL_MS = 2 * 60 * 6e4;
1287
+ function parseSessdata(cookieText) {
1288
+ const m = /(?:^|[;\s])SESSDATA=([^;\s]+)/.exec(cookieText);
1289
+ if (m && m[1]) return m[1];
1290
+ const bare = cookieText.trim();
1291
+ if (bare && !/^[A-Za-z_]+=/m.test(bare)) return bare;
1292
+ return null;
1293
+ }
1294
+ function readVaultSessdata(guard, dataDir) {
1295
+ try {
1296
+ const session = loadJson(
1297
+ guard,
1298
+ path5.join(dataDir, BILI_SESSION_FILE)
1299
+ );
1300
+ const field = session?.sessdata;
1301
+ if (typeof field !== "string") return null;
1302
+ const raw = field.trim();
1303
+ if (!raw) return null;
1304
+ if (raw.includes("SESSDATA=")) return parseSessdata(raw);
1305
+ return raw;
1306
+ } catch {
1307
+ return null;
1308
+ }
1309
+ }
1310
+ function readCookieFileSessdata(file) {
1311
+ if (!file) return null;
1312
+ try {
1313
+ const raw = fs5.readFileSync(file, "utf8");
1314
+ if (!raw) return null;
1315
+ const v = parseSessdata(raw);
1316
+ return v || null;
1317
+ } catch {
1318
+ return null;
1319
+ }
1320
+ }
1321
+ function resolveSessdata(guard, dataDir, cookieFile) {
1322
+ return readVaultSessdata(guard, dataDir) ?? readCookieFileSessdata(cookieFile ?? "");
1323
+ }
1324
+ function shouldDropRecord(r) {
1325
+ if (typeof r.duration !== "number" || r.duration < BILI_MIN_DURATION_SEC) return "short";
1326
+ if (r.history?.business === "live") return "live";
1327
+ const progress = r.progress;
1328
+ if (typeof progress === "number" && progress >= 0 && r.duration > 0 && progress / r.duration < BILI_MIN_WATCH_RATIO) {
1329
+ return "barely-watched";
1330
+ }
1331
+ return null;
1332
+ }
1333
+ function sanitizeTitle(t) {
1334
+ return t.replace(/《/g, "\uFF08").replace(/》/g, "\uFF09").replace(/\s+/g, " ").trim();
1335
+ }
1336
+ function seedTextFor(r) {
1337
+ const rawTitle = r.title?.trim() || r.show_title?.trim() || "";
1338
+ if (!rawTitle) return null;
1339
+ const title = sanitizeTitle(rawTitle);
1340
+ if (!title) return null;
1341
+ const business = r.history?.business;
1342
+ let text;
1343
+ if (business === "pgc") {
1344
+ const part = r.show_title?.trim();
1345
+ text = part && part !== rawTitle ? `\u4ED6\u5728\u8FFD\u300A${title}\u300B\xB7 ${sanitizeTitle(part)}` : `\u4ED6\u5728\u8FFD\u300A${title}\u300B`;
1346
+ } else {
1347
+ const progress = typeof r.progress === "number" ? r.progress : -1;
1348
+ const duration = typeof r.duration === "number" ? r.duration : 0;
1349
+ const finished = progress < 0 || duration > 0 && progress >= duration * BILI_FINISHED_RATIO;
1350
+ if (finished) {
1351
+ text = `\u4ED6\u521A\u770B\u5B8C\u300A${title}\u300B`;
1352
+ } else {
1353
+ const minute = Math.max(1, Math.ceil(progress / 60));
1354
+ text = `\u300A${title}\u300B\u4ED6\u770B\u5230\u7B2C ${minute} \u5206\u949F`;
1355
+ }
1356
+ }
1357
+ return text.length > BILI_TEXT_MAX_CHARS ? text.slice(0, BILI_TEXT_MAX_CHARS) : text;
1358
+ }
1359
+ function emptyBiliState() {
1360
+ return { lastFetchAt: 0, bvids: [] };
1361
+ }
1362
+ function bilibiliStatePath(dataDir) {
1363
+ return path5.join(dataDir, BILI_STATE_FILE);
1364
+ }
1365
+ function normalizeBiliState(raw) {
1366
+ const out = emptyBiliState();
1367
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
1368
+ const r = raw;
1369
+ if (typeof r.lastFetchAt === "number" && Number.isFinite(r.lastFetchAt) && r.lastFetchAt >= 0) {
1370
+ out.lastFetchAt = r.lastFetchAt;
1371
+ }
1372
+ if (Array.isArray(r.bvids)) {
1373
+ for (const e of r.bvids) {
1374
+ if (e && typeof e === "object" && typeof e.bvid === "string" && typeof e.at === "number") {
1375
+ out.bvids.push({ bvid: e.bvid, at: e.at });
1376
+ }
1377
+ }
1378
+ }
1379
+ return out;
1380
+ }
1381
+ function loadBiliState(guard, file) {
1382
+ try {
1383
+ return normalizeBiliState(loadJson(guard, file));
1384
+ } catch {
1385
+ return emptyBiliState();
1386
+ }
1387
+ }
1388
+ function saveBiliState(guard, file, state) {
1389
+ saveJson(guard, file, state);
1390
+ }
1391
+ function pruneBvids(state, now) {
1392
+ return {
1393
+ lastFetchAt: state.lastFetchAt,
1394
+ bvids: state.bvids.filter((e) => now - e.at < BILI_DEDUPE_WINDOW_MS)
1395
+ };
1396
+ }
1397
+ async function fetchBiliHistory(sessdata, fetchImpl = fetch) {
1398
+ try {
1399
+ const res = await fetchImpl(BILI_HISTORY_URL, {
1400
+ headers: {
1401
+ Cookie: `SESSDATA=${sessdata}`,
1402
+ "User-Agent": BILI_USER_AGENT
1403
+ }
1404
+ });
1405
+ if (!res.ok) return null;
1406
+ const j = await res.json();
1407
+ if (!j || typeof j !== "object" || typeof j.code !== "number") return null;
1408
+ const list = Array.isArray(j.data?.list) ? j.data.list : [];
1409
+ return { code: j.code, list };
1410
+ } catch {
1411
+ return null;
1412
+ }
1413
+ }
1414
+ var NO_AUDIT = () => {
1415
+ };
1416
+ async function runBilibiliSource(deps) {
1417
+ const { guard, paths, policy } = deps;
1418
+ const now = deps.now ?? Date.now();
1419
+ const debug = deps.debug ?? (() => {
1420
+ });
1421
+ const say = (msg) => {
1422
+ try {
1423
+ debug(msg);
1424
+ } catch {
1425
+ }
1426
+ };
1427
+ const cfg = policy.sources?.bilibili;
1428
+ if (cfg?.enabled === false) return { skipped: "disabled" };
1429
+ const sessdata = resolveSessdata(guard, paths.dataDir, cfg?.cookieFile);
1430
+ if (!sessdata) {
1431
+ say("bilibili: no SESSDATA (vault/cookieFile) \u2014 source off");
1432
+ return { skipped: "no-credential" };
1433
+ }
1434
+ const stateFile = bilibiliStatePath(paths.dataDir);
1435
+ const state = loadBiliState(guard, stateFile);
1436
+ if (now - state.lastFetchAt < BILI_FETCH_INTERVAL_MS) {
1437
+ return { skipped: "throttled" };
1438
+ }
1439
+ saveBiliState(guard, stateFile, { ...pruneBvids(state, now), lastFetchAt: now });
1440
+ const res = await fetchBiliHistory(sessdata, deps.fetchImpl);
1441
+ if (res === null) {
1442
+ say("bilibili: history/cursor fetch failed \u2014 skipping this round");
1443
+ return { skipped: "fetch-failed" };
1444
+ }
1445
+ if (res.code !== 0) {
1446
+ say(`bilibili: history/cursor code ${res.code} \u2014 skipping this round`);
1447
+ return { skipped: `code-${res.code}` };
1448
+ }
1449
+ const audit = deps.audit ?? NO_AUDIT;
1450
+ const recent = new Set(pruneBvids(state, now).bvids.map((e) => e.bvid));
1451
+ const result = { fetched: res.list.length, added: 0, dropped: 0, deduped: 0 };
1452
+ const fresh = [];
1453
+ const poolFile = seedsFilePath(paths.dataDir);
1454
+ for (const raw of res.list) {
1455
+ const r = raw ?? {};
1456
+ const drop = shouldDropRecord(r);
1457
+ if (drop) {
1458
+ result.dropped = (result.dropped ?? 0) + 1;
1459
+ continue;
1460
+ }
1461
+ const bvid = r.history?.bvid;
1462
+ if (!bvid || recent.has(bvid)) {
1463
+ result.deduped = (result.deduped ?? 0) + 1;
1464
+ if (bvid) fresh.push({ bvid, at: now });
1465
+ continue;
1466
+ }
1467
+ const text = seedTextFor(r);
1468
+ if (!text) {
1469
+ result.dropped = (result.dropped ?? 0) + 1;
1470
+ continue;
1471
+ }
1472
+ try {
1473
+ const added = addSeed(guard, poolFile, policy, {
1474
+ text,
1475
+ tag: "scene",
1476
+ source: "bilibili",
1477
+ category: "topic",
1478
+ noMerge: true,
1479
+ ttlDaysOverride: BILI_SEED_TTL_DAYS
1480
+ }, now, audit);
1481
+ fresh.push({ bvid, at: now });
1482
+ if (added.kind === "added") result.added = (result.added ?? 0) + 1;
1483
+ else result.deduped = (result.deduped ?? 0) + 1;
1484
+ } catch {
1485
+ result.dropped = (result.dropped ?? 0) + 1;
1486
+ }
1487
+ }
1488
+ const merged = /* @__PURE__ */ new Map();
1489
+ for (const e of [...pruneBvids(state, now).bvids, ...fresh]) merged.set(e.bvid, e);
1490
+ saveBiliState(guard, stateFile, {
1491
+ lastFetchAt: now,
1492
+ bvids: [...merged.values()].filter((e) => now - e.at < BILI_DEDUPE_WINDOW_MS)
1493
+ });
1494
+ return result;
1495
+ }
1496
+ var activeTimer = null;
1497
+ function startBilibiliSource(deps) {
1498
+ stopBilibiliSource();
1499
+ const tick = () => {
1500
+ void runBilibiliSource(deps).catch(() => {
1501
+ });
1502
+ };
1503
+ tick();
1504
+ activeTimer = setInterval(tick, BILI_FETCH_INTERVAL_MS);
1505
+ activeTimer.unref?.();
1506
+ return stopBilibiliSource;
1507
+ }
1508
+ function stopBilibiliSource() {
1509
+ if (activeTimer !== null) {
1510
+ clearInterval(activeTimer);
1511
+ activeTimer = null;
1512
+ }
1513
+ }
1514
+
1201
1515
  // src/index.ts
1202
1516
  var name = "heartbeat";
1203
1517
  var inject = ["agents"];
@@ -1412,13 +1726,23 @@ function apply(ctx, config = {}) {
1412
1726
  statusbar: statusbarEnabledRef,
1413
1727
  idleMode: idleModeRef,
1414
1728
  tokenSaver: tokenSaverRef,
1415
- psyEnabled: getRuntime().policy.profile.psyEnabled
1729
+ psyEnabled: getRuntime().policy.profile.psyEnabled,
1730
+ quietStart: getRuntime().policy.gate.quietHours.start,
1731
+ quietEnd: getRuntime().policy.gate.quietHours.end
1416
1732
  });
1417
1733
  const uiSet = (patch) => {
1418
1734
  if (typeof patch.psyEnabled === "boolean") {
1419
1735
  updateUserPolicy(guard, paths.settingsDir, { profile: { psyEnabled: patch.psyEnabled } });
1420
1736
  getRuntime().policy.profile.psyEnabled = patch.psyEnabled;
1421
1737
  }
1738
+ if (patch.quietStart !== void 0 || patch.quietEnd !== void 0) {
1739
+ const next = resolveQuietHours(patch.quietStart, patch.quietEnd, getRuntime().policy.gate.quietHours);
1740
+ if (!next) throw new Error("quiet hours must be HH:MM (00:00-23:59)");
1741
+ updateUserPolicy(guard, paths.settingsDir, { gate: { quietHours: next } });
1742
+ const q = getRuntime().policy.gate.quietHours;
1743
+ q.start = next.start;
1744
+ q.end = next.end;
1745
+ }
1422
1746
  const merged = saveUiConfig(guard, paths.settingsDir, patch);
1423
1747
  applyLiveSettings(merged);
1424
1748
  };
@@ -1454,6 +1778,21 @@ function apply(ctx, config = {}) {
1454
1778
  registerGlobalTool("excerpt", () => buildExcerptTool(guard, excerptFilePath(paths.dataDir)));
1455
1779
  }
1456
1780
  startOrchestrator(deps);
1781
+ ctx.effect(() => {
1782
+ const audit = (entry) => {
1783
+ try {
1784
+ appendAuditLine(guard.assert(paths.logsDir + "/heartbeat.jsonl"), entry);
1785
+ } catch {
1786
+ }
1787
+ };
1788
+ const debug = (msg) => {
1789
+ try {
1790
+ ctx.logger.debug?.("heartbeat: %s", msg);
1791
+ } catch {
1792
+ }
1793
+ };
1794
+ return startBilibiliSource({ guard, paths, policy: getRuntime().policy, audit, debug });
1795
+ }, "heartbeat: bilibili source");
1457
1796
  const statusReader = new StatusReader();
1458
1797
  registerStatusbarSection(ctx, guard, paths, {
1459
1798
  enabled: () => statusbarEnabledRef,