@kanadego/dsh-heartbeat 2.1.1 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -16
- package/client.js +275 -60
- package/dist/bili-login-XQVEE4M6.js +32 -0
- package/dist/{chunk-HE6IF6OU.js → chunk-F2XVKX55.js} +14 -1
- package/dist/chunk-F2XVKX55.js.map +1 -0
- package/dist/{chunk-63E5OYSI.js → chunk-N6SMIGYJ.js} +46 -19
- package/dist/chunk-N6SMIGYJ.js.map +1 -0
- package/dist/chunk-OCBE2AKW.js +25 -0
- package/dist/chunk-OCBE2AKW.js.map +1 -0
- package/dist/chunk-SIY3YHFY.js +221 -0
- package/dist/chunk-SIY3YHFY.js.map +1 -0
- package/dist/{chunk-XCMGPIUQ.js → chunk-WF7ZBW5C.js} +196 -70
- package/dist/chunk-WF7ZBW5C.js.map +1 -0
- package/dist/{chunk-LPPRI53J.js → chunk-XYBII5PR.js} +2 -2
- package/dist/cli/index.js +47 -14
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.js +368 -29
- package/dist/index.js.map +1 -1
- package/dist/{orchestrator-MNFCPH43.js → orchestrator-QE2XVVM6.js} +12 -4
- package/dist/{pool-MAABBHC4.js → pool-76VLAZER.js} +4 -2
- package/dist/pool-76VLAZER.js.map +1 -0
- package/package.json +5 -3
- package/dist/chunk-63E5OYSI.js.map +0 -1
- package/dist/chunk-HE6IF6OU.js.map +0 -1
- package/dist/chunk-XCMGPIUQ.js.map +0 -1
- /package/dist/{orchestrator-MNFCPH43.js.map → bili-login-XQVEE4M6.js.map} +0 -0
- /package/dist/{chunk-LPPRI53J.js.map → chunk-XYBII5PR.js.map} +0 -0
- /package/dist/{pool-MAABBHC4.js.map → orchestrator-QE2XVVM6.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/bili-login.ts"],"sourcesContent":["// `heartbeat bili login` — bilibili QR-code login (v2.2.0).\n//\n// Scans a QR code to log the user into bilibili and lands SESSDATA in the\n// vault as <dataDir>/bilibili-session.json (shape: { sessdata, savedAt }).\n// That file/field pair is a CROSS-SUBTASK contract with the data-source\n// module (it reads `sessdata` back verbatim) — rename it and you break the\n// reader, so treat it like a wire format.\n//\n// Flow (passport web QR login):\n// 1. POST-less generate: GET .../web/qrcode/generate -> { url, qrcode_key }\n// 2. Render the login url as a PNG (~400x400, margin 2) into the OS temp dir\n// 3. Open it with the platform's default viewer (spawn the system command\n// directly, no shell wrapper). No GUI / missing viewer is NOT an error:\n// print the image path, its directory and the login url so the user can\n// open it by hand, then keep polling.\n// 4. Poll .../web/qrcode/poll every 2s for up to 3 minutes. The login state\n// lives in data.code (the outer code is the API call status and stays 0\n// while the QR flow runs; data.code ?? code keeps old flat shapes\n// working):\n// 0 success -> pull SESSDATA out of Set-Cookie (preferred) or the\n// data.url query string, store it, delete the PNG\n// 86101 not scanned yet -> keep going\n// 86090 scanned, not confirmed -> keep going\n// 86038 / 86103 QR expired -> tell the user to rerun, exit non-zero\n// other unknown protocol code -> report the code only, exit non-zero\n// 5. SESSDATA never reaches a log line, an error message, or stdout — the\n// only trace of it is the ciphertext in the vault container.\n//\n// Every side effect (fetch, render, open, sleep, clock, storage) is injected\n// through BiliLoginDeps so the whole state machine runs in tests with a fake\n// fetch and a fake renderer. Only `runBiliLogin`'s default wiring touches the\n// real world; `main` (cli/index.ts) builds that wiring.\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { openerFor } from '../core/open-path.js';\nimport type { PathGuard } from '../core/path-guard.js';\nimport type { WorkspacePaths } from '../core/paths.js';\nimport { loadJson, saveJson } from '../vault/vault.js';\n\nconst GENERATE_URL = 'https://passport.bilibili.com/x/passport-login/web/qrcode/generate';\nconst POLL_URL = 'https://passport.bilibili.com/x/passport-login/web/qrcode/poll';\n\n/**\n * Where the login cookie lands. CROSS-SUBTASK CONTRACT (reviewer, q-cbcb4c51c3b20b39):\n * the data-source module reads SESSDATA back from\n * file: <dataDir>/bilibili-session.json (KHBV2 container via vault.saveJson)\n * shape: { \"sessdata\": \"<SESSDATA value>\", \"savedAt\": <ms timestamp> }\n * This file holds only the bilibili session — do not grow it into a flat key\n * table, and do not move or rename it without syncing the reader.\n */\nexport const BILI_SESSION_FILE_NAME = 'bilibili-session.json';\n\nexport function bilibiliSessionFilePath(paths: WorkspacePaths): string {\n return path.join(paths.dataDir, BILI_SESSION_FILE_NAME);\n}\n\nexport interface BiliSessionRecord {\n sessdata: string;\n savedAt: number;\n}\n\n/**\n * Write the login cookie into the vault-managed session file (KHBV2 container\n * via vault.saveJson — the cookie value never touches the disk in plaintext).\n */\nexport function saveBiliSession(guard: PathGuard, paths: WorkspacePaths, value: string): void {\n const record: BiliSessionRecord = { sessdata: value, savedAt: Date.now() };\n saveJson(guard, bilibiliSessionFilePath(paths), record);\n}\n\nexport interface BiliLoginDeps {\n fetchImpl: typeof fetch;\n /** Render `url` as a PNG at `file` (production: qrcode, 400x400, margin 2). */\n renderQrPng: (url: string, file: string) => Promise<void>;\n /** Open a file with the system viewer; false = could not (no GUI etc.). */\n openImage: (file: string) => Promise<boolean>;\n sleep: (ms: number) => Promise<void>;\n /** Line logger (stdout). Must never receive the cookie value. */\n log: (line: string) => void;\n /** Wall clock, ms. Injectable so the 3-minute deadline is testable. */\n now: () => number;\n /** Directory the QR PNG goes to (production: os.tmpdir()). */\n tmpDir?: string;\n platform: NodeJS.Platform;\n pollIntervalMs?: number;\n maxDurationMs?: number;\n /** Where the cookie is stored on success (production: vault). */\n saveCredential?: (value: string) => void;\n}\n\ninterface GenerateOk {\n code: number;\n data: { url: string; qrcode_key: string };\n}\n\ninterface PollResponse {\n code: number;\n message?: string;\n data?: { url?: string; code?: number; message?: string };\n}\n\n/**\n * Pull SESSDATA out of the poll response's Set-Cookie header(s). The cookie\n * is the primary source because it is what a browser session would carry.\n */\nexport function sessdataFromCookies(resp: Response): string | null {\n const cookies = typeof resp.headers.getSetCookie === 'function' ? resp.headers.getSetCookie() : [];\n for (const cookie of cookies) {\n const first = cookie.split(';')[0]!.trim();\n if (first.startsWith('SESSDATA=')) {\n const value = first.slice('SESSDATA='.length);\n return value.length > 0 ? value : null;\n }\n }\n return null;\n}\n\n/**\n * Fallback source: the SESSDATA query parameter on data.url (a redirect).\n * Extracted raw (URLSearchParams would percent-decode `%2C` into `,`), because\n * the value is stored and later sent as a Cookie — which carries the encoded\n * form — exactly like the Set-Cookie source above.\n */\nexport function sessdataFromUrl(url: string | undefined | null): string | null {\n if (!url) return null;\n try {\n const m = /[?&]SESSDATA=([^&]*)/.exec(new URL(url).search);\n return m && m[1]!.length > 0 ? m[1]! : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Spawn the platform's default viewer directly (win32: `cmd /c start \"\" <path>`,\n * darwin: `open <path>`, linux: `xdg-open <path>` — the same command table as\n * core/open-path.ts) and report whether the spawn went out. Unlike openPath,\n * the caller needs to KNOW about failure: the no-GUI branch must print the\n * image path + directory + login url instead of silently doing nothing.\n * The `error` event is async (ENOENT does not throw synchronously), so wait\n * for either `spawn` (success) or `error`.\n */\nexport function tryOpenImage(platform: NodeJS.Platform, file: string): Promise<boolean> {\n const opener = openerFor(platform);\n return new Promise((resolve) => {\n try {\n const child = spawn(opener.cmd, opener.args(file), { detached: true, stdio: 'ignore' });\n child.once('error', () => resolve(false));\n child.once('spawn', () => resolve(true));\n // A viewer that exits nonzero (e.g. xdg-open with no DE) still opened\n // nothing, but the spawn itself went out — same contract as openPath.\n } catch {\n resolve(false);\n }\n });\n}\n\n/** Production QR renderer: `qrcode` is pure JS, PNG straight to file. */\nasync function renderQrPngProduction(url: string, file: string): Promise<void> {\n const { default: QRCode } = await import('qrcode');\n await QRCode.toFile(file, url, { type: 'png', width: 400, margin: 2 });\n}\n\n/** Status line for a poll code, without echoing anything sensitive. */\nfunction pollStatusLine(code: number): string {\n if (code === 86101) return '等待扫码…';\n if (code === 86090) return '已扫码,请在手机上确认登录…';\n return `poll code ${code}`;\n}\n\n/**\n * The whole login flow. Returns the process exit code:\n * 0 = SESSDATA stored, 1 = expired / timed out / protocol error.\n */\nexport async function runBiliLogin(deps: BiliLoginDeps): Promise<number> {\n const pollIntervalMs = deps.pollIntervalMs ?? 2_000;\n const maxDurationMs = deps.maxDurationMs ?? 3 * 60_000;\n const platform = deps.platform;\n const tmpDir = deps.tmpDir ?? os.tmpdir();\n\n // 1. Generate.\n let gen: GenerateOk;\n try {\n const resp = await deps.fetchImpl(GENERATE_URL);\n gen = (await resp.json()) as GenerateOk;\n } catch (e) {\n deps.log(`获取二维码失败:${e instanceof Error ? e.message : String(e)}`);\n return 1;\n }\n if (gen.code !== 0 || !gen.data?.url || !gen.data?.qrcode_key) {\n deps.log(`获取二维码失败:generate code=${gen.code}`);\n return 1;\n }\n const { url, qrcode_key } = gen.data;\n\n // 2. Render the PNG into the OS temp dir.\n const pngPath = path.join(tmpDir, `bili-login-qr-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`);\n try {\n await deps.renderQrPng(url, pngPath);\n } catch (e) {\n deps.log(`二维码渲染失败:${e instanceof Error ? e.message : String(e)}`);\n return 1;\n }\n\n // 3. Try to open it; failure is a fallback, not an error.\n const opened = await deps.openImage(pngPath);\n if (!opened) {\n deps.log('无法自动打开图片(无 GUI 或缺少查看器)。请自己打开这张图用手机扫:');\n deps.log(` 图片:${pngPath}`);\n deps.log(` 目录:${path.dirname(pngPath)}`);\n deps.log(` 链接:${url}`);\n }\n\n // 4. Poll until success / expiry / deadline.\n const deadline = deps.now() + maxDurationMs;\n try {\n for (;;) {\n let poll: PollResponse | null = null;\n let resp: Response | null = null;\n try {\n resp = await deps.fetchImpl(`${POLL_URL}?qrcode_key=${encodeURIComponent(qrcode_key)}`);\n poll = (await resp.json()) as PollResponse;\n } catch (e) {\n deps.log(`轮询网络错误,重试中:${e instanceof Error ? e.message : String(e)}`);\n }\n if (poll) {\n // The login state lives in data.code; the outer code is the API call\n // status (stays 0 while the QR flow runs). Fall back to the outer code\n // for old flat shapes without data.code.\n const state = poll.data?.code ?? poll.code;\n if (state === 0) {\n // SESSDATA: Set-Cookie first, then the data.url query param.\n const value = (resp ? sessdataFromCookies(resp) : null) ?? sessdataFromUrl(poll.data?.url);\n if (!value) {\n deps.log('登录成功但响应里找不到 SESSDATA(Set-Cookie 与 data.url 都没有),未写入。');\n return 1;\n }\n deps.saveCredential?.(value);\n deps.log('登录成功。SESSDATA 已加密存入 vault(bilibili-session.json 的 sessdata 字段),未在日志中显示原文。');\n return 0;\n }\n if (state === 86038 || state === 86103) {\n deps.log('二维码已过期,请重跑 `heartbeat bili login` 生成新的二维码。');\n return 1;\n }\n if (state === 86101 || state === 86090) {\n deps.log(pollStatusLine(state));\n } else {\n // Unknown protocol code: report code only (message text is third-party).\n deps.log(`${pollStatusLine(state)},终止。`);\n return 1;\n }\n }\n if (deps.now() >= deadline) {\n deps.log('等待超时(3 分钟内未完成扫码确认),请重跑 `heartbeat bili login`。');\n return 1;\n }\n await deps.sleep(pollIntervalMs);\n }\n } finally {\n // 5. The temp PNG holds no secret, but it is a one-shot credential prompt —\n // remove it whichever way the flow ends.\n try {\n fs.rmSync(pngPath, { force: true });\n } catch {\n /* best effort */\n }\n }\n}\n\n// ── Reusable login service (panel RPC, v2.3.0) ─────────────────────────────\n// The flow above is a blocking CLI loop; the panel needs the same protocol\n// chopped into two awaited steps (start = get a QR, poll = one poll call).\n// Same wire protocol (login state in data.code, SESSDATA from Set-Cookie →\n// data.url), same vault contract via the injected saveCredential. The session\n// lives in a memory Map for 3 minutes and a poll/start sweep drops expired\n// entries; a consumed (successful) session is removed immediately, so a second\n// poll on it reports expired instead of re-saving the cookie.\n\nexport type BiliRpcPollState = 'waiting' | 'scanned' | 'success' | 'expired' | 'error';\n\nexport interface BiliRpcPollResult {\n state: BiliRpcPollState;\n /** Detail for the error state (protocol code or network message) — never the cookie. */\n message?: string;\n}\n\nexport interface BiliRpcStartResult {\n sessionId: string;\n qrDataUrl: string;\n expiresAt: number;\n}\n\nexport interface BiliLoginServiceDeps {\n fetchImpl: typeof fetch;\n /** Render the login url as a PNG data URL (production: qrcode.toDataURL). */\n renderQrDataUrl: (url: string) => Promise<string>;\n /** Wall clock, ms — also drives the 3-minute session TTL. */\n now: () => number;\n /** Where the cookie is stored on success (production: saveBiliSession). */\n saveCredential?: (value: string) => void;\n}\n\nexport interface BiliLoginService {\n startBiliLogin(): Promise<BiliRpcStartResult>;\n pollBiliLogin(sessionId: string): Promise<BiliRpcPollResult>;\n}\n\ninterface BiliRpcSession {\n qrcodeKey: string;\n expiresAt: number;\n}\n\nconst RPC_SESSION_TTL_MS = 3 * 60_000;\n\n/**\n * Two-step (start/poll) QR login for the panel. Every side effect (fetch,\n * render, clock, storage) is injected, exactly like runBiliLogin, so the whole\n * service runs in tests with a fake fetch; rpc.ts builds the production one.\n */\nexport function createBiliLoginService(deps: BiliLoginServiceDeps): BiliLoginService {\n const sessions = new Map<string, BiliRpcSession>();\n // Every start/poll sweeps: no background timer, expired entries die lazily.\n const sweep = (): void => {\n const t = deps.now();\n for (const [id, session] of sessions) {\n if (t >= session.expiresAt) sessions.delete(id);\n }\n };\n\n const startBiliLogin = async (): Promise<BiliRpcStartResult> => {\n sweep();\n const resp = await deps.fetchImpl(GENERATE_URL);\n const gen = (await resp.json()) as GenerateOk;\n if (gen.code !== 0 || !gen.data?.url || !gen.data?.qrcode_key) {\n throw new Error(`generate code=${gen.code}`);\n }\n const qrDataUrl = await deps.renderQrDataUrl(gen.data.url);\n if (!qrDataUrl.startsWith('data:image/png;base64,')) {\n throw new Error('qr renderer did not return a png data URL');\n }\n const now = deps.now();\n const sessionId = `bili-${now.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n const expiresAt = now + RPC_SESSION_TTL_MS;\n sessions.set(sessionId, { qrcodeKey: gen.data.qrcode_key, expiresAt });\n return { sessionId, qrDataUrl, expiresAt };\n };\n\n const pollBiliLogin = async (sessionId: string): Promise<BiliRpcPollResult> => {\n sweep();\n const session = sessions.get(sessionId);\n if (!session) return { state: 'expired' };\n if (deps.now() >= session.expiresAt) {\n sessions.delete(sessionId);\n return { state: 'expired' };\n }\n let resp: Response;\n let poll: PollResponse;\n try {\n resp = await deps.fetchImpl(`${POLL_URL}?qrcode_key=${encodeURIComponent(session.qrcodeKey)}`);\n poll = (await resp.json()) as PollResponse;\n } catch (e) {\n return { state: 'error', message: e instanceof Error ? e.message : String(e) };\n }\n // Same state mapping as runBiliLogin: the login state lives in data.code\n // (the outer code is the API call status); fall back for old flat shapes.\n const state = poll.data?.code ?? poll.code;\n if (state === 0) {\n const value = sessdataFromCookies(resp) ?? sessdataFromUrl(poll.data?.url);\n if (!value) return { state: 'error', message: 'no SESSDATA in poll response' };\n deps.saveCredential?.(value);\n sessions.delete(sessionId); // one-shot: never write the cookie twice\n return { state: 'success' };\n }\n if (state === 86038 || state === 86103) {\n sessions.delete(sessionId);\n return { state: 'expired' };\n }\n if (state === 86101) return { state: 'waiting' };\n if (state === 86090) return { state: 'scanned' };\n return { state: 'error', message: `poll code ${state}` };\n };\n\n return { startBiliLogin, pollBiliLogin };\n}\n\n/** Production wiring for `openImage` (platform command table). */\nexport function openImageProduction(platform: NodeJS.Platform): (file: string) => Promise<boolean> {\n return (file: string) => tryOpenImage(platform, file);\n}\n\nexport { renderQrPngProduction, GENERATE_URL, POLL_URL };\n"],"mappings":";;;;;;;;AAiCA,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AAMjB,IAAM,eAAe;AACrB,IAAM,WAAW;AAUV,IAAM,yBAAyB;AAE/B,SAAS,wBAAwB,OAA+B;AACrE,SAAO,KAAK,KAAK,MAAM,SAAS,sBAAsB;AACxD;AAWO,SAAS,gBAAgB,OAAkB,OAAuB,OAAqB;AAC5F,QAAM,SAA4B,EAAE,UAAU,OAAO,SAAS,KAAK,IAAI,EAAE;AACzE,WAAS,OAA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AAK;AAAA,IAC1B,SAAS,GAAG;AACV,aAAO,EAAE,OAAO,SAAS,SAAS,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,EAAE;AAAA,IAC/E;AAGA,UAAM,QAAQ,KAAK,MAAM,QAAQ,KAAK;AACtC,QAAI,UAAU,GAAG;AACf,YAAM,QAAQ,oBAAoB,IAAI,KAAK,gBAAgB,KAAK,MAAM,GAAG;AACzE,UAAI,CAAC,MAAO,QAAO,EAAE,OAAO,SAAS,SAAS,+BAA+B;AAC7E,WAAK,iBAAiB,KAAK;AAC3B,eAAS,OAAO,SAAS;AACzB,aAAO,EAAE,OAAO,UAAU;AAAA,IAC5B;AACA,QAAI,UAAU,SAAS,UAAU,OAAO;AACtC,eAAS,OAAO,SAAS;AACzB,aAAO,EAAE,OAAO,UAAU;AAAA,IAC5B;AACA,QAAI,UAAU,MAAO,QAAO,EAAE,OAAO,UAAU;AAC/C,QAAI,UAAU,MAAO,QAAO,EAAE,OAAO,UAAU;AAC/C,WAAO,EAAE,OAAO,SAAS,SAAS,aAAa,KAAK,GAAG;AAAA,EACzD;AAEA,SAAO,EAAE,gBAAgB,cAAc;AACzC;AAGO,SAAS,oBAAoB,UAA+D;AACjG,SAAO,CAAC,SAAiB,aAAa,UAAU,IAAI;AACtD;","names":[]}
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
sendNewMessageHint,
|
|
23
23
|
sendWeeklyReadyHint,
|
|
24
24
|
weeklyDue
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-XYBII5PR.js";
|
|
26
26
|
import {
|
|
27
27
|
getRuntime
|
|
28
28
|
} from "./chunk-3QJJRXIR.js";
|
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
loadPool,
|
|
34
34
|
seedsFilePath,
|
|
35
35
|
surfaceSeed
|
|
36
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-N6SMIGYJ.js";
|
|
37
37
|
import {
|
|
38
38
|
resolveFocusUntil
|
|
39
39
|
} from "./chunk-LQKOYTRL.js";
|
|
@@ -63,6 +63,7 @@ import {
|
|
|
63
63
|
} from "./chunk-ECXYNTEV.js";
|
|
64
64
|
import {
|
|
65
65
|
decryptFile,
|
|
66
|
+
dshHomeDir,
|
|
66
67
|
encryptFile,
|
|
67
68
|
loadEncryptedText,
|
|
68
69
|
loadJson,
|
|
@@ -79,8 +80,8 @@ import {
|
|
|
79
80
|
|
|
80
81
|
// src/core/orchestrator.ts
|
|
81
82
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
82
|
-
import
|
|
83
|
-
import
|
|
83
|
+
import fs9 from "fs";
|
|
84
|
+
import path11 from "path";
|
|
84
85
|
|
|
85
86
|
// src/env/envpulse.ts
|
|
86
87
|
import fs2 from "fs";
|
|
@@ -244,47 +245,81 @@ function readPulse(guard, paths) {
|
|
|
244
245
|
}
|
|
245
246
|
}
|
|
246
247
|
|
|
247
|
-
// src/
|
|
248
|
+
// src/core/archived-sessions.ts
|
|
248
249
|
import fs3 from "fs";
|
|
249
250
|
import path3 from "path";
|
|
251
|
+
function parseArchivedSessionIds(text) {
|
|
252
|
+
try {
|
|
253
|
+
const j = JSON.parse(text);
|
|
254
|
+
const raw = j.global?.archivedSessionIds;
|
|
255
|
+
if (!Array.isArray(raw)) return /* @__PURE__ */ new Set();
|
|
256
|
+
return new Set(raw.map((s) => String(s)));
|
|
257
|
+
} catch {
|
|
258
|
+
return /* @__PURE__ */ new Set();
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function loadArchivedSessionIds(registryFile) {
|
|
262
|
+
const file = registryFile ?? path3.join(dshHomeDir(), "storages", "workspace.json");
|
|
263
|
+
try {
|
|
264
|
+
return parseArchivedSessionIds(fs3.readFileSync(file, "utf8"));
|
|
265
|
+
} catch {
|
|
266
|
+
return /* @__PURE__ */ new Set();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function isArchivedSession(archived, id) {
|
|
270
|
+
return archived.has(id) || archived.has(id.replace(/^session-/, ""));
|
|
271
|
+
}
|
|
272
|
+
function splitDeliverTargets(all, archived) {
|
|
273
|
+
const usable = [];
|
|
274
|
+
const skipped = [];
|
|
275
|
+
for (const t of all) {
|
|
276
|
+
if (isArchivedSession(archived, t.sessionId)) skipped.push(t);
|
|
277
|
+
else usable.push(t);
|
|
278
|
+
}
|
|
279
|
+
return { usable, skipped };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/screen/screenpulse.ts
|
|
283
|
+
import fs4 from "fs";
|
|
284
|
+
import path4 from "path";
|
|
250
285
|
var SCREEN_JSON = "screen.json";
|
|
251
286
|
var SCREEN_JPG = "screen.jpg";
|
|
252
287
|
function screenJsonPath(paths) {
|
|
253
|
-
return
|
|
288
|
+
return path4.join(paths.dataDir, SCREEN_JSON);
|
|
254
289
|
}
|
|
255
290
|
function screenJpgPath(paths) {
|
|
256
|
-
return
|
|
291
|
+
return path4.join(paths.dataDir, SCREEN_JPG);
|
|
257
292
|
}
|
|
258
293
|
var SCREEN_STAMP = "screen.capture";
|
|
259
294
|
function screenStampPath(paths) {
|
|
260
|
-
return
|
|
295
|
+
return path4.join(paths.dataDir, SCREEN_STAMP);
|
|
261
296
|
}
|
|
262
297
|
function readScreenStamp(paths) {
|
|
263
298
|
try {
|
|
264
|
-
return
|
|
299
|
+
return fs4.readFileSync(screenStampPath(paths), "utf8").trim();
|
|
265
300
|
} catch {
|
|
266
301
|
return "";
|
|
267
302
|
}
|
|
268
303
|
}
|
|
269
304
|
function shotIsCurrent(guard, paths) {
|
|
270
305
|
const f = screenJpgPath(paths);
|
|
271
|
-
if (!
|
|
306
|
+
if (!fs4.existsSync(guard.assert(f))) return false;
|
|
272
307
|
const stamp = readScreenStamp(paths);
|
|
273
308
|
const capturedAt = readScreenJson(guard, paths)?.captured_at ?? "";
|
|
274
309
|
return Boolean(stamp) && stamp === capturedAt;
|
|
275
310
|
}
|
|
276
311
|
function dropStaleShot(guard, paths) {
|
|
277
312
|
burnFileSync(guard.assert(screenJpgPath(paths)));
|
|
278
|
-
|
|
313
|
+
fs4.rmSync(screenStampPath(paths), { force: true });
|
|
279
314
|
}
|
|
280
315
|
async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, signal) {
|
|
281
|
-
const rawJson =
|
|
282
|
-
const rawJpg =
|
|
316
|
+
const rawJson = path4.join(paths.tmpDir, "screen.raw.json");
|
|
317
|
+
const rawJpg = path4.join(paths.tmpDir, "screen.raw.jpg");
|
|
283
318
|
let encJson = "";
|
|
284
319
|
let shotThisBeat = false;
|
|
285
320
|
try {
|
|
286
321
|
const r = await runPowerShellFile(
|
|
287
|
-
|
|
322
|
+
path4.join(paths.assetsDir, "screenpulse.ps1"),
|
|
288
323
|
["-outdir", paths.tmpDir, "-cap", String(windowCap)],
|
|
289
324
|
45e3,
|
|
290
325
|
signal
|
|
@@ -296,12 +331,12 @@ async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, sig
|
|
|
296
331
|
dropStaleShot(guard, paths);
|
|
297
332
|
return { ok: false, capturedAt: null, hasShot: false, visibleCount: 0, error: `collector exit ${r.status}` };
|
|
298
333
|
}
|
|
299
|
-
const raw =
|
|
334
|
+
const raw = fs4.readFileSync(rawJson, "utf8");
|
|
300
335
|
const meta = JSON.parse(raw);
|
|
301
|
-
if (meta.shot_path &&
|
|
336
|
+
if (meta.shot_path && fs4.existsSync(meta.shot_path)) {
|
|
302
337
|
try {
|
|
303
338
|
encryptFile(guard, meta.shot_path, screenJpgPath(paths));
|
|
304
|
-
|
|
339
|
+
fs4.writeFileSync(
|
|
305
340
|
screenStampPath(paths),
|
|
306
341
|
String(meta.captured_at ?? new Date(now).toISOString()),
|
|
307
342
|
"utf8"
|
|
@@ -313,8 +348,8 @@ async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, sig
|
|
|
313
348
|
if (!shotThisBeat) dropStaleShot(guard, paths);
|
|
314
349
|
const { shot_path: _drop, ...clean } = meta;
|
|
315
350
|
void _drop;
|
|
316
|
-
encJson =
|
|
317
|
-
|
|
351
|
+
encJson = path4.join(paths.tmpDir, `screen.enc.${now}.json`);
|
|
352
|
+
fs4.writeFileSync(encJson, JSON.stringify(clean, null, 1), "utf8");
|
|
318
353
|
encryptFile(guard, encJson, screenJsonPath(paths));
|
|
319
354
|
return {
|
|
320
355
|
ok: true,
|
|
@@ -327,17 +362,17 @@ async function collectScreen(guard, paths, now = Date.now(), windowCap = 20, sig
|
|
|
327
362
|
return { ok: false, capturedAt: null, hasShot: false, visibleCount: 0, error: String(e) };
|
|
328
363
|
} finally {
|
|
329
364
|
for (const leftover of [rawJson, rawJpg, encJson]) {
|
|
330
|
-
|
|
365
|
+
fs4.rmSync(leftover, { force: true });
|
|
331
366
|
}
|
|
332
367
|
}
|
|
333
368
|
}
|
|
334
369
|
function readScreenJson(guard, paths) {
|
|
335
370
|
const f = screenJsonPath(paths);
|
|
336
|
-
if (!
|
|
337
|
-
const tmp =
|
|
371
|
+
if (!fs4.existsSync(guard.assert(f))) return null;
|
|
372
|
+
const tmp = path4.join(paths.tmpDir, `screen.read.${Date.now()}.json`);
|
|
338
373
|
try {
|
|
339
374
|
decryptFile(guard, f, guard.assert(tmp));
|
|
340
|
-
return JSON.parse(
|
|
375
|
+
return JSON.parse(fs4.readFileSync(tmp, "utf8"));
|
|
341
376
|
} catch {
|
|
342
377
|
return null;
|
|
343
378
|
} finally {
|
|
@@ -347,7 +382,7 @@ function readScreenJson(guard, paths) {
|
|
|
347
382
|
function unlockShot(guard, paths) {
|
|
348
383
|
const f = screenJpgPath(paths);
|
|
349
384
|
if (!shotIsCurrent(guard, paths)) return null;
|
|
350
|
-
const tmp =
|
|
385
|
+
const tmp = path4.join(paths.tmpDir, `screen.view.${Date.now()}.jpg`);
|
|
351
386
|
try {
|
|
352
387
|
decryptFile(guard, f, guard.assert(tmp));
|
|
353
388
|
} catch (e) {
|
|
@@ -362,8 +397,8 @@ function burnUnlocked(guard, tmpPath) {
|
|
|
362
397
|
|
|
363
398
|
// src/screen/vision.ts
|
|
364
399
|
import { createRequire } from "module";
|
|
365
|
-
import
|
|
366
|
-
import
|
|
400
|
+
import fs5 from "fs";
|
|
401
|
+
import path5 from "path";
|
|
367
402
|
import { spawn } from "child_process";
|
|
368
403
|
var VISION_TIMEOUT_MS = 12e4;
|
|
369
404
|
var VISION_MAX_SUMMARY = 300;
|
|
@@ -371,8 +406,8 @@ function resolveModlensMain(fromUrl) {
|
|
|
371
406
|
try {
|
|
372
407
|
const req = createRequire(fromUrl);
|
|
373
408
|
const pkgJson = req.resolve("@liustack/modlens/package.json");
|
|
374
|
-
const main =
|
|
375
|
-
return
|
|
409
|
+
const main = path5.join(path5.dirname(pkgJson), "dist", "main.js");
|
|
410
|
+
return fs5.existsSync(main) ? main : null;
|
|
376
411
|
} catch {
|
|
377
412
|
return null;
|
|
378
413
|
}
|
|
@@ -410,7 +445,7 @@ function extractSummary(raw) {
|
|
|
410
445
|
var DEFAULT_VISION_PROVIDER = "openai";
|
|
411
446
|
function readVisionSettings(guard, paths) {
|
|
412
447
|
try {
|
|
413
|
-
const raw =
|
|
448
|
+
const raw = fs5.readFileSync(guard.assert(path5.join(paths.settingsDir, "vision.json")), "utf8");
|
|
414
449
|
const obj = JSON.parse(raw);
|
|
415
450
|
return {
|
|
416
451
|
...typeof obj.provider === "string" && obj.provider.trim() ? { provider: obj.provider.trim() } : {},
|
|
@@ -423,7 +458,7 @@ function readVisionSettings(guard, paths) {
|
|
|
423
458
|
async function describeScreenShot(guard, paths, opts) {
|
|
424
459
|
const mainJs = opts.mainPath ?? resolveModlensMain(opts.moduleUrl);
|
|
425
460
|
if (!mainJs) return { ok: false, summary: null, error: "modlens not installed" };
|
|
426
|
-
const outJson =
|
|
461
|
+
const outJson = path5.join(paths.tmpDir, `screen.vision.${Date.now()}.json`);
|
|
427
462
|
const spawnCli = opts.spawnCli ?? defaultSpawn;
|
|
428
463
|
const timeoutMs = opts.timeoutMs ?? VISION_TIMEOUT_MS;
|
|
429
464
|
const settings = opts.settings ?? readVisionSettings(guard, paths);
|
|
@@ -451,7 +486,7 @@ async function describeScreenShot(guard, paths, opts) {
|
|
|
451
486
|
if (code !== 0) {
|
|
452
487
|
return { ok: false, summary: null, error: `modlens exit ${code}${stderr ? `: ${stderr.slice(0, 140)}` : ""}` };
|
|
453
488
|
}
|
|
454
|
-
const raw =
|
|
489
|
+
const raw = fs5.existsSync(outJson) ? fs5.readFileSync(outJson, "utf8") : "";
|
|
455
490
|
const summary = extractSummary(raw);
|
|
456
491
|
if (!summary) return { ok: false, summary: null, error: "modlens produced no summary" };
|
|
457
492
|
return { ok: true, summary };
|
|
@@ -459,16 +494,16 @@ async function describeScreenShot(guard, paths, opts) {
|
|
|
459
494
|
return { ok: false, summary: null, error: String(e).slice(0, 160) };
|
|
460
495
|
} finally {
|
|
461
496
|
if (shot) burnUnlocked(guard, shot);
|
|
462
|
-
|
|
497
|
+
fs5.rmSync(outJson, { force: true });
|
|
463
498
|
}
|
|
464
499
|
}
|
|
465
500
|
|
|
466
501
|
// src/gate/gate.ts
|
|
467
|
-
import
|
|
468
|
-
import
|
|
502
|
+
import path6 from "path";
|
|
503
|
+
import fs6 from "fs";
|
|
469
504
|
var STABLE_WINDOW_MS = 15e3;
|
|
470
505
|
function sentFilePath(paths) {
|
|
471
|
-
return
|
|
506
|
+
return path6.join(paths.dataDir, "sent.json");
|
|
472
507
|
}
|
|
473
508
|
function localDay(now) {
|
|
474
509
|
const d = new Date(now);
|
|
@@ -511,16 +546,16 @@ function evaluateGate(input) {
|
|
|
511
546
|
};
|
|
512
547
|
}
|
|
513
548
|
async function probeFrontWindowLive(guard, paths, signal) {
|
|
514
|
-
const tmp =
|
|
549
|
+
const tmp = path6.join(paths.tmpDir, `frontwin.${Date.now()}.json`);
|
|
515
550
|
try {
|
|
516
551
|
const out = guard.assert(tmp);
|
|
517
|
-
const r = await runPowerShellFile(
|
|
518
|
-
if (r.status !== 0 || !
|
|
519
|
-
return JSON.parse(
|
|
552
|
+
const r = await runPowerShellFile(path6.join(paths.assetsDir, "frontwin.ps1"), ["-out", out], 1e4, signal);
|
|
553
|
+
if (r.status !== 0 || !fs6.existsSync(out)) return null;
|
|
554
|
+
return JSON.parse(fs6.readFileSync(out, "utf8"));
|
|
520
555
|
} catch {
|
|
521
556
|
return null;
|
|
522
557
|
} finally {
|
|
523
|
-
|
|
558
|
+
fs6.rmSync(tmp, { force: true });
|
|
524
559
|
}
|
|
525
560
|
}
|
|
526
561
|
function probeFrontWindowSnapshot(guard, paths, rules) {
|
|
@@ -610,10 +645,23 @@ function shuffle(items, rand) {
|
|
|
610
645
|
}
|
|
611
646
|
return out;
|
|
612
647
|
}
|
|
648
|
+
var BILI_TOPIC_SOFT_CAP = 2;
|
|
613
649
|
function assembleCandidates(seeds, opts = {}) {
|
|
614
650
|
const rand = opts.rand ?? Math.random;
|
|
615
651
|
const cat = (s) => s.category ?? "topic";
|
|
616
|
-
const
|
|
652
|
+
const isBili = (s) => s.source === "bilibili";
|
|
653
|
+
const shuffled = shuffle(seeds.filter((s) => cat(s) === "topic"), rand);
|
|
654
|
+
const head = [];
|
|
655
|
+
const tail = [];
|
|
656
|
+
let biliSeen = 0;
|
|
657
|
+
for (const s of shuffled) {
|
|
658
|
+
if (isBili(s) && biliSeen >= BILI_TOPIC_SOFT_CAP) tail.push(s);
|
|
659
|
+
else {
|
|
660
|
+
if (isBili(s)) biliSeen += 1;
|
|
661
|
+
head.push(s);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
const topicPool = [...head, ...tail];
|
|
617
665
|
const chatPool = seeds.filter((s) => cat(s) === "chat").sort((a, b) => Date.parse(b.lastEvidenceAt) - Date.parse(a.lastEvidenceAt));
|
|
618
666
|
const topic = topicPool.slice(0, 4);
|
|
619
667
|
const chat = chatPool.slice(0, 2);
|
|
@@ -712,12 +760,12 @@ function reconcileDelivery(materials, report, decisionIds, spokeText) {
|
|
|
712
760
|
function buildRuminationPrompt(input) {
|
|
713
761
|
const max = input.max ?? 3;
|
|
714
762
|
const lines = [
|
|
715
|
-
"\u8FD9\u662F\u5FC3\u8DF3\u8F6E\u6B21\u7684\u53CD\u520D\u5907\u6599\u73AF\u8282:\u4ECE\u5019\u9009\u7D20\u6750\u91CC\u6311(\u6700\u591A " + max + " \u6761),\
|
|
763
|
+
"\u8FD9\u662F\u5FC3\u8DF3\u8F6E\u6B21\u7684\u53CD\u520D\u5907\u6599\u73AF\u8282:\u4ECE\u5019\u9009\u7D20\u6750\u91CC\u6311(\u6700\u591A " + max + " \u6761),\u9009\u51FA\u6700\u60F3\u8BF4\u7684\u51E0\u6761\u3002",
|
|
716
764
|
"\u7D20\u6750\u53EA\u4ECE\u4E0B\u9762\u7ED9\u7684\u5019\u9009\u91CC\u6311,\u4E0D\u8981\u81EA\u5DF1\u7F16;\u6CA1\u5408\u9002\u7684\u5C31\u5C11\u6311,\u751A\u81F3\u53EF\u4EE5\u4E0D\u6311\u3002",
|
|
717
765
|
"\u4E0D\u8981\u4F7F\u7528\u4EFB\u4F55\u5DE5\u5177\u3002\u53EA\u8F93\u51FA\u4E00\u4E2A JSON \u5BF9\u8C61:",
|
|
718
|
-
'- \u6709\u60F3\u9012\u7684:{"
|
|
719
|
-
'- \u4E00\u6761\u90FD\u4E0D\u5408\u9002:{"
|
|
720
|
-
"-
|
|
766
|
+
'- \u6709\u60F3\u9012\u7684:{"seed_ids":["s1","s2"],"doing":"\u4ED6\u6B64\u523B\u5728\u5E72\u4EC0\u4E48(\u4E00\u53E5\u8BDD)"}',
|
|
767
|
+
'- \u4E00\u6761\u90FD\u4E0D\u5408\u9002:{"seed_ids":[],"doing":"\u4ED6\u6B64\u523B\u5728\u5E72\u4EC0\u4E48(\u4E00\u53E5\u8BDD)"}',
|
|
768
|
+
"- seed_ids = \u5BF9\u5E94\u7684\u7D20\u6750 id\u3002",
|
|
721
769
|
"",
|
|
722
770
|
"## \u6B64\u523B\u5904\u5883",
|
|
723
771
|
input.digestTact,
|
|
@@ -749,10 +797,10 @@ function buildRuminationPrompt(input) {
|
|
|
749
797
|
}
|
|
750
798
|
|
|
751
799
|
// src/seeds/report.ts
|
|
752
|
-
import
|
|
800
|
+
import path7 from "path";
|
|
753
801
|
var REPORT_REASONS = ["\u4E0D\u60F3\u8BF4\u8BDD", "\u7D20\u6750\u4E0D\u642D", "\u5728\u5FD9\u6216\u521A\u804A\u8FC7"];
|
|
754
802
|
function reportFilePath(dataDir) {
|
|
755
|
-
return
|
|
803
|
+
return path7.join(dataDir, "seed_report.jsonl");
|
|
756
804
|
}
|
|
757
805
|
var REPORT_KEEP = 400;
|
|
758
806
|
function parseEntry(obj) {
|
|
@@ -868,9 +916,9 @@ function buildSeedReportTool(guard, file) {
|
|
|
868
916
|
}
|
|
869
917
|
|
|
870
918
|
// src/notepad/store.ts
|
|
871
|
-
import
|
|
919
|
+
import path8 from "path";
|
|
872
920
|
function notepadFilePath(dataDir) {
|
|
873
|
-
return
|
|
921
|
+
return path8.join(dataDir, "notepad.json");
|
|
874
922
|
}
|
|
875
923
|
function emptyState() {
|
|
876
924
|
return { note: null, counters: { beats: 0, delivers: 0 } };
|
|
@@ -968,8 +1016,8 @@ function notepadView(st, now = Date.now()) {
|
|
|
968
1016
|
}
|
|
969
1017
|
|
|
970
1018
|
// src/statusbar/store.ts
|
|
971
|
-
import
|
|
972
|
-
import
|
|
1019
|
+
import fs7 from "fs";
|
|
1020
|
+
import path9 from "path";
|
|
973
1021
|
function deriveScene(input) {
|
|
974
1022
|
if (input.quietHours) return "quiet-hours";
|
|
975
1023
|
if (input.spokeThisBeat) return "just-spoke";
|
|
@@ -984,14 +1032,14 @@ function clampNote(note) {
|
|
|
984
1032
|
return t.length <= 30 ? t : t.slice(0, 30);
|
|
985
1033
|
}
|
|
986
1034
|
function statusFilePath(dataDir) {
|
|
987
|
-
return
|
|
1035
|
+
return path9.join(dataDir, "settings", "status.json");
|
|
988
1036
|
}
|
|
989
1037
|
function writeStatus(guard, paths, state) {
|
|
990
1038
|
atomicWriteJsonSync(guard.assert(statusFilePath(paths.dataDir)), state);
|
|
991
1039
|
}
|
|
992
1040
|
function readStatus(guard, paths) {
|
|
993
1041
|
try {
|
|
994
|
-
const raw =
|
|
1042
|
+
const raw = fs7.readFileSync(guard.assert(statusFilePath(paths.dataDir)), "utf8");
|
|
995
1043
|
const parsed = JSON.parse(raw);
|
|
996
1044
|
if (typeof parsed?.at !== "string" || typeof parsed?.scene !== "string") return null;
|
|
997
1045
|
return parsed;
|
|
@@ -1007,7 +1055,7 @@ var StatusReader = class {
|
|
|
1007
1055
|
const file = statusFilePath(paths.dataDir);
|
|
1008
1056
|
let st;
|
|
1009
1057
|
try {
|
|
1010
|
-
st =
|
|
1058
|
+
st = fs7.statSync(guard.assert(file));
|
|
1011
1059
|
} catch {
|
|
1012
1060
|
this.mtimeMs = -1;
|
|
1013
1061
|
this.cached = null;
|
|
@@ -1218,7 +1266,7 @@ async function runConsolidation(guard, paths, policy, llm, now = Date.now()) {
|
|
|
1218
1266
|
rejected,
|
|
1219
1267
|
entries: [...report.entries ?? [], ...aged.entries]
|
|
1220
1268
|
});
|
|
1221
|
-
const { addSeed: addSeed2, seedsFilePath: seedsFilePath2 } = await import("./pool-
|
|
1269
|
+
const { addSeed: addSeed2, seedsFilePath: seedsFilePath2 } = await import("./pool-76VLAZER.js");
|
|
1222
1270
|
const seedAudit = (entry) => {
|
|
1223
1271
|
try {
|
|
1224
1272
|
appendAuditLine(paths.dataDir + "/logs/heartbeat.jsonl", entry);
|
|
@@ -1272,19 +1320,19 @@ async function runConsolidation(guard, paths, policy, llm, now = Date.now()) {
|
|
|
1272
1320
|
}
|
|
1273
1321
|
|
|
1274
1322
|
// src/rhythm/rhythm.ts
|
|
1275
|
-
import
|
|
1276
|
-
import
|
|
1323
|
+
import fs8 from "fs";
|
|
1324
|
+
import path10 from "path";
|
|
1277
1325
|
var DAY_MS = 864e5;
|
|
1278
1326
|
var TAU_DAYS = 10;
|
|
1279
1327
|
var CELL_EPSILON = 1e-3;
|
|
1280
1328
|
var PEAK_MIN_ACTIVE = 0.25;
|
|
1281
1329
|
var PEAK_MIN_SHARE = 0.05;
|
|
1282
1330
|
function rhythmFilePath(paths) {
|
|
1283
|
-
return
|
|
1331
|
+
return path10.join(paths.dataDir, "profile_rhythm.json");
|
|
1284
1332
|
}
|
|
1285
1333
|
function loadRhythm(paths) {
|
|
1286
1334
|
try {
|
|
1287
|
-
return JSON.parse(
|
|
1335
|
+
return JSON.parse(fs8.readFileSync(rhythmFilePath(paths), "utf8"));
|
|
1288
1336
|
} catch {
|
|
1289
1337
|
return { histogram: {}, days: [], lastDecayAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
1290
1338
|
}
|
|
@@ -1659,7 +1707,7 @@ function noteBeat(verdict, detail) {
|
|
|
1659
1707
|
lastBeat = { at: (/* @__PURE__ */ new Date()).toISOString(), verdict, ...detail };
|
|
1660
1708
|
}
|
|
1661
1709
|
function gateFilePath(paths) {
|
|
1662
|
-
return
|
|
1710
|
+
return path11.join(paths.dataDir, "gate.json");
|
|
1663
1711
|
}
|
|
1664
1712
|
function readBeatState(guard, paths) {
|
|
1665
1713
|
try {
|
|
@@ -1677,7 +1725,7 @@ function homeSessionId(guard, paths) {
|
|
|
1677
1725
|
function resetHomeSession(guard, paths, id) {
|
|
1678
1726
|
if (homeSessionId(guard, paths) !== id) return false;
|
|
1679
1727
|
try {
|
|
1680
|
-
|
|
1728
|
+
fs9.rmSync(guard.assert(gateFilePath(paths)), { force: true });
|
|
1681
1729
|
} catch {
|
|
1682
1730
|
}
|
|
1683
1731
|
appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "home_reset", oldSessionId: id });
|
|
@@ -1746,6 +1794,30 @@ function pinEngineRoomTools(deps, agentCtx, notes) {
|
|
|
1746
1794
|
}
|
|
1747
1795
|
}
|
|
1748
1796
|
}
|
|
1797
|
+
async function waitForVisibleTool(getSchemas, name, opts) {
|
|
1798
|
+
const timeoutMs = opts?.timeoutMs ?? 2e3;
|
|
1799
|
+
const pollMs = opts?.pollMs ?? 50;
|
|
1800
|
+
const now = opts?.now ?? (() => Date.now());
|
|
1801
|
+
const sleep = opts?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1802
|
+
const startedAt = now();
|
|
1803
|
+
let sawNames = [];
|
|
1804
|
+
for (; ; ) {
|
|
1805
|
+
let schemas = [];
|
|
1806
|
+
try {
|
|
1807
|
+
schemas = getSchemas() ?? [];
|
|
1808
|
+
} catch {
|
|
1809
|
+
}
|
|
1810
|
+
sawNames = schemas.map((s) => String(s?.name ?? ""));
|
|
1811
|
+
if (sawNames.includes(name)) {
|
|
1812
|
+
return { ready: true, waitedMs: now() - startedAt, sawNames };
|
|
1813
|
+
}
|
|
1814
|
+
const elapsed = now() - startedAt;
|
|
1815
|
+
if (elapsed >= timeoutMs) {
|
|
1816
|
+
return { ready: false, waitedMs: elapsed, sawNames };
|
|
1817
|
+
}
|
|
1818
|
+
await sleep(Math.min(pollMs, timeoutMs - elapsed));
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1749
1821
|
function makeHomeSetup(deps) {
|
|
1750
1822
|
const { ctx, paths } = deps;
|
|
1751
1823
|
return async (agentCtx) => {
|
|
@@ -1756,6 +1828,7 @@ function makeHomeSetup(deps) {
|
|
|
1756
1828
|
} catch (e) {
|
|
1757
1829
|
notes.push(`preset-register=threw(${String(e).slice(0, 120)})`);
|
|
1758
1830
|
}
|
|
1831
|
+
let presetMounted = false;
|
|
1759
1832
|
try {
|
|
1760
1833
|
const presets = agentCtx.get("agentPresets");
|
|
1761
1834
|
if (typeof presets?.mount !== "function") {
|
|
@@ -1764,10 +1837,26 @@ function makeHomeSetup(deps) {
|
|
|
1764
1837
|
const preset = await presets.mount(agentCtx, presetId);
|
|
1765
1838
|
const joined = preset?.id;
|
|
1766
1839
|
notes.push(`preset=mounted(${joined ?? presetId})`);
|
|
1840
|
+
presetMounted = true;
|
|
1767
1841
|
}
|
|
1768
1842
|
} catch (e) {
|
|
1769
1843
|
notes.push(`preset=threw(${String(e).slice(0, 200)})`);
|
|
1770
1844
|
}
|
|
1845
|
+
if (presetMounted) {
|
|
1846
|
+
const tools = agentCtx.get("tools");
|
|
1847
|
+
if (typeof tools?.schemas !== "function") {
|
|
1848
|
+
notes.push("toolsReady=no-api");
|
|
1849
|
+
} else {
|
|
1850
|
+
try {
|
|
1851
|
+
const wait = await waitForVisibleTool(() => tools.schemas(agentCtx) ?? [], "web_search");
|
|
1852
|
+
notes.push(
|
|
1853
|
+
wait.ready ? `toolsReady=ok(${wait.waitedMs}ms)` : `toolsReady=timeout(${wait.waitedMs}ms saw=${wait.sawNames.slice(0, 5).join(",") || "(empty)"})`
|
|
1854
|
+
);
|
|
1855
|
+
} catch (e) {
|
|
1856
|
+
notes.push(`toolsReady=threw(${String(e).slice(0, 120)})`);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1771
1860
|
pinEngineRoomTools(deps, agentCtx, notes);
|
|
1772
1861
|
ctx.logger.info("heartbeat: tool policy %s", notes.join(" "));
|
|
1773
1862
|
appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "tool_policy", policy: notes.join(" ") });
|
|
@@ -2131,7 +2220,7 @@ async function collectPhase(bc) {
|
|
|
2131
2220
|
}
|
|
2132
2221
|
function loadCursors(file) {
|
|
2133
2222
|
try {
|
|
2134
|
-
const raw = JSON.parse(
|
|
2223
|
+
const raw = JSON.parse(fs9.readFileSync(file, "utf8"));
|
|
2135
2224
|
if (raw?.version === 2 && raw.sessions && typeof raw.sessions === "object") {
|
|
2136
2225
|
const sessions = {};
|
|
2137
2226
|
for (const [id, v] of Object.entries(raw.sessions)) {
|
|
@@ -2162,6 +2251,20 @@ function spokeTextSince(session, fromSeq) {
|
|
|
2162
2251
|
}
|
|
2163
2252
|
return null;
|
|
2164
2253
|
}
|
|
2254
|
+
function turnEndKindSince(session, fromSeq) {
|
|
2255
|
+
let kind = null;
|
|
2256
|
+
for (const e of sessionEvents(session, fromSeq)) {
|
|
2257
|
+
if (e.type !== "turn/end") continue;
|
|
2258
|
+
const d = e.data;
|
|
2259
|
+
if (typeof d?.reason?.kind === "string") kind = d.reason.kind;
|
|
2260
|
+
}
|
|
2261
|
+
return kind;
|
|
2262
|
+
}
|
|
2263
|
+
function classifySilentReason(raw, turnEndKind) {
|
|
2264
|
+
if (turnEndKind === "blocked") return "target turn blocked";
|
|
2265
|
+
if (!raw.trim()) return "empty model output";
|
|
2266
|
+
return "non-Chinese output discarded";
|
|
2267
|
+
}
|
|
2165
2268
|
async function observeBoundSessions(bc) {
|
|
2166
2269
|
throwIfAborted(bc.signal, "observe");
|
|
2167
2270
|
const { deps, now } = bc;
|
|
@@ -2171,7 +2274,7 @@ async function observeBoundSessions(bc) {
|
|
|
2171
2274
|
const data = loadBindings(guard, paths.settingsDir);
|
|
2172
2275
|
const targets = observeTargets(data);
|
|
2173
2276
|
if (targets.length === 0) return;
|
|
2174
|
-
const cursorFile =
|
|
2277
|
+
const cursorFile = path11.join(paths.dataDir, "cursors.json");
|
|
2175
2278
|
const loaded = loadCursors(cursorFile);
|
|
2176
2279
|
const cursors = loaded.sessions;
|
|
2177
2280
|
if (loaded.discardedLegacy) {
|
|
@@ -2458,7 +2561,24 @@ async function deliverPackage(bc, materials, opts) {
|
|
|
2458
2561
|
const homeId = bc.agent?.session?.id ?? null;
|
|
2459
2562
|
const { loadBindings, deliverTargets } = await import("./bindings-U2M3CO2D.js");
|
|
2460
2563
|
const data = loadBindings(guard, paths.settingsDir);
|
|
2461
|
-
const
|
|
2564
|
+
const archived = loadArchivedSessionIds();
|
|
2565
|
+
const all = deliverTargets(data).filter((b) => b.sessionId !== homeId);
|
|
2566
|
+
const { usable: targets, skipped } = splitDeliverTargets(all, archived);
|
|
2567
|
+
if (skipped.length > 0) {
|
|
2568
|
+
appendAuditLine(paths.logsDir + "/heartbeat.jsonl", {
|
|
2569
|
+
event: "deliver_target_skipped",
|
|
2570
|
+
reason: "archived",
|
|
2571
|
+
targets: skipped.map((t) => t.sessionId).join(",")
|
|
2572
|
+
});
|
|
2573
|
+
}
|
|
2574
|
+
if (targets.length === 0 && all.length > 0) {
|
|
2575
|
+
appendAuditLine(paths.logsDir + "/heartbeat.jsonl", {
|
|
2576
|
+
event: "spoke_failed",
|
|
2577
|
+
reason: "all deliver targets archived"
|
|
2578
|
+
});
|
|
2579
|
+
noteBeat("spoke_failed", { reason: "all deliver targets archived" });
|
|
2580
|
+
return;
|
|
2581
|
+
}
|
|
2462
2582
|
let liveTarget = null;
|
|
2463
2583
|
for (const b of targets) {
|
|
2464
2584
|
const acquired = await acquireTargetAgent(deps, b.sessionId);
|
|
@@ -2544,8 +2664,9 @@ async function deliverPackage(bc, materials, opts) {
|
|
|
2544
2664
|
appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "preference_record_failed", error: String(e).slice(0, 120) });
|
|
2545
2665
|
}
|
|
2546
2666
|
} else {
|
|
2547
|
-
|
|
2548
|
-
|
|
2667
|
+
const silentReason = classifySilentReason(spokenRaw, turnEndKindSince(voiceAgent.session, beforeSeq));
|
|
2668
|
+
appendAuditLine(paths.logsDir + "/heartbeat.jsonl", { event: "spoke_failed", reason: silentReason });
|
|
2669
|
+
noteBeat("spoke_failed", { reason: silentReason });
|
|
2549
2670
|
}
|
|
2550
2671
|
return;
|
|
2551
2672
|
}
|
|
@@ -2677,8 +2798,7 @@ async function expressionPhases(bc) {
|
|
|
2677
2798
|
if (!Array.isArray(parsed.seed_ids) || parsed.seed_ids.length === 0) {
|
|
2678
2799
|
appendAuditLine(paths.logsDir + "/heartbeat.jsonl", {
|
|
2679
2800
|
event: "expression_dropped",
|
|
2680
|
-
why: "no seed_ids from the decision turn"
|
|
2681
|
-
speak_flag: typeof parsed.speak === "boolean" ? parsed.speak : null
|
|
2801
|
+
why: "no seed_ids from the decision turn"
|
|
2682
2802
|
});
|
|
2683
2803
|
noteDroppedStreak(paths.logsDir + "/heartbeat.jsonl", "no seed_ids from the decision turn");
|
|
2684
2804
|
noteBeat("silent", { reason: "no material" });
|
|
@@ -2798,7 +2918,7 @@ async function userActiveInBoundSessions(deps) {
|
|
|
2798
2918
|
const { loadBindings, observeTargets } = await import("./bindings-U2M3CO2D.js");
|
|
2799
2919
|
const targets = observeTargets(loadBindings(deps.guard, deps.paths.settingsDir));
|
|
2800
2920
|
if (targets.length === 0) return false;
|
|
2801
|
-
const cursors = loadCursors(
|
|
2921
|
+
const cursors = loadCursors(path11.join(deps.paths.dataDir, "cursors.json")).sessions;
|
|
2802
2922
|
for (const b of targets) {
|
|
2803
2923
|
const agent = ctx_getAgent(deps, b.sessionId);
|
|
2804
2924
|
if (!agent) continue;
|
|
@@ -3050,6 +3170,8 @@ function startOrchestrator(deps) {
|
|
|
3050
3170
|
}
|
|
3051
3171
|
|
|
3052
3172
|
export {
|
|
3173
|
+
parseArchivedSessionIds,
|
|
3174
|
+
isArchivedSession,
|
|
3053
3175
|
readSentState,
|
|
3054
3176
|
inQuietHours,
|
|
3055
3177
|
reportFilePath,
|
|
@@ -3087,6 +3209,8 @@ export {
|
|
|
3087
3209
|
ENGINE_ROOM_EXTRA_TOOLS,
|
|
3088
3210
|
buildEngineRoomAllowList,
|
|
3089
3211
|
pinEngineRoomTools,
|
|
3212
|
+
waitForVisibleTool,
|
|
3213
|
+
makeHomeSetup,
|
|
3090
3214
|
shouldArchiveRotatedHome,
|
|
3091
3215
|
agentLooksAlive,
|
|
3092
3216
|
agentTurn,
|
|
@@ -3095,6 +3219,8 @@ export {
|
|
|
3095
3219
|
loadCursors,
|
|
3096
3220
|
pickSpokenLine,
|
|
3097
3221
|
spokeTextSince,
|
|
3222
|
+
turnEndKindSince,
|
|
3223
|
+
classifySilentReason,
|
|
3098
3224
|
TOKEN_SAVER_IDLE_SECONDS,
|
|
3099
3225
|
TOKEN_SAVER_WAKE_MS,
|
|
3100
3226
|
userActiveInBoundSessions,
|
|
@@ -3104,4 +3230,4 @@ export {
|
|
|
3104
3230
|
jitteredIntervalMs,
|
|
3105
3231
|
startOrchestrator
|
|
3106
3232
|
};
|
|
3107
|
-
//# sourceMappingURL=chunk-
|
|
3233
|
+
//# sourceMappingURL=chunk-WF7ZBW5C.js.map
|