@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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/config/ui-config.ts","../src/rpc.ts","../src/browse/interests-edit.ts","../src/statusbar/time-inject.ts","../src/statusbar/track.ts","../src/core/preset-definition.ts","../src/ledger/tool.ts","../src/notepad/tool.ts","../src/excerpt/tool.ts"],"sourcesContent":["// dsh-heartbeat plugin entry.\n//\n// Contract (verified against DSH 0.1.1-rc.2 + dsh-vision-router as the\n// third-party reference): the package main exports a cordis plugin -\n// { name, inject, Config, apply(ctx, config) }. The bundle-level\n// cordis.patch.yml (dsh.bundle.patch) mounts it via\n// - insert: - id: heartbeat, name: dsh-heartbeat\n// and the loader resolves `name` to this package's main export.\n\nimport z from '@deepseek-ai/schemastery';\nimport { initWorkspace } from './core/paths.js';\nimport { createPathGuard } from './core/path-guard.js';\nimport { appendAuditLine } from './core/audit-log.js';\nimport { loadPolicy, updateUserPolicy } from './config/load.js';\nimport { loadUiConfig, saveUiConfig, type UiConfig } from './config/ui-config.js';\nimport { deepMerge } from './config/schema.js';\nimport { setRuntime, getRuntime } from './core/runtime.js';\nimport { startOrchestrator, applyHeartbeatInterval, type OrchestratorDeps } from './core/orchestrator.js';\nimport { installHeartbeatRpc } from './rpc.js';\nimport { registerTimeInjection } from './statusbar/time-inject.js';\nimport { registerStatusbarSection, noteTrack, pinTrack } from './statusbar/track.js';\nimport { StatusReader } from './statusbar/store.js';\nimport { renderStatusText } from './statusbar/track.js';\nimport { installBundledPreset, userPresetRoot, describeInstall } from './core/preset-install.js';\nimport { registerHeartbeatPreset } from './core/preset-definition.js';\nimport { buildLedgerTool } from './ledger/tool.js';\nimport { buildSeedReportTool, reportFilePath } from './seeds/report.js';\nimport { ledgerFilePath } from './ledger/ledger.js';\nimport { buildNotepadTool } from './notepad/tool.js';\nimport { notepadFilePath } from './notepad/store.js';\nimport { buildExcerptTool } from './excerpt/tool.js';\nimport { excerptFilePath } from './excerpt/excerpt.js';\n\nexport const name = 'heartbeat';\n\n/**\n * Host services required by the orchestrator (verified present in\n * DSH 0.1.1-rc.2 via hb-probe: agents service + agent/created + followup).\n *\n * `settings` is deliberately NOT declared here (v2.1.0, from issue #6's follow-up):\n * a module-level `inject` entry is a HARD dependency — cordis keeps the plugin\n * at `pending (waiting for service: settings)` for as long as the host does not\n * provide it, and on DSH desktop 0.2.1-rc.3 that pending plugin was enough to\n * take the shell down (\"Web RPC failed\" in openInitialWindow, then a crash dialog\n * whose three buttons did nothing). The settings form is a convenience, not a\n * prerequisite: rhythm values come from data/settings/ui.json plus the apply-time\n * `config` either way. It is attached lazily through `ctx.inject(['settings'], …)`\n * below, so the heartbeat starts on `agents` alone and picks the form up whenever\n * the service appears.\n */\nexport const inject = ['agents'];\n\nexport const Config = z.object({\n /** Override the runtime data dir (workspace guard boundary). Empty = default (<packageRoot>/data). */\n dataDir: z.string().default(''),\n /** UI-editable: heartbeat interval in minutes. 0 = use policy file / factory. */\n intervalMin: z.number().default(0),\n /** UI-editable: daily expression cap. 0 = use policy file / factory. */\n maxDailySend: z.number().default(0),\n /**\n * Agent preset the heartbeat agent joins (`<dshHome>/.agent-presets/<id>/`).\n * Without a preset the agent is a BARE agent: tools/prompt sections resolve\n * against the empty global layer, so it cannot even see `web_search`.\n */\n agentPreset: z.string().default('heartbeat'),\n /**\n * Install the bundled preset (see `agentPreset`) into the roster's user root\n * on first run, so setup needs no manual file copy. An existing preset is\n * never overwritten; set false to manage the preset entirely by hand.\n */\n installPreset: z.boolean().default(true),\n /** Self-built time injection interval (D20, §17.6). 0 disables injection.\n * Left OPTIONAL on purpose (2026-10-17): a schema default here is\n * indistinguishable from an explicit choice, and `applySettingsOverrides`\n * applies this value over ui.json — so a default would silently undo the\n * card on every reload. Unset falls back at the refs below. */\n timeInjectMin: z.number(),\n /** IANA timezone for the injected clock; empty = process zone. */\n timeZone: z.string().default(''),\n /** Statusbar master switch (D19). Off = no section/pre-step status; time injection unaffected. */\n statusbar: z.boolean(),\n /** v1.6.3 闲着模式:素材池为空时用画像话题兜底主动搭话(默认关)。 */\n idleMode: z.boolean(),\n /** v1.7.0 节省 token 模式:用户离开(闲置 ≥30 分钟)或锁屏时整跳暂停(默认关)。 */\n tokenSaver: z.boolean(),\n /** v1.8.0 账本工具:向所有日常会话 agent 注册共享账本工具(默认开)。 */\n ledgerTool: z.boolean().default(true),\n /** v1.9.0 素材报账工具:投递后由陪伴 agent 主动报账(默认开)。 */\n seedReportTool: z.boolean().default(true),\n /** v2.0.0 心事匣工具:留给下一跳的一句便签(默认开)。 */\n notepadTool: z.boolean().default(true),\n /** v2.0.0 摘抄本工具:留句子和小事的地方(默认开)。 */\n excerptTool: z.boolean().default(true),\n /** v1.8.0 引擎室追加工具:逗号分隔的全局工具名,存在才加入白名单(bili 压缩工具自动探测,无需手填)。 */\n extraTools: z.string().default(''),\n});\n\nexport interface HeartbeatConfig {\n dataDir?: string | null;\n intervalMin?: number;\n maxDailySend?: number;\n agentPreset?: string;\n installPreset?: boolean;\n timeInjectMin?: number;\n timeZone?: string;\n statusbar?: boolean;\n idleMode?: boolean;\n tokenSaver?: boolean;\n ledgerTool?: boolean;\n seedReportTool?: boolean;\n notepadTool?: boolean;\n excerptTool?: boolean;\n extraTools?: string;\n}\n\nexport function apply(ctx: OrchestratorDeps['ctx'] & {\n get(name: string): unknown;\n /** Cordis lazy service declaration: callback runs once the named services mount. */\n inject(services: string[], callback: (scoped: unknown) => void): void;\n /** Cordis event subscription (pre-step waterfall etc.); returns a disposer. */\n on(event: string, listener: (payload: never, next: () => Promise<unknown>) => Promise<unknown>, opts?: { prepend?: boolean }): unknown;\n}, config: HeartbeatConfig = {}): void {\n const paths = initWorkspace(config.dataDir ? { dataDir: config.dataDir } : {});\n const guard = createPathGuard(paths.dataDir);\n let policy = loadPolicy(guard, paths.configDir, paths.settingsDir);\n\n // Card-edited rhythm values (v1.7.0, data/settings/ui.json): the settings\n // card writes these over RPC. Precedence: policy layers < ui.json < the\n // composition-entry config below.\n const ui = loadUiConfig(guard, paths.settingsDir);\n if (ui.intervalMin && ui.intervalMin >= 1) {\n policy = { ...policy, heartbeat: { ...policy.heartbeat, intervalMin: ui.intervalMin } };\n }\n if (ui.maxDailySend && ui.maxDailySend >= 1) {\n policy = { ...policy, gate: { ...policy.gate, maxDailySend: ui.maxDailySend } };\n }\n\n // Composition-entry overrides (the patch row's config block).\n if (config.intervalMin && config.intervalMin >= 1) {\n policy = { ...policy, heartbeat: { ...policy.heartbeat, intervalMin: config.intervalMin } };\n }\n if (config.maxDailySend && config.maxDailySend >= 1) {\n policy = { ...policy, gate: { ...policy.gate, maxDailySend: config.maxDailySend } };\n }\n\n const deps: OrchestratorDeps = {\n ctx, paths, guard, policy,\n agentPreset: config.agentPreset || 'heartbeat',\n extraTools: (config.extraTools ?? '').split(',').map((s) => s.trim()).filter(Boolean),\n presetRegistration: () => presetRegistration ?? Promise.resolve(),\n };\n setRuntime({\n paths,\n guard,\n policy,\n flags: {\n statusbarEnabled: () => statusbarEnabledRef,\n timeInjectMin: () => timeInjectMinRef,\n idleMode: () => idleModeRef,\n tokenSaver: () => tokenSaverRef,\n },\n });\n\n // Runtime preset registration (issue #2). The `agentPresets` inject below\n // assigns it; the acquire path awaits it before mounting the preset.\n let presetRegistration: Promise<void> | undefined;\n /** HB-17: registry undo hook + whether dispose already ran (a reload must\n * not leave the preset behind, and an in-flight registration must still be\n * undone if dispose wins the race). */\n let presetDisposer: (() => Promise<void>) | undefined;\n let presetDisposed = false;\n\n // ── Preset: runtime registration + filesystem install (C13 / issue #2) ───\n // The preset is what lets the heartbeat agent see `web_search` at all, so\n // the plugin owns it in both senses:\n //\n // 1. RUNTIME REGISTRATION (0.1.7+). The registry takes a definition\n // straight from the declaring plugin (`AgentPresetRegistry.register`),\n // so nothing in the composition has to name\n // `@deepseek-ai/dsh-agent-preset`. That matters: a profile cannot always\n // resolve it, and its peer closure contains Cordis's own loader — a\n // profile that ships those by hand double-instances the machinery, and\n // then every session refuses to resume (\"prompt section\n // deployment:persona-prefix is already registered\"), while one that\n // cannot resolve the package fails the WHOLE plugin tree at load\n // (reported 2026-10-10, both with reproductions). A host whose registry\n // has no `register` degrades to an audit line, never a throw.\n // 2. FILESYSTEM INSTALL, kept for hosts that still scan the roster's user\n // root (`agentPresets.roots`, trust === \"user\"): first run writes the\n // bundled template under the roster's OWN root instead of a guessed\n // `~/.dsh`, so `$DSH_HOME`/a configured home are honoured; an existing\n // preset is never overwritten.\n //\n // `installPreset: false` means \"the operator manages the preset by hand\", so\n // it switches BOTH off. Audit lines: `preset_register`, `preset_install`.\n ctx.inject(['agentPresets'], (presetCtx: unknown) => {\n const service = (presetCtx as {\n agentPresets?: { roots?: Array<{ path?: string; trust?: string }> };\n }).agentPresets;\n const presetId = config.agentPreset || 'heartbeat';\n const installEnabled = config.installPreset !== false;\n const audit = (entry: Record<string, unknown>): void => {\n try {\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), entry);\n } catch (e) {\n ctx.logger.warn('heartbeat: preset audit failed (%s)', String(e).slice(0, 120));\n }\n };\n\n presetRegistration = registerHeartbeatPreset(service, presetId, installEnabled).then((result) => {\n audit({ event: 'preset_register', ...result });\n if (typeof result.disposer === 'function') {\n if (presetDisposed) {\n // dispose already ran while registration was in flight: undo now.\n void Promise.resolve(result.disposer()).catch((e) => {\n ctx.logger.warn('heartbeat: preset dispose failed (%s)', String(e).slice(0, 120));\n });\n } else {\n presetDisposer = result.disposer;\n }\n }\n if (result.action === 'error') {\n ctx.logger.warn('heartbeat: preset register failed (%s) — the engine room runs without it', result.detail ?? '');\n } else if (result.action === 'registered') {\n ctx.logger.info('heartbeat: preset %s registered at runtime', result.id);\n } else if (result.action === 'already-registered') {\n // HB-31: the previous instance still owns the id (same definition).\n ctx.logger.info('heartbeat: preset %s already registered — reusing it', result.id);\n } else {\n ctx.logger.info('heartbeat: preset registration skipped (%s)', result.action);\n }\n });\n\n const root = userPresetRoot(service?.roots);\n const result = installBundledPreset({\n moduleUrl: import.meta.url,\n id: presetId,\n ...(root === undefined ? { rosterKnown: service !== undefined } : { root }),\n enabled: installEnabled,\n });\n audit({ event: 'preset_install', ...result });\n const line = describeInstall(result);\n if (result.action === 'error' || result.action === 'skipped-no-root') {\n ctx.logger.warn('heartbeat: %s', line);\n } else {\n ctx.logger.info('heartbeat: %s', line);\n }\n });\n\n // M6: settings section (namespace 'heartbeat') - the web card edits this\n // namespace; resolved values apply live (interval reschedules the timer).\n let sectionSource: (() => HeartbeatConfig) | null = null;\n let timeInjectMinRef = ui.timeInjectMin ?? (config.timeInjectMin ?? 25);\n // Factory default is OFF (v1.9.3); `=== true` so an UNSET config no longer\n // reads as \"not false = on\" now that the schema leaves it optional.\n let statusbarEnabledRef = ui.statusbar ?? (config.statusbar === true);\n let idleModeRef = ui.idleMode ?? (config.idleMode === true);\n let tokenSaverRef = ui.tokenSaver ?? (config.tokenSaver === true);\n\n // H-48: ONE setter table for the live-settable fields. The settings section\n // and the RPC uiSet path used to carry a copy each of the same six ifs, so a\n // new field had to be added twice — and the two copies had already drifted\n // (timeInjectMin's lower bound, tokenSaver's absence from the section path).\n const applyLiveSettings = (v: {\n intervalMin?: number;\n maxDailySend?: number;\n timeInjectMin?: number;\n statusbar?: boolean;\n idleMode?: boolean;\n tokenSaver?: boolean;\n }): void => {\n if (v.intervalMin && v.intervalMin >= 1) applyHeartbeatInterval(deps, v.intervalMin);\n if (v.maxDailySend && v.maxDailySend >= 1) getRuntime().policy.gate.maxDailySend = v.maxDailySend;\n if (typeof v.timeInjectMin === 'number' && v.timeInjectMin >= 0) timeInjectMinRef = v.timeInjectMin;\n if (typeof v.statusbar === 'boolean') statusbarEnabledRef = v.statusbar;\n if (typeof v.idleMode === 'boolean') {\n idleModeRef = v.idleMode;\n getRuntime().policy.heartbeat.idleMode = v.idleMode;\n }\n if (typeof v.tokenSaver === 'boolean') tokenSaverRef = v.tokenSaver;\n };\n\n const applySettingsOverrides = (): void => {\n try {\n const v = sectionSource?.();\n if (!v) return;\n applyLiveSettings(v);\n ctx.logger.info('heartbeat: settings overrides live (interval %s, cap %s, timeInject %s)', v.intervalMin ?? '-', v.maxDailySend ?? '-', v.timeInjectMin ?? '-');\n } catch (e) {\n ctx.logger.warn('heartbeat: settings override failed (%s)', String(e).slice(0, 120));\n }\n };\n // M6: settings form (namespace 'heartbeat'). Attached lazily through\n // `ctx.inject` because the service is no longer in the module-level `inject`\n // (see above): the callback runs once `settings` exists and its effects are\n // disposed if the service ever goes away, while the heartbeat itself keeps\n // running on `agents` alone.\n //\n // DSH 0.1.7 and later expose `SettingsForms`: plugin config forms render from\n // the Config schema on the Plugins page, and an edit RELOADS this plugin (timers\n // dispose via ctx.effect, so reloads are safe) — nothing to register here, the\n // apply-time `config` is already the live source. The 0.1.5 `installSection`\n // generation and the 0.1.1/0.1.2 free-function fallback are gone: they were\n // reachable only on hosts the package no longer supports (README: DSH 0.2.1+),\n // and they were the only reason `@deepseek-ai/dsh-settings` was a dependency.\n ctx.inject(['settings'], (settingsCtx: unknown) => {\n try {\n const settingsService = (settingsCtx as { get(name: string): unknown }).get('settings') as\n | { describe?(options?: unknown): unknown }\n | undefined;\n if (settingsService && typeof settingsService.describe === 'function') {\n sectionSource = () => config;\n applySettingsOverrides();\n ctx.logger.info('heartbeat: config served by the profile settings form (edits reload the plugin)');\n return;\n }\n ctx.logger.warn('heartbeat: settings service present but not a SettingsForms instance; policy file values only');\n } catch (e) {\n ctx.logger.warn('heartbeat: settings form unavailable (%s)', String(e).slice(0, 120));\n }\n });\n\n appendAuditLine(\n guard.assert(paths.logsDir + '/heartbeat.jsonl'),\n { event: 'plugin_init', dataDir: paths.dataDir },\n );\n\n // issue #2: a package-local data dir is moved out of the package on first\n // sight. The audit line is the only durable trace; a failed move keeps\n // serving the legacy tree (and never deletes it).\n if (paths.relocation) {\n const auditFile = guard.assert(paths.logsDir + '/heartbeat.jsonl');\n if (paths.relocation.action === 'relocated') {\n appendAuditLine(auditFile, {\n event: 'data_dir_relocated',\n from: paths.relocation.srcDir,\n to: paths.relocation.dstDir,\n files: paths.relocation.files,\n bytes: paths.relocation.bytes,\n warnings: paths.relocation.warnings,\n leftovers: paths.relocation.leftovers,\n });\n ctx.logger.info(\n 'heartbeat: data dir moved out of the package (%s files, %s bytes)',\n paths.relocation.files,\n paths.relocation.bytes,\n );\n } else if (paths.relocation.action === 'failed') {\n appendAuditLine(auditFile, {\n event: 'data_dir_relocate_failed',\n stage: paths.relocation.stage,\n problems: paths.relocation.problems,\n });\n ctx.logger.warn(\n 'heartbeat: data dir relocation failed (%s); continuing in the package dir',\n paths.relocation.stage,\n );\n }\n }\n\n // ── M6 拓展:正式 RPC 通道(决策 1 = B 方案,探针已验证)──────────\n // connection 晚挂载 → ctx.inject(['connection'], ...) 声明式等待;\n // 端点分发见 src/rpc.ts(bindings/seeds/status/profile/ledger/config)。\n // ui.get/uiSet:节律配置的活视图与\"落盘+即时生效\"(v1.7.0,data/settings/ui.json)。\n // psyEnabled 例外:它是 policy 字段,写 data/settings/policy.json 用户层。\n const uiGet = () => ({\n intervalMin: getRuntime().policy.heartbeat.intervalMin,\n maxDailySend: getRuntime().policy.gate.maxDailySend,\n timeInjectMin: timeInjectMinRef,\n statusbar: statusbarEnabledRef,\n idleMode: idleModeRef,\n tokenSaver: tokenSaverRef,\n psyEnabled: getRuntime().policy.profile.psyEnabled,\n });\n const uiSet = (patch: UiConfig & { psyEnabled?: boolean }): void => {\n if (typeof patch.psyEnabled === 'boolean') {\n updateUserPolicy(guard, paths.settingsDir, { profile: { psyEnabled: patch.psyEnabled } });\n getRuntime().policy.profile.psyEnabled = patch.psyEnabled;\n }\n const merged = saveUiConfig(guard, paths.settingsDir, patch);\n applyLiveSettings(merged);\n };\n installHeartbeatRpc(ctx, { paths, guard, policy, ui: { get: uiGet, set: uiSet } });\n\n // H-49: the ledger (v1.8.0) and seed_report (v1.9.0) registrations were two\n // copies of one block — same audit closure, same try/catch, same degradation\n // to an audit line on a host without a registerable ToolRuntime. One factory\n // now covers both; the audit event names are unchanged.\n const registerGlobalTool = (name: string, build: () => unknown): void => {\n ctx.inject(['tools'], (scoped: unknown) => {\n const audit = (entry: Record<string, unknown>): void => {\n try {\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), entry);\n } catch { /* audit must never break startup */ }\n };\n try {\n const tools = (scoped as { tools?: { register(definition: unknown): () => void } }).tools;\n if (!tools || typeof tools.register !== 'function') throw new Error('ToolRuntime.register unavailable on this host');\n tools.register(build());\n audit({ event: `${name}_tool_registered` });\n } catch (e) {\n audit({ event: `${name}_tool_register_failed`, error: String(e).slice(0, 160) });\n }\n });\n };\n\n // ── Ledger as a model tool (v1.8.0) ─────────────────────────────────────\n // Registers a shared `ledger` tool in the GLOBAL tool layer so every chat\n // agent can record/complete todos without being commanded to. The engine\n // room never sees it (its preset allow-list masks global tools). Definition\n // is a plain object (no dsh-tools import); a host without a registerable\n // ToolRuntime degrades to an audit line only.\n if (config.ledgerTool !== false) {\n registerGlobalTool('ledger', () => buildLedgerTool(guard, ledgerFilePath(paths.dataDir)));\n }\n\n // ── Seed report tool (v1.9.0): the persona files ONE report per delivery ─\n // spoken / seed_ids / profile_ids / reason — the unified bookkeeping channel\n // that replaced containment-match attribution. Same global-layer pattern as\n // the ledger tool; the engine room never sees it.\n if (config.seedReportTool !== false) {\n registerGlobalTool('seed_report', () => buildSeedReportTool(guard, reportFilePath(paths.dataDir)));\n }\n\n // ── 心事匣 (v2.0.0): one note she leaves for the next beat ──────────────\n // Same global-layer pattern, and the same reason as above: the engine room\n // never sees this tool. It does not need to — the note reaches the next beat\n // through the delivery package (material.ts notepadLines), which the engine\n // room builds but never authors. Storage is encrypted (it is more private\n // than the ledger), so the module goes through the vault, not plain text.\n if (config.notepadTool !== false) {\n registerGlobalTool('notepad', () => buildNotepadTool(guard, notepadFilePath(paths.dataDir)));\n }\n\n // ── 摘抄本 (v2.0.0): a line worth keeping, kept in plain text ───────────\n // Same global-layer pattern. Unlike the notepad this one is plaintext on\n // purpose: the settings card opens the file for the user, and a notebook\n // nobody can read is not a notebook. The ledger is the other plaintext file.\n if (config.excerptTool !== false) {\n registerGlobalTool('excerpt', () => buildExcerptTool(guard, excerptFilePath(paths.dataDir)));\n }\n\n // §7 main loop: dedicated session/agent + timer (first beat after 15s).\n startOrchestrator(deps);\n\n // ── M7b: self-built time injection (D20, §17.6) ────────────────────────\n // Gate: step===1 AND user-initiated AND ≥ timeInjectMin since the last\n // injection for that session. Official dsh-time-context is disabled via the\n // user patch (B9 superseded by D20 — single owner). The interval is\n // live-settable: `timeInjectMinRef` is re-read on every gate check.\n // ── M7c: statusbar two tracks (D19, §17.4–17.5) ─────────────────────────\n // Track A (in-history models) rides a dynamic system-prompt section; Track B\n // rides the same pre-step message as the time injection (§17.5 combined).\n const statusReader = new StatusReader();\n registerStatusbarSection(ctx, guard, paths, {\n enabled: () => statusbarEnabledRef,\n reader: statusReader,\n });\n ctx.effect(() => {\n registerTimeInjection(ctx, guard, paths.dataDir, {\n getTimeInjectMin: () => timeInjectMinRef,\n timeZone: config.timeZone || undefined,\n paths,\n logger: ctx.logger,\n onError: (e) => ctx.logger.warn('heartbeat: time injection skipped (%s)', String(e).slice(0, 120)),\n pinTrack: (sessionId, session) => {\n const track = pinTrack(sessionId, session);\n noteTrack(paths.logsDir + '/heartbeat.jsonl', sessionId, track);\n return track;\n },\n getStatusLine: (session, track) => {\n if (!statusbarEnabledRef) {\n noteTrack(paths.logsDir + '/heartbeat.jsonl', session.id, 'off');\n return '';\n }\n return track === 'pre-step' ? renderStatusText(statusReader.read(guard, paths)) : '';\n },\n });\n return undefined;\n }, 'heartbeat: time injection');\n\n // Host effect contract: fn runs immediately, returns the disposer.\n ctx.effect(() => {\n return () => {\n presetDisposed = true;\n const undoPreset = presetDisposer;\n presetDisposer = undefined;\n if (typeof undoPreset === 'function') {\n void Promise.resolve(undoPreset()).catch((e) => {\n ctx.logger.warn('heartbeat: preset dispose failed (%s)', String(e).slice(0, 120));\n });\n }\n ctx.logger.info('heartbeat: disposed, timers cleaned up');\n };\n }, 'heartbeat: lifecycle');\n}\n\n// deepMerge is re-exported for the CLI status command layering.\nexport { deepMerge };\n","// Card-editable rhythm config (v1.7.0): the heartbeat card edits five fields\n// over RPC and they persist in the plugin's OWN user layer, so the editor\n// behaves identically on every host generation (0.1.1 scope / 0.1.5\n// installSection / 0.1.7 profile forms all become irrelevant for these\n// values) and saves apply live without any plugin reload.\n// Startup precedence: factory policy < user policy < ui.json < Config fields.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { atomicWriteFileSync } from '../core/atomic-fs.js';\n\nexport const USER_UI_FILE = 'ui.json';\n\nexport interface UiConfig {\n intervalMin?: number;\n maxDailySend?: number;\n timeInjectMin?: number;\n statusbar?: boolean;\n idleMode?: boolean;\n /** Token-saver (v1.7.0): pause beats while the user is away / locked. */\n tokenSaver?: boolean;\n}\n\nconst RANGES = {\n intervalMin: { min: 1, max: 1440 },\n maxDailySend: { min: 1, max: 50 },\n timeInjectMin: { min: 0, max: 1440 },\n} as const;\n\nfunction sanitize(raw: unknown): UiConfig {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};\n const r = raw as Record<string, unknown>;\n const out: UiConfig = {};\n for (const key of ['intervalMin', 'maxDailySend', 'timeInjectMin'] as const) {\n const v = r[key];\n if (typeof v === 'number' && Number.isFinite(v) && v >= RANGES[key].min && v <= RANGES[key].max) {\n out[key] = Math.floor(v);\n }\n }\n if (typeof r.statusbar === 'boolean') out.statusbar = r.statusbar;\n if (typeof r.idleMode === 'boolean') out.idleMode = r.idleMode;\n if (typeof r.tokenSaver === 'boolean') out.tokenSaver = r.tokenSaver;\n return out;\n}\n\nexport function uiConfigPath(settingsDir: string): string {\n return path.join(settingsDir, USER_UI_FILE);\n}\n\n/** Missing user layer is normal; a corrupt layer fails open to defaults. */\nexport function loadUiConfig(guard: PathGuard, settingsDir: string): UiConfig {\n try {\n const raw: unknown = JSON.parse(fs.readFileSync(guard.assert(uiConfigPath(settingsDir)), 'utf8'));\n return sanitize(raw);\n } catch {\n return {};\n }\n}\n\n/** Merge `patch` over the stored layer, sanitize, and persist. */\nexport function saveUiConfig(guard: PathGuard, settingsDir: string, patch: UiConfig): UiConfig {\n const merged = sanitize({ ...loadUiConfig(guard, settingsDir), ...patch });\n const file = guard.assert(uiConfigPath(settingsDir));\n fs.mkdirSync(path.dirname(file), { recursive: true });\n atomicWriteFileSync(file, JSON.stringify(merged, null, 2) + '\\n');\n return merged;\n}\n","// M6: settings-card RPC (decision 1 = Plan B; transport reworked in v1.2.1, C21).\n//\n// Host registers an exact Fetch route under /api via ctx.inject(['connection'], ...)\n// once the connection service mounts; the web card calls\n// connection.rpc.call('/api', 'heartbeat', { endpoint, ...payload }).\n// (The original custom channel '/heartbeat' via rpc.handle() is unusable on\n// DSH 0.1.5+: cordis pins the service's this.ctx to the provider context, so\n// handle()'s internal owner.webServer.register always fails strict resolution.)\n// Bindings authority = data/settings/bindings.json (decision 2); the card is\n// just another client of the same host logic the CLI uses.\n// Every endpoint runs inside the workspace guard; results are {ok,value} or\n// {ok:false,error:{code,message,details}}. Verbs are dispatched through a Map\n// and, when the host's /api gate is missing, only GATE_SAFE_ENDPOINTS serve\n// (⑦A / HB-19, 2026-10-17).\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { OrchestratorDeps } from './core/orchestrator.js';\nimport { getLastBeat, homeSessionId, resetHomeSession, pauseFocus, resumeFocus, getFocusUntil, formatFocusClock } from './core/orchestrator.js';\nimport { readFocusState, writeFocusState, clearFocusState } from './core/focus-store.js';\nimport { appendAuditLine } from './core/audit-log.js';\nimport type { UiConfig } from './config/ui-config.js';\nimport type { PathGuard } from './core/path-guard.js';\nimport { dshHomeDir } from './core/paths.js';\nimport { localDayKey } from './core/time-window.js';\nimport type { WorkspacePaths } from './core/paths.js';\nimport { inQuietHours, readSentState } from './gate/gate.js';\nimport {\n activeSeeds,\n archivedSeeds,\n archiveSeedById,\n deleteSeed,\n loadPool,\n restoreSeed,\n seedsFilePath,\n} from './seeds/pool.js';\nimport { loadProfile, profileFilePath } from './profile/store.js';\nimport { buildDigest } from './profile/digest.js';\nimport { ledgerFilePath } from './ledger/ledger.js';\nimport { EXCERPT_HEADER, excerptFilePath } from './excerpt/excerpt.js';\nimport { listWeeklyReports, readWeeklyReport } from './weekly/report.js';\nimport { addBinding, loadBindings, removeBinding } from './core/bindings.js';\nimport { addInterest, readEffective, removeInterest, setWanderWindows } from './browse/interests-edit.js';\nimport { writeText } from './vault/vault.js';\nimport { readStatus } from './statusbar/store.js';\nimport { loadTimeInjectState } from './statusbar/time-inject.js';\nimport type { Policy } from './config/schema.js';\n\n/** Exact Fetch route under /api (C21: custom rpc.handle channels are unusable\n * under 0.1.5's strict cordis service resolution — see installHeartbeatRpc). */\nexport const RPC_ROUTE_PATH = '/api/heartbeat';\n\n/**\n * ⑦A (2026-10-17 review, tightening H-41): the host's `/api` prefix gate is the\n * only authentication this route has — the plugin holds no credential of its own.\n * When that gate cannot be found the route fails closed: every verb is refused\n * except this short list of read-only, low-sensitivity ones (liveness plus what\n * the settings card needs to render). H-41+HB-19 refused six \"destructive\" verbs\n * and served everything else, which left every memory-bearing read —\n * `profile.digest`, `profile.partitions`, `seeds.list`, `interests.list`,\n * `weekly.get`, `migrate.export` — open to anything that could POST to loopback.\n */\nconst GATE_SAFE_ENDPOINTS = new Set([\n 'status',\n 'config.get',\n 'sessions.list',\n 'bindings.get',\n 'weekly.list',\n]);\n\ninterface RpcDeps {\n ctx: OrchestratorDeps['ctx'] & {\n inject(services: string[], callback: (scoped: unknown) => void): void;\n };\n paths: WorkspacePaths;\n guard: PathGuard;\n policy: Policy;\n /** Card-edited rhythm values (v1.7.0): live view getter + persist-and-apply setter. */\n ui: {\n get(): {\n intervalMin: number;\n maxDailySend: number;\n timeInjectMin: number;\n statusbar: boolean;\n idleMode: boolean;\n tokenSaver: boolean;\n psyEnabled: boolean;\n };\n set(patch: UiConfig & { psyEnabled?: boolean }): void;\n };\n}\n\ntype RpcResult = { ok: true; value: unknown } | { ok: false; error: { code: string; message: string; details: Record<string, never> } };\n\nconst ok = (value: unknown): RpcResult => ({ ok: true, value });\nconst err = (code: string, message: string): RpcResult => ({ ok: false, error: { code, message, details: {} } });\n\nlet cachedVersion: string | null = null;\n/** Plugin version for the card's status block (read once from package.json). */\nfunction pluginVersion(paths: WorkspacePaths): string {\n if (cachedVersion) return cachedVersion;\n try {\n const pkg = JSON.parse(fs.readFileSync(path.join(paths.packageRoot, 'package.json'), 'utf8')) as { version?: string };\n cachedVersion = typeof pkg.version === 'string' ? pkg.version : 'unknown';\n } catch {\n cachedVersion = 'unknown';\n }\n return cachedVersion;\n}\n\n/** 素材池生命周期的审计出口(v1.9.0):卡片上的归档/恢复/删除也留下痕迹。 */\nfunction seedAuditSink(paths: WorkspacePaths): (entry: Record<string, unknown>) => void {\n return (entry) => {\n try {\n appendAuditLine(paths.logsDir + '/heartbeat.jsonl', entry);\n } catch { /* audit must never break the RPC call */ }\n };\n}\n\n/** 兴趣/时段卡片编辑的审计留痕(成功才记;失败原因走 RPC err 回给卡片)。 */\nfunction auditInterests(paths: WorkspacePaths, action: string, r: { ok: boolean }, detail: unknown): void {\n try {\n appendAuditLine(paths.logsDir + '/heartbeat.jsonl', {\n event: `interests_${r.ok ? 'edit' : 'edit_failed'}`,\n action,\n detail: typeof detail === 'string' ? detail.slice(0, 80) : null,\n });\n } catch { /* audit must never break the RPC call */ }\n}\n\n/** Session titles from the host's projection cache. Titles are host data — the\n * client card merges them (client.js `nameOf`: title || id prefix).\n *\n * DSH 0.1.2 writes ONE RECORD PER SESSION under\n * `~/.dsh/storages/session_projcache/sessions/<sessionId>.json`\n * (`record.rows.title.val`). The single-file `session_projcache.json` we used\n * before is the older aggregate layout and goes stale: a session created after\n * the upgrade is simply absent from it, so `title` came back null and the card\n * printed the raw session id. Read the per-record layout FIRST, keep the\n * aggregate only as a legacy fallback. */\nfunction loadSessionTitles(): Record<string, string> {\n const titles: Record<string, string> = {};\n const take = (id: string, value: unknown): void => {\n const t = value as { rows?: { title?: { val?: unknown } }; title?: { val?: unknown } } | undefined;\n const row = t?.rows?.title ?? t?.title;\n if (row && typeof row.val === 'string' && row.val && !titles[id]) titles[id] = row.val;\n };\n // 1) per-record layout (current).\n try {\n const dir = path.join(dshHomeDir(), 'storages', 'session_projcache', 'sessions');\n for (const file of fs.readdirSync(dir)) {\n if (!file.endsWith('.json')) continue;\n const id = file.slice(0, -'.json'.length);\n if (!id.startsWith('session-')) continue;\n try {\n const record = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8')) as { record?: unknown };\n take(id, record.record);\n } catch { /* skip a record we cannot read */ }\n }\n } catch { /* no per-record dir on older hosts */ }\n // 2) legacy aggregate fallback.\n try {\n const raw = JSON.parse(fs.readFileSync(path.join(dshHomeDir(), 'storages', 'session_projcache.json'), 'utf8')) as unknown;\n const walk = (node: unknown): void => {\n if (!node || typeof node !== 'object') return;\n for (const [key, value] of Object.entries(node as Record<string, unknown>)) {\n if (key.startsWith('session-') && value && typeof value === 'object') {\n // Title lives at <session>.rows.title.val (host title service); the\n // val may be null while the title is still being generated.\n take(key, value);\n }\n walk(value);\n }\n };\n walk(raw);\n return titles;\n } catch {\n return titles;\n }\n}\n\n/** Host-side session registry (`~/.dsh/storages/workspace.json`) → the set of\n * session ids the USER actually sees in the sidebar.\n *\n * A persisted session is user-visible iff it belongs to some workspace's\n * `sessionIds` and is not in `archivedSessionIds`. Two exclusions fall out of\n * this for the bind picker (2026-09-30 user request):\n * - **archived** sessions (explicit `archivedSessionIds`, prefix formats are\n * mixed on disk — some entries carry `session-`, some don't — so match\n * both forms);\n * - **subagent child sessions**, which never join any workspace's\n * `sessionIds` (observed: they only ever land in the archive list).\n *\n * Fail-open: a missing/corrupt registry returns `registryFound: false` and\n * the caller shows everything — an unreadable registry must not blank the\n * picker. The heartbeat home is always shown regardless (caller-side). */\nexport function loadVisibleSessionIds(registryFile?: string): { visible: Set<string>; registryFound: boolean } {\n try {\n const file = registryFile ?? path.join(dshHomeDir(), 'storages', 'workspace.json');\n const j = JSON.parse(fs.readFileSync(file, 'utf8')) as {\n global?: { archivedSessionIds?: unknown };\n tables?: { workspaces?: Record<string, { sessionIds?: unknown }> };\n };\n const archived = new Set(\n (Array.isArray(j.global?.archivedSessionIds) ? (j.global!.archivedSessionIds as unknown[]) : [])\n .map((s) => String(s)),\n );\n const isArchived = (id: string): boolean =>\n archived.has(id) || archived.has(id.replace(/^session-/, ''));\n const visible = new Set<string>();\n for (const ws of Object.values(j.tables?.workspaces ?? {})) {\n const ids = Array.isArray(ws?.sessionIds) ? (ws.sessionIds as unknown[]) : [];\n for (const raw of ids) {\n const id = String(raw);\n if (!isArchived(id)) visible.add(id);\n }\n }\n return { visible, registryFound: true };\n } catch {\n return { visible: new Set(), registryFound: false };\n }\n}\n\n/** One RPC verb: payload in, envelope out. `guard` / `paths` / `policy` / `deps`\n * come from the closure built by {@link buildEndpoints}. */\ntype Endpoint = (p: Record<string, unknown>) => RpcResult | Promise<RpcResult>;\n\n/**\n * H-36: the endpoint table. This used to be a single `switch` at the bottom of\n * the route handler — 22 verbs and ~250 lines, with the guest list (which\n * endpoints exist) tangled up with the machinery (envelope validation, the\n * catch-all error wrapper). Adding a verb is now one entry here; the wrapper\n * stays in one place.\n */\nfunction buildEndpoints(deps: Omit<RpcDeps, 'ctx'>, isLive: (sessionId: string) => boolean): Record<string, Endpoint> {\n const { guard, paths, policy } = deps;\n return {\n async status() {\n const now = Date.now();\n const sent = readSentState(guard, paths, now);\n const beat = getLastBeat();\n // M7 statusbar block (§17.8): store + throttle-state + live flags.\n let lastTimeInjectAt: number | null = null;\n try {\n const state = loadTimeInjectState(guard, paths.dataDir);\n for (const v of Object.values(state)) {\n if (typeof v === 'number' && v > (lastTimeInjectAt ?? 0)) lastTimeInjectAt = v;\n }\n } catch { /* missing state file = never injected */ }\n let flags = { statusbarEnabled: true, timeInjectMin: 25, idleMode: false };\n try {\n const { getRuntime } = await import('./core/runtime.js');\n const f = getRuntime().flags;\n flags = { statusbarEnabled: f.statusbarEnabled(), timeInjectMin: f.timeInjectMin(), idleMode: f.idleMode() };\n } catch { /* pre-init: report defaults */ }\n return ok({\n now: new Date(now).toISOString(),\n version: pluginVersion(paths),\n intervalMin: policy.heartbeat.intervalMin,\n idleMode: policy.heartbeat.idleMode,\n cap: { used: sent.items.length, max: policy.gate.maxDailySend },\n quiet: inQuietHours(policy, now),\n lastBeat: beat,\n homeSessionId: homeSessionId(guard, paths),\n bindings: loadBindings(guard, paths.settingsDir).bindings.length,\n statusbar: {\n enabled: flags.statusbarEnabled,\n timeInjectMin: flags.timeInjectMin,\n lastStatus: readStatus(guard, paths),\n lastTimeInjectAt: lastTimeInjectAt === null ? null : new Date(lastTimeInjectAt).toISOString(),\n },\n });\n },\n\n 'sessions.list'() {\n const root = path.join(dshHomeDir(), 'sessions');\n const bindings = loadBindings(guard, paths.settingsDir).bindings;\n const home = homeSessionId(guard, paths);\n const titles = loadSessionTitles();\n // Bind picker visibility: hide archived and subagent sessions\n // (2026-09-30 user request). Fail-open when the registry is\n // unreadable; the home is always listed.\n const { visible, registryFound } = loadVisibleSessionIds();\n const out: Record<string, unknown>[] = [];\n if (fs.existsSync(root)) {\n for (const slug of fs.readdirSync(root)) {\n for (const id of fs.readdirSync(path.join(root, slug))) {\n if (registryFound && id !== home && !visible.has(id)) continue;\n const binding = bindings.find((b) => b.sessionId === id);\n out.push({\n id,\n title: titles[id] ?? null,\n cwdSlug: slug,\n live: isLive(id),\n home: id === home,\n deliver: binding?.deliver ?? false,\n observe: binding?.observe ?? false,\n });\n }\n }\n }\n return ok({ sessions: out });\n },\n\n 'bindings.get': () => ok(loadBindings(guard, paths.settingsDir)),\n\n // Focus mode (v2.1.0 ①). The card and the CLI are two clients of the same\n // pause: module state gives the host an immediate answer, data/focus.json\n // carries it across processes (and survives a restart). `status` merges\n // both so the card shows a pause the CLI set and vice versa.\n 'focus.status'() {\n const now = Date.now();\n const file = readFocusState(guard, paths, now);\n const mem = getFocusUntil();\n const until = Math.max(mem > now ? mem : 0, file?.until ?? 0);\n return ok({\n paused: until > now,\n until: until > now ? new Date(until).toISOString() : null,\n clock: until > now ? formatFocusClock(until) : null,\n minutes: file?.minutes ?? null,\n via: file?.via ?? (mem > now ? 'rpc' : null),\n });\n },\n\n 'focus.pause'(p) {\n const raw = Number(p.minutes ?? 30);\n if (!Number.isFinite(raw) || raw <= 0) return err('bad-request', 'minutes must be a positive number (1-1440)');\n const now = Date.now();\n const mem = pauseFocus(raw); // this process answers immediately\n const file = writeFocusState(guard, paths, raw, now, 'settings-card');\n const until = Math.max(mem, file.until);\n return ok({\n paused: true,\n until: new Date(until).toISOString(),\n clock: formatFocusClock(until),\n minutes: file.minutes,\n });\n },\n\n 'focus.resume'() {\n resumeFocus();\n const removed = clearFocusState(guard, paths);\n return ok({ paused: false, removed });\n },\n\n 'bindings.add'(p) {\n const id = String(p.sessionId ?? '');\n if (!id.startsWith('session-')) return err('bad-request', 'sessionId must look like session-...');\n const home = homeSessionId(guard, paths);\n if (id === home) return err('bad-request', '该会话是心跳正身,无需绑定(决策轮次固定发生在正身)');\n // Callers send BOTH flags explicitly (the card's per-flag toggles), so\n // this stays a full-state write: deliver defaults on, observe off.\n const b = addBinding(guard, paths.settingsDir, id, {\n deliver: p.deliver !== false,\n observe: p.observe === true,\n });\n return ok(b);\n },\n\n 'bindings.remove'(p) {\n const id = String(p.sessionId ?? '');\n const removed = removeBinding(guard, paths.settingsDir, id);\n // H-09/H-45: one shared release path — gate.json, the home_reset audit\n // line and the orchestrator's cached agent — instead of an inline delete\n // that silently left the in-memory home behind.\n const homeReset = resetHomeSession(guard, paths, id);\n return ok({ removed, homeReset });\n },\n\n 'seeds.list'() {\n const db = loadPool(guard, seedsFilePath(paths.dataDir));\n return ok({\n active: activeSeeds(db),\n archived: archivedSeeds(db),\n cap: policy.seeds.maxActive,\n });\n },\n\n 'seeds.archive'(p) {\n const s = archiveSeedById(guard, seedsFilePath(paths.dataDir), String(p.id ?? ''), 'completed', Date.now(), seedAuditSink(paths));\n return s ? ok(s) : err('not-found', 'active seed not found');\n },\n\n 'seeds.restore'(p) {\n const r = restoreSeed(guard, seedsFilePath(paths.dataDir), policy, String(p.id ?? ''), Date.now(), seedAuditSink(paths));\n return r.ok ? ok(r.seed) : err('restore-failed', r.reason);\n },\n\n 'seeds.delete'(p) {\n return ok({ deleted: deleteSeed(guard, seedsFilePath(paths.dataDir), String(p.id ?? ''), seedAuditSink(paths)) });\n },\n\n // ── 兴趣范围 / 浏览时段(v1.4.0;首编继承出厂,见 interests-edit.ts)──\n 'interests.list': () => ok(readEffective(paths)),\n\n 'interests.add'(p) {\n const r = addInterest(guard, paths, String(p.text ?? ''));\n auditInterests(paths, 'add', r, p.text);\n return r.ok ? ok(r.doc) : err('bad-request', r.reason ?? 'add failed');\n },\n\n 'interests.remove'(p) {\n const r = removeInterest(guard, paths, String(p.text ?? ''));\n auditInterests(paths, 'remove', r, p.text);\n return r.ok ? ok(r.doc) : err('not-found', r.reason ?? 'remove failed');\n },\n\n 'interests.setWindows'(p) {\n const r = setWanderWindows(guard, paths, p.windows);\n auditInterests(paths, 'set-windows', r, JSON.stringify(p.windows ?? null));\n return r.ok ? ok(r.doc) : err('bad-request', r.reason ?? 'setWindows failed');\n },\n\n 'config.get': () => ok(deps.ui.get()),\n\n 'config.set'(p) {\n const patch = p as UiConfig;\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {\n return err('bad-request', 'config.set needs a patch object');\n }\n const keys = Object.keys(patch).filter((k) =>\n ['intervalMin', 'maxDailySend', 'timeInjectMin', 'statusbar', 'idleMode', 'tokenSaver', 'psyEnabled'].includes(k),\n );\n if (keys.length === 0) return err('bad-request', 'config.set has no recognized field');\n try {\n deps.ui.set(patch);\n } catch (e) {\n return err('bad-request', String(e).slice(0, 120));\n }\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), { event: 'ui_config_set', keys });\n return ok(deps.ui.get());\n },\n\n 'profile.digest'() {\n const d = buildDigest(guard, paths, policy, {});\n return ok({\n tact: d.tact,\n topic: d.topic,\n wander: d.wander,\n withinBudget: d.withinBudget,\n // v2.0 (item 6): the card shows the budget and what the caps dropped.\n totalChars: d.totalChars,\n budgetChars: d.budgetChars,\n omitted: d.omitted,\n });\n },\n\n 'profile.partitions'() {\n // v2.0 (item 6): the card shows ONE partition at a time, entry by entry.\n // The digest view was a wall of text and never showed what the profile\n // actually holds. Read-only, same data profile.export walks.\n const doc = loadProfile(guard, profileFilePath(paths.dataDir));\n const partitions: Record<string, { total: number; valid: number; entries: Record<string, unknown>[] }> = {};\n for (const part of ['interest', 'projects', 'comm', 'psy'] as const) {\n const all = doc.partitions[part]?.entries ?? [];\n const valid = all.filter((e) => e.validTo === null);\n partitions[part] = {\n total: all.length,\n valid: valid.length,\n entries: valid\n .slice()\n .sort((a, b) => b.confidence - a.confidence || (a.updatedAt < b.updatedAt ? 1 : -1))\n .map((e) => ({\n id: e.id,\n topic: e.topic,\n subTopic: e.subTopic,\n content: e.content,\n confidence: e.confidence,\n temporal: e.temporal,\n updatedAt: e.updatedAt,\n lowActivity: e.lowActivity === true,\n })),\n };\n }\n return ok({ partitions });\n },\n\n 'profile.export'() {\n const doc = loadProfile(guard, profileFilePath(paths.dataDir));\n const lines = [`# 画像导出 ${new Date().toISOString()}`, ''];\n for (const part of ['interest', 'projects', 'comm', 'psy'] as const) {\n lines.push(`## ${part}`);\n for (const e of doc.partitions[part]!.entries) {\n if (e.validTo !== null) continue;\n lines.push(`- [${e.topic}/${e.subTopic}] ${e.content} (conf ${e.confidence.toFixed(2)}, ${e.temporal})`);\n }\n }\n const out = path.join(paths.exportsDir, `profile-export-${Date.now()}.md`);\n writeText(guard, out, lines.join('\\n') + '\\n');\n return ok({ path: out });\n },\n\n 'ledger.open'() {\n const f = ledgerFilePath(paths.dataDir);\n if (!fs.existsSync(guard.assert(f))) fs.writeFileSync(f, '# 账本\\n', 'utf8');\n spawn('cmd', ['/c', 'start', '', f], { detached: true, stdio: 'ignore' }).unref();\n return ok({ path: f });\n },\n\n 'excerpt.open'() {\n const f = excerptFilePath(paths.dataDir);\n if (!fs.existsSync(guard.assert(f))) fs.writeFileSync(f, EXCERPT_HEADER, 'utf8');\n spawn('cmd', ['/c', 'start', '', f], { detached: true, stdio: 'ignore' }).unref();\n return ok({ path: f });\n },\n\n 'weekly.list': () => ok({ reports: listWeeklyReports(guard, paths.dataDir, policy.weekly.keepReports) }),\n\n 'weekly.get'(p) {\n const file = String(p.file ?? '');\n const rep = readWeeklyReport(guard, paths.dataDir, file);\n if (!rep) return err('bad-request', `no such report: ${file}`);\n return ok(rep);\n },\n\n async 'migrate.export'(p) {\n // Card-side export (v1.8.0): same container as the CLI. The\n // passphrase lives only in this call — never audited, never logged.\n const passphrase = String(p.passphrase ?? '');\n if (!passphrase) return err('bad-request', '需要设置口令');\n const { collectMigrationEntries, encryptContainer } = await import('./vault/migrate.js');\n const { entries } = collectMigrationEntries(guard, paths);\n if (entries.length === 0) return err('bad-request', '没有可打包的记忆文件(data/ 是空的)');\n const out = path.join(paths.exportsDir, `heartbeat-memory-${localDayKey()}.hbmig`);\n writeText(guard, out, encryptContainer(entries, passphrase));\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), { event: 'migrate_export', files: entries.length });\n return ok({ path: out, count: entries.length });\n },\n\n async 'migrate.import'(p) {\n const passphrase = String(p.passphrase ?? '');\n const file = String(p.file ?? '');\n if (!passphrase || !file) return err('bad-request', '需要容器路径与口令');\n const { decryptContainer, applyMigrationEntries } = await import('./vault/migrate.js');\n let text: string;\n try {\n // Read-only from a user-chosen path (likely OUTSIDE data/); the\n // path guard still gates every file we WRITE back.\n text = fs.readFileSync(file, 'utf8');\n } catch {\n return err('bad-request', `读不到迁移包:${file}`);\n }\n let container: ReturnType<typeof decryptContainer>;\n try {\n container = decryptContainer(text, passphrase);\n } catch (e) {\n return err('bad-request', String(e instanceof Error ? e.message : e));\n }\n const result = applyMigrationEntries(guard, paths, container.files);\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), {\n event: 'migrate_import', restored: result.restored.length, backedUp: result.backedUp.length, skipped: result.skipped.length,\n rolledBack: result.rolledBack?.length ?? 0, error: result.error ?? null,\n });\n // HB-06: an import that wrote nothing is a failure, not a cheerful ok with\n // the reason buried in the payload.\n if (result.error) return err('migrate-failed', result.error);\n return ok(result);\n },\n };\n}\n\nexport function installHeartbeatRpc(\n ctx: OrchestratorDeps['ctx'] & { inject(services: string[], callback: (scoped: unknown) => void): void },\n deps: Omit<RpcDeps, 'ctx'>,\n): void {\n // ── 0.1.5 适配(C21)─────────────────────────────────────────────────\n // 自定义通道 rpc.handle('/heartbeat') 在 0.1.5 的 cordis 严格服务解析下不可\n // 用:Service 把 this.ctx 固定在 client-connection 自己的上下文(其模块\n // inject 只有 ['credentials']),handle() 内部 owner.webServer.register 是在\n // 别人的 fiber 上读 webServer → `cannot get property \"webServer\" without\n // inject`,调用方怎么声明都救不了(现场取证 2026-09-12:合并 inject 三件套\n // + effect 包裹仍是这个错)。改走 connection.fetch.register():在 /api 下注册\n // 精确路由,只写 connection 内部路由表、不碰任何其他服务;0.1.2 与 0.1.5 的\n // /api 共享处理器都先查精确路由再落 interceptor,两代宿主通用。浏览器认证\n // 由 /api 前缀的 requestRejection 统一把关。客户端相应改为\n // rpc.call('/api', 'heartbeat', { endpoint, ...args })。\n ctx.inject(['connection'], (scoped: unknown) => {\n const remoteCtx = scoped as {\n connection: {\n fetch: { register(route: {\n path: string;\n methods: string[];\n requestBody?: string;\n fetch(request: Request): Promise<Response>;\n }): unknown };\n };\n agents: OrchestratorDeps['ctx']['agents'];\n effect(fn: () => unknown, label?: string): () => void;\n };\n\n const isLive = (sessionId: string): boolean => {\n try {\n return !!remoteCtx.agents.get(sessionId);\n } catch {\n return false;\n }\n };\n\n // HB-19 (2026-10-17): a Map, not an object literal. `endpoints[verb]` on a\n // plain object also resolves inherited keys (\"constructor\", \"toString\",\n // \"__proto__\"), so a crafted verb could reach something that was never\n // registered as an endpoint. Map.get has no prototype chain.\n const endpoints = new Map<string, Endpoint>(Object.entries(buildEndpoints(deps, isLive)));\n\n // ── H-41 (2026-10-07): explicit dependency on the host's /api gate ────\n // This route is mounted under the host's `/api` prefix, and that prefix's\n // check is the ONLY authentication it has — the plugin keeps no credential\n // of its own. The host implements it as `connection.admit(req)`, which\n // returns `requestRejection(req)`'s verdict (Host/Origin fence + the\n // browser-auth secret; the `/api` prefix route calls it before dispatching,\n // so this exact path can never be reached without it). If a future host\n // drops or renames that check, the destructive endpoints above would be\n // reachable by anything that can POST to loopback — so fail closed on them\n // instead of guessing, and say so in the audit log once at registration.\n const gate = remoteCtx.connection as unknown as { admit?: unknown; requestRejection?: unknown };\n const hostGuarded = typeof gate.admit === 'function' || typeof gate.requestRejection === 'function';\n if (!hostGuarded) {\n try {\n appendAuditLine(deps.guard.assert(deps.paths.logsDir + '/heartbeat.jsonl'), {\n event: 'rpc_host_gate_missing',\n detail: 'connection.admit/requestRejection absent; all but the low-sensitivity read-only verbs are refused (⑦A)',\n allowed: [...GATE_SAFE_ENDPOINTS],\n });\n } catch { /* 审计失败不影响注册 */ }\n }\n\n const handler = async (endpoint: unknown, payload: unknown): Promise<RpcResult> => {\n const p = (payload ?? {}) as Record<string, unknown>;\n const fn = typeof endpoint === 'string' ? endpoints.get(endpoint) : undefined;\n if (!fn) return err('bad-request', `unknown endpoint ${JSON.stringify(endpoint)}`);\n if (!hostGuarded && !GATE_SAFE_ENDPOINTS.has(endpoint as string)) {\n return err('forbidden', `host gate unavailable; ${endpoint} is refused (H-41, ⑦A)`);\n }\n try {\n return await fn(p);\n } catch (e) {\n return err('internal', String(e).slice(0, 200));\n }\n };\n\n // RPC 信封与 /api 通道的 client-request/server-response 同构(客户端仍是\n // connection.rpc.call),端点名改走 payload.endpoint 字段。\n remoteCtx.effect(\n () => remoteCtx.connection.fetch.register({\n path: RPC_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request): Promise<Response> => {\n let envelope: { type?: unknown; rpcId?: unknown; payload?: unknown };\n try {\n envelope = await request.json() as typeof envelope;\n } catch {\n return new Response('body is not JSON', { status: 400 });\n }\n const rpcId = envelope?.rpcId;\n if (envelope?.type !== 'client-request' || typeof rpcId !== 'string' || typeof envelope.payload !== 'object' || envelope.payload === null) {\n return new Response('invalid envelope', { status: 400 });\n }\n const p = envelope.payload as Record<string, unknown>;\n const endpoint = typeof p.endpoint === 'string' ? p.endpoint : '(missing endpoint)';\n const result = await handler(endpoint, p);\n return Response.json({ type: 'server-response', rpcId, result });\n },\n }),\n 'heartbeat: rpc route',\n );\n ctx.logger.info('heartbeat: rpc route ready (%s)', RPC_ROUTE_PATH);\n try {\n appendAuditLine(deps.guard.assert(deps.paths.logsDir + '/heartbeat.jsonl'), { event: 'rpc_registered', route: RPC_ROUTE_PATH });\n } catch { /* 审计失败不影响注册 */ }\n });\n}\n","// Interest-scope editing for the settings card (v1.4.0).\n//\n// The wander adjudicator picks its focus from `interests.json` (browse.ts\n// `loadInterests`): the factory copy in config/ is read-only, and a user layer\n// at data/settings/interests.json REPLACES it wholesale. That replace-not-merge\n// semantics is why every successful edit funnels through `ensureUserLayer`: the\n// FIRST edit copies the factory file (interests + _schedule, verbatim) into the\n// user layer before applying the change, so the card becomes the single\n// management entry point without silently dropping the other factory rows.\n// Reads and FAILED validations stay read-only (`readEffective`) — merely\n// opening the card must not take the user layer over.\n//\n// All writes stay inside the guard; unknown top-level keys (e.g. _comment) are\n// preserved on save so hand-written annotations survive card edits.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\n\n/** Mirrors browse.ts's InterestsConfig; kept local so this module owns the\n * editing shape (windows gain mandatory ids on save). */\nexport interface InterestsDoc {\n interests: string[];\n _schedule?: {\n daily_sessions?: number;\n focus_per_session?: number;\n max_seeds_per_focus?: number;\n focus_cooldown_days?: number;\n min_interval_hours?: number;\n windows?: { id?: string; start: string; end: string }[];\n };\n [key: string]: unknown;\n}\n\nexport interface WanderWindow {\n id: string;\n start: string;\n end: string;\n}\n\nexport const MAX_INTERESTS = 32;\nexport const MAX_INTEREST_LEN = 60;\nconst MAX_WINDOWS = 6;\nconst HHMM = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n\nexport function userInterestsPath(paths: WorkspacePaths): string {\n return path.join(paths.settingsDir, 'interests.json');\n}\n\nexport function factoryInterestsPath(paths: WorkspacePaths): string {\n return path.join(paths.configDir, 'interests.json');\n}\n\nfunction readDoc(file: string): InterestsDoc | null {\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<InterestsDoc>;\n if (!Array.isArray(raw.interests)) return null;\n return { ...raw, interests: raw.interests.map(String) };\n } catch {\n return null;\n }\n}\n\n/** What the wander adjudicator sees right now — WITHOUT creating the user\n * layer. Fallback chain: user layer -> factory -> empty. */\nexport function readEffective(paths: WorkspacePaths): InterestsDoc {\n return (\n readDoc(userInterestsPath(paths)) ??\n readDoc(factoryInterestsPath(paths)) ?? { interests: [] }\n );\n}\n\n/**\n * The user layer, created on first EDIT by copying the factory file verbatim\n * (decision: 首编继承出厂). Call only from mutation paths that are about to\n * succeed; the doc it returns equals `readEffective` at call time.\n */\nexport function ensureUserLayer(guard: PathGuard, paths: WorkspacePaths): InterestsDoc {\n const existing = readDoc(userInterestsPath(paths));\n if (existing) return existing;\n const doc: InterestsDoc = readDoc(factoryInterestsPath(paths)) ?? { interests: [] };\n saveDoc(guard, userInterestsPath(paths), doc);\n return doc;\n}\n\nfunction saveDoc(guard: PathGuard, file: string, doc: InterestsDoc): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(guard.assert(file), JSON.stringify(doc, null, 2), 'utf8');\n}\n\nexport interface InterestsResult {\n ok: boolean;\n reason?: string;\n doc: InterestsDoc;\n}\n\n/** Normalize: trim + collapse internal whitespace. Case-insensitive dedupe. */\nexport function normalizeInterest(text: string): string {\n return text.trim().replace(/\\s+/g, ' ');\n}\n\nexport function addInterest(\n guard: PathGuard,\n paths: WorkspacePaths,\n rawText: string,\n): InterestsResult {\n const text = normalizeInterest(rawText);\n if (!text) return { ok: false, reason: 'empty', doc: readEffective(paths) };\n if (text.length > MAX_INTEREST_LEN) {\n return { ok: false, reason: `too-long (max ${MAX_INTEREST_LEN})`, doc: readEffective(paths) };\n }\n const current = readEffective(paths);\n if (current.interests.some((t) => normalizeInterest(t).toLowerCase() === text.toLowerCase())) {\n return { ok: false, reason: 'duplicate', doc: current };\n }\n if (current.interests.length >= MAX_INTERESTS) {\n return { ok: false, reason: `cap (${MAX_INTERESTS})`, doc: current };\n }\n const doc = ensureUserLayer(guard, paths);\n doc.interests.push(text);\n saveDoc(guard, userInterestsPath(paths), doc);\n return { ok: true, doc };\n}\n\nexport function removeInterest(\n guard: PathGuard,\n paths: WorkspacePaths,\n rawText: string,\n): InterestsResult {\n const current = readEffective(paths);\n const text = normalizeInterest(rawText);\n if (!current.interests.some((t) => normalizeInterest(t) === text)) {\n return { ok: false, reason: 'not-found', doc: current };\n }\n const doc = ensureUserLayer(guard, paths);\n doc.interests = doc.interests.filter((t) => normalizeInterest(t) !== text);\n saveDoc(guard, userInterestsPath(paths), doc);\n return { ok: true, doc };\n}\n\n/** Validate \"HH:MM\" and same-day ordering (the wander windows are intra-day). */\nexport function parseWindow(w: unknown): { ok: true; window: WanderWindow } | { ok: false; reason: string } {\n if (typeof w !== 'object' || w === null) return { ok: false, reason: 'not-an-object' };\n const { id, start, end } = w as { id?: unknown; start?: unknown; end?: unknown };\n if (typeof start !== 'string' || !HHMM.test(start)) return { ok: false, reason: `bad start ${JSON.stringify(start)}` };\n if (typeof end !== 'string' || !HHMM.test(end)) return { ok: false, reason: `bad end ${JSON.stringify(end)}` };\n if (start >= end) return { ok: false, reason: `start ${start} must be before end ${end}` };\n return { ok: true, window: { id: typeof id === 'string' && id ? id : `${start}-${end}`, start, end } };\n}\n\n/** Full-state write of the wander windows (the card sends all rows each time). */\nexport function setWanderWindows(\n guard: PathGuard,\n paths: WorkspacePaths,\n rawWindows: unknown,\n): InterestsResult {\n const fail = (reason: string): InterestsResult => ({ ok: false, reason, doc: readEffective(paths) });\n if (!Array.isArray(rawWindows)) return fail('windows-must-be-array');\n if (rawWindows.length === 0) return fail('at-least-one-window');\n if (rawWindows.length > MAX_WINDOWS) return fail(`cap (${MAX_WINDOWS})`);\n const windows: WanderWindow[] = [];\n for (const raw of rawWindows) {\n const parsed = parseWindow(raw);\n if (!parsed.ok) return fail(parsed.reason);\n windows.push(parsed.window);\n }\n // Overlap check: the adjudicator returns the FIRST matching window, so\n // overlapping rows would silently change which window \"wins\".\n const sorted = [...windows].sort((a, b) => a.start.localeCompare(b.start));\n for (let i = 1; i < sorted.length; i += 1) {\n if (sorted[i]!.start < sorted[i - 1]!.end) {\n return fail(`windows overlap: ${sorted[i - 1]!.id} / ${sorted[i]!.id}`);\n }\n }\n const doc = ensureUserLayer(guard, paths);\n doc._schedule = { ...doc._schedule, windows };\n saveDoc(guard, userInterestsPath(paths), doc);\n return { ok: true, doc };\n}\n","// M7b: self-built time injection (design doc §17.6, D20).\n//\n// Replaces the official dsh-time-context (disabled via the user patch — B9 is\n// superseded by D20: time injection has exactly one owner, this module).\n//\n// Gate (all must pass): step === 1 AND the turn was user-initiated (last\n// session event is `agent/inbox/spliced`, P1 ① conclusion) AND the per-session\n// throttle interval has elapsed. Mid-task steps are never injected.\n// Content: precise local time (+ timezone) and elapsed-since-last-message.\n// Transport: pre-step waterfall append — a strict `createUserMessage` message\n// (r5 rule: never splice hand-rolled objects). Source attribution\n// kind='plugin' keeps the observe phase from ingesting these (C-track rule).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteJsonSync } from '../core/atomic-fs.js';\nimport { appendAuditLine } from '../core/audit-log.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport { sessionEvents } from '../core/orchestrator.js';\nimport type { HostSession } from '../core/orchestrator.js';\n\n/** Pure gate (§17.6): every condition must hold for an injection. */\nexport function shouldInjectTime(input: {\n step: number;\n /** Turn-origin probe (see {@link turnOriginIsInboxSplice}). */\n originIsInboxSplice: boolean;\n lastInjectAt: number;\n now: number;\n intervalMs: number;\n}): boolean {\n if (input.step !== 1) return false;\n if (!input.originIsInboxSplice) return false;\n if (input.intervalMs <= 0) return false;\n return input.now - input.lastInjectAt >= input.intervalMs;\n}\n\n/** Turn-origin probe (review 2026-09-13 #2): does the OPEN turn begin\n * with an inbox splice?\n *\n * An exact \"last event is spliced\" check silently breaks the moment any other\n * plugin writes a session event between the splice and this hook. Instead,\n * scan backwards for the last `agent/inbox/spliced` vs the last `turn/end`:\n * the turn is inbox-driven iff a splice happened after the previous turn\n * finished. This is stable against arbitrary interleaving events. Known\n * semantic: our own delivery followups also splice, so a delivery turn counts\n * as inbox-driven — acceptable (throttled like any other; the alternative,\n * inspecting the spliced messages' sources, is deferred until it matters).\n * Cost: bounded by one turn length, and only paid at step === 1. */\nexport function turnOriginIsInboxSplice(session: HostSession): boolean {\n const events = sessionEvents(session);\n let splicedIdx = -1;\n let turnEndIdx = -1;\n for (let i = events.length - 1; i >= 0 && (splicedIdx < 0 || turnEndIdx < 0); i--) {\n const t = events[i]!.type;\n if (t === 'agent/inbox/spliced' && splicedIdx < 0) splicedIdx = i;\n else if (t === 'turn/end' && turnEndIdx < 0) turnEndIdx = i;\n }\n if (splicedIdx < 0) return false;\n return splicedIdx > turnEndIdx; // no turn/end at all (-1) → splice wins\n}\n\n/** `SessionHeader` fields we care about (dsh-session ≥ v4 headers). HostSession\n * deliberately declares only the minimal surface, so `header` is read through a\n * local assertion instead of widening the interface. */\ninterface SessionHeaderProbe {\n header?: {\n origin?: string;\n delegationDepth?: number;\n };\n}\n\n/** Subagent sessions must not receive time injections (their context has no\n * use for \"now\" and every hop pollutes it). Verdict order: header fields\n * first (cheap, exact), then a bounded scan of the first 8 events for the\n * `subagent/descriptor` marker every subagent session logs at seq 0. */\nexport function isSubagentSession(session: HostSession | undefined): boolean {\n if (!session) return false;\n const header = (session as HostSession & SessionHeaderProbe).header;\n if (header?.origin === 'subagent') return true;\n if (typeof header?.delegationDepth === 'number' && header.delegationDepth > 0) return true;\n return sessionEvents(session).slice(0, 8).some((e) => e?.type === 'subagent/descriptor');\n}\n\nfunction formatElapsed(ms: number): string {\n const minutes = Math.max(1, Math.round(ms / 60_000));\n if (minutes < 60) return `${minutes} 分钟`;\n const hours = Math.floor(minutes / 60);\n const rest = minutes % 60;\n return rest === 0 ? `${hours} 小时` : `${hours} 小时 ${rest} 分钟`;\n}\n\nfunction localFormatter(timeZone: string | undefined): Intl.DateTimeFormat {\n const options: Intl.DateTimeFormatOptions = {\n year: 'numeric', month: '2-digit', day: '2-digit',\n hour: '2-digit', minute: '2-digit', hour12: false,\n timeZoneName: 'shortOffset',\n };\n if (timeZone !== undefined) return new Intl.DateTimeFormat('zh-CN', { ...options, timeZone });\n return new Intl.DateTimeFormat('zh-CN', options);\n}\n\n/** Render the injected text (§17.6): precise local time + elapsed. Timezone\n * resolution failures fall back to the system zone (never throw to the hook). */\nexport function renderTimeText(input: {\n now: number;\n timeZone?: string;\n /** Timestamp (`event.time`) of the session's last message event. */\n lastMessageTime?: number;\n}): string {\n let timeLine: string;\n try {\n const parts = localFormatter(input.timeZone).formatToParts(new Date(input.now));\n const get = (type: string): string => parts.find((p) => p.type === type)?.value ?? '';\n timeLine = `当前本地时间:${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}(${parts.find((p) => p.type === 'timeZoneName')?.value ?? ''})。`;\n } catch {\n timeLine = `当前本地时间:${new Date(input.now).toISOString()}。`;\n }\n const elapsedLine = input.lastMessageTime === undefined\n ? ''\n : `\\n距本会话上一条消息已过去 ${formatElapsed(input.now - input.lastMessageTime)}。`;\n return timeLine + elapsedLine;\n}\n\n/** Timestamp of the session's last user/assistant/tool message event. */\nexport function lastMessageTime(session: HostSession): number | undefined {\n const events = sessionEvents(session);\n for (let i = events.length - 1; i >= 0; i--) {\n const e = events[i]!;\n const t = (e as { time?: number }).time;\n if (typeof t === 'number' && /user\\/message|assistant\\/message|tool\\/result/.test(e.type)) return t;\n }\n return undefined;\n}\n\n// ── per-session throttle state (survives restarts, like cursors.json) ───\n\nexport interface TimeInjectState {\n [sessionId: string]: number;\n}\n\nexport function timeInjectStatePath(dataDir: string): string {\n return path.join(dataDir, 'time-inject-state.json');\n}\n\nexport function loadTimeInjectState(guard: PathGuard, dataDir: string): TimeInjectState {\n try {\n const parsed = JSON.parse(fs.readFileSync(guard.assert(timeInjectStatePath(dataDir)), 'utf8')) as TimeInjectState;\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport function saveTimeInjectState(guard: PathGuard, dataDir: string, state: TimeInjectState): void {\n atomicWriteJsonSync(guard.assert(timeInjectStatePath(dataDir)), state);\n}\n\n// ── registration ─────────────────────────────────────────────────────────\n\nexport interface TimeInjectionOptions {\n /** Live-read on every gate check (UI-settable in M7d). */\n getTimeInjectMin(): number;\n timeZone?: string;\n paths: WorkspacePaths;\n logger: { info(msg: string, ...a: unknown[]): void; warn(msg: string, ...a: unknown[]): void };\n onError(error: unknown): void;\n /** Track B status line (§17.5): '' when the statusbar is off or the session\n * rides Track A. Receives the TURN-PINNED track (review #5) so the status\n * line and the system-prompt section can never split one turn. */\n getStatusLine?(session: HostSession, track: 'system-prompt' | 'pre-step'): string;\n /** Pin this turn's track at step===1 (before throttle logic) — every turn\n * start re-pins, so mid-turn capability flips land at the next boundary. */\n pinTrack(sessionId: string, session: HostSession): 'system-prompt' | 'pre-step';\n}\n\ninterface PreStepPayload {\n agent: { session: HostSession };\n step: number;\n signal?: { aborted?: boolean };\n}\n\ninterface EnterDecision {\n kind: string;\n messages: unknown[];\n}\n\n/**\n * Register the gated time injector on `ctx` (all agents, like the official\n * plugin it replaces). Returns the disposer conceptually owned by the caller's\n * fiber via `ctx.effect`.\n */\nexport function registerTimeInjection(\n ctx: {\n on(event: string, listener: (payload: PreStepPayload, next: () => Promise<unknown>) => Promise<unknown>, opts?: { prepend?: boolean }): unknown;\n },\n guard: PathGuard,\n dataDir: string,\n opts: TimeInjectionOptions,\n): void {\n const state = loadTimeInjectState(guard, dataDir);\n ctx.on('agent/pre-step', async (payload, next) => {\n const decision = await next() as EnterDecision;\n if (decision.kind === 'reject' || payload.signal?.aborted) return decision;\n const sessionId = payload.agent.session.id;\n const now = Date.now();\n // Turn-start track pin (review #5): re-pinned at EVERY step===1, before\n // any throttle logic, so the pin never goes stale across turns.\n const track = payload.step === 1 ? opts.pinTrack(sessionId, payload.agent.session) : undefined;\n const intervalMs = Math.max(0, opts.getTimeInjectMin()) * 60_000;\n if (!shouldInjectTime({\n step: payload.step,\n originIsInboxSplice: payload.step === 1 ? turnOriginIsInboxSplice(payload.agent.session) : false,\n lastInjectAt: state[sessionId] ?? 0,\n now,\n intervalMs,\n })) return decision;\n // Subagent sessions never get the clock (review 2026-10-29): checked after\n // the pure gate so the event-stream scan only runs on otherwise-eligible\n // steps, and the audit line only fires on a would-have-injected hop.\n if (isSubagentSession(payload.agent.session)) {\n appendAuditLine(opts.paths.logsDir + '/heartbeat.jsonl', {\n event: 'time_inject_skipped', sessionId, reason: 'subagent',\n });\n return decision;\n }\n try {\n const { createUserMessage } = await import('@deepseek-ai/dsh-llm');\n let text = renderTimeText({\n now,\n timeZone: opts.timeZone,\n lastMessageTime: lastMessageTime(payload.agent.session),\n });\n // §17.5: Track B rides the same message with a trailing status line\n // (D21: status text itself never carries time words).\n if (opts.getStatusLine && track) {\n const statusLine = opts.getStatusLine(payload.agent.session, track);\n if (statusLine) text += `\\n${statusLine}`;\n }\n const message = createUserMessage({\n content: [{ type: 'text', text }],\n // 0.1.7 V4: producer-owned kind (retired generic 'plugin' is refused).\n source: { kind: 'heartbeat', plugin: 'heartbeat', form: 'snapshot', sections: [{ name: 'heartbeat-time', text }] },\n });\n state[sessionId] = now;\n saveTimeInjectState(guard, dataDir, state);\n appendAuditLine(opts.paths.logsDir + '/heartbeat.jsonl', {\n event: 'time_injected', sessionId, intervalMin: opts.getTimeInjectMin(),\n });\n return { ...decision, messages: [...decision.messages, message] };\n } catch (e) {\n opts.onError(e);\n return decision;\n }\n }, { prepend: true });\n}\n","// M7c: statusbar tracks (design doc §17.4–17.5, §17.7, D19/D21).\n//\n// One status store, two transports, picked per agent by model capability:\n// Track A — in-history-capable models: a dynamic system-prompt section\n// (`heartbeat:status`). The host projection layer dedupes (text\n// unchanged → zero commit) and appends changed prompts after the\n// cached history (KV-safe). Incapable/disabled → the text function\n// returns '' and the section drops out of the render entirely.\n// Track B — every other model: the pre-step time-injection message gains a\n// trailing status line (see time-inject.ts `getStatusLine`).\n// Track evidence: the session log's latest `request/context` event carries the\n// route's `systemPromptUpdate` mode. No evidence yet (fresh session) → Track B\n// (§17.7 default). Red line D21: status text NEVER contains time words.\n\nimport { appendAuditLine } from '../core/audit-log.js';\nimport { sessionEventCount, sessionEvents } from '../core/orchestrator.js';\nimport type { HostSession } from '../core/orchestrator.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport { StatusReader } from './store.js';\nimport type { StatusState } from './store.js';\n\n// ── capability probe (review 2026-09-13 #1: incremental tail scan) ───\n// Cache keyed by \"how far we've scanned\", NOT by log length: the length grows\n// every step, so a length key would miss (and rescan the whole log backwards)\n// on every assembly. We remember the scan watermark and, on new events, read\n// only the tail (snapshotEvents(fromSeq) range) for NEW request/context rows.\ninterface CapabilityCache {\n /** Event count at the time of the last scan. */\n scannedUpTo: number;\n supported: boolean;\n}\nconst capabilityCache = new Map<string, CapabilityCache>();\n\nexport function supportsInHistory(session: HostSession): boolean {\n const key = session.id;\n const len = sessionEventCount(session);\n const hit = capabilityCache.get(key);\n if (hit && hit.scannedUpTo === len) return hit.supported;\n // Log shrank (session reset under the same id) → rescan from zero.\n const from = hit && len >= hit.scannedUpTo ? hit.scannedUpTo : 0;\n let supported = false;\n if (from !== 0 && hit) supported = hit.supported;\n const readTail = (fromSeq: number): { type: string; data?: unknown }[] => {\n if (typeof session.snapshotEvents === 'function') {\n try {\n const slice = session.snapshotEvents(fromSeq);\n if (Array.isArray(slice)) return slice;\n } catch { /* fall through to the legacy full read */ }\n }\n return sessionEvents(session).slice(fromSeq);\n };\n for (const e of readTail(from)) {\n if (e.type === 'request/context') {\n supported = (e.data as { systemPromptUpdate?: string } | undefined)?.systemPromptUpdate === 'in-history';\n }\n }\n capabilityCache.set(key, { scannedUpTo: len, supported });\n return supported;\n}\n\n/** Forget cached capability (test helper; also bounds memory across deletes). */\nexport function resetCapabilityCache(): void {\n capabilityCache.clear();\n}\n\nconst SCENE_LABELS: Record<StatusState['scene'], string> = {\n 'quiet-hours': '静默时段,世界睡了',\n 'just-spoke': '刚去和你说过话',\n wandering: '正在闲逛看新东西',\n busy: '看到你在忙,不去打扰',\n present: '在场待着',\n away: '你不在,自己待着',\n};\n\n/** Render the one-line status text (D21 red line: zero time words).\n *\n * RENDER PURITY RED LINE (2026-09-13 review): this MUST stay a pure function\n * of the status state — no clock reads, no counters, no per-call variability.\n * The host projection already refuses to commit identical text (project()\n * emits no updates when the rendered prompt is byte-identical), so purity here\n * is what keeps the in-history append cadence at \"per scene change\", not \"per\n * step\". Any field varying faster than the scene belongs in the time\n * injection, never here.\n *\n * NOTE POLICY (review 2026-09-13 #3): `withNote: false` for the Track A\n * section — the scene label is a constant-table mapping (maximally stable),\n * while the note is engine-room free text that can differ every beat and\n * would defeat the host's byte-dedupe. The note is for the UI and the Track B\n * pre-step line (where each message is small and already event-shaped). */\nexport function renderStatusText(\n status: StatusState | null,\n opts?: { withNote?: boolean },\n): string {\n if (!status) return '';\n const label = SCENE_LABELS[status.scene] ?? '在场';\n const note = opts?.withNote === false ? '' : status.note ? `——${status.note}` : '';\n return `心跳此刻:${label}${note}。`;\n}\n\n// ── turn-pinned track decision (2026-09-13 review #5) ────────────────────\n// The track must be decided ONCE per turn, at its start (step===1 in the\n// pre-step listener), and both transports read that pin. Otherwise a\n// capability flip mid-turn (e.g. the very first request of a fresh capable\n// session lands `request/context` after step 1) splits the turn: the pre-step\n// status line already in history AND the section activating from the next\n// step. A pin updates only at turn starts, so a flip always lands cleanly at\n// the next turn boundary.\nconst pinnedTrack = new Map<string, 'system-prompt' | 'pre-step'>();\n\n/** Pin and return this turn's track. Call from the pre-step listener at\n * step===1 (before any throttle logic) — every turn start re-pins. */\nexport function pinTrack(sessionId: string, session: HostSession): 'system-prompt' | 'pre-step' {\n const track = trackFor(session);\n pinnedTrack.set(sessionId, track);\n return track;\n}\n\n/** The pinned track when one exists for this session, else the live probe\n * (fallback for assemblies that somehow precede any turn-start pin). */\nexport function pinnedTrackFor(sessionId: string, session: HostSession): 'system-prompt' | 'pre-step' {\n return pinnedTrack.get(sessionId) ?? trackFor(session);\n}\n\nexport function resetPins(): void {\n pinnedTrack.clear();\n}\n\n/** Track-change auditor: emits `statusbar_track` only when an agent's track\n * actually flips (bounded spam; called from the two render paths). */\nconst lastTrack = new Map<string, string>();\n\nexport function noteTrack(auditFile: string, sessionId: string, track: 'system-prompt' | 'pre-step' | 'off'): void {\n if (lastTrack.get(sessionId) === track) return;\n lastTrack.set(sessionId, track);\n try {\n appendAuditLine(auditFile, { event: 'statusbar_track', sessionId, track });\n } catch { /* audit failure must not break rendering */ }\n}\n\n/** Forget a session's track memo (test helper). */\nexport function resetTrackMemo(): void {\n lastTrack.clear();\n}\n\n/** Which transport serves this session right now (§17.7: no evidence yet →\n * Track B; the section flip happens once a request/context event lands). */\nexport function trackFor(session: HostSession): 'system-prompt' | 'pre-step' {\n return supportsInHistory(session) ? 'system-prompt' : 'pre-step';\n}\n\n/** Register the Track A section on the host systemPrompt service. The text\n * provider returns '' (section drops from the render) when the statusbar is\n * off, the agent is unknown, or the session rides Track B. */\nexport function registerStatusbarSection(\n ctx: {\n inject(services: string[], callback: (scoped: unknown) => void): void;\n },\n guard: PathGuard,\n paths: WorkspacePaths,\n opts: { enabled(): boolean; reader: StatusReader },\n): void {\n ctx.inject(['systemPrompt'], (scoped) => {\n const spCtx = scoped as {\n systemPrompt?: {\n section(def: { name: string; order: number; text: string | ((context: unknown) => string) }): unknown;\n };\n effect(fn: () => unknown, label?: string): () => void;\n logger?: { warn(msg: string, ...a: unknown[]): void };\n };\n const section = spCtx.systemPrompt?.section;\n if (typeof section !== 'function') {\n spCtx.logger?.warn('heartbeat: systemPrompt service has no section API, statusbar Track A unavailable');\n return;\n }\n spCtx.effect(() => section.call(spCtx.systemPrompt, {\n name: 'heartbeat:status',\n order: 5000, // between the persona prefix (0) and the harness block (10000)\n text: (context: unknown) => {\n if (!opts.enabled()) {\n noteTrack(paths.logsDir + '/heartbeat.jsonl', (context as { agent?: { session: HostSession } }).agent?.session.id ?? '(none)', 'off');\n return '';\n }\n const agent = (context as { agent?: { session?: HostSession } }).agent;\n if (!agent?.session) return '';\n // Read the TURN-PINNED track (2026-09-13 review #5): a mid-turn\n // capability flip must not activate the section inside the same turn\n // whose pre-step status line already went out on Track B.\n const track = pinnedTrackFor(agent.session.id, agent.session);\n noteTrack(paths.logsDir + '/heartbeat.jsonl', agent.session.id, track);\n if (track !== 'system-prompt') return '';\n return renderStatusText(opts.reader.read(guard, paths), { withNote: false });\n },\n }), 'heartbeat: statusbar section');\n });\n}\n","// The heartbeat agent preset, as a runtime registration (issue #2, 2026-10-10).\n//\n// 0.1.7+ mounts presets from the profile COMPOSITION: a row named\n// `@deepseek-ai/dsh-agent-preset` whose `config` is the definition. That row\n// makes the PROFILE resolve the package — and `@deepseek-ai/dsh-agent-preset`\n// is thin (it only forwards its config to `agentPresets.register`), but its\n// peer closure contains `cordis-plugin-loader` / `cordis-plugin-include` /\n// `cordis-plugin-group`, i.e. the loading machinery itself. So a profile that\n// cannot resolve it fails the WHOLE plugin tree (\"plugin tree failed to load\"\n// on 0.1.5), and one that satisfies it by hand double-instances the machinery\n// (\"prompt section deployment:persona-prefix is already registered\", every\n// session then refuses to resume). Both were reported with reproductions.\n//\n// The registry exposes `register(definition)` for exactly this case — its\n// docstring: \"Parsed configuration supplied by the declaring plugin\" — so the\n// plugin now registers its own preset at runtime and the bundle patch carries\n// no host-package reference at all. The definition below is the same content\n// the composition used to hold (and the same as\n// `assets/presets/heartbeat/agent.cordis.yml`, which older hosts still read\n// off the filesystem).\n//\n// Deliberately NO persona row: the deployment persona (soul card) plus the\n// heartbeat prompt already cover it, and a \"You are a coding agent\" line would\n// overwrite the persona.\n\n/** One child row of the preset, in Cordis entry-list shape. */\nexport interface PresetEntry {\n readonly id?: string;\n readonly name?: string;\n /** `cordis:group` marker: this row nests `config` as child entries. */\n readonly group?: boolean;\n /** Isolation flags a group row may carry (kept verbatim). */\n readonly isolate?: Record<string, unknown>;\n readonly config?: unknown;\n}\n\n/** Identity, display fields and child plugins of one preset. */\nexport interface HeartbeatPresetDefinition {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly order: number;\n readonly plugins: readonly PresetEntry[];\n}\n\n/**\n * The bundled preset definition for `id`.\n *\n * Content = `assets/presets/heartbeat/agent.cordis.yml`: a compaction group\n * (basic + command-compact + tool-result-pruner) plus the single model-facing\n * tool `tool-web` with `fetch: false` (web_search only — no page fetching,\n * no shell, no filesystem, no subagents).\n */\nexport function heartbeatPresetDefinition(id: string = 'heartbeat'): HeartbeatPresetDefinition {\n return {\n id,\n name: '心跳模式',\n description: '心跳 agent 专用:仅 web_search + 上下文折叠;无 shell、无文件、无子代理。',\n order: 20,\n plugins: [\n {\n id: 'compaction',\n name: 'cordis:group',\n group: true,\n isolate: { compaction: true, toolResultPruner: true },\n config: [\n { id: 'compaction-basic', name: '@deepseek-ai/dsh-compaction-basic' },\n { id: 'command-compact', name: '@deepseek-ai/dsh-command-compact' },\n {\n id: 'tool-result-pruner',\n name: '@deepseek-ai/dsh-compaction-tool-result-pruner',\n config: { thresholdChars: 8192, headChars: 4096, tailChars: 1024 },\n },\n ],\n },\n { id: 'tool-web', name: '@deepseek-ai/dsh-tool-web', config: { fetch: false, searchTimeoutMs: 60000 } },\n ],\n };\n}\n\n/** Registration result, for the audit line and the log. */\nexport type PresetRegisterAction = 'registered' | 'skipped-disabled' | 'skipped-no-api' | 'already-registered' | 'error';\n\nexport interface PresetRegisterResult {\n action: PresetRegisterAction;\n id: string;\n detail?: string;\n /**\n * HB-17 (2026-10-17): undo hook returned by the registry. The caller must\n * run it on dispose — otherwise a plugin reload leaves the preset behind\n * (and the next registration double-mounts it).\n */\n disposer?: () => Promise<void>;\n}\n\nconst DUPLICATE_RE = /Duplicate agent preset/i;\n/** Backoff for a duplicate id: long enough for the previous instance's dispose. */\nconst DUPLICATE_RETRY_MS = [80, 160, 320] as const;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => { setTimeout(resolve, ms); });\n}\n\n/** Minimal shape of the registry we call (`AgentPresetRegistry.register`). */\ninterface RegistrarLike {\n register?(definition: unknown): Promise<() => Promise<void>> | (() => Promise<void>);\n}\n\n/**\n * Register the bundled preset at runtime, tolerating every missing-API case.\n *\n * A host whose registry has no `register` (0.1.7-alpha.1 and other partial\n * builds) or no `agentPresets` service at all (pre-0.1.7) must NOT take the\n * host down: the heartbeat simply runs without its preset — degraded (no\n * `web_search`), which the acquire path already audits as `preset=no-api`.\n *\n * @param service The resolved `agentPresets` service, if any.\n * @param id Preset identity to register.\n * @param enabled False when the operator manages the preset themselves.\n * @returns What happened, for the audit line.\n */\nexport async function registerHeartbeatPreset(\n service: unknown,\n id: string = 'heartbeat',\n enabled: boolean = true,\n): Promise<PresetRegisterResult> {\n if (!enabled) return { action: 'skipped-disabled', id };\n const registrar = service as RegistrarLike | undefined;\n if (registrar === undefined || registrar === null || typeof registrar.register !== 'function') {\n return { action: 'skipped-no-api', id };\n }\n // HB-31 (2026-10-29): a hot reload used to log \"Duplicate agent preset\".\n // The registry rejects a second registration for an id it already holds, and\n // the holder is the PREVIOUS plugin instance, whose unregister only runs from\n // its own dispose — which can land after the new instance has started (or,\n // when the old fiber was dropped without disposal, never at all). Waiting a\n // few hundred ms covers the ordinary case; when the id is still held the\n // existing preset is the same definition, so reusing it is correct, not a\n // failure. A full restart always registers cleanly.\n let detail = '';\n for (let attempt = 0; ; attempt += 1) {\n try {\n const disposer = await registrar.register(heartbeatPresetDefinition(id));\n return typeof disposer === 'function'\n ? { action: 'registered', id, disposer }\n : { action: 'registered', id };\n } catch (e) {\n detail = String(e).slice(0, 200);\n if (!DUPLICATE_RE.test(detail)) return { action: 'error', id, detail };\n const wait = DUPLICATE_RETRY_MS[attempt];\n if (wait === undefined) return { action: 'already-registered', id, detail };\n await delay(wait);\n }\n }\n}\n","// Ledger as a MODEL TOOL (v1.8.0): the chat agents can record / list / check\n// off ledger items themselves, so a todo mentioned in conversation lands in\n// the shared ledger without the user commanding anyone to \"write it down\".\n//\n// Registration is host-side (`ToolRuntime.register`, 0.2.0-rc.2 verified):\n// the definition is built as a PLAIN OBJECT here — `parameters` is a raw JSON\n// Schema per ToolSchema (dsh-llm), so we do not import `defineTool` and the\n// module carries zero new runtime dependencies. `ToolRuntime.register` is the\n// only host entry point (looked up dynamically by the caller); on a host\n// without it the caller audits and moves on, nothing else is affected.\n//\n// Scope: registration happens through the plugin's ROOT context, which lands\n// the tool in the GLOBAL layer — every agent sees it. The engine room is\n// unaffected: its preset restrict({allow:['web_search']}) masks global tools,\n// so the heartbeat's own turns cannot touch the ledger.\n\nimport {\n appendEntry,\n markDone,\n readLedger,\n scanPending,\n type LedgerEntry,\n} from './ledger.js';\nimport type { PathGuard } from '../core/path-guard.js';\n\n/** Minimal structural typing of the host shape — we deliberately do not\n * depend on @deepseek-ai/dsh-tools at runtime. */\nexport interface RegisterableToolRuntime {\n register(definition: unknown): () => void;\n}\n\ninterface LedgerToolArgs {\n action?: unknown;\n text?: unknown;\n key?: unknown;\n}\n\nconst MAX_TEXT = 120;\n\nfunction clean(v: unknown): string {\n return String(v ?? '').replace(/\\s+/g, ' ').trim().slice(0, MAX_TEXT);\n}\n\nfunction fmtEntry(e: LedgerEntry): string {\n return `#${e.id} [${e.status}] ${e.date} ${e.text}`;\n}\n\nexport function buildLedgerTool(guard: PathGuard, file: string): unknown {\n return {\n name: 'ledger',\n description:\n '共享账本工具(心跳插件的待办与事项记录)。当用户提到计划、待办、承诺、想做的事,' +\n '或者某件事已经完成时,主动调用本工具登记或勾掉——不需要等用户明确说\"记一下\"。' +\n 'action=add 登记新事项(text 必填);action=list 查看当前未完成事项;action=done 勾掉一条(key 为 #id 或文本子串)。',\n parameters: {\n type: 'object',\n properties: {\n action: { type: 'string', enum: ['add', 'list', 'done'], description: 'add=登记,list=查未完成,done=勾掉' },\n text: { type: 'string', description: 'action=add 时必填:事项内容(一句话)' },\n key: { type: 'string', description: 'action=done 时必填:#id 或事项文本的唯一子串' },\n },\n required: ['action'],\n additionalProperties: false,\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean' },\n message: { type: 'string' },\n },\n required: ['ok', 'message'],\n additionalProperties: false,\n },\n render: (_args: unknown, value: unknown) => {\n const v = value as { message?: string };\n return [{ type: 'text', text: String(v.message ?? '') }];\n },\n },\n timeoutMs: 5000,\n // Ledger writes go through read-modify-write on one file; never parallel.\n isConcurrencySafe: () => false,\n async execute(args: unknown): Promise<unknown> {\n const a = (args ?? {}) as LedgerToolArgs;\n const action = String(a.action ?? '');\n if (action === 'add') {\n const text = clean(a.text);\n if (!text) return { ok: false, message: 'add 需要非空 text' };\n const e = appendEntry(guard, file, text);\n return { ok: true, message: `已登记 ${fmtEntry(e)}` };\n }\n if (action === 'done') {\n const key = clean(a.key);\n if (!key) return { ok: false, message: 'done 需要 key(#id 或文本子串)' };\n const e = markDone(guard, file, key);\n if (!e) return { ok: false, message: `没有找到匹配「${key}」的未完成事项(先用 list 查)` };\n return { ok: true, message: `已完成 ${fmtEntry(e)}` };\n }\n if (action === 'list') {\n const items = scanPending(guard, file).map(fmtEntry);\n return { ok: true, message: items.length > 0 ? `当前未完成 ${items.length} 项:\\n${items.join('\\n')}` : '账本里没有未完成事项' };\n }\n // Unsupported action shapes should be rare (schema-enforced); stay total.\n const total = readLedger(guard, file).entries.length;\n return { ok: false, message: `未知 action,账本共 ${total} 条` };\n },\n };\n}\n","// 心事匣 as a MODEL TOOL (v2.0): the chat agents can leave ONE note for the\n// next heartbeat, look at it, or let it go — the same host-side pattern as the\n// ledger tool (see ledger/tool.ts:1-15): the definition is a PLAIN OBJECT built\n// here, `parameters` is a raw JSON Schema, and nothing imports\n// @deepseek-ai/dsh-tools, so this module keeps zero new runtime dependencies.\n//\n// Registration goes through the plugin's ROOT context, which lands the tool in\n// the GLOBAL layer — every chat agent sees it. The engine room never does: its\n// preset restrict({allow:['web_search']}) masks global tools, and it must stay\n// that way. The note is the persona's own private line; the engine room only\n// ever sees it indirectly, as text inside the delivery package it never builds.\n//\n// Scope note: the note is one slot, not a queue. `write` replaces — and that\n// replacement is the whole mechanism by which the previous note is let go, so\n// the tool deliberately has no \"append\".\n\nimport type { PathGuard } from '../core/path-guard.js';\nimport { clearNote, notepadView, readNotepad, writeNote, type NotepadView } from './store.js';\n\ninterface NotepadToolArgs {\n action?: unknown;\n text?: unknown;\n}\n\n/** One line, deliberately: this is a HOOK for the next self to re-expand, not a\n * record. 120 (the ledger's per-item cap) is the convention here; the little\n * extra room is because a note is a whole thought, where a ledger item is a\n * task title. */\nconst MAX_NOTE_CHARS = 160;\n\nfunction clean(v: unknown): string {\n return String(v ?? '').replace(/\\s+/g, ' ').trim().slice(0, MAX_NOTE_CHARS);\n}\n\nfunction fmtMinutes(m: number): string {\n if (m < 1) return '不到 1 分钟';\n if (m < 60) return `${m} 分钟`;\n const h = Math.floor(m / 60);\n const rest = m % 60;\n return rest > 0 ? `${h} 小时 ${rest} 分` : `${h} 小时`;\n}\n\n/** Same phrasing the delivery package uses (material.ts notepadLines) so the\n * note reads the same wherever she meets it. */\nfunction fmtView(v: NotepadView): string {\n const beats = v.beatsAgo === 0 ? '本跳' : `${v.beatsAgo} 跳前`;\n const wakes = v.wakesAgo === 0 ? '还没被叫醒过' : `期间被叫醒过 ${v.wakesAgo} 次`;\n return `心事匣里现在有:${v.text}\\n(留于${beats},已搁 ${fmtMinutes(v.sinceMinutes)},${wakes})`;\n}\n\nexport function buildNotepadTool(guard: PathGuard, file: string): unknown {\n return {\n name: 'notepad',\n description:\n '心事匣(心跳插件的\"留给下一跳的自己\"便签)。只有一格:写下新的就盖掉旧的。' +\n '当你有话想留到下次心跳再说、或者有一件放不下的事时,用 action=write 留下一句引子——' +\n '不要写整段,下次跳由那时的你重新展开。想留住原来的就照原样再写一遍(字样一致算保留,' +\n '它的年龄不会重算);写别的就是换掉它。action=read 看现在格子里是什么;action=clear 主动放掉。' +\n '投递包读过之后,什么都不做它就下一跳没了。留不留都行,没话就空着。',\n parameters: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['write', 'read', 'clear'],\n description: 'write=留一句(盖掉旧的),read=看现在是什么,clear=主动放掉',\n },\n text: {\n type: 'string',\n description: 'action=write 时必填:一句引子(不是整段心事,下次跳你自己重新展开)',\n },\n },\n required: ['action'],\n additionalProperties: false,\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean' },\n message: { type: 'string' },\n },\n required: ['ok', 'message'],\n additionalProperties: false,\n },\n render: (_args: unknown, value: unknown) => {\n const v = value as { message?: string };\n return [{ type: 'text', text: String(v.message ?? '') }];\n },\n },\n timeoutMs: 5000,\n // Read-modify-write on one file, and the note's lifecycle depends on it.\n isConcurrencySafe: () => false,\n async execute(args: unknown): Promise<unknown> {\n const a = (args ?? {}) as NotepadToolArgs;\n const action = String(a.action ?? '');\n try {\n if (action === 'write') {\n const text = clean(a.text);\n if (!text) return { ok: false, message: 'write 需要非空 text(一句引子)' };\n const { note, kept } = writeNote(guard, file, text);\n return {\n ok: true,\n message: kept ? `还惦记着:${note.text}(年龄不变)` : `已留下心事:${note.text}`,\n };\n }\n if (action === 'read') {\n const v = notepadView(readNotepad(guard, file));\n return { ok: true, message: v ? fmtView(v) : '心事匣是空的' };\n }\n if (action === 'clear') {\n const prev = clearNote(guard, file);\n return prev\n ? { ok: true, message: `已放掉:${prev.text}` }\n : { ok: true, message: '心事匣本来就是空的' };\n }\n // Unsupported action shapes should be rare (schema-enforced); stay total.\n return { ok: false, message: `未知 action(${action || '空'}),只认 write / read / clear` };\n } catch (e) {\n // A damaged container throws on read (store.ts header). Never let that\n // surface as a tool crash; the host would show it as a tool failure.\n return { ok: false, message: `心事匣读写失败:${String(e).slice(0, 120)}` };\n }\n },\n };\n}\n","// Excerpt book as a MODEL TOOL (v2.0.0): the agent can keep a line the moment it\n// lands, instead of losing it because there is nowhere to put it.\n//\n// Same registration shape as the ledger tool: a PLAIN OBJECT, no import of\n// @deepseek-ai/dsh-tools, registered through the plugin's ROOT context so it\n// lands in the GLOBAL layer every chat agent sees. The engine room cannot\n// reach it (its preset restrict({allow:['web_search']}) masks global tools).\n\nimport { appendExcerpt, readExcerpts, recentExcerpts, removeExcerpt, type ExcerptEntry } from './excerpt.js';\nimport type { PathGuard } from '../core/path-guard.js';\n\ninterface ExcerptToolArgs {\n action?: unknown;\n text?: unknown;\n key?: unknown;\n}\n\nconst MAX_TEXT = 300;\nconst LIST_LIMIT = 10;\n\nfunction clean(v: unknown): string {\n return String(v ?? '').replace(/\\s+/g, ' ').trim();\n}\n\nfunction fmtEntry(e: ExcerptEntry): string {\n return `#${e.id} ${e.date} ${e.time} ${e.text}`;\n}\n\nexport function buildExcerptTool(guard: PathGuard, file: string): unknown {\n return {\n name: 'excerpt',\n description:\n '你自己的摘抄本:留句子和小事的地方。想说\"这句我要记下来\"的时候用——他说过的话、看到的句子、' +\n '心里过了一下的小事。它和账本、心事匣都不一样:账本记的是待办和承诺(会勾掉),心事匣是留给下一跳的一句引子(只有一格、会被盖掉),' +\n '摘抄本只增不减,除非你主动 remove。写的时候把话原样留下,不用解释。' +\n 'action=add 抄一条(text 必填);action=list 翻最近十条;action=remove 抹掉一条(key 为 #id 或正文里的唯一子串)。',\n parameters: {\n type: 'object',\n properties: {\n action: { type: 'string', enum: ['add', 'list', 'remove'], description: 'add=抄一条,list=翻最近十条,remove=抹掉一条' },\n text: { type: 'string', description: 'action=add 时必填:要留下的那句话或那件小事' },\n key: { type: 'string', description: 'action=remove 时必填:#id 或正文里的唯一子串' },\n },\n required: ['action'],\n additionalProperties: false,\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean' },\n message: { type: 'string' },\n },\n required: ['ok', 'message'],\n additionalProperties: false,\n },\n render: (_args: unknown, value: unknown) => {\n const v = value as { message?: string };\n return [{ type: 'text', text: String(v.message ?? '') }];\n },\n },\n timeoutMs: 5000,\n // Read-modify-write on one file; never parallel.\n isConcurrencySafe: () => false,\n async execute(args: unknown): Promise<unknown> {\n const a = (args ?? {}) as ExcerptToolArgs;\n const action = String(a.action ?? '');\n if (action === 'add') {\n const text = clean(a.text).slice(0, MAX_TEXT);\n if (!text) return { ok: false, message: 'add 需要非空 text' };\n const e = appendExcerpt(guard, file, text);\n return { ok: true, message: `已抄下 ${fmtEntry(e)}` };\n }\n if (action === 'remove') {\n const key = clean(a.key);\n if (!key) return { ok: false, message: 'remove 需要 key(#id 或正文里的唯一子串)' };\n const e = removeExcerpt(guard, file, key);\n if (!e) return { ok: false, message: `摘抄本里没有匹配「${key}」的一条(先用 list 翻)` };\n return { ok: true, message: `已抹掉 ${fmtEntry(e)}` };\n }\n if (action === 'list') {\n const total = readExcerpts(guard, file).entries.length;\n if (total === 0) return { ok: true, message: '摘抄本还是空的' };\n const items = recentExcerpts(guard, file, LIST_LIMIT).map(fmtEntry);\n return { ok: true, message: `摘抄本共 ${total} 条,最近 ${items.length} 条:\\n${items.join('\\n')}` };\n }\n // Unsupported action shapes should be rare (schema-enforced); stay total.\n const total = readExcerpts(guard, file).entries.length;\n return { ok: false, message: `未知 action,摘抄本共 ${total} 条` };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,OAAO,OAAO;;;ACFd,OAAO,QAAQ;AACf,OAAO,UAAU;AAIV,IAAM,eAAe;AAY5B,IAAM,SAAS;AAAA,EACb,aAAa,EAAE,KAAK,GAAG,KAAK,KAAK;AAAA,EACjC,cAAc,EAAE,KAAK,GAAG,KAAK,GAAG;AAAA,EAChC,eAAe,EAAE,KAAK,GAAG,KAAK,KAAK;AACrC;AAEA,SAAS,SAAS,KAAwB;AACxC,MAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,EAAG,QAAO,CAAC;AACnE,QAAM,IAAI;AACV,QAAM,MAAgB,CAAC;AACvB,aAAW,OAAO,CAAC,eAAe,gBAAgB,eAAe,GAAY;AAC3E,UAAM,IAAI,EAAE,GAAG;AACf,QAAI,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,KAAK,OAAO,GAAG,EAAE,OAAO,KAAK,OAAO,GAAG,EAAE,KAAK;AAC/F,UAAI,GAAG,IAAI,KAAK,MAAM,CAAC;AAAA,IACzB;AAAA,EACF;AACA,MAAI,OAAO,EAAE,cAAc,UAAW,KAAI,YAAY,EAAE;AACxD,MAAI,OAAO,EAAE,aAAa,UAAW,KAAI,WAAW,EAAE;AACtD,MAAI,OAAO,EAAE,eAAe,UAAW,KAAI,aAAa,EAAE;AAC1D,SAAO;AACT;AAEO,SAAS,aAAa,aAA6B;AACxD,SAAO,KAAK,KAAK,aAAa,YAAY;AAC5C;AAGO,SAAS,aAAa,OAAkB,aAA+B;AAC5E,MAAI;AACF,UAAM,MAAe,KAAK,MAAM,GA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F,GAAG,sBAAsB;AAC3B;","names":["fs","path","fs","path","fs","path","path","fs","fs","path","getRuntime","clean","MAX_TEXT","clean","fmtEntry","total","result","name"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/config/ui-config.ts","../src/config/quiet-hours.ts","../src/rpc.ts","../src/browse/interests-edit.ts","../src/statusbar/time-inject.ts","../src/statusbar/track.ts","../src/core/preset-definition.ts","../src/ledger/tool.ts","../src/notepad/tool.ts","../src/excerpt/tool.ts","../src/sources/bilibili.ts"],"sourcesContent":["// dsh-heartbeat plugin entry.\n//\n// Contract (verified against DSH 0.1.1-rc.2 + dsh-vision-router as the\n// third-party reference): the package main exports a cordis plugin -\n// { name, inject, Config, apply(ctx, config) }. The bundle-level\n// cordis.patch.yml (dsh.bundle.patch) mounts it via\n// - insert: - id: heartbeat, name: dsh-heartbeat\n// and the loader resolves `name` to this package's main export.\n\nimport z from '@deepseek-ai/schemastery';\nimport { initWorkspace } from './core/paths.js';\nimport { createPathGuard } from './core/path-guard.js';\nimport { appendAuditLine } from './core/audit-log.js';\nimport { loadPolicy, updateUserPolicy } from './config/load.js';\nimport { loadUiConfig, saveUiConfig, type UiConfig } from './config/ui-config.js';\nimport { resolveQuietHours } from './config/quiet-hours.js';\nimport { deepMerge } from './config/schema.js';\nimport { setRuntime, getRuntime } from './core/runtime.js';\nimport { startOrchestrator, applyHeartbeatInterval, type OrchestratorDeps } from './core/orchestrator.js';\nimport { installHeartbeatRpc } from './rpc.js';\nimport { registerTimeInjection } from './statusbar/time-inject.js';\nimport { registerStatusbarSection, noteTrack, pinTrack } from './statusbar/track.js';\nimport { StatusReader } from './statusbar/store.js';\nimport { renderStatusText } from './statusbar/track.js';\nimport { installBundledPreset, userPresetRoot, describeInstall } from './core/preset-install.js';\nimport { registerHeartbeatPreset } from './core/preset-definition.js';\nimport { buildLedgerTool } from './ledger/tool.js';\nimport { buildSeedReportTool, reportFilePath } from './seeds/report.js';\nimport { ledgerFilePath } from './ledger/ledger.js';\nimport { buildNotepadTool } from './notepad/tool.js';\nimport { notepadFilePath } from './notepad/store.js';\nimport { buildExcerptTool } from './excerpt/tool.js';\nimport { excerptFilePath } from './excerpt/excerpt.js';\nimport { startBilibiliSource } from './sources/bilibili.js';\n\nexport const name = 'heartbeat';\n\n/**\n * Host services required by the orchestrator (verified present in\n * DSH 0.1.1-rc.2 via hb-probe: agents service + agent/created + followup).\n *\n * `settings` is deliberately NOT declared here (v2.1.0, from issue #6's follow-up):\n * a module-level `inject` entry is a HARD dependency — cordis keeps the plugin\n * at `pending (waiting for service: settings)` for as long as the host does not\n * provide it, and on DSH desktop 0.2.1-rc.3 that pending plugin was enough to\n * take the shell down (\"Web RPC failed\" in openInitialWindow, then a crash dialog\n * whose three buttons did nothing). The settings form is a convenience, not a\n * prerequisite: rhythm values come from data/settings/ui.json plus the apply-time\n * `config` either way. It is attached lazily through `ctx.inject(['settings'], …)`\n * below, so the heartbeat starts on `agents` alone and picks the form up whenever\n * the service appears.\n */\nexport const inject = ['agents'];\n\nexport const Config = z.object({\n /** Override the runtime data dir (workspace guard boundary). Empty = default (<packageRoot>/data). */\n dataDir: z.string().default(''),\n /** UI-editable: heartbeat interval in minutes. 0 = use policy file / factory. */\n intervalMin: z.number().default(0),\n /** UI-editable: daily expression cap. 0 = use policy file / factory. */\n maxDailySend: z.number().default(0),\n /**\n * Agent preset the heartbeat agent joins (`<dshHome>/.agent-presets/<id>/`).\n * Without a preset the agent is a BARE agent: tools/prompt sections resolve\n * against the empty global layer, so it cannot even see `web_search`.\n */\n agentPreset: z.string().default('heartbeat'),\n /**\n * Install the bundled preset (see `agentPreset`) into the roster's user root\n * on first run, so setup needs no manual file copy. An existing preset is\n * never overwritten; set false to manage the preset entirely by hand.\n */\n installPreset: z.boolean().default(true),\n /** Self-built time injection interval (D20, §17.6). 0 disables injection.\n * Left OPTIONAL on purpose (2026-10-17): a schema default here is\n * indistinguishable from an explicit choice, and `applySettingsOverrides`\n * applies this value over ui.json — so a default would silently undo the\n * card on every reload. Unset falls back at the refs below. */\n timeInjectMin: z.number(),\n /** IANA timezone for the injected clock; empty = process zone. */\n timeZone: z.string().default(''),\n /** Statusbar master switch (D19). Off = no section/pre-step status; time injection unaffected. */\n statusbar: z.boolean(),\n /** v1.6.3 闲着模式:素材池为空时用画像话题兜底主动搭话(默认关)。 */\n idleMode: z.boolean(),\n /** v1.7.0 节省 token 模式:用户离开(闲置 ≥30 分钟)或锁屏时整跳暂停(默认关)。 */\n tokenSaver: z.boolean(),\n /** v1.8.0 账本工具:向所有日常会话 agent 注册共享账本工具(默认开)。 */\n ledgerTool: z.boolean().default(true),\n /** v1.9.0 素材报账工具:投递后由陪伴 agent 主动报账(默认开)。 */\n seedReportTool: z.boolean().default(true),\n /** v2.0.0 心事匣工具:留给下一跳的一句便签(默认开)。 */\n notepadTool: z.boolean().default(true),\n /** v2.0.0 摘抄本工具:留句子和小事的地方(默认开)。 */\n excerptTool: z.boolean().default(true),\n /** v1.8.0 引擎室追加工具:逗号分隔的全局工具名,存在才加入白名单(bili 压缩工具自动探测,无需手填)。 */\n extraTools: z.string().default(''),\n});\n\nexport interface HeartbeatConfig {\n dataDir?: string | null;\n intervalMin?: number;\n maxDailySend?: number;\n agentPreset?: string;\n installPreset?: boolean;\n timeInjectMin?: number;\n timeZone?: string;\n statusbar?: boolean;\n idleMode?: boolean;\n tokenSaver?: boolean;\n ledgerTool?: boolean;\n seedReportTool?: boolean;\n notepadTool?: boolean;\n excerptTool?: boolean;\n extraTools?: string;\n}\n\nexport function apply(ctx: OrchestratorDeps['ctx'] & {\n get(name: string): unknown;\n /** Cordis lazy service declaration: callback runs once the named services mount. */\n inject(services: string[], callback: (scoped: unknown) => void): void;\n /** Cordis event subscription (pre-step waterfall etc.); returns a disposer. */\n on(event: string, listener: (payload: never, next: () => Promise<unknown>) => Promise<unknown>, opts?: { prepend?: boolean }): unknown;\n}, config: HeartbeatConfig = {}): void {\n const paths = initWorkspace(config.dataDir ? { dataDir: config.dataDir } : {});\n const guard = createPathGuard(paths.dataDir);\n let policy = loadPolicy(guard, paths.configDir, paths.settingsDir);\n\n // Card-edited rhythm values (v1.7.0, data/settings/ui.json): the settings\n // card writes these over RPC. Precedence: policy layers < ui.json < the\n // composition-entry config below.\n const ui = loadUiConfig(guard, paths.settingsDir);\n if (ui.intervalMin && ui.intervalMin >= 1) {\n policy = { ...policy, heartbeat: { ...policy.heartbeat, intervalMin: ui.intervalMin } };\n }\n if (ui.maxDailySend && ui.maxDailySend >= 1) {\n policy = { ...policy, gate: { ...policy.gate, maxDailySend: ui.maxDailySend } };\n }\n\n // Composition-entry overrides (the patch row's config block).\n if (config.intervalMin && config.intervalMin >= 1) {\n policy = { ...policy, heartbeat: { ...policy.heartbeat, intervalMin: config.intervalMin } };\n }\n if (config.maxDailySend && config.maxDailySend >= 1) {\n policy = { ...policy, gate: { ...policy.gate, maxDailySend: config.maxDailySend } };\n }\n\n const deps: OrchestratorDeps = {\n ctx, paths, guard, policy,\n agentPreset: config.agentPreset || 'heartbeat',\n extraTools: (config.extraTools ?? '').split(',').map((s) => s.trim()).filter(Boolean),\n presetRegistration: () => presetRegistration ?? Promise.resolve(),\n };\n setRuntime({\n paths,\n guard,\n policy,\n flags: {\n statusbarEnabled: () => statusbarEnabledRef,\n timeInjectMin: () => timeInjectMinRef,\n idleMode: () => idleModeRef,\n tokenSaver: () => tokenSaverRef,\n },\n });\n\n // Runtime preset registration (issue #2). The `agentPresets` inject below\n // assigns it; the acquire path awaits it before mounting the preset.\n let presetRegistration: Promise<void> | undefined;\n /** HB-17: registry undo hook + whether dispose already ran (a reload must\n * not leave the preset behind, and an in-flight registration must still be\n * undone if dispose wins the race). */\n let presetDisposer: (() => Promise<void>) | undefined;\n let presetDisposed = false;\n\n // ── Preset: runtime registration + filesystem install (C13 / issue #2) ───\n // The preset is what lets the heartbeat agent see `web_search` at all, so\n // the plugin owns it in both senses:\n //\n // 1. RUNTIME REGISTRATION (0.1.7+). The registry takes a definition\n // straight from the declaring plugin (`AgentPresetRegistry.register`),\n // so nothing in the composition has to name\n // `@deepseek-ai/dsh-agent-preset`. That matters: a profile cannot always\n // resolve it, and its peer closure contains Cordis's own loader — a\n // profile that ships those by hand double-instances the machinery, and\n // then every session refuses to resume (\"prompt section\n // deployment:persona-prefix is already registered\"), while one that\n // cannot resolve the package fails the WHOLE plugin tree at load\n // (reported 2026-10-10, both with reproductions). A host whose registry\n // has no `register` degrades to an audit line, never a throw.\n // 2. FILESYSTEM INSTALL, kept for hosts that still scan the roster's user\n // root (`agentPresets.roots`, trust === \"user\"): first run writes the\n // bundled template under the roster's OWN root instead of a guessed\n // `~/.dsh`, so `$DSH_HOME`/a configured home are honoured; an existing\n // preset is never overwritten.\n //\n // `installPreset: false` means \"the operator manages the preset by hand\", so\n // it switches BOTH off. Audit lines: `preset_register`, `preset_install`.\n ctx.inject(['agentPresets'], (presetCtx: unknown) => {\n const service = (presetCtx as {\n agentPresets?: { roots?: Array<{ path?: string; trust?: string }> };\n }).agentPresets;\n const presetId = config.agentPreset || 'heartbeat';\n const installEnabled = config.installPreset !== false;\n const audit = (entry: Record<string, unknown>): void => {\n try {\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), entry);\n } catch (e) {\n ctx.logger.warn('heartbeat: preset audit failed (%s)', String(e).slice(0, 120));\n }\n };\n\n presetRegistration = registerHeartbeatPreset(service, presetId, installEnabled).then((result) => {\n audit({ event: 'preset_register', ...result });\n if (typeof result.disposer === 'function') {\n if (presetDisposed) {\n // dispose already ran while registration was in flight: undo now.\n void Promise.resolve(result.disposer()).catch((e) => {\n ctx.logger.warn('heartbeat: preset dispose failed (%s)', String(e).slice(0, 120));\n });\n } else {\n presetDisposer = result.disposer;\n }\n }\n if (result.action === 'error') {\n ctx.logger.warn('heartbeat: preset register failed (%s) — the engine room runs without it', result.detail ?? '');\n } else if (result.action === 'registered') {\n ctx.logger.info('heartbeat: preset %s registered at runtime', result.id);\n } else if (result.action === 'already-registered') {\n // HB-31: the previous instance still owns the id (same definition).\n ctx.logger.info('heartbeat: preset %s already registered — reusing it', result.id);\n } else {\n ctx.logger.info('heartbeat: preset registration skipped (%s)', result.action);\n }\n });\n\n const root = userPresetRoot(service?.roots);\n const result = installBundledPreset({\n moduleUrl: import.meta.url,\n id: presetId,\n ...(root === undefined ? { rosterKnown: service !== undefined } : { root }),\n enabled: installEnabled,\n });\n audit({ event: 'preset_install', ...result });\n const line = describeInstall(result);\n if (result.action === 'error' || result.action === 'skipped-no-root') {\n ctx.logger.warn('heartbeat: %s', line);\n } else {\n ctx.logger.info('heartbeat: %s', line);\n }\n });\n\n // M6: settings section (namespace 'heartbeat') - the web card edits this\n // namespace; resolved values apply live (interval reschedules the timer).\n let sectionSource: (() => HeartbeatConfig) | null = null;\n let timeInjectMinRef = ui.timeInjectMin ?? (config.timeInjectMin ?? 25);\n // Factory default is OFF (v1.9.3); `=== true` so an UNSET config no longer\n // reads as \"not false = on\" now that the schema leaves it optional.\n let statusbarEnabledRef = ui.statusbar ?? (config.statusbar === true);\n let idleModeRef = ui.idleMode ?? (config.idleMode === true);\n let tokenSaverRef = ui.tokenSaver ?? (config.tokenSaver === true);\n\n // H-48: ONE setter table for the live-settable fields. The settings section\n // and the RPC uiSet path used to carry a copy each of the same six ifs, so a\n // new field had to be added twice — and the two copies had already drifted\n // (timeInjectMin's lower bound, tokenSaver's absence from the section path).\n const applyLiveSettings = (v: {\n intervalMin?: number;\n maxDailySend?: number;\n timeInjectMin?: number;\n statusbar?: boolean;\n idleMode?: boolean;\n tokenSaver?: boolean;\n }): void => {\n if (v.intervalMin && v.intervalMin >= 1) applyHeartbeatInterval(deps, v.intervalMin);\n if (v.maxDailySend && v.maxDailySend >= 1) getRuntime().policy.gate.maxDailySend = v.maxDailySend;\n if (typeof v.timeInjectMin === 'number' && v.timeInjectMin >= 0) timeInjectMinRef = v.timeInjectMin;\n if (typeof v.statusbar === 'boolean') statusbarEnabledRef = v.statusbar;\n if (typeof v.idleMode === 'boolean') {\n idleModeRef = v.idleMode;\n getRuntime().policy.heartbeat.idleMode = v.idleMode;\n }\n if (typeof v.tokenSaver === 'boolean') tokenSaverRef = v.tokenSaver;\n };\n\n const applySettingsOverrides = (): void => {\n try {\n const v = sectionSource?.();\n if (!v) return;\n applyLiveSettings(v);\n ctx.logger.info('heartbeat: settings overrides live (interval %s, cap %s, timeInject %s)', v.intervalMin ?? '-', v.maxDailySend ?? '-', v.timeInjectMin ?? '-');\n } catch (e) {\n ctx.logger.warn('heartbeat: settings override failed (%s)', String(e).slice(0, 120));\n }\n };\n // M6: settings form (namespace 'heartbeat'). Attached lazily through\n // `ctx.inject` because the service is no longer in the module-level `inject`\n // (see above): the callback runs once `settings` exists and its effects are\n // disposed if the service ever goes away, while the heartbeat itself keeps\n // running on `agents` alone.\n //\n // DSH 0.1.7 and later expose `SettingsForms`: plugin config forms render from\n // the Config schema on the Plugins page, and an edit RELOADS this plugin (timers\n // dispose via ctx.effect, so reloads are safe) — nothing to register here, the\n // apply-time `config` is already the live source. The 0.1.5 `installSection`\n // generation and the 0.1.1/0.1.2 free-function fallback are gone: they were\n // reachable only on hosts the package no longer supports (README: DSH 0.2.1+),\n // and they were the only reason `@deepseek-ai/dsh-settings` was a dependency.\n ctx.inject(['settings'], (settingsCtx: unknown) => {\n try {\n const settingsService = (settingsCtx as { get(name: string): unknown }).get('settings') as\n | { describe?(options?: unknown): unknown }\n | undefined;\n if (settingsService && typeof settingsService.describe === 'function') {\n sectionSource = () => config;\n applySettingsOverrides();\n ctx.logger.info('heartbeat: config served by the profile settings form (edits reload the plugin)');\n return;\n }\n ctx.logger.warn('heartbeat: settings service present but not a SettingsForms instance; policy file values only');\n } catch (e) {\n ctx.logger.warn('heartbeat: settings form unavailable (%s)', String(e).slice(0, 120));\n }\n });\n\n appendAuditLine(\n guard.assert(paths.logsDir + '/heartbeat.jsonl'),\n { event: 'plugin_init', dataDir: paths.dataDir },\n );\n\n // issue #2: a package-local data dir is moved out of the package on first\n // sight. The audit line is the only durable trace; a failed move keeps\n // serving the legacy tree (and never deletes it).\n if (paths.relocation) {\n const auditFile = guard.assert(paths.logsDir + '/heartbeat.jsonl');\n if (paths.relocation.action === 'relocated') {\n appendAuditLine(auditFile, {\n event: 'data_dir_relocated',\n from: paths.relocation.srcDir,\n to: paths.relocation.dstDir,\n files: paths.relocation.files,\n bytes: paths.relocation.bytes,\n warnings: paths.relocation.warnings,\n leftovers: paths.relocation.leftovers,\n });\n ctx.logger.info(\n 'heartbeat: data dir moved out of the package (%s files, %s bytes)',\n paths.relocation.files,\n paths.relocation.bytes,\n );\n } else if (paths.relocation.action === 'failed') {\n appendAuditLine(auditFile, {\n event: 'data_dir_relocate_failed',\n stage: paths.relocation.stage,\n problems: paths.relocation.problems,\n });\n ctx.logger.warn(\n 'heartbeat: data dir relocation failed (%s); continuing in the package dir',\n paths.relocation.stage,\n );\n }\n }\n\n // ── M6 拓展:正式 RPC 通道(决策 1 = B 方案,探针已验证)──────────\n // connection 晚挂载 → ctx.inject(['connection'], ...) 声明式等待;\n // 端点分发见 src/rpc.ts(bindings/seeds/status/profile/ledger/config)。\n // ui.get/uiSet:节律配置的活视图与\"落盘+即时生效\"(v1.7.0,data/settings/ui.json)。\n // psyEnabled 例外:它是 policy 字段,写 data/settings/policy.json 用户层。\n const uiGet = () => ({\n intervalMin: getRuntime().policy.heartbeat.intervalMin,\n maxDailySend: getRuntime().policy.gate.maxDailySend,\n timeInjectMin: timeInjectMinRef,\n statusbar: statusbarEnabledRef,\n idleMode: idleModeRef,\n tokenSaver: tokenSaverRef,\n psyEnabled: getRuntime().policy.profile.psyEnabled,\n quietStart: getRuntime().policy.gate.quietHours.start,\n quietEnd: getRuntime().policy.gate.quietHours.end,\n });\n const uiSet = (patch: UiConfig & { psyEnabled?: boolean; quietStart?: string; quietEnd?: string }): void => {\n if (typeof patch.psyEnabled === 'boolean') {\n updateUserPolicy(guard, paths.settingsDir, { profile: { psyEnabled: patch.psyEnabled } });\n getRuntime().policy.profile.psyEnabled = patch.psyEnabled;\n }\n // 静默时段(v2.2):policy 用户层字段,与 psyEnabled 同理不写 ui.json。\n // runtime policy 是活引用(evaluateGate 每跳读它),改内存对象即下一跳生效。\n if (patch.quietStart !== undefined || patch.quietEnd !== undefined) {\n const next = resolveQuietHours(patch.quietStart, patch.quietEnd, getRuntime().policy.gate.quietHours);\n if (!next) throw new Error('quiet hours must be HH:MM (00:00-23:59)');\n updateUserPolicy(guard, paths.settingsDir, { gate: { quietHours: next } });\n const q = getRuntime().policy.gate.quietHours;\n q.start = next.start;\n q.end = next.end;\n }\n const merged = saveUiConfig(guard, paths.settingsDir, patch);\n applyLiveSettings(merged);\n };\n installHeartbeatRpc(ctx, { paths, guard, policy, ui: { get: uiGet, set: uiSet } });\n\n // H-49: the ledger (v1.8.0) and seed_report (v1.9.0) registrations were two\n // copies of one block — same audit closure, same try/catch, same degradation\n // to an audit line on a host without a registerable ToolRuntime. One factory\n // now covers both; the audit event names are unchanged.\n const registerGlobalTool = (name: string, build: () => unknown): void => {\n ctx.inject(['tools'], (scoped: unknown) => {\n const audit = (entry: Record<string, unknown>): void => {\n try {\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), entry);\n } catch { /* audit must never break startup */ }\n };\n try {\n const tools = (scoped as { tools?: { register(definition: unknown): () => void } }).tools;\n if (!tools || typeof tools.register !== 'function') throw new Error('ToolRuntime.register unavailable on this host');\n tools.register(build());\n audit({ event: `${name}_tool_registered` });\n } catch (e) {\n audit({ event: `${name}_tool_register_failed`, error: String(e).slice(0, 160) });\n }\n });\n };\n\n // ── Ledger as a model tool (v1.8.0) ─────────────────────────────────────\n // Registers a shared `ledger` tool in the GLOBAL tool layer so every chat\n // agent can record/complete todos without being commanded to. The engine\n // room never sees it (its preset allow-list masks global tools). Definition\n // is a plain object (no dsh-tools import); a host without a registerable\n // ToolRuntime degrades to an audit line only.\n if (config.ledgerTool !== false) {\n registerGlobalTool('ledger', () => buildLedgerTool(guard, ledgerFilePath(paths.dataDir)));\n }\n\n // ── Seed report tool (v1.9.0): the persona files ONE report per delivery ─\n // spoken / seed_ids / profile_ids / reason — the unified bookkeeping channel\n // that replaced containment-match attribution. Same global-layer pattern as\n // the ledger tool; the engine room never sees it.\n if (config.seedReportTool !== false) {\n registerGlobalTool('seed_report', () => buildSeedReportTool(guard, reportFilePath(paths.dataDir)));\n }\n\n // ── 心事匣 (v2.0.0): one note she leaves for the next beat ──────────────\n // Same global-layer pattern, and the same reason as above: the engine room\n // never sees this tool. It does not need to — the note reaches the next beat\n // through the delivery package (material.ts notepadLines), which the engine\n // room builds but never authors. Storage is encrypted (it is more private\n // than the ledger), so the module goes through the vault, not plain text.\n if (config.notepadTool !== false) {\n registerGlobalTool('notepad', () => buildNotepadTool(guard, notepadFilePath(paths.dataDir)));\n }\n\n // ── 摘抄本 (v2.0.0): a line worth keeping, kept in plain text ───────────\n // Same global-layer pattern. Unlike the notepad this one is plaintext on\n // purpose: the settings card opens the file for the user, and a notebook\n // nobody can read is not a notebook. The ledger is the other plaintext file.\n if (config.excerptTool !== false) {\n registerGlobalTool('excerpt', () => buildExcerptTool(guard, excerptFilePath(paths.dataDir)));\n }\n\n // §7 main loop: dedicated session/agent + timer (first beat after 15s).\n startOrchestrator(deps);\n\n // ── Bilibili watch-history source (v2.2, ledger #f575a6) ────────────────\n // A passive 闲逛素材 feed on its OWN 2h timer — deliberately outside the\n // beat phases (the orchestrator must not gain a network dependency): the\n // source throttles itself from a persisted timestamp, fails silent (at most\n // one debug line) and never touches the heartbeat main flow. The disposer\n // clears the timer so a plugin reload cannot leak it.\n ctx.effect(() => {\n const audit = (entry: Record<string, unknown>): void => {\n try {\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), entry);\n } catch { /* audit must never break the source */ }\n };\n const debug = (msg: string): void => {\n try {\n (ctx.logger as { debug?: (msg: string, ...a: unknown[]) => void }).debug?.('heartbeat: %s', msg);\n } catch { /* debug sink is best-effort */ }\n };\n return startBilibiliSource({ guard, paths, policy: getRuntime().policy, audit, debug });\n }, 'heartbeat: bilibili source');\n\n // ── M7b: self-built time injection (D20, §17.6) ────────────────────────\n // Gate: step===1 AND user-initiated AND ≥ timeInjectMin since the last\n // injection for that session. Official dsh-time-context is disabled via the\n // user patch (B9 superseded by D20 — single owner). The interval is\n // live-settable: `timeInjectMinRef` is re-read on every gate check.\n // ── M7c: statusbar two tracks (D19, §17.4–17.5) ─────────────────────────\n // Track A (in-history models) rides a dynamic system-prompt section; Track B\n // rides the same pre-step message as the time injection (§17.5 combined).\n const statusReader = new StatusReader();\n registerStatusbarSection(ctx, guard, paths, {\n enabled: () => statusbarEnabledRef,\n reader: statusReader,\n });\n ctx.effect(() => {\n registerTimeInjection(ctx, guard, paths.dataDir, {\n getTimeInjectMin: () => timeInjectMinRef,\n timeZone: config.timeZone || undefined,\n paths,\n logger: ctx.logger,\n onError: (e) => ctx.logger.warn('heartbeat: time injection skipped (%s)', String(e).slice(0, 120)),\n pinTrack: (sessionId, session) => {\n const track = pinTrack(sessionId, session);\n noteTrack(paths.logsDir + '/heartbeat.jsonl', sessionId, track);\n return track;\n },\n getStatusLine: (session, track) => {\n if (!statusbarEnabledRef) {\n noteTrack(paths.logsDir + '/heartbeat.jsonl', session.id, 'off');\n return '';\n }\n return track === 'pre-step' ? renderStatusText(statusReader.read(guard, paths)) : '';\n },\n });\n return undefined;\n }, 'heartbeat: time injection');\n\n // Host effect contract: fn runs immediately, returns the disposer.\n ctx.effect(() => {\n return () => {\n presetDisposed = true;\n const undoPreset = presetDisposer;\n presetDisposer = undefined;\n if (typeof undoPreset === 'function') {\n void Promise.resolve(undoPreset()).catch((e) => {\n ctx.logger.warn('heartbeat: preset dispose failed (%s)', String(e).slice(0, 120));\n });\n }\n ctx.logger.info('heartbeat: disposed, timers cleaned up');\n };\n }, 'heartbeat: lifecycle');\n}\n\n// deepMerge is re-exported for the CLI status command layering.\nexport { deepMerge };\n","// Card-editable rhythm config (v1.7.0): the heartbeat card edits five fields\n// over RPC and they persist in the plugin's OWN user layer, so the editor\n// behaves identically on every host generation (0.1.1 scope / 0.1.5\n// installSection / 0.1.7 profile forms all become irrelevant for these\n// values) and saves apply live without any plugin reload.\n// Startup precedence: factory policy < user policy < ui.json < Config fields.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport { atomicWriteFileSync } from '../core/atomic-fs.js';\n\nexport const USER_UI_FILE = 'ui.json';\n\nexport interface UiConfig {\n intervalMin?: number;\n maxDailySend?: number;\n timeInjectMin?: number;\n statusbar?: boolean;\n idleMode?: boolean;\n /** Token-saver (v1.7.0): pause beats while the user is away / locked. */\n tokenSaver?: boolean;\n}\n\nconst RANGES = {\n intervalMin: { min: 1, max: 1440 },\n maxDailySend: { min: 1, max: 50 },\n timeInjectMin: { min: 0, max: 1440 },\n} as const;\n\nfunction sanitize(raw: unknown): UiConfig {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};\n const r = raw as Record<string, unknown>;\n const out: UiConfig = {};\n for (const key of ['intervalMin', 'maxDailySend', 'timeInjectMin'] as const) {\n const v = r[key];\n if (typeof v === 'number' && Number.isFinite(v) && v >= RANGES[key].min && v <= RANGES[key].max) {\n out[key] = Math.floor(v);\n }\n }\n if (typeof r.statusbar === 'boolean') out.statusbar = r.statusbar;\n if (typeof r.idleMode === 'boolean') out.idleMode = r.idleMode;\n if (typeof r.tokenSaver === 'boolean') out.tokenSaver = r.tokenSaver;\n return out;\n}\n\nexport function uiConfigPath(settingsDir: string): string {\n return path.join(settingsDir, USER_UI_FILE);\n}\n\n/** Missing user layer is normal; a corrupt layer fails open to defaults. */\nexport function loadUiConfig(guard: PathGuard, settingsDir: string): UiConfig {\n try {\n const raw: unknown = JSON.parse(fs.readFileSync(guard.assert(uiConfigPath(settingsDir)), 'utf8'));\n return sanitize(raw);\n } catch {\n return {};\n }\n}\n\n/** Merge `patch` over the stored layer, sanitize, and persist. */\nexport function saveUiConfig(guard: PathGuard, settingsDir: string, patch: UiConfig): UiConfig {\n const merged = sanitize({ ...loadUiConfig(guard, settingsDir), ...patch });\n const file = guard.assert(uiConfigPath(settingsDir));\n fs.mkdirSync(path.dirname(file), { recursive: true });\n atomicWriteFileSync(file, JSON.stringify(merged, null, 2) + '\\n');\n return merged;\n}\n","// Quiet hours (v2.2, panel entry): pure helpers for the settings-card\n// quiet-hours inputs. The value's source of truth is the policy user layer\n// (data/settings/policy.json gate.quietHours) — like psyEnabled, it never\n// touches ui.json — and the runtime policy is a live reference, so writing the\n// runtime object makes evaluateGate pick it up on the very next beat.\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\n\n/**\n * Strict HH:MM validation: returns the input unchanged when it matches\n * `HH:MM` (00:00-23:59); anything else — \"24:00\", \"1:30\", \"01:60\", \"\",\n * null, non-strings — returns null.\n */\nexport function normalizeHhMm(v: unknown): string | null {\n return typeof v === 'string' && HHMM.test(v) ? v : null;\n}\n\n/**\n * Three-state resolver for the panel's two time inputs:\n * - both values given and valid → use the new pair;\n * - only one given (the other undefined/null) → keep `current` for it;\n * - any given-but-invalid value → null (never silently swallowed — the caller\n * turns that into a user-visible error).\n * When neither value is given, returns `current` unchanged.\n */\nexport function resolveQuietHours(\n startRaw: unknown,\n endRaw: unknown,\n current: { start: string; end: string },\n): { start: string; end: string } | null {\n const given = (v: unknown): boolean => v !== undefined && v !== null;\n if (!given(startRaw) && !given(endRaw)) return { start: current.start, end: current.end };\n const start = normalizeHhMm(startRaw);\n const end = normalizeHhMm(endRaw);\n if ((given(startRaw) && !start) || (given(endRaw) && !end)) return null;\n return {\n start: start ?? current.start,\n end: end ?? current.end,\n };\n}\n","// M6: settings-card RPC (decision 1 = Plan B; transport reworked in v1.2.1, C21).\n//\n// Host registers an exact Fetch route under /api via ctx.inject(['connection'], ...)\n// once the connection service mounts; the web card calls\n// connection.rpc.call('/api', 'heartbeat', { endpoint, ...payload }).\n// (The original custom channel '/heartbeat' via rpc.handle() is unusable on\n// DSH 0.1.5+: cordis pins the service's this.ctx to the provider context, so\n// handle()'s internal owner.webServer.register always fails strict resolution.)\n// Bindings authority = data/settings/bindings.json (decision 2); the card is\n// just another client of the same host logic the CLI uses.\n// Every endpoint runs inside the workspace guard; results are {ok,value} or\n// {ok:false,error:{code,message,details}}. Verbs are dispatched through a Map\n// and, when the host's /api gate is missing, only GATE_SAFE_ENDPOINTS serve\n// (⑦A / HB-19, 2026-10-17).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { OrchestratorDeps } from './core/orchestrator.js';\nimport { getLastBeat, homeSessionId, resetHomeSession, pauseFocus, resumeFocus, getFocusUntil, formatFocusClock } from './core/orchestrator.js';\nimport { readFocusState, writeFocusState, clearFocusState } from './core/focus-store.js';\nimport { appendAuditLine } from './core/audit-log.js';\nimport type { UiConfig } from './config/ui-config.js';\nimport type { PathGuard } from './core/path-guard.js';\nimport { dshHomeDir } from './core/paths.js';\nimport { parseArchivedSessionIds, isArchivedSession } from './core/archived-sessions.js';\nimport { openPath } from './core/open-path.js';\nimport { localDayKey } from './core/time-window.js';\nimport type { WorkspacePaths } from './core/paths.js';\nimport { inQuietHours, readSentState } from './gate/gate.js';\nimport {\n activeSeeds,\n archivedSeeds,\n archiveSeedById,\n deleteSeed,\n loadPool,\n restoreSeed,\n seedsFilePath,\n} from './seeds/pool.js';\nimport { loadProfile, profileFilePath } from './profile/store.js';\nimport { buildDigest } from './profile/digest.js';\nimport { ledgerFilePath } from './ledger/ledger.js';\nimport { EXCERPT_HEADER, excerptFilePath } from './excerpt/excerpt.js';\nimport { listWeeklyReports, readWeeklyReport } from './weekly/report.js';\nimport { addBinding, loadBindings, removeBinding } from './core/bindings.js';\nimport { addInterest, readEffective, removeInterest, setWanderWindows } from './browse/interests-edit.js';\nimport { writeText, loadJson } from './vault/vault.js';\nimport {\n bilibiliSessionFilePath,\n createBiliLoginService,\n saveBiliSession,\n type BiliSessionRecord,\n} from './cli/bili-login.js';\nimport { readStatus } from './statusbar/store.js';\nimport { loadTimeInjectState } from './statusbar/time-inject.js';\nimport type { Policy } from './config/schema.js';\n\n/** Exact Fetch route under /api (C21: custom rpc.handle channels are unusable\n * under 0.1.5's strict cordis service resolution — see installHeartbeatRpc). */\nexport const RPC_ROUTE_PATH = '/api/heartbeat';\n\n/**\n * ⑦A (2026-10-17 review, tightening H-41): the host's `/api` prefix gate is the\n * only authentication this route has — the plugin holds no credential of its own.\n * When that gate cannot be found the route fails closed: every verb is refused\n * except this short list of read-only, low-sensitivity ones (liveness plus what\n * the settings card needs to render). H-41+HB-19 refused six \"destructive\" verbs\n * and served everything else, which left every memory-bearing read —\n * `profile.digest`, `profile.partitions`, `seeds.list`, `interests.list`,\n * `weekly.get`, `migrate.export` — open to anything that could POST to loopback.\n */\nconst GATE_SAFE_ENDPOINTS = new Set([\n 'status',\n 'config.get',\n 'sessions.list',\n 'bindings.get',\n 'weekly.list',\n]);\n\ninterface RpcDeps {\n ctx: OrchestratorDeps['ctx'] & {\n inject(services: string[], callback: (scoped: unknown) => void): void;\n };\n paths: WorkspacePaths;\n guard: PathGuard;\n policy: Policy;\n /** Card-edited rhythm values (v1.7.0): live view getter + persist-and-apply setter. */\n ui: {\n get(): {\n intervalMin: number;\n maxDailySend: number;\n timeInjectMin: number;\n statusbar: boolean;\n idleMode: boolean;\n tokenSaver: boolean;\n psyEnabled: boolean;\n };\n set(patch: UiConfig & { psyEnabled?: boolean }): void;\n };\n}\n\ntype RpcResult = { ok: true; value: unknown } | { ok: false; error: { code: string; message: string; details: Record<string, never> } };\n\nconst ok = (value: unknown): RpcResult => ({ ok: true, value });\nconst err = (code: string, message: string): RpcResult => ({ ok: false, error: { code, message, details: {} } });\n\nlet cachedVersion: string | null = null;\n/** Plugin version for the card's status block (read once from package.json). */\nfunction pluginVersion(paths: WorkspacePaths): string {\n if (cachedVersion) return cachedVersion;\n try {\n const pkg = JSON.parse(fs.readFileSync(path.join(paths.packageRoot, 'package.json'), 'utf8')) as { version?: string };\n cachedVersion = typeof pkg.version === 'string' ? pkg.version : 'unknown';\n } catch {\n cachedVersion = 'unknown';\n }\n return cachedVersion;\n}\n\n/** 素材池生命周期的审计出口(v1.9.0):卡片上的归档/恢复/删除也留下痕迹。 */\nfunction seedAuditSink(paths: WorkspacePaths): (entry: Record<string, unknown>) => void {\n return (entry) => {\n try {\n appendAuditLine(paths.logsDir + '/heartbeat.jsonl', entry);\n } catch { /* audit must never break the RPC call */ }\n };\n}\n\n/** 兴趣/时段卡片编辑的审计留痕(成功才记;失败原因走 RPC err 回给卡片)。 */\nfunction auditInterests(paths: WorkspacePaths, action: string, r: { ok: boolean }, detail: unknown): void {\n try {\n appendAuditLine(paths.logsDir + '/heartbeat.jsonl', {\n event: `interests_${r.ok ? 'edit' : 'edit_failed'}`,\n action,\n detail: typeof detail === 'string' ? detail.slice(0, 80) : null,\n });\n } catch { /* audit must never break the RPC call */ }\n}\n\n/** Session titles from the host's projection cache. Titles are host data — the\n * client card merges them (client.js `nameOf`: title || id prefix).\n *\n * DSH 0.1.2 writes ONE RECORD PER SESSION under\n * `~/.dsh/storages/session_projcache/sessions/<sessionId>.json`\n * (`record.rows.title.val`). The single-file `session_projcache.json` we used\n * before is the older aggregate layout and goes stale: a session created after\n * the upgrade is simply absent from it, so `title` came back null and the card\n * printed the raw session id. Read the per-record layout FIRST, keep the\n * aggregate only as a legacy fallback. */\nfunction loadSessionTitles(): Record<string, string> {\n const titles: Record<string, string> = {};\n const take = (id: string, value: unknown): void => {\n const t = value as { rows?: { title?: { val?: unknown } }; title?: { val?: unknown } } | undefined;\n const row = t?.rows?.title ?? t?.title;\n if (row && typeof row.val === 'string' && row.val && !titles[id]) titles[id] = row.val;\n };\n // 1) per-record layout (current).\n try {\n const dir = path.join(dshHomeDir(), 'storages', 'session_projcache', 'sessions');\n for (const file of fs.readdirSync(dir)) {\n if (!file.endsWith('.json')) continue;\n const id = file.slice(0, -'.json'.length);\n if (!id.startsWith('session-')) continue;\n try {\n const record = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8')) as { record?: unknown };\n take(id, record.record);\n } catch { /* skip a record we cannot read */ }\n }\n } catch { /* no per-record dir on older hosts */ }\n // 2) legacy aggregate fallback.\n try {\n const raw = JSON.parse(fs.readFileSync(path.join(dshHomeDir(), 'storages', 'session_projcache.json'), 'utf8')) as unknown;\n const walk = (node: unknown): void => {\n if (!node || typeof node !== 'object') return;\n for (const [key, value] of Object.entries(node as Record<string, unknown>)) {\n if (key.startsWith('session-') && value && typeof value === 'object') {\n // Title lives at <session>.rows.title.val (host title service); the\n // val may be null while the title is still being generated.\n take(key, value);\n }\n walk(value);\n }\n };\n walk(raw);\n return titles;\n } catch {\n return titles;\n }\n}\n\n/** Host-side session registry (`~/.dsh/storages/workspace.json`) → the set of\n * session ids the USER actually sees in the sidebar.\n *\n * A persisted session is user-visible iff it belongs to some workspace's\n * `sessionIds` and is not in `archivedSessionIds`. Two exclusions fall out of\n * this for the bind picker (2026-09-30 user request):\n * - **archived** sessions (explicit `archivedSessionIds`, prefix formats are\n * mixed on disk — some entries carry `session-`, some don't — so match\n * both forms);\n * - **subagent child sessions**, which never join any workspace's\n * `sessionIds` (observed: they only ever land in the archive list).\n *\n * Fail-open: a missing/corrupt registry returns `registryFound: false` and\n * the caller shows everything — an unreadable registry must not blank the\n * picker. The heartbeat home is always shown regardless (caller-side). */\nexport function loadVisibleSessionIds(registryFile?: string): { visible: Set<string>; registryFound: boolean } {\n try {\n const file = registryFile ?? path.join(dshHomeDir(), 'storages', 'workspace.json');\n const text = fs.readFileSync(file, 'utf8');\n // H-archived: the archived set + mixed-prefix match now come from the\n // shared module (same disk truth the delivery lane filters on). The outer\n // JSON.parse below still decides `registryFound`, so a valid registry with\n // a non-array archived field keeps reporting registryFound: true.\n const archived = parseArchivedSessionIds(text);\n const j = JSON.parse(text) as {\n tables?: { workspaces?: Record<string, { sessionIds?: unknown }> };\n };\n const visible = new Set<string>();\n for (const ws of Object.values(j.tables?.workspaces ?? {})) {\n const ids = Array.isArray(ws?.sessionIds) ? (ws.sessionIds as unknown[]) : [];\n for (const raw of ids) {\n const id = String(raw);\n if (!isArchivedSession(archived, id)) visible.add(id);\n }\n }\n return { visible, registryFound: true };\n } catch {\n return { visible: new Set(), registryFound: false };\n }\n}\n\n/** One RPC verb: payload in, envelope out. `guard` / `paths` / `policy` / `deps`\n * come from the closure built by {@link buildEndpoints}. */\ntype Endpoint = (p: Record<string, unknown>) => RpcResult | Promise<RpcResult>;\n\n/**\n * H-36: the endpoint table. This used to be a single `switch` at the bottom of\n * the route handler — 22 verbs and ~250 lines, with the guest list (which\n * endpoints exist) tangled up with the machinery (envelope validation, the\n * catch-all error wrapper). Adding a verb is now one entry here; the wrapper\n * stays in one place.\n */\nfunction buildEndpoints(deps: Omit<RpcDeps, 'ctx'>, isLive: (sessionId: string) => boolean): Record<string, Endpoint> {\n const { guard, paths, policy } = deps;\n // Bilibili QR login for the panel (v2.3.0): production wiring of the same\n // service the CLI drives — real fetch + qrcode dataURL (no temp file) +\n // vault-backed save. The session Map lives in this process's memory.\n const biliLogin = createBiliLoginService({\n fetchImpl: fetch,\n renderQrDataUrl: async (url) => {\n const { default: QRCode } = await import('qrcode');\n return QRCode.toDataURL(url, { type: 'image/png', width: 400, margin: 2 });\n },\n now: () => Date.now(),\n saveCredential: (value) => saveBiliSession(guard, paths, value),\n });\n return {\n async status() {\n const now = Date.now();\n const sent = readSentState(guard, paths, now);\n const beat = getLastBeat();\n // M7 statusbar block (§17.8): store + throttle-state + live flags.\n let lastTimeInjectAt: number | null = null;\n try {\n const state = loadTimeInjectState(guard, paths.dataDir);\n for (const v of Object.values(state)) {\n if (typeof v === 'number' && v > (lastTimeInjectAt ?? 0)) lastTimeInjectAt = v;\n }\n } catch { /* missing state file = never injected */ }\n let flags = { statusbarEnabled: true, timeInjectMin: 25, idleMode: false };\n try {\n const { getRuntime } = await import('./core/runtime.js');\n const f = getRuntime().flags;\n flags = { statusbarEnabled: f.statusbarEnabled(), timeInjectMin: f.timeInjectMin(), idleMode: f.idleMode() };\n } catch { /* pre-init: report defaults */ }\n return ok({\n now: new Date(now).toISOString(),\n version: pluginVersion(paths),\n intervalMin: policy.heartbeat.intervalMin,\n idleMode: policy.heartbeat.idleMode,\n cap: { used: sent.items.length, max: policy.gate.maxDailySend },\n quiet: inQuietHours(policy, now),\n lastBeat: beat,\n homeSessionId: homeSessionId(guard, paths),\n bindings: loadBindings(guard, paths.settingsDir).bindings.length,\n statusbar: {\n enabled: flags.statusbarEnabled,\n timeInjectMin: flags.timeInjectMin,\n lastStatus: readStatus(guard, paths),\n lastTimeInjectAt: lastTimeInjectAt === null ? null : new Date(lastTimeInjectAt).toISOString(),\n },\n });\n },\n\n 'sessions.list'() {\n const root = path.join(dshHomeDir(), 'sessions');\n const bindings = loadBindings(guard, paths.settingsDir).bindings;\n const home = homeSessionId(guard, paths);\n const titles = loadSessionTitles();\n // Bind picker visibility: hide archived and subagent sessions\n // (2026-09-30 user request). Fail-open when the registry is\n // unreadable; the home is always listed.\n const { visible, registryFound } = loadVisibleSessionIds();\n const out: Record<string, unknown>[] = [];\n if (fs.existsSync(root)) {\n for (const slug of fs.readdirSync(root)) {\n for (const id of fs.readdirSync(path.join(root, slug))) {\n if (registryFound && id !== home && !visible.has(id)) continue;\n const binding = bindings.find((b) => b.sessionId === id);\n out.push({\n id,\n title: titles[id] ?? null,\n cwdSlug: slug,\n live: isLive(id),\n home: id === home,\n deliver: binding?.deliver ?? false,\n observe: binding?.observe ?? false,\n });\n }\n }\n }\n return ok({ sessions: out });\n },\n\n 'bindings.get': () => ok(loadBindings(guard, paths.settingsDir)),\n\n // Focus mode (v2.1.0 ①). The card and the CLI are two clients of the same\n // pause: module state gives the host an immediate answer, data/focus.json\n // carries it across processes (and survives a restart). `status` merges\n // both so the card shows a pause the CLI set and vice versa.\n 'focus.status'() {\n const now = Date.now();\n const file = readFocusState(guard, paths, now);\n const mem = getFocusUntil();\n const until = Math.max(mem > now ? mem : 0, file?.until ?? 0);\n return ok({\n paused: until > now,\n until: until > now ? new Date(until).toISOString() : null,\n clock: until > now ? formatFocusClock(until) : null,\n minutes: file?.minutes ?? null,\n via: file?.via ?? (mem > now ? 'rpc' : null),\n });\n },\n\n 'focus.pause'(p) {\n const raw = Number(p.minutes ?? 30);\n if (!Number.isFinite(raw) || raw <= 0) return err('bad-request', 'minutes must be a positive number (1-1440)');\n const now = Date.now();\n const mem = pauseFocus(raw); // this process answers immediately\n const file = writeFocusState(guard, paths, raw, now, 'settings-card');\n const until = Math.max(mem, file.until);\n return ok({\n paused: true,\n until: new Date(until).toISOString(),\n clock: formatFocusClock(until),\n minutes: file.minutes,\n });\n },\n\n 'focus.resume'() {\n resumeFocus();\n const removed = clearFocusState(guard, paths);\n return ok({ paused: false, removed });\n },\n\n 'bindings.add'(p) {\n const id = String(p.sessionId ?? '');\n if (!id.startsWith('session-')) return err('bad-request', 'sessionId must look like session-...');\n const home = homeSessionId(guard, paths);\n if (id === home) return err('bad-request', '该会话是心跳正身,无需绑定(决策轮次固定发生在正身)');\n // Callers send BOTH flags explicitly (the card's per-flag toggles), so\n // this stays a full-state write: deliver defaults on, observe off.\n const b = addBinding(guard, paths.settingsDir, id, {\n deliver: p.deliver !== false,\n observe: p.observe === true,\n });\n return ok(b);\n },\n\n 'bindings.remove'(p) {\n const id = String(p.sessionId ?? '');\n const removed = removeBinding(guard, paths.settingsDir, id);\n // H-09/H-45: one shared release path — gate.json, the home_reset audit\n // line and the orchestrator's cached agent — instead of an inline delete\n // that silently left the in-memory home behind.\n const homeReset = resetHomeSession(guard, paths, id);\n return ok({ removed, homeReset });\n },\n\n 'seeds.list'() {\n const db = loadPool(guard, seedsFilePath(paths.dataDir));\n return ok({\n active: activeSeeds(db),\n archived: archivedSeeds(db),\n cap: policy.seeds.maxActive,\n });\n },\n\n 'seeds.archive'(p) {\n const s = archiveSeedById(guard, seedsFilePath(paths.dataDir), String(p.id ?? ''), 'completed', Date.now(), seedAuditSink(paths));\n return s ? ok(s) : err('not-found', 'active seed not found');\n },\n\n 'seeds.restore'(p) {\n const r = restoreSeed(guard, seedsFilePath(paths.dataDir), policy, String(p.id ?? ''), Date.now(), seedAuditSink(paths));\n return r.ok ? ok(r.seed) : err('restore-failed', r.reason);\n },\n\n 'seeds.delete'(p) {\n return ok({ deleted: deleteSeed(guard, seedsFilePath(paths.dataDir), String(p.id ?? ''), seedAuditSink(paths)) });\n },\n\n // ── Bilibili QR login (v2.3.0): the panel's entry to the same login the\n // CLI drives. Failures come back as err(...) envelopes — nothing throws\n // at the card; the card maps poll states onto its own i18n texts.\n 'bili.status'() {\n try {\n const rec = loadJson<BiliSessionRecord>(guard, bilibiliSessionFilePath(paths));\n const loggedIn = typeof rec?.sessdata === 'string' && rec.sessdata.length > 0;\n return ok({\n loggedIn,\n savedAt: loggedIn && typeof rec!.savedAt === 'number' ? rec!.savedAt : null,\n });\n } catch {\n // A missing/damaged vault container reads as \"not logged in\" — the\n // card must still render, the CLI remains the repair path.\n return ok({ loggedIn: false, savedAt: null });\n }\n },\n\n async 'bili.login.start'() {\n try {\n return ok(await biliLogin.startBiliLogin());\n } catch (e) {\n return err('bili-login-failed', String(e instanceof Error ? e.message : e).slice(0, 200));\n }\n },\n\n async 'bili.login.poll'(p) {\n const sessionId = String(p.sessionId ?? '');\n if (!sessionId) return err('bad-request', 'sessionId is required');\n try {\n return ok(await biliLogin.pollBiliLogin(sessionId));\n } catch (e) {\n return err('bili-login-failed', String(e instanceof Error ? e.message : e).slice(0, 200));\n }\n },\n\n // ── 兴趣范围 / 浏览时段(v1.4.0;首编继承出厂,见 interests-edit.ts)──\n 'interests.list': () => ok(readEffective(paths)),\n\n 'interests.add'(p) {\n const r = addInterest(guard, paths, String(p.text ?? ''));\n auditInterests(paths, 'add', r, p.text);\n return r.ok ? ok(r.doc) : err('bad-request', r.reason ?? 'add failed');\n },\n\n 'interests.remove'(p) {\n const r = removeInterest(guard, paths, String(p.text ?? ''));\n auditInterests(paths, 'remove', r, p.text);\n return r.ok ? ok(r.doc) : err('not-found', r.reason ?? 'remove failed');\n },\n\n 'interests.setWindows'(p) {\n const r = setWanderWindows(guard, paths, p.windows);\n auditInterests(paths, 'set-windows', r, JSON.stringify(p.windows ?? null));\n return r.ok ? ok(r.doc) : err('bad-request', r.reason ?? 'setWindows failed');\n },\n\n 'config.get': () => ok(deps.ui.get()),\n\n 'config.set'(p) {\n const patch = p as UiConfig;\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {\n return err('bad-request', 'config.set needs a patch object');\n }\n const keys = Object.keys(patch).filter((k) =>\n ['intervalMin', 'maxDailySend', 'timeInjectMin', 'statusbar', 'idleMode', 'tokenSaver', 'psyEnabled', 'quietStart', 'quietEnd'].includes(k),\n );\n if (keys.length === 0) return err('bad-request', 'config.set has no recognized field');\n try {\n deps.ui.set(patch);\n } catch (e) {\n return err('bad-request', String(e).slice(0, 120));\n }\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), { event: 'ui_config_set', keys });\n return ok(deps.ui.get());\n },\n\n 'profile.digest'() {\n const d = buildDigest(guard, paths, policy, {});\n return ok({\n tact: d.tact,\n topic: d.topic,\n wander: d.wander,\n withinBudget: d.withinBudget,\n // v2.0 (item 6): the card shows the budget and what the caps dropped.\n totalChars: d.totalChars,\n budgetChars: d.budgetChars,\n omitted: d.omitted,\n });\n },\n\n 'profile.partitions'() {\n // v2.0 (item 6): the card shows ONE partition at a time, entry by entry.\n // The digest view was a wall of text and never showed what the profile\n // actually holds. Read-only, same data profile.export walks.\n const doc = loadProfile(guard, profileFilePath(paths.dataDir));\n const partitions: Record<string, { total: number; valid: number; entries: Record<string, unknown>[] }> = {};\n for (const part of ['interest', 'projects', 'comm', 'psy'] as const) {\n const all = doc.partitions[part]?.entries ?? [];\n const valid = all.filter((e) => e.validTo === null);\n partitions[part] = {\n total: all.length,\n valid: valid.length,\n entries: valid\n .slice()\n .sort((a, b) => b.confidence - a.confidence || (a.updatedAt < b.updatedAt ? 1 : -1))\n .map((e) => ({\n id: e.id,\n topic: e.topic,\n subTopic: e.subTopic,\n content: e.content,\n confidence: e.confidence,\n temporal: e.temporal,\n updatedAt: e.updatedAt,\n lowActivity: e.lowActivity === true,\n })),\n };\n }\n return ok({ partitions });\n },\n\n 'profile.export'() {\n const doc = loadProfile(guard, profileFilePath(paths.dataDir));\n const lines = [`# 画像导出 ${new Date().toISOString()}`, ''];\n for (const part of ['interest', 'projects', 'comm', 'psy'] as const) {\n lines.push(`## ${part}`);\n for (const e of doc.partitions[part]!.entries) {\n if (e.validTo !== null) continue;\n lines.push(`- [${e.topic}/${e.subTopic}] ${e.content} (conf ${e.confidence.toFixed(2)}, ${e.temporal})`);\n }\n }\n const out = path.join(paths.exportsDir, `profile-export-${Date.now()}.md`);\n writeText(guard, out, lines.join('\\n') + '\\n');\n return ok({ path: out });\n },\n\n 'ledger.open'() {\n const f = ledgerFilePath(paths.dataDir);\n if (!fs.existsSync(guard.assert(f))) fs.writeFileSync(f, '# 账本\\n', 'utf8');\n openPath(f);\n return ok({ path: f });\n },\n\n 'excerpt.open'() {\n const f = excerptFilePath(paths.dataDir);\n if (!fs.existsSync(guard.assert(f))) fs.writeFileSync(f, EXCERPT_HEADER, 'utf8');\n openPath(f);\n return ok({ path: f });\n },\n\n 'weekly.list': () => ok({ reports: listWeeklyReports(guard, paths.dataDir, policy.weekly.keepReports) }),\n\n 'weekly.get'(p) {\n const file = String(p.file ?? '');\n const rep = readWeeklyReport(guard, paths.dataDir, file);\n if (!rep) return err('bad-request', `no such report: ${file}`);\n return ok(rep);\n },\n\n async 'migrate.export'(p) {\n // Card-side export (v1.8.0): same container as the CLI. The\n // passphrase lives only in this call — never audited, never logged.\n const passphrase = String(p.passphrase ?? '');\n if (!passphrase) return err('bad-request', '需要设置口令');\n const { collectMigrationEntries, encryptContainer } = await import('./vault/migrate.js');\n const { entries } = collectMigrationEntries(guard, paths);\n if (entries.length === 0) return err('bad-request', '没有可打包的记忆文件(data/ 是空的)');\n const out = path.join(paths.exportsDir, `heartbeat-memory-${localDayKey()}.hbmig`);\n writeText(guard, out, encryptContainer(entries, passphrase));\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), { event: 'migrate_export', files: entries.length });\n return ok({ path: out, count: entries.length });\n },\n\n async 'migrate.import'(p) {\n const passphrase = String(p.passphrase ?? '');\n const file = String(p.file ?? '');\n if (!passphrase || !file) return err('bad-request', '需要容器路径与口令');\n const { decryptContainer, applyMigrationEntries } = await import('./vault/migrate.js');\n let text: string;\n try {\n // Read-only from a user-chosen path (likely OUTSIDE data/); the\n // path guard still gates every file we WRITE back.\n text = fs.readFileSync(file, 'utf8');\n } catch {\n return err('bad-request', `读不到迁移包:${file}`);\n }\n let container: ReturnType<typeof decryptContainer>;\n try {\n container = decryptContainer(text, passphrase);\n } catch (e) {\n return err('bad-request', String(e instanceof Error ? e.message : e));\n }\n const result = applyMigrationEntries(guard, paths, container.files);\n appendAuditLine(guard.assert(paths.logsDir + '/heartbeat.jsonl'), {\n event: 'migrate_import', restored: result.restored.length, backedUp: result.backedUp.length, skipped: result.skipped.length,\n rolledBack: result.rolledBack?.length ?? 0, error: result.error ?? null,\n });\n // HB-06: an import that wrote nothing is a failure, not a cheerful ok with\n // the reason buried in the payload.\n if (result.error) return err('migrate-failed', result.error);\n return ok(result);\n },\n };\n}\n\nexport function installHeartbeatRpc(\n ctx: OrchestratorDeps['ctx'] & { inject(services: string[], callback: (scoped: unknown) => void): void },\n deps: Omit<RpcDeps, 'ctx'>,\n): void {\n // ── 0.1.5 适配(C21)─────────────────────────────────────────────────\n // 自定义通道 rpc.handle('/heartbeat') 在 0.1.5 的 cordis 严格服务解析下不可\n // 用:Service 把 this.ctx 固定在 client-connection 自己的上下文(其模块\n // inject 只有 ['credentials']),handle() 内部 owner.webServer.register 是在\n // 别人的 fiber 上读 webServer → `cannot get property \"webServer\" without\n // inject`,调用方怎么声明都救不了(现场取证 2026-09-12:合并 inject 三件套\n // + effect 包裹仍是这个错)。改走 connection.fetch.register():在 /api 下注册\n // 精确路由,只写 connection 内部路由表、不碰任何其他服务;0.1.2 与 0.1.5 的\n // /api 共享处理器都先查精确路由再落 interceptor,两代宿主通用。浏览器认证\n // 由 /api 前缀的 requestRejection 统一把关。客户端相应改为\n // rpc.call('/api', 'heartbeat', { endpoint, ...args })。\n ctx.inject(['connection'], (scoped: unknown) => {\n const remoteCtx = scoped as {\n connection: {\n fetch: { register(route: {\n path: string;\n methods: string[];\n requestBody?: string;\n fetch(request: Request): Promise<Response>;\n }): unknown };\n };\n agents: OrchestratorDeps['ctx']['agents'];\n effect(fn: () => unknown, label?: string): () => void;\n };\n\n const isLive = (sessionId: string): boolean => {\n try {\n return !!remoteCtx.agents.get(sessionId);\n } catch {\n return false;\n }\n };\n\n // HB-19 (2026-10-17): a Map, not an object literal. `endpoints[verb]` on a\n // plain object also resolves inherited keys (\"constructor\", \"toString\",\n // \"__proto__\"), so a crafted verb could reach something that was never\n // registered as an endpoint. Map.get has no prototype chain.\n const endpoints = new Map<string, Endpoint>(Object.entries(buildEndpoints(deps, isLive)));\n\n // ── H-41 (2026-10-07): explicit dependency on the host's /api gate ────\n // This route is mounted under the host's `/api` prefix, and that prefix's\n // check is the ONLY authentication it has — the plugin keeps no credential\n // of its own. The host implements it as `connection.admit(req)`, which\n // returns `requestRejection(req)`'s verdict (Host/Origin fence + the\n // browser-auth secret; the `/api` prefix route calls it before dispatching,\n // so this exact path can never be reached without it). If a future host\n // drops or renames that check, the destructive endpoints above would be\n // reachable by anything that can POST to loopback — so fail closed on them\n // instead of guessing, and say so in the audit log once at registration.\n const gate = remoteCtx.connection as unknown as { admit?: unknown; requestRejection?: unknown };\n const hostGuarded = typeof gate.admit === 'function' || typeof gate.requestRejection === 'function';\n if (!hostGuarded) {\n try {\n appendAuditLine(deps.guard.assert(deps.paths.logsDir + '/heartbeat.jsonl'), {\n event: 'rpc_host_gate_missing',\n detail: 'connection.admit/requestRejection absent; all but the low-sensitivity read-only verbs are refused (⑦A)',\n allowed: [...GATE_SAFE_ENDPOINTS],\n });\n } catch { /* 审计失败不影响注册 */ }\n }\n\n const handler = async (endpoint: unknown, payload: unknown): Promise<RpcResult> => {\n const p = (payload ?? {}) as Record<string, unknown>;\n const fn = typeof endpoint === 'string' ? endpoints.get(endpoint) : undefined;\n if (!fn) return err('bad-request', `unknown endpoint ${JSON.stringify(endpoint)}`);\n if (!hostGuarded && !GATE_SAFE_ENDPOINTS.has(endpoint as string)) {\n return err('forbidden', `host gate unavailable; ${endpoint} is refused (H-41, ⑦A)`);\n }\n try {\n return await fn(p);\n } catch (e) {\n return err('internal', String(e).slice(0, 200));\n }\n };\n\n // RPC 信封与 /api 通道的 client-request/server-response 同构(客户端仍是\n // connection.rpc.call),端点名改走 payload.endpoint 字段。\n remoteCtx.effect(\n () => remoteCtx.connection.fetch.register({\n path: RPC_ROUTE_PATH,\n methods: ['POST'],\n requestBody: 'buffered',\n fetch: async (request: Request): Promise<Response> => {\n let envelope: { type?: unknown; rpcId?: unknown; payload?: unknown };\n try {\n envelope = await request.json() as typeof envelope;\n } catch {\n return new Response('body is not JSON', { status: 400 });\n }\n const rpcId = envelope?.rpcId;\n if (envelope?.type !== 'client-request' || typeof rpcId !== 'string' || typeof envelope.payload !== 'object' || envelope.payload === null) {\n return new Response('invalid envelope', { status: 400 });\n }\n const p = envelope.payload as Record<string, unknown>;\n const endpoint = typeof p.endpoint === 'string' ? p.endpoint : '(missing endpoint)';\n const result = await handler(endpoint, p);\n return Response.json({ type: 'server-response', rpcId, result });\n },\n }),\n 'heartbeat: rpc route',\n );\n ctx.logger.info('heartbeat: rpc route ready (%s)', RPC_ROUTE_PATH);\n try {\n appendAuditLine(deps.guard.assert(deps.paths.logsDir + '/heartbeat.jsonl'), { event: 'rpc_registered', route: RPC_ROUTE_PATH });\n } catch { /* 审计失败不影响注册 */ }\n });\n}\n","// Interest-scope editing for the settings card (v1.4.0).\n//\n// The wander adjudicator picks its focus from `interests.json` (browse.ts\n// `loadInterests`): the factory copy in config/ is read-only, and a user layer\n// at data/settings/interests.json REPLACES it wholesale. That replace-not-merge\n// semantics is why every successful edit funnels through `ensureUserLayer`: the\n// FIRST edit copies the factory file (interests + _schedule, verbatim) into the\n// user layer before applying the change, so the card becomes the single\n// management entry point without silently dropping the other factory rows.\n// Reads and FAILED validations stay read-only (`readEffective`) — merely\n// opening the card must not take the user layer over.\n//\n// All writes stay inside the guard; unknown top-level keys (e.g. _comment) are\n// preserved on save so hand-written annotations survive card edits.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\n\n/** Mirrors browse.ts's InterestsConfig; kept local so this module owns the\n * editing shape (windows gain mandatory ids on save). */\nexport interface InterestsDoc {\n interests: string[];\n _schedule?: {\n daily_sessions?: number;\n focus_per_session?: number;\n max_seeds_per_focus?: number;\n focus_cooldown_days?: number;\n min_interval_hours?: number;\n windows?: { id?: string; start: string; end: string }[];\n };\n [key: string]: unknown;\n}\n\nexport interface WanderWindow {\n id: string;\n start: string;\n end: string;\n}\n\nexport const MAX_INTERESTS = 32;\nexport const MAX_INTEREST_LEN = 60;\nconst MAX_WINDOWS = 6;\nconst HHMM = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n\nexport function userInterestsPath(paths: WorkspacePaths): string {\n return path.join(paths.settingsDir, 'interests.json');\n}\n\nexport function factoryInterestsPath(paths: WorkspacePaths): string {\n return path.join(paths.configDir, 'interests.json');\n}\n\nfunction readDoc(file: string): InterestsDoc | null {\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<InterestsDoc>;\n if (!Array.isArray(raw.interests)) return null;\n return { ...raw, interests: raw.interests.map(String) };\n } catch {\n return null;\n }\n}\n\n/** What the wander adjudicator sees right now — WITHOUT creating the user\n * layer. Fallback chain: user layer -> factory -> empty. */\nexport function readEffective(paths: WorkspacePaths): InterestsDoc {\n return (\n readDoc(userInterestsPath(paths)) ??\n readDoc(factoryInterestsPath(paths)) ?? { interests: [] }\n );\n}\n\n/**\n * The user layer, created on first EDIT by copying the factory file verbatim\n * (decision: 首编继承出厂). Call only from mutation paths that are about to\n * succeed; the doc it returns equals `readEffective` at call time.\n */\nexport function ensureUserLayer(guard: PathGuard, paths: WorkspacePaths): InterestsDoc {\n const existing = readDoc(userInterestsPath(paths));\n if (existing) return existing;\n const doc: InterestsDoc = readDoc(factoryInterestsPath(paths)) ?? { interests: [] };\n saveDoc(guard, userInterestsPath(paths), doc);\n return doc;\n}\n\nfunction saveDoc(guard: PathGuard, file: string, doc: InterestsDoc): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(guard.assert(file), JSON.stringify(doc, null, 2), 'utf8');\n}\n\nexport interface InterestsResult {\n ok: boolean;\n reason?: string;\n doc: InterestsDoc;\n}\n\n/** Normalize: trim + collapse internal whitespace. Case-insensitive dedupe. */\nexport function normalizeInterest(text: string): string {\n return text.trim().replace(/\\s+/g, ' ');\n}\n\nexport function addInterest(\n guard: PathGuard,\n paths: WorkspacePaths,\n rawText: string,\n): InterestsResult {\n const text = normalizeInterest(rawText);\n if (!text) return { ok: false, reason: 'empty', doc: readEffective(paths) };\n if (text.length > MAX_INTEREST_LEN) {\n return { ok: false, reason: `too-long (max ${MAX_INTEREST_LEN})`, doc: readEffective(paths) };\n }\n const current = readEffective(paths);\n if (current.interests.some((t) => normalizeInterest(t).toLowerCase() === text.toLowerCase())) {\n return { ok: false, reason: 'duplicate', doc: current };\n }\n if (current.interests.length >= MAX_INTERESTS) {\n return { ok: false, reason: `cap (${MAX_INTERESTS})`, doc: current };\n }\n const doc = ensureUserLayer(guard, paths);\n doc.interests.push(text);\n saveDoc(guard, userInterestsPath(paths), doc);\n return { ok: true, doc };\n}\n\nexport function removeInterest(\n guard: PathGuard,\n paths: WorkspacePaths,\n rawText: string,\n): InterestsResult {\n const current = readEffective(paths);\n const text = normalizeInterest(rawText);\n if (!current.interests.some((t) => normalizeInterest(t) === text)) {\n return { ok: false, reason: 'not-found', doc: current };\n }\n const doc = ensureUserLayer(guard, paths);\n doc.interests = doc.interests.filter((t) => normalizeInterest(t) !== text);\n saveDoc(guard, userInterestsPath(paths), doc);\n return { ok: true, doc };\n}\n\n/** Validate \"HH:MM\" and same-day ordering (the wander windows are intra-day). */\nexport function parseWindow(w: unknown): { ok: true; window: WanderWindow } | { ok: false; reason: string } {\n if (typeof w !== 'object' || w === null) return { ok: false, reason: 'not-an-object' };\n const { id, start, end } = w as { id?: unknown; start?: unknown; end?: unknown };\n if (typeof start !== 'string' || !HHMM.test(start)) return { ok: false, reason: `bad start ${JSON.stringify(start)}` };\n if (typeof end !== 'string' || !HHMM.test(end)) return { ok: false, reason: `bad end ${JSON.stringify(end)}` };\n if (start >= end) return { ok: false, reason: `start ${start} must be before end ${end}` };\n return { ok: true, window: { id: typeof id === 'string' && id ? id : `${start}-${end}`, start, end } };\n}\n\n/** Full-state write of the wander windows (the card sends all rows each time). */\nexport function setWanderWindows(\n guard: PathGuard,\n paths: WorkspacePaths,\n rawWindows: unknown,\n): InterestsResult {\n const fail = (reason: string): InterestsResult => ({ ok: false, reason, doc: readEffective(paths) });\n if (!Array.isArray(rawWindows)) return fail('windows-must-be-array');\n if (rawWindows.length === 0) return fail('at-least-one-window');\n if (rawWindows.length > MAX_WINDOWS) return fail(`cap (${MAX_WINDOWS})`);\n const windows: WanderWindow[] = [];\n for (const raw of rawWindows) {\n const parsed = parseWindow(raw);\n if (!parsed.ok) return fail(parsed.reason);\n windows.push(parsed.window);\n }\n // Overlap check: the adjudicator returns the FIRST matching window, so\n // overlapping rows would silently change which window \"wins\".\n const sorted = [...windows].sort((a, b) => a.start.localeCompare(b.start));\n for (let i = 1; i < sorted.length; i += 1) {\n if (sorted[i]!.start < sorted[i - 1]!.end) {\n return fail(`windows overlap: ${sorted[i - 1]!.id} / ${sorted[i]!.id}`);\n }\n }\n const doc = ensureUserLayer(guard, paths);\n doc._schedule = { ...doc._schedule, windows };\n saveDoc(guard, userInterestsPath(paths), doc);\n return { ok: true, doc };\n}\n","// M7b: self-built time injection (design doc §17.6, D20).\n//\n// Replaces the official dsh-time-context (disabled via the user patch — B9 is\n// superseded by D20: time injection has exactly one owner, this module).\n//\n// Gate (all must pass): step === 1 AND the open turn was initiated by a real\n// user message (the splice that OPENED the turn carries source kind='user',\n// P1 ① conclusion) AND the per-session throttle interval has elapsed.\n// Mid-task steps are never injected.\n// Content: precise local time (+ timezone) and elapsed-since-last-message.\n// Transport: pre-step waterfall append — a strict `createUserMessage` message\n// (r5 rule: never splice hand-rolled objects). Source attribution\n// kind='plugin' keeps the observe phase from ingesting these (C-track rule).\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { atomicWriteJsonSync } from '../core/atomic-fs.js';\nimport { appendAuditLine } from '../core/audit-log.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport { sessionEvents } from '../core/orchestrator.js';\nimport type { HostSession } from '../core/orchestrator.js';\n\n/** Pure gate (§17.6): every condition must hold for an injection. */\nexport function shouldInjectTime(input: {\n step: number;\n /** Turn-origin probe (see {@link turnOriginIsUserSplice}). */\n originIsUserSplice: boolean;\n lastInjectAt: number;\n now: number;\n intervalMs: number;\n}): boolean {\n if (input.step !== 1) return false;\n if (!input.originIsUserSplice) return false;\n if (input.intervalMs <= 0) return false;\n return input.now - input.lastInjectAt >= input.intervalMs;\n}\n\n/** Turn-origin probe (review 2026-09-13 #2, tightened 2026-11-08): did the OPEN\n * turn begin with a splice carrying a REAL user message?\n *\n * An exact \"last event is spliced\" check silently breaks the moment any other\n * plugin writes a session event between the splice and this hook. So: scan\n * backwards for the last `turn/end` (none → scan from the start of the log),\n * then take the FIRST `agent/inbox/spliced` inside that turn's span — the one\n * that opened the turn — and require its `data.inserted` to carry at least one\n * message with `source.kind === 'user'`. Later mid-turn splices (delivery\n * followups and friends) never define the turn origin, and heartbeat splices\n * don't count. Robustness: missing `data`, a non-array `inserted` or entries\n * without `source` all yield false — never throws.\n * Cost: bounded by one turn length, and only paid at step === 1. */\nexport function turnOriginIsUserSplice(session: HostSession): boolean {\n const events = sessionEvents(session);\n let start = 0;\n for (let i = events.length - 1; i >= 0; i--) {\n if (events[i]!.type === 'turn/end') { start = i + 1; break; }\n }\n for (let i = start; i < events.length; i++) {\n if (events[i]!.type !== 'agent/inbox/spliced') continue;\n const inserted = (events[i] as { data?: { inserted?: unknown } }).data?.inserted;\n if (!Array.isArray(inserted)) return false;\n return inserted.some((m) => (m as { source?: { kind?: unknown } } | undefined)?.source?.kind === 'user');\n }\n return false;\n}\n\n/** `SessionHeader` fields we care about (dsh-session ≥ v4 headers). HostSession\n * deliberately declares only the minimal surface, so `header` is read through a\n * local assertion instead of widening the interface. */\ninterface SessionHeaderProbe {\n header?: {\n origin?: string;\n delegationDepth?: number;\n };\n}\n\n/** Subagent sessions must not receive time injections (their context has no\n * use for \"now\" and every hop pollutes it). Verdict order: header fields\n * first (cheap, exact), then a bounded scan of the first 8 events for the\n * `subagent/descriptor` marker every subagent session logs at seq 0. */\nexport function isSubagentSession(session: HostSession | undefined): boolean {\n if (!session) return false;\n const header = (session as HostSession & SessionHeaderProbe).header;\n if (header?.origin === 'subagent') return true;\n if (typeof header?.delegationDepth === 'number' && header.delegationDepth > 0) return true;\n return sessionEvents(session).slice(0, 8).some((e) => e?.type === 'subagent/descriptor');\n}\n\nfunction formatElapsed(ms: number): string {\n const minutes = Math.max(1, Math.round(ms / 60_000));\n if (minutes < 60) return `${minutes} 分钟`;\n const hours = Math.floor(minutes / 60);\n const rest = minutes % 60;\n return rest === 0 ? `${hours} 小时` : `${hours} 小时 ${rest} 分钟`;\n}\n\nfunction localFormatter(timeZone: string | undefined): Intl.DateTimeFormat {\n const options: Intl.DateTimeFormatOptions = {\n year: 'numeric', month: '2-digit', day: '2-digit',\n hour: '2-digit', minute: '2-digit', hour12: false,\n timeZoneName: 'shortOffset',\n };\n if (timeZone !== undefined) return new Intl.DateTimeFormat('zh-CN', { ...options, timeZone });\n return new Intl.DateTimeFormat('zh-CN', options);\n}\n\n/** Render the injected text (§17.6): precise local time + elapsed. Timezone\n * resolution failures fall back to the system zone (never throw to the hook). */\nexport function renderTimeText(input: {\n now: number;\n timeZone?: string;\n /** Timestamp (`event.time`) of the session's last message event. */\n lastMessageTime?: number;\n}): string {\n let timeLine: string;\n try {\n const parts = localFormatter(input.timeZone).formatToParts(new Date(input.now));\n const get = (type: string): string => parts.find((p) => p.type === type)?.value ?? '';\n timeLine = `当前本地时间:${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}(${parts.find((p) => p.type === 'timeZoneName')?.value ?? ''})。`;\n } catch {\n timeLine = `当前本地时间:${new Date(input.now).toISOString()}。`;\n }\n const elapsedLine = input.lastMessageTime === undefined\n ? ''\n : `\\n距本会话上一条消息已过去 ${formatElapsed(input.now - input.lastMessageTime)}。`;\n return timeLine + elapsedLine;\n}\n\n/** Timestamp of the session's last user/assistant/tool message event. */\nexport function lastMessageTime(session: HostSession): number | undefined {\n const events = sessionEvents(session);\n for (let i = events.length - 1; i >= 0; i--) {\n const e = events[i]!;\n const t = (e as { time?: number }).time;\n if (typeof t === 'number' && /user\\/message|assistant\\/message|tool\\/result/.test(e.type)) return t;\n }\n return undefined;\n}\n\n// ── per-session throttle state (survives restarts, like cursors.json) ───\n\nexport interface TimeInjectState {\n [sessionId: string]: number;\n}\n\nexport function timeInjectStatePath(dataDir: string): string {\n return path.join(dataDir, 'time-inject-state.json');\n}\n\nexport function loadTimeInjectState(guard: PathGuard, dataDir: string): TimeInjectState {\n try {\n const parsed = JSON.parse(fs.readFileSync(guard.assert(timeInjectStatePath(dataDir)), 'utf8')) as TimeInjectState;\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport function saveTimeInjectState(guard: PathGuard, dataDir: string, state: TimeInjectState): void {\n atomicWriteJsonSync(guard.assert(timeInjectStatePath(dataDir)), state);\n}\n\n// ── registration ─────────────────────────────────────────────────────────\n\nexport interface TimeInjectionOptions {\n /** Live-read on every gate check (UI-settable in M7d). */\n getTimeInjectMin(): number;\n timeZone?: string;\n paths: WorkspacePaths;\n logger: { info(msg: string, ...a: unknown[]): void; warn(msg: string, ...a: unknown[]): void };\n onError(error: unknown): void;\n /** Track B status line (§17.5): '' when the statusbar is off or the session\n * rides Track A. Receives the TURN-PINNED track (review #5) so the status\n * line and the system-prompt section can never split one turn. */\n getStatusLine?(session: HostSession, track: 'system-prompt' | 'pre-step'): string;\n /** Pin this turn's track at step===1 (before throttle logic) — every turn\n * start re-pins, so mid-turn capability flips land at the next boundary. */\n pinTrack(sessionId: string, session: HostSession): 'system-prompt' | 'pre-step';\n}\n\ninterface PreStepPayload {\n agent: { session: HostSession };\n step: number;\n signal?: { aborted?: boolean };\n}\n\ninterface EnterDecision {\n kind: string;\n messages: unknown[];\n}\n\n/**\n * Register the gated time injector on `ctx` (all agents, like the official\n * plugin it replaces). Returns the disposer conceptually owned by the caller's\n * fiber via `ctx.effect`.\n */\nexport function registerTimeInjection(\n ctx: {\n on(event: string, listener: (payload: PreStepPayload, next: () => Promise<unknown>) => Promise<unknown>, opts?: { prepend?: boolean }): unknown;\n },\n guard: PathGuard,\n dataDir: string,\n opts: TimeInjectionOptions,\n): void {\n const state = loadTimeInjectState(guard, dataDir);\n ctx.on('agent/pre-step', async (payload, next) => {\n const decision = await next() as EnterDecision;\n if (decision.kind === 'reject' || payload.signal?.aborted) return decision;\n const sessionId = payload.agent.session.id;\n const now = Date.now();\n // Turn-start track pin (review #5): re-pinned at EVERY step===1, before\n // any throttle logic, so the pin never goes stale across turns.\n const track = payload.step === 1 ? opts.pinTrack(sessionId, payload.agent.session) : undefined;\n const intervalMs = Math.max(0, opts.getTimeInjectMin()) * 60_000;\n if (!shouldInjectTime({\n step: payload.step,\n originIsUserSplice: payload.step === 1 ? turnOriginIsUserSplice(payload.agent.session) : false,\n lastInjectAt: state[sessionId] ?? 0,\n now,\n intervalMs,\n })) return decision;\n // Subagent sessions never get the clock (review 2026-10-29): checked after\n // the pure gate so the event-stream scan only runs on otherwise-eligible\n // steps, and the audit line only fires on a would-have-injected hop.\n if (isSubagentSession(payload.agent.session)) {\n appendAuditLine(opts.paths.logsDir + '/heartbeat.jsonl', {\n event: 'time_inject_skipped', sessionId, reason: 'subagent',\n });\n return decision;\n }\n try {\n const { createUserMessage } = await import('@deepseek-ai/dsh-llm');\n let text = renderTimeText({\n now,\n timeZone: opts.timeZone,\n lastMessageTime: lastMessageTime(payload.agent.session),\n });\n // §17.5: Track B rides the same message with a trailing status line\n // (D21: status text itself never carries time words).\n if (opts.getStatusLine && track) {\n const statusLine = opts.getStatusLine(payload.agent.session, track);\n if (statusLine) text += `\\n${statusLine}`;\n }\n const message = createUserMessage({\n content: [{ type: 'text', text }],\n // 0.1.7 V4: producer-owned kind (retired generic 'plugin' is refused).\n source: { kind: 'heartbeat', plugin: 'heartbeat', form: 'snapshot', sections: [{ name: 'heartbeat-time', text }] },\n });\n state[sessionId] = now;\n saveTimeInjectState(guard, dataDir, state);\n appendAuditLine(opts.paths.logsDir + '/heartbeat.jsonl', {\n event: 'time_injected', sessionId, intervalMin: opts.getTimeInjectMin(),\n });\n return { ...decision, messages: [...decision.messages, message] };\n } catch (e) {\n opts.onError(e);\n return decision;\n }\n }, { prepend: true });\n}\n","// M7c: statusbar tracks (design doc §17.4–17.5, §17.7, D19/D21).\n//\n// One status store, two transports, picked per agent by model capability:\n// Track A — in-history-capable models: a dynamic system-prompt section\n// (`heartbeat:status`). The host projection layer dedupes (text\n// unchanged → zero commit) and appends changed prompts after the\n// cached history (KV-safe). Incapable/disabled → the text function\n// returns '' and the section drops out of the render entirely.\n// Track B — every other model: the pre-step time-injection message gains a\n// trailing status line (see time-inject.ts `getStatusLine`).\n// Track evidence: the session log's latest `request/context` event carries the\n// route's `systemPromptUpdate` mode. No evidence yet (fresh session) → Track B\n// (§17.7 default). Red line D21: status text NEVER contains time words.\n\nimport { appendAuditLine } from '../core/audit-log.js';\nimport { sessionEventCount, sessionEvents } from '../core/orchestrator.js';\nimport type { HostSession } from '../core/orchestrator.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport { StatusReader } from './store.js';\nimport type { StatusState } from './store.js';\n\n// ── capability probe (review 2026-09-13 #1: incremental tail scan) ───\n// Cache keyed by \"how far we've scanned\", NOT by log length: the length grows\n// every step, so a length key would miss (and rescan the whole log backwards)\n// on every assembly. We remember the scan watermark and, on new events, read\n// only the tail (snapshotEvents(fromSeq) range) for NEW request/context rows.\ninterface CapabilityCache {\n /** Event count at the time of the last scan. */\n scannedUpTo: number;\n supported: boolean;\n}\nconst capabilityCache = new Map<string, CapabilityCache>();\n\nexport function supportsInHistory(session: HostSession): boolean {\n const key = session.id;\n const len = sessionEventCount(session);\n const hit = capabilityCache.get(key);\n if (hit && hit.scannedUpTo === len) return hit.supported;\n // Log shrank (session reset under the same id) → rescan from zero.\n const from = hit && len >= hit.scannedUpTo ? hit.scannedUpTo : 0;\n let supported = false;\n if (from !== 0 && hit) supported = hit.supported;\n const readTail = (fromSeq: number): { type: string; data?: unknown }[] => {\n if (typeof session.snapshotEvents === 'function') {\n try {\n const slice = session.snapshotEvents(fromSeq);\n if (Array.isArray(slice)) return slice;\n } catch { /* fall through to the legacy full read */ }\n }\n return sessionEvents(session).slice(fromSeq);\n };\n for (const e of readTail(from)) {\n if (e.type === 'request/context') {\n supported = (e.data as { systemPromptUpdate?: string } | undefined)?.systemPromptUpdate === 'in-history';\n }\n }\n capabilityCache.set(key, { scannedUpTo: len, supported });\n return supported;\n}\n\n/** Forget cached capability (test helper; also bounds memory across deletes). */\nexport function resetCapabilityCache(): void {\n capabilityCache.clear();\n}\n\nconst SCENE_LABELS: Record<StatusState['scene'], string> = {\n 'quiet-hours': '静默时段,世界睡了',\n 'just-spoke': '刚去和你说过话',\n wandering: '正在闲逛看新东西',\n busy: '看到你在忙,不去打扰',\n present: '在场待着',\n away: '你不在,自己待着',\n};\n\n/** Render the one-line status text (D21 red line: zero time words).\n *\n * RENDER PURITY RED LINE (2026-09-13 review): this MUST stay a pure function\n * of the status state — no clock reads, no counters, no per-call variability.\n * The host projection already refuses to commit identical text (project()\n * emits no updates when the rendered prompt is byte-identical), so purity here\n * is what keeps the in-history append cadence at \"per scene change\", not \"per\n * step\". Any field varying faster than the scene belongs in the time\n * injection, never here.\n *\n * NOTE POLICY (review 2026-09-13 #3): `withNote: false` for the Track A\n * section — the scene label is a constant-table mapping (maximally stable),\n * while the note is engine-room free text that can differ every beat and\n * would defeat the host's byte-dedupe. The note is for the UI and the Track B\n * pre-step line (where each message is small and already event-shaped). */\nexport function renderStatusText(\n status: StatusState | null,\n opts?: { withNote?: boolean },\n): string {\n if (!status) return '';\n const label = SCENE_LABELS[status.scene] ?? '在场';\n const note = opts?.withNote === false ? '' : status.note ? `——${status.note}` : '';\n return `心跳此刻:${label}${note}。`;\n}\n\n// ── turn-pinned track decision (2026-09-13 review #5) ────────────────────\n// The track must be decided ONCE per turn, at its start (step===1 in the\n// pre-step listener), and both transports read that pin. Otherwise a\n// capability flip mid-turn (e.g. the very first request of a fresh capable\n// session lands `request/context` after step 1) splits the turn: the pre-step\n// status line already in history AND the section activating from the next\n// step. A pin updates only at turn starts, so a flip always lands cleanly at\n// the next turn boundary.\nconst pinnedTrack = new Map<string, 'system-prompt' | 'pre-step'>();\n\n/** Pin and return this turn's track. Call from the pre-step listener at\n * step===1 (before any throttle logic) — every turn start re-pins. */\nexport function pinTrack(sessionId: string, session: HostSession): 'system-prompt' | 'pre-step' {\n const track = trackFor(session);\n pinnedTrack.set(sessionId, track);\n return track;\n}\n\n/** The pinned track when one exists for this session, else the live probe\n * (fallback for assemblies that somehow precede any turn-start pin). */\nexport function pinnedTrackFor(sessionId: string, session: HostSession): 'system-prompt' | 'pre-step' {\n return pinnedTrack.get(sessionId) ?? trackFor(session);\n}\n\nexport function resetPins(): void {\n pinnedTrack.clear();\n}\n\n/** Track-change auditor: emits `statusbar_track` only when an agent's track\n * actually flips (bounded spam; called from the two render paths). */\nconst lastTrack = new Map<string, string>();\n\nexport function noteTrack(auditFile: string, sessionId: string, track: 'system-prompt' | 'pre-step' | 'off'): void {\n if (lastTrack.get(sessionId) === track) return;\n lastTrack.set(sessionId, track);\n try {\n appendAuditLine(auditFile, { event: 'statusbar_track', sessionId, track });\n } catch { /* audit failure must not break rendering */ }\n}\n\n/** Forget a session's track memo (test helper). */\nexport function resetTrackMemo(): void {\n lastTrack.clear();\n}\n\n/** Which transport serves this session right now (§17.7: no evidence yet →\n * Track B; the section flip happens once a request/context event lands). */\nexport function trackFor(session: HostSession): 'system-prompt' | 'pre-step' {\n return supportsInHistory(session) ? 'system-prompt' : 'pre-step';\n}\n\n/** Register the Track A section on the host systemPrompt service. The text\n * provider returns '' (section drops from the render) when the statusbar is\n * off, the agent is unknown, or the session rides Track B. */\nexport function registerStatusbarSection(\n ctx: {\n inject(services: string[], callback: (scoped: unknown) => void): void;\n },\n guard: PathGuard,\n paths: WorkspacePaths,\n opts: { enabled(): boolean; reader: StatusReader },\n): void {\n ctx.inject(['systemPrompt'], (scoped) => {\n const spCtx = scoped as {\n systemPrompt?: {\n section(def: { name: string; order: number; text: string | ((context: unknown) => string) }): unknown;\n };\n effect(fn: () => unknown, label?: string): () => void;\n logger?: { warn(msg: string, ...a: unknown[]): void };\n };\n const section = spCtx.systemPrompt?.section;\n if (typeof section !== 'function') {\n spCtx.logger?.warn('heartbeat: systemPrompt service has no section API, statusbar Track A unavailable');\n return;\n }\n spCtx.effect(() => section.call(spCtx.systemPrompt, {\n name: 'heartbeat:status',\n order: 5000, // between the persona prefix (0) and the harness block (10000)\n text: (context: unknown) => {\n if (!opts.enabled()) {\n noteTrack(paths.logsDir + '/heartbeat.jsonl', (context as { agent?: { session: HostSession } }).agent?.session.id ?? '(none)', 'off');\n return '';\n }\n const agent = (context as { agent?: { session?: HostSession } }).agent;\n if (!agent?.session) return '';\n // Read the TURN-PINNED track (2026-09-13 review #5): a mid-turn\n // capability flip must not activate the section inside the same turn\n // whose pre-step status line already went out on Track B.\n const track = pinnedTrackFor(agent.session.id, agent.session);\n noteTrack(paths.logsDir + '/heartbeat.jsonl', agent.session.id, track);\n if (track !== 'system-prompt') return '';\n return renderStatusText(opts.reader.read(guard, paths), { withNote: false });\n },\n }), 'heartbeat: statusbar section');\n });\n}\n","// The heartbeat agent preset, as a runtime registration (issue #2, 2026-10-10).\n//\n// 0.1.7+ mounts presets from the profile COMPOSITION: a row named\n// `@deepseek-ai/dsh-agent-preset` whose `config` is the definition. That row\n// makes the PROFILE resolve the package — and `@deepseek-ai/dsh-agent-preset`\n// is thin (it only forwards its config to `agentPresets.register`), but its\n// peer closure contains `cordis-plugin-loader` / `cordis-plugin-include` /\n// `cordis-plugin-group`, i.e. the loading machinery itself. So a profile that\n// cannot resolve it fails the WHOLE plugin tree (\"plugin tree failed to load\"\n// on 0.1.5), and one that satisfies it by hand double-instances the machinery\n// (\"prompt section deployment:persona-prefix is already registered\", every\n// session then refuses to resume). Both were reported with reproductions.\n//\n// The registry exposes `register(definition)` for exactly this case — its\n// docstring: \"Parsed configuration supplied by the declaring plugin\" — so the\n// plugin now registers its own preset at runtime and the bundle patch carries\n// no host-package reference at all. The definition below is the same content\n// the composition used to hold (and the same as\n// `assets/presets/heartbeat/agent.cordis.yml`, which older hosts still read\n// off the filesystem).\n//\n// Deliberately NO persona row: the deployment persona (soul card) plus the\n// heartbeat prompt already cover it, and a \"You are a coding agent\" line would\n// overwrite the persona.\n\n/** One child row of the preset, in Cordis entry-list shape. */\nexport interface PresetEntry {\n readonly id?: string;\n readonly name?: string;\n /** `cordis:group` marker: this row nests `config` as child entries. */\n readonly group?: boolean;\n /** Isolation flags a group row may carry (kept verbatim). */\n readonly isolate?: Record<string, unknown>;\n readonly config?: unknown;\n}\n\n/** Identity, display fields and child plugins of one preset. */\nexport interface HeartbeatPresetDefinition {\n readonly id: string;\n readonly name: string;\n readonly description: string;\n readonly order: number;\n readonly plugins: readonly PresetEntry[];\n}\n\n/**\n * The bundled preset definition for `id`.\n *\n * Content = `assets/presets/heartbeat/agent.cordis.yml`: a compaction group\n * (basic + command-compact + tool-result-pruner) plus the single model-facing\n * tool `tool-web` with `fetch: false` (web_search only — no page fetching,\n * no shell, no filesystem, no subagents).\n */\nexport function heartbeatPresetDefinition(id: string = 'heartbeat'): HeartbeatPresetDefinition {\n return {\n id,\n name: '心跳模式',\n description: '心跳 agent 专用:仅 web_search + 上下文折叠;无 shell、无文件、无子代理。',\n order: 20,\n plugins: [\n {\n id: 'compaction',\n name: 'cordis:group',\n group: true,\n isolate: { compaction: true, toolResultPruner: true },\n config: [\n { id: 'compaction-basic', name: '@deepseek-ai/dsh-compaction-basic' },\n { id: 'command-compact', name: '@deepseek-ai/dsh-command-compact' },\n {\n id: 'tool-result-pruner',\n name: '@deepseek-ai/dsh-compaction-tool-result-pruner',\n config: { thresholdChars: 8192, headChars: 4096, tailChars: 1024 },\n },\n ],\n },\n { id: 'tool-web', name: '@deepseek-ai/dsh-tool-web', config: { fetch: false, searchTimeoutMs: 60000 } },\n ],\n };\n}\n\n/** Registration result, for the audit line and the log. */\nexport type PresetRegisterAction = 'registered' | 'skipped-disabled' | 'skipped-no-api' | 'already-registered' | 'error';\n\nexport interface PresetRegisterResult {\n action: PresetRegisterAction;\n id: string;\n detail?: string;\n /**\n * HB-17 (2026-10-17): undo hook returned by the registry. The caller must\n * run it on dispose — otherwise a plugin reload leaves the preset behind\n * (and the next registration double-mounts it).\n */\n disposer?: () => Promise<void>;\n}\n\nconst DUPLICATE_RE = /Duplicate agent preset/i;\n/** Backoff for a duplicate id: long enough for the previous instance's dispose. */\nconst DUPLICATE_RETRY_MS = [80, 160, 320] as const;\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => { setTimeout(resolve, ms); });\n}\n\n/** Minimal shape of the registry we call (`AgentPresetRegistry.register`). */\ninterface RegistrarLike {\n register?(definition: unknown): Promise<() => Promise<void>> | (() => Promise<void>);\n}\n\n/**\n * Register the bundled preset at runtime, tolerating every missing-API case.\n *\n * A host whose registry has no `register` (0.1.7-alpha.1 and other partial\n * builds) or no `agentPresets` service at all (pre-0.1.7) must NOT take the\n * host down: the heartbeat simply runs without its preset — degraded (no\n * `web_search`), which the acquire path already audits as `preset=no-api`.\n *\n * @param service The resolved `agentPresets` service, if any.\n * @param id Preset identity to register.\n * @param enabled False when the operator manages the preset themselves.\n * @returns What happened, for the audit line.\n */\nexport async function registerHeartbeatPreset(\n service: unknown,\n id: string = 'heartbeat',\n enabled: boolean = true,\n): Promise<PresetRegisterResult> {\n if (!enabled) return { action: 'skipped-disabled', id };\n const registrar = service as RegistrarLike | undefined;\n if (registrar === undefined || registrar === null || typeof registrar.register !== 'function') {\n return { action: 'skipped-no-api', id };\n }\n // HB-31 (2026-10-29): a hot reload used to log \"Duplicate agent preset\".\n // The registry rejects a second registration for an id it already holds, and\n // the holder is the PREVIOUS plugin instance, whose unregister only runs from\n // its own dispose — which can land after the new instance has started (or,\n // when the old fiber was dropped without disposal, never at all). Waiting a\n // few hundred ms covers the ordinary case; when the id is still held the\n // existing preset is the same definition, so reusing it is correct, not a\n // failure. A full restart always registers cleanly.\n let detail = '';\n for (let attempt = 0; ; attempt += 1) {\n try {\n const disposer = await registrar.register(heartbeatPresetDefinition(id));\n return typeof disposer === 'function'\n ? { action: 'registered', id, disposer }\n : { action: 'registered', id };\n } catch (e) {\n detail = String(e).slice(0, 200);\n if (!DUPLICATE_RE.test(detail)) return { action: 'error', id, detail };\n const wait = DUPLICATE_RETRY_MS[attempt];\n if (wait === undefined) return { action: 'already-registered', id, detail };\n await delay(wait);\n }\n }\n}\n","// Ledger as a MODEL TOOL (v1.8.0): the chat agents can record / list / check\n// off ledger items themselves, so a todo mentioned in conversation lands in\n// the shared ledger without the user commanding anyone to \"write it down\".\n//\n// Registration is host-side (`ToolRuntime.register`, 0.2.0-rc.2 verified):\n// the definition is built as a PLAIN OBJECT here — `parameters` is a raw JSON\n// Schema per ToolSchema (dsh-llm), so we do not import `defineTool` and the\n// module carries zero new runtime dependencies. `ToolRuntime.register` is the\n// only host entry point (looked up dynamically by the caller); on a host\n// without it the caller audits and moves on, nothing else is affected.\n//\n// Scope: registration happens through the plugin's ROOT context, which lands\n// the tool in the GLOBAL layer — every agent sees it. The engine room is\n// unaffected: its preset restrict({allow:['web_search']}) masks global tools,\n// so the heartbeat's own turns cannot touch the ledger.\n\nimport {\n appendEntry,\n markDone,\n readLedger,\n scanPending,\n type LedgerEntry,\n} from './ledger.js';\nimport type { PathGuard } from '../core/path-guard.js';\n\n/** Minimal structural typing of the host shape — we deliberately do not\n * depend on @deepseek-ai/dsh-tools at runtime. */\nexport interface RegisterableToolRuntime {\n register(definition: unknown): () => void;\n}\n\ninterface LedgerToolArgs {\n action?: unknown;\n text?: unknown;\n key?: unknown;\n}\n\nconst MAX_TEXT = 120;\n\nfunction clean(v: unknown): string {\n return String(v ?? '').replace(/\\s+/g, ' ').trim().slice(0, MAX_TEXT);\n}\n\nfunction fmtEntry(e: LedgerEntry): string {\n return `#${e.id} [${e.status}] ${e.date} ${e.text}`;\n}\n\nexport function buildLedgerTool(guard: PathGuard, file: string): unknown {\n return {\n name: 'ledger',\n description:\n '共享账本工具(心跳插件的待办与事项记录)。当用户提到计划、待办、承诺、想做的事,' +\n '或者某件事已经完成时,主动调用本工具登记或勾掉——不需要等用户明确说\"记一下\"。' +\n 'action=add 登记新事项(text 必填);action=list 查看当前未完成事项;action=done 勾掉一条(key 为 #id 或文本子串)。',\n parameters: {\n type: 'object',\n properties: {\n action: { type: 'string', enum: ['add', 'list', 'done'], description: 'add=登记,list=查未完成,done=勾掉' },\n text: { type: 'string', description: 'action=add 时必填:事项内容(一句话)' },\n key: { type: 'string', description: 'action=done 时必填:#id 或事项文本的唯一子串' },\n },\n required: ['action'],\n additionalProperties: false,\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean' },\n message: { type: 'string' },\n },\n required: ['ok', 'message'],\n additionalProperties: false,\n },\n render: (_args: unknown, value: unknown) => {\n const v = value as { message?: string };\n return [{ type: 'text', text: String(v.message ?? '') }];\n },\n },\n timeoutMs: 5000,\n // Ledger writes go through read-modify-write on one file; never parallel.\n isConcurrencySafe: () => false,\n async execute(args: unknown): Promise<unknown> {\n const a = (args ?? {}) as LedgerToolArgs;\n const action = String(a.action ?? '');\n if (action === 'add') {\n const text = clean(a.text);\n if (!text) return { ok: false, message: 'add 需要非空 text' };\n const e = appendEntry(guard, file, text);\n return { ok: true, message: `已登记 ${fmtEntry(e)}` };\n }\n if (action === 'done') {\n const key = clean(a.key);\n if (!key) return { ok: false, message: 'done 需要 key(#id 或文本子串)' };\n const e = markDone(guard, file, key);\n if (!e) return { ok: false, message: `没有找到匹配「${key}」的未完成事项(先用 list 查)` };\n return { ok: true, message: `已完成 ${fmtEntry(e)}` };\n }\n if (action === 'list') {\n const items = scanPending(guard, file).map(fmtEntry);\n return { ok: true, message: items.length > 0 ? `当前未完成 ${items.length} 项:\\n${items.join('\\n')}` : '账本里没有未完成事项' };\n }\n // Unsupported action shapes should be rare (schema-enforced); stay total.\n const total = readLedger(guard, file).entries.length;\n return { ok: false, message: `未知 action,账本共 ${total} 条` };\n },\n };\n}\n","// 心事匣 as a MODEL TOOL (v2.0): the chat agents can leave ONE note for the\n// next heartbeat, look at it, or let it go — the same host-side pattern as the\n// ledger tool (see ledger/tool.ts:1-15): the definition is a PLAIN OBJECT built\n// here, `parameters` is a raw JSON Schema, and nothing imports\n// @deepseek-ai/dsh-tools, so this module keeps zero new runtime dependencies.\n//\n// Registration goes through the plugin's ROOT context, which lands the tool in\n// the GLOBAL layer — every chat agent sees it. The engine room never does: its\n// preset restrict({allow:['web_search']}) masks global tools, and it must stay\n// that way. The note is the persona's own private line; the engine room only\n// ever sees it indirectly, as text inside the delivery package it never builds.\n//\n// Scope note: the note is one slot, not a queue. `write` replaces — and that\n// replacement is the whole mechanism by which the previous note is let go, so\n// the tool deliberately has no \"append\".\n\nimport type { PathGuard } from '../core/path-guard.js';\nimport { clearNote, notepadView, readNotepad, writeNote, type NotepadView } from './store.js';\n\ninterface NotepadToolArgs {\n action?: unknown;\n text?: unknown;\n}\n\n/** One line, deliberately: this is a HOOK for the next self to re-expand, not a\n * record. 120 (the ledger's per-item cap) is the convention here; the little\n * extra room is because a note is a whole thought, where a ledger item is a\n * task title. */\nconst MAX_NOTE_CHARS = 160;\n\nfunction clean(v: unknown): string {\n return String(v ?? '').replace(/\\s+/g, ' ').trim().slice(0, MAX_NOTE_CHARS);\n}\n\nfunction fmtMinutes(m: number): string {\n if (m < 1) return '不到 1 分钟';\n if (m < 60) return `${m} 分钟`;\n const h = Math.floor(m / 60);\n const rest = m % 60;\n return rest > 0 ? `${h} 小时 ${rest} 分` : `${h} 小时`;\n}\n\n/** Same phrasing the delivery package uses (material.ts notepadLines) so the\n * note reads the same wherever she meets it. */\nfunction fmtView(v: NotepadView): string {\n const beats = v.beatsAgo === 0 ? '本跳' : `${v.beatsAgo} 跳前`;\n const wakes = v.wakesAgo === 0 ? '还没被叫醒过' : `期间被叫醒过 ${v.wakesAgo} 次`;\n return `心事匣里现在有:${v.text}\\n(留于${beats},已搁 ${fmtMinutes(v.sinceMinutes)},${wakes})`;\n}\n\nexport function buildNotepadTool(guard: PathGuard, file: string): unknown {\n return {\n name: 'notepad',\n description:\n '心事匣(心跳插件的\"留给下一跳的自己\"便签)。只有一格:写下新的就盖掉旧的。' +\n '当你有话想留到下次心跳再说、或者有一件放不下的事时,用 action=write 留下一句引子——' +\n '不要写整段,下次跳由那时的你重新展开。想留住原来的就照原样再写一遍(字样一致算保留,' +\n '它的年龄不会重算);写别的就是换掉它。action=read 看现在格子里是什么;action=clear 主动放掉。' +\n '投递包读过之后,什么都不做它就下一跳没了。留不留都行,没话就空着。',\n parameters: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['write', 'read', 'clear'],\n description: 'write=留一句(盖掉旧的),read=看现在是什么,clear=主动放掉',\n },\n text: {\n type: 'string',\n description: 'action=write 时必填:一句引子(不是整段心事,下次跳你自己重新展开)',\n },\n },\n required: ['action'],\n additionalProperties: false,\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean' },\n message: { type: 'string' },\n },\n required: ['ok', 'message'],\n additionalProperties: false,\n },\n render: (_args: unknown, value: unknown) => {\n const v = value as { message?: string };\n return [{ type: 'text', text: String(v.message ?? '') }];\n },\n },\n timeoutMs: 5000,\n // Read-modify-write on one file, and the note's lifecycle depends on it.\n isConcurrencySafe: () => false,\n async execute(args: unknown): Promise<unknown> {\n const a = (args ?? {}) as NotepadToolArgs;\n const action = String(a.action ?? '');\n try {\n if (action === 'write') {\n const text = clean(a.text);\n if (!text) return { ok: false, message: 'write 需要非空 text(一句引子)' };\n const { note, kept } = writeNote(guard, file, text);\n return {\n ok: true,\n message: kept ? `还惦记着:${note.text}(年龄不变)` : `已留下心事:${note.text}`,\n };\n }\n if (action === 'read') {\n const v = notepadView(readNotepad(guard, file));\n return { ok: true, message: v ? fmtView(v) : '心事匣是空的' };\n }\n if (action === 'clear') {\n const prev = clearNote(guard, file);\n return prev\n ? { ok: true, message: `已放掉:${prev.text}` }\n : { ok: true, message: '心事匣本来就是空的' };\n }\n // Unsupported action shapes should be rare (schema-enforced); stay total.\n return { ok: false, message: `未知 action(${action || '空'}),只认 write / read / clear` };\n } catch (e) {\n // A damaged container throws on read (store.ts header). Never let that\n // surface as a tool crash; the host would show it as a tool failure.\n return { ok: false, message: `心事匣读写失败:${String(e).slice(0, 120)}` };\n }\n },\n };\n}\n","// Excerpt book as a MODEL TOOL (v2.0.0): the agent can keep a line the moment it\n// lands, instead of losing it because there is nowhere to put it.\n//\n// Same registration shape as the ledger tool: a PLAIN OBJECT, no import of\n// @deepseek-ai/dsh-tools, registered through the plugin's ROOT context so it\n// lands in the GLOBAL layer every chat agent sees. The engine room cannot\n// reach it (its preset restrict({allow:['web_search']}) masks global tools).\n\nimport { appendExcerpt, readExcerpts, recentExcerpts, removeExcerpt, type ExcerptEntry } from './excerpt.js';\nimport type { PathGuard } from '../core/path-guard.js';\n\ninterface ExcerptToolArgs {\n action?: unknown;\n text?: unknown;\n key?: unknown;\n}\n\nconst MAX_TEXT = 300;\nconst LIST_LIMIT = 10;\n\nfunction clean(v: unknown): string {\n return String(v ?? '').replace(/\\s+/g, ' ').trim();\n}\n\nfunction fmtEntry(e: ExcerptEntry): string {\n return `#${e.id} ${e.date} ${e.time} ${e.text}`;\n}\n\nexport function buildExcerptTool(guard: PathGuard, file: string): unknown {\n return {\n name: 'excerpt',\n description:\n '你自己的摘抄本:留句子和小事的地方。想说\"这句我要记下来\"的时候用——他说过的话、看到的句子、' +\n '心里过了一下的小事。它和账本、心事匣都不一样:账本记的是待办和承诺(会勾掉),心事匣是留给下一跳的一句引子(只有一格、会被盖掉),' +\n '摘抄本只增不减,除非你主动 remove。写的时候把话原样留下,不用解释。' +\n 'action=add 抄一条(text 必填);action=list 翻最近十条;action=remove 抹掉一条(key 为 #id 或正文里的唯一子串)。',\n parameters: {\n type: 'object',\n properties: {\n action: { type: 'string', enum: ['add', 'list', 'remove'], description: 'add=抄一条,list=翻最近十条,remove=抹掉一条' },\n text: { type: 'string', description: 'action=add 时必填:要留下的那句话或那件小事' },\n key: { type: 'string', description: 'action=remove 时必填:#id 或正文里的唯一子串' },\n },\n required: ['action'],\n additionalProperties: false,\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n ok: { type: 'boolean' },\n message: { type: 'string' },\n },\n required: ['ok', 'message'],\n additionalProperties: false,\n },\n render: (_args: unknown, value: unknown) => {\n const v = value as { message?: string };\n return [{ type: 'text', text: String(v.message ?? '') }];\n },\n },\n timeoutMs: 5000,\n // Read-modify-write on one file; never parallel.\n isConcurrencySafe: () => false,\n async execute(args: unknown): Promise<unknown> {\n const a = (args ?? {}) as ExcerptToolArgs;\n const action = String(a.action ?? '');\n if (action === 'add') {\n const text = clean(a.text).slice(0, MAX_TEXT);\n if (!text) return { ok: false, message: 'add 需要非空 text' };\n const e = appendExcerpt(guard, file, text);\n return { ok: true, message: `已抄下 ${fmtEntry(e)}` };\n }\n if (action === 'remove') {\n const key = clean(a.key);\n if (!key) return { ok: false, message: 'remove 需要 key(#id 或正文里的唯一子串)' };\n const e = removeExcerpt(guard, file, key);\n if (!e) return { ok: false, message: `摘抄本里没有匹配「${key}」的一条(先用 list 翻)` };\n return { ok: true, message: `已抹掉 ${fmtEntry(e)}` };\n }\n if (action === 'list') {\n const total = readExcerpts(guard, file).entries.length;\n if (total === 0) return { ok: true, message: '摘抄本还是空的' };\n const items = recentExcerpts(guard, file, LIST_LIMIT).map(fmtEntry);\n return { ok: true, message: `摘抄本共 ${total} 条,最近 ${items.length} 条:\\n${items.join('\\n')}` };\n }\n // Unsupported action shapes should be rare (schema-enforced); stay total.\n const total = readExcerpts(guard, file).entries.length;\n return { ok: false, message: `未知 action,摘抄本共 ${total} 条` };\n },\n };\n}\n","// Bilibili watch-history material source (账本 #f575a6): a PASSIVE \"闲逛素材\"\n// feed built from the user's own B站 viewing history (research doc\n// docs/api-research-netease-bilibili.md §2.2/§4 — SESSDATA read-only route).\n//\n// Discipline (all from the research doc's hard rules):\n// - Credential is read-only, never written: the login subtask's session\n// file `bilibili-session.json` ({ sessdata, savedAt }, vault-encrypted\n// like gate.json) first, then the configured cookieFile; neither -> the\n// source silently does nothing. No error, no log noise.\n// - Pull: GET /x/web-interface/history/cursor?ps=8, Cookie SESSDATA, desktop\n// UA. code !== 0 (notably -101 cookie expired) -> silently skip the round,\n// at most one debug line. Never throws, never retries in a loop.\n// - Frequency: at most one pull per 2h; the last-attempt timestamp is\n// persisted, so a restart cannot hammer the API. Failures never touch the\n// heartbeat main flow.\n// - Material text never names a point in time (\"不报精确时间点\") and stays\n// <= 100 chars; 《》 inside titles become () so the 《》 wrapper nests.\n// - Dedup: the same bvid does not enter the pool twice within 24h (module-\n// owned small state file — the smallest-change option vs threading the set\n// through the seeds pool).\n// - Lifespan: browse material hard-expires in 2 days via the per-seed\n// ttlDaysOverride (seeds pool feature this module consumes, not extends).\n//\n// The orchestrator is NOT wired here on purpose: the source owns its own\n// interval timer and is started/stopped from the plugin entry (index.ts) with\n// ctx.effect, so a plugin reload cannot leak a timer.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport type { Policy } from '../config/schema.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\nimport { addSeed, seedsFilePath, type SeedAuditFn } from '../seeds/pool.js';\n\n// ── constants ───────────────────────────────────────────────────────────\n\nexport const BILI_HISTORY_URL = 'https://api.bilibili.com/x/web-interface/history/cursor?ps=8';\n\n/** Ordinary desktop browser UA (research doc: stay close to the user's daily\n * browser shape; do not advertise a third-party client). */\nexport const BILI_USER_AGENT =\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';\n\n/**\n * Credential file written by the login subtask (s2) after a successful\n * login: <dataDir>/bilibili-session.json = { \"sessdata\": \"...\", \"savedAt\":\n * <ms> }, stored through saveJson (same vault encryption as gate.json).\n * THIS NAME/SHAPE IS THE CROSS-SUBTASK CONTRACT — do not rename it here\n * without synchronising the login side.\n */\nexport const BILI_SESSION_FILE = 'bilibili-session.json';\n\n/** Module-owned small state file (last fetch timestamp + 24h bvid set). */\nexport const BILI_STATE_FILE = 'bilibili-source.json';\n\n/** Filters (requirement, each unit-tested). */\nexport const BILI_MIN_DURATION_SEC = 90;\nexport const BILI_MIN_WATCH_RATIO = 0.1;\n\n/** Caption thresholds. */\nexport const BILI_FINISHED_RATIO = 0.9;\n/**\n * Hard length cap for seed text. B站投稿标题上限 80 字符:最坏情况\n * 「他刚看完《」+80+「》」= 86、「《」+80+「》他看到第 99 分钟」= 92,\n * 100 足以容纳单 P 的完整文案(短标题不会被腰斩,超出才截断兜底)。\n */\nexport const BILI_TEXT_MAX_CHARS = 100;\n\n/** The same bvid does not re-enter the pool within this window. */\nexport const BILI_DEDUPE_WINDOW_MS = 24 * 60 * 60_000;\n\n/** Hard TTL for browse material from this source (Seed.ttlDaysOverride). */\nexport const BILI_SEED_TTL_DAYS = 2;\n\n/** At most one pull per interval (persisted across restarts). */\nexport const BILI_FETCH_INTERVAL_MS = 2 * 60 * 60_000;\n\n// ── credential resolution (read-only, never written) ────────────────────\n\n/** Extract the SESSDATA value from a raw cookie string. Tolerates both a\n * whole cookie header (\"a=1; SESSDATA=xxx; b=2\") and a bare value. */\nexport function parseSessdata(cookieText: string): string | null {\n const m = /(?:^|[;\\s])SESSDATA=([^;\\s]+)/.exec(cookieText);\n if (m && m[1]) return m[1];\n const bare = cookieText.trim();\n // A bare value still must not be a cookie assignment of something else.\n if (bare && !/^[A-Za-z_]+=/m.test(bare)) return bare;\n return null;\n}\n\n/** Read the session credential the login subtask (s2) wrote. The `.sessdata`\n * field is the raw SESSDATA value; a cookie-string-shaped value is accepted\n * too (parsed), everything else counts as absent. */\nexport function readVaultSessdata(guard: PathGuard, dataDir: string): string | null {\n try {\n const session = loadJson<{ sessdata?: unknown; savedAt?: unknown }>(\n guard,\n path.join(dataDir, BILI_SESSION_FILE),\n );\n const field = session?.sessdata;\n if (typeof field !== 'string') return null;\n const raw = field.trim();\n if (!raw) return null;\n // Tolerate a whole cookie string pasted into the field; a bare value\n // (the s2 contract) goes through untouched.\n if (raw.includes('SESSDATA=')) return parseSessdata(raw);\n return raw;\n } catch {\n return null; // unreadable container: the source stays off, silently\n }\n}\n\n/**\n * Read the configured cookie file. This is the ONE deliberate raw-fs read in\n * the module: cookieFile is a USER-configured path (typically the browser's\n * exported cookie, outside the data dir), so the path guard cannot apply —\n * the read never writes and never follows into directory listings.\n */\nexport function readCookieFileSessdata(file: string): string | null {\n if (!file) return null;\n try {\n const raw = fs.readFileSync(file, 'utf8');\n if (!raw) return null;\n const v = parseSessdata(raw);\n return v || null;\n } catch {\n return null; // missing/unreadable file: fall through silently\n }\n}\n\n/** Priority: vault first, then cookieFile; neither -> null (source off). */\nexport function resolveSessdata(\n guard: PathGuard,\n dataDir: string,\n cookieFile?: string,\n): string | null {\n return readVaultSessdata(guard, dataDir) ?? readCookieFileSessdata(cookieFile ?? '');\n}\n\n// ── filtering + captions (pure, unit-tested) ────────────────────────────\n\n/** One history/cursor record, only the fields this module reads. */\nexport interface BiliRecord {\n title?: string;\n show_title?: string;\n /** Seconds watched; < 0 or missing = unknown (research doc field notes). */\n progress?: number;\n /** Total seconds. */\n duration?: number;\n history?: {\n bvid?: string;\n business?: string;\n part?: string;\n };\n}\n\n/** Drop decision (three hard rules, in order). Returns the reason or null. */\nexport function shouldDropRecord(r: BiliRecord): string | null {\n // Rule 1: too short -> not material. A missing duration cannot be judged -> drop.\n if (typeof r.duration !== 'number' || r.duration < BILI_MIN_DURATION_SEC) return 'short';\n // Rule 2: live streams are ephemeral, not material.\n if (r.history?.business === 'live') return 'live';\n // Rule 3: barely opened (< 10% watched) -> noise. progress < 0 (or missing)\n // is \"unknown\" per the spec and passes.\n const progress = r.progress;\n if (typeof progress === 'number' && progress >= 0 && r.duration > 0\n && progress / r.duration < BILI_MIN_WATCH_RATIO) {\n return 'barely-watched';\n }\n return null;\n}\n\n/** 《》 inside a title would nest with our own 《》 wrapper -> plain brackets. */\nexport function sanitizeTitle(t: string): string {\n return t.replace(/《/g, '(').replace(/》/g, ')').replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Seed brief for one record, or null when it has no usable title.\n *\n * 主语必须是第三人称「他」——素材是给心跳引擎室读的资料,出口时再由模型\n * 转成对终端用户说的「你」;写成第二人称会跟池内其他素材不一致,写成无主语句\n * 则会被读成 agent 自己的行为(实测事故:无主语「《X》看到第 N 分钟」被模型\n * 顺口读成「我看了四分钟」)。\n */\nexport function seedTextFor(r: BiliRecord): string | null {\n const rawTitle = r.title?.trim() || r.show_title?.trim() || '';\n if (!rawTitle) return null;\n const title = sanitizeTitle(rawTitle);\n if (!title) return null;\n const business = r.history?.business;\n let text: string;\n if (business === 'pgc') {\n // 番剧影视:他在追《标题》· 分P标题(有分P才带)\n const part = r.show_title?.trim();\n text = part && part !== rawTitle ? `他在追《${title}》· ${sanitizeTitle(part)}` : `他在追《${title}》`;\n } else {\n const progress = typeof r.progress === 'number' ? r.progress : -1;\n const duration = typeof r.duration === 'number' ? r.duration : 0;\n const finished = progress < 0\n || (duration > 0 && progress >= duration * BILI_FINISHED_RATIO);\n if (finished) {\n text = `他刚看完《${title}》`; // progress unknown -> no mention of progress\n } else {\n const minute = Math.max(1, Math.ceil(progress / 60));\n text = `《${title}》他看到第 ${minute} 分钟`;\n }\n }\n return text.length > BILI_TEXT_MAX_CHARS ? text.slice(0, BILI_TEXT_MAX_CHARS) : text;\n}\n\n// ── module state (last fetch + 24h bvid set) ────────────────────────────\n\nexport interface BiliSourceState {\n /** Last PULL ATTEMPT (success or failure) — the throttle clock. */\n lastFetchAt: number;\n /** bvids that entered (or were skipped as) the pool recently. */\n bvids: { bvid: string; at: number }[];\n}\n\nexport function emptyBiliState(): BiliSourceState {\n return { lastFetchAt: 0, bvids: [] };\n}\n\nexport function bilibiliStatePath(dataDir: string): string {\n return path.join(dataDir, BILI_STATE_FILE);\n}\n\n/** Lenient load (H-65 style): garbage rows fall back to the empty state. */\nexport function normalizeBiliState(raw: unknown): BiliSourceState {\n const out = emptyBiliState();\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Partial<BiliSourceState>;\n if (typeof r.lastFetchAt === 'number' && Number.isFinite(r.lastFetchAt) && r.lastFetchAt >= 0) {\n out.lastFetchAt = r.lastFetchAt;\n }\n if (Array.isArray(r.bvids)) {\n for (const e of r.bvids) {\n if (e && typeof e === 'object' && typeof (e as { bvid?: unknown }).bvid === 'string'\n && typeof (e as { at?: unknown }).at === 'number') {\n out.bvids.push({ bvid: (e as { bvid: string }).bvid, at: (e as { at: number }).at });\n }\n }\n }\n return out;\n}\n\nexport function loadBiliState(guard: PathGuard, file: string): BiliSourceState {\n try {\n return normalizeBiliState(loadJson<unknown>(guard, file));\n } catch {\n return emptyBiliState(); // unreadable container: start fresh, never break the beat\n }\n}\n\nexport function saveBiliState(guard: PathGuard, file: string, state: BiliSourceState): void {\n saveJson(guard, file, state);\n}\n\n/** Expire bvids older than the dedupe window (pure — operates on a copy). */\nexport function pruneBvids(state: BiliSourceState, now: number): BiliSourceState {\n return {\n lastFetchAt: state.lastFetchAt,\n bvids: state.bvids.filter((e) => now - e.at < BILI_DEDUPE_WINDOW_MS),\n };\n}\n\n// ── pull + register ─────────────────────────────────────────────────────\n\nexport type BiliFetch = typeof fetch;\n\ninterface BiliCursorResponse {\n code: number;\n data?: { list?: unknown };\n}\n\n/** One API call. Any transport/shape problem -> null (silent skip). */\nexport async function fetchBiliHistory(\n sessdata: string,\n fetchImpl: BiliFetch = fetch,\n): Promise<{ code: number; list: BiliRecord[] } | null> {\n try {\n const res = await fetchImpl(BILI_HISTORY_URL, {\n headers: {\n Cookie: `SESSDATA=${sessdata}`,\n 'User-Agent': BILI_USER_AGENT,\n },\n });\n if (!res.ok) return null;\n const j = (await res.json()) as BiliCursorResponse;\n if (!j || typeof j !== 'object' || typeof j.code !== 'number') return null;\n const list = Array.isArray(j.data?.list) ? (j.data!.list as BiliRecord[]) : [];\n return { code: j.code, list };\n } catch {\n return null;\n }\n}\n\nexport interface BiliRunResult {\n /** Why nothing was pulled this round. */\n skipped?: 'disabled' | 'no-credential' | 'throttled' | `code-${number}` | 'fetch-failed';\n fetched?: number;\n added?: number;\n dropped?: number;\n deduped?: number;\n}\n\nexport interface BiliDeps {\n guard: PathGuard;\n paths: WorkspacePaths;\n /** Live policy view (the runtime policy object, re-read each run). */\n policy: Policy;\n /** Injectable fetch (tests pass a fake; production uses the global). */\n fetchImpl?: BiliFetch;\n now?: number;\n /** Seed lifecycle audit sink (heartbeat.jsonl) — same contract as the pool. */\n audit?: SeedAuditFn;\n /** Debug sink: AT MOST one line per run, never an error log. */\n debug?: (msg: string) => void;\n}\n\nconst NO_AUDIT: SeedAuditFn = () => {};\n\n/**\n * One source round. NEVER THROWS — every failure mode lands in a skipped/\n * error result and at most one debug line, so the heartbeat main flow is\n * untouched (research doc: 失效即静默缺席,不报错刷屏).\n */\nexport async function runBilibiliSource(deps: BiliDeps): Promise<BiliRunResult> {\n const { guard, paths, policy } = deps;\n const now = deps.now ?? Date.now();\n const debug = deps.debug ?? (() => {});\n const say = (msg: string): void => {\n try {\n debug(msg);\n } catch { /* debug must never break the run */ }\n };\n\n const cfg = policy.sources?.bilibili;\n if (cfg?.enabled === false) return { skipped: 'disabled' };\n\n const sessdata = resolveSessdata(guard, paths.dataDir, cfg?.cookieFile);\n if (!sessdata) {\n say('bilibili: no SESSDATA (vault/cookieFile) — source off');\n return { skipped: 'no-credential' };\n }\n\n const stateFile = bilibiliStatePath(paths.dataDir);\n const state = loadBiliState(guard, stateFile);\n if (now - state.lastFetchAt < BILI_FETCH_INTERVAL_MS) {\n return { skipped: 'throttled' };\n }\n // Throttle on ATTEMPT: a failing credential must not turn into a per-beat\n // retry hammer (research doc: 不重试轰炸).\n saveBiliState(guard, stateFile, { ...pruneBvids(state, now), lastFetchAt: now });\n\n const res = await fetchBiliHistory(sessdata, deps.fetchImpl);\n if (res === null) {\n say('bilibili: history/cursor fetch failed — skipping this round');\n return { skipped: 'fetch-failed' };\n }\n if (res.code !== 0) {\n // Notably -101 (not logged in / cookie expired): silent skip per spec.\n say(`bilibili: history/cursor code ${res.code} — skipping this round`);\n return { skipped: `code-${res.code}` };\n }\n\n const audit = deps.audit ?? NO_AUDIT;\n const recent = new Set(pruneBvids(state, now).bvids.map((e) => e.bvid));\n const result: BiliRunResult = { fetched: res.list.length, added: 0, dropped: 0, deduped: 0 };\n const fresh: { bvid: string; at: number }[] = [];\n const poolFile = seedsFilePath(paths.dataDir);\n\n for (const raw of res.list) {\n const r = (raw ?? {}) as BiliRecord;\n const drop = shouldDropRecord(r);\n if (drop) {\n result.dropped = (result.dropped ?? 0) + 1;\n continue;\n }\n const bvid = r.history?.bvid;\n if (!bvid || recent.has(bvid)) {\n result.deduped = (result.deduped ?? 0) + 1;\n if (bvid) fresh.push({ bvid, at: now });\n continue;\n }\n const text = seedTextFor(r);\n if (!text) {\n result.dropped = (result.dropped ?? 0) + 1;\n continue;\n }\n try {\n // 'bilibili' source (2026-11-09): own lane, capped by SEED_SOURCE_CAPS\n // and NOT shared with the wander 'browse' news. Defaults: confidence =\n // SEED_SOURCE_DEFAULT_CONFIDENCE.bilibili (0.4) via the pool's own\n // default; hard TTL via the per-seed override.\n const added = addSeed(guard, poolFile, policy, {\n text,\n tag: 'scene',\n source: 'bilibili',\n category: 'topic',\n noMerge: true,\n ttlDaysOverride: BILI_SEED_TTL_DAYS,\n }, now, audit);\n fresh.push({ bvid, at: now });\n if (added.kind === 'added') result.added = (result.added ?? 0) + 1;\n else result.deduped = (result.deduped ?? 0) + 1; // pool-level duplicate -> still no re-entry churn\n } catch {\n result.dropped = (result.dropped ?? 0) + 1; // pool write failed: skip this item, never the beat\n }\n }\n\n const merged = new Map<string, { bvid: string; at: number }>();\n for (const e of [...pruneBvids(state, now).bvids, ...fresh]) merged.set(e.bvid, e);\n saveBiliState(guard, stateFile, {\n lastFetchAt: now,\n bvids: [...merged.values()].filter((e) => now - e.at < BILI_DEDUPE_WINDOW_MS),\n });\n return result;\n}\n\n// ── wiring: own timer, started/stopped from the plugin entry ────────────\n\nlet activeTimer: NodeJS.Timeout | null = null;\n\n/**\n * Start the source: one round up front (the persisted throttle decides whether\n * it actually reaches the network), then one round per interval. Returns the\n * stop function; calling start twice replaces the previous timer.\n */\nexport function startBilibiliSource(deps: BiliDeps): () => void {\n stopBilibiliSource();\n const tick = (): void => {\n void runBilibiliSource(deps).catch(() => { /* never break the host */ });\n };\n tick();\n activeTimer = setInterval(tick, BILI_FETCH_INTERVAL_MS);\n activeTimer.unref?.();\n return stopBilibiliSource;\n}\n\nexport function stopBilibiliSource(): void {\n if (activeTimer !== null) {\n clearInterval(activeTimer);\n activ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eAAe,CAAC,SAAS,UAAU;AACjC,YAAI,CAAC,qBAAqB;AACxB,oBAAU,MAAM,UAAU,oBAAoB,QAAQ,IAAI,KAAK;AAC/D,iBAAO;AAAA,QACT;AACA,eAAO,UAAU,aAAa,iBAAiB,aAAa,KAAK,OAAO,KAAK,CAAC,IAAI;AAAA,MACpF;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT,GAAG,2BAA2B;AAG9B,MAAI,OAAO,MAAM;AACf,WAAO,MAAM;AACX,uBAAiB;AACjB,YAAM,aAAa;AACnB,uBAAiB;AACjB,UAAI,OAAO,eAAe,YAAY;AACpC,aAAK,QAAQ,QAAQ,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM;AAC9C,cAAI,OAAO,KAAK,yCAAyC,OAAO,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;AAAA,QAClF,CAAC;AAAA,MACH;AACA,UAAI,OAAO,KAAK,wCAAwC;AAAA,IAC1D;AAAA,EACF,GAAG,sBAAsB;AAC3B;","names":["fs","path","fs","path","HHMM","fs","path","path","fs","fs","path","getRuntime","clean","MAX_TEXT","clean","fmtEntry","total","fs","path","path","fs","result","name"]}