@jjh32456/longlive 0.0.0-stage → 2.0.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/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,1459 @@
|
|
|
1
|
+
// router.mjs — 后台 Router 骨架(spike 原型)
|
|
2
|
+
//
|
|
3
|
+
// 这一版针对第二轮复核 mustFix 重写,关键不变量:
|
|
4
|
+
// 1. 预算硬上限是「每个 run 目录」的:预留/结算都走 budget-ledger.mjs 的
|
|
5
|
+
// 文件锁账本,跨实例串行、跨重启累加;调用前按 callMaxTokens 预留,
|
|
6
|
+
// 剩余不够就绝不发起调用(而不是先花了再发现超了)。
|
|
7
|
+
// 2. start() 从账本恢复 used + reserved;只有「账本不存在」时才用审计
|
|
8
|
+
// bootstrap 一次。审计有 CRC,坏行/截断行会被计数;没有账本又发现审计
|
|
9
|
+
// 损坏时 fail-closed(E_AUDIT_CORRUPT),不再静默少算预算。
|
|
10
|
+
// 3. 整个 tick 包在 try/catch 里,包括每一次 audit.append;审计写失败
|
|
11
|
+
// 转 stopped + 记录,tick 不 reject。
|
|
12
|
+
// 4. stop 先 abort,再等在飞 tick 到边界(带超时);超时就强制释放本实例
|
|
13
|
+
// 的预留(僵尸 tick 不能继续占额度),最后才关审计。router.stop 写不进去
|
|
14
|
+
// 时 stop() 返回 ok:false + E_AUDIT_WRITE,而不是假报成功。
|
|
15
|
+
// 5. busy flag:并发 tick 只跑一个,另一个立即返回 E_BUSY。
|
|
16
|
+
// 6. 任务队列按 id 去重并带容量上限;写路径只给可信生产者(queue.writer)。
|
|
17
|
+
// 7. 工具面 restrict/guard 在 tool-policy.mjs;后台 agent 只读。
|
|
18
|
+
// 8. stream 按 AsyncIterable 契约消费,iterator.return() 有时限(stream.mjs)。
|
|
19
|
+
// 9. agent 生命周期 create -> agent.followup -> agent.whenIdle -> dispose
|
|
20
|
+
// (agent-runner.mjs,真宿主返回 {agent, dispose})。
|
|
21
|
+
// 10. RATE_LIMIT 退避 / QUOTA 立即停(retry.mjs),每次 attempt 的 usage 都累加。
|
|
22
|
+
// 11. llm.stream 必须带 provider + model(dsh-llm README:50-57),否则真机
|
|
23
|
+
// NO_ADAPTER;配置从 constructor 或 llm 实例解析,并写进审计。
|
|
24
|
+
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
import { AuditLog, readAudit } from './audit.mjs';
|
|
28
|
+
import { BudgetLedger, readLedger } from './budget-ledger.mjs';
|
|
29
|
+
import { AnchorLog, verifyAnchor } from './anchor.mjs';
|
|
30
|
+
import { TaskQueue } from './queue.mjs';
|
|
31
|
+
import { MemoryReader, memoryToSystemPrompt } from './memory.mjs';
|
|
32
|
+
import { buildMessages, consumeStream } from './stream.mjs';
|
|
33
|
+
import { retryOnFailure } from './retry.mjs';
|
|
34
|
+
import { runAgentTask } from './agent-runner.mjs';
|
|
35
|
+
|
|
36
|
+
export const FORBIDDEN_ACTIONS = Object.freeze([
|
|
37
|
+
'router.start',
|
|
38
|
+
'router.spawn',
|
|
39
|
+
'spawn_router',
|
|
40
|
+
'subagent.spawn',
|
|
41
|
+
'queue.append',
|
|
42
|
+
'queue.write',
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_ALLOWED_ACTIONS = Object.freeze(['note', 'report', 'noop']);
|
|
46
|
+
|
|
47
|
+
/** 递归任务:由 Router 自己派生,或 depth > 0。 */
|
|
48
|
+
export function isRecursiveTask(task) {
|
|
49
|
+
return task?.origin === 'router' || (Number.isInteger(task?.depth) && task.depth > 0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 从文本末尾的 `ACTION: {...}` 行解析动作;解析失败返回 null。 */
|
|
53
|
+
export function parseAction(text) {
|
|
54
|
+
if (typeof text !== 'string') return null;
|
|
55
|
+
const matches = [...text.matchAll(/ACTION:\s*(\{.*\})\s*$/gm)];
|
|
56
|
+
if (matches.length === 0) return null;
|
|
57
|
+
try {
|
|
58
|
+
return JSON.parse(matches[matches.length - 1][1]);
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function recursiveAction(type) {
|
|
65
|
+
return FORBIDDEN_ACTIONS.includes(type)
|
|
66
|
+
|| (typeof type === 'string' && (type.startsWith('router.') || type.startsWith('subagent')));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 只有审计、没有账本时的一次性 bootstrap:把已发生的 settle 累加起来。
|
|
71
|
+
* 旧实现用 max(tokens_total),多实例/多任务时会少算;这里改成求和。
|
|
72
|
+
* 未 settle 的 reserve 按「预留已花」保守计入(崩溃恢复)。
|
|
73
|
+
* 记录里带 reservation_id 时按 id 配对;旧审计退回 task_id。
|
|
74
|
+
*/
|
|
75
|
+
export function foldAuditUsage(records) {
|
|
76
|
+
let settledUsed = 0;
|
|
77
|
+
const active = new Map();
|
|
78
|
+
const settled = new Set();
|
|
79
|
+
for (const rec of records) {
|
|
80
|
+
if (!rec || typeof rec !== 'object') continue;
|
|
81
|
+
const key = rec.reservation_id ?? (rec.task_id ? `task:${rec.task_id}` : null);
|
|
82
|
+
if (rec.kind === 'budget.reserve') {
|
|
83
|
+
const tokens = Number(rec.budgetReserved);
|
|
84
|
+
if (key && Number.isFinite(tokens) && tokens >= 0) active.set(key, tokens);
|
|
85
|
+
} else if (rec.kind === 'budget.settle') {
|
|
86
|
+
const tokens = Number(rec.actual_tokens);
|
|
87
|
+
if (key) {
|
|
88
|
+
if (settled.has(key)) continue;
|
|
89
|
+
settled.add(key);
|
|
90
|
+
active.delete(key);
|
|
91
|
+
}
|
|
92
|
+
if (Number.isFinite(tokens) && tokens >= 0) settledUsed += tokens;
|
|
93
|
+
} else if (rec.kind === 'budget.release' || rec.kind === 'stop.timeout') {
|
|
94
|
+
if (key) active.delete(key);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
let openTokens = 0;
|
|
98
|
+
for (const tokens of active.values()) openTokens += tokens;
|
|
99
|
+
return {
|
|
100
|
+
used: settledUsed + openTokens,
|
|
101
|
+
settledUsed,
|
|
102
|
+
openReservations: active.size,
|
|
103
|
+
openTokens,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export class Router {
|
|
108
|
+
constructor({
|
|
109
|
+
queuePath,
|
|
110
|
+
auditPath,
|
|
111
|
+
memoryPath = null,
|
|
112
|
+
llm,
|
|
113
|
+
provider = null,
|
|
114
|
+
model = null,
|
|
115
|
+
maxTokens = 4000,
|
|
116
|
+
callMaxTokens = null,
|
|
117
|
+
maxTicks = 50,
|
|
118
|
+
maxTasksPerTick = 3,
|
|
119
|
+
maxConsecutiveErrors = 3,
|
|
120
|
+
callTimeoutMs = 2000,
|
|
121
|
+
stopTimeoutMs = 1000,
|
|
122
|
+
stopFile = null,
|
|
123
|
+
runId = `run-${process.pid}-${Date.now().toString(36)}`,
|
|
124
|
+
now = () => new Date().toISOString(),
|
|
125
|
+
logger = null,
|
|
126
|
+
retry = {},
|
|
127
|
+
auditMaxBytes = undefined,
|
|
128
|
+
auditMaxRotations = undefined,
|
|
129
|
+
maxQueuedTasks = 500,
|
|
130
|
+
maxQueueBytes = 1024 * 1024,
|
|
131
|
+
heartbeatMs = 0,
|
|
132
|
+
ledgerPath = null,
|
|
133
|
+
ledgerLockTimeoutMs = 3000,
|
|
134
|
+
anchorPath = null,
|
|
135
|
+
allowMissingAnchor = false,
|
|
136
|
+
reservationLeaseMs = 60000,
|
|
137
|
+
ctx = null,
|
|
138
|
+
agents = null,
|
|
139
|
+
agentOptions = {},
|
|
140
|
+
agentSetup = null,
|
|
141
|
+
sessionId = null,
|
|
142
|
+
} = {}) {
|
|
143
|
+
if (!queuePath) throw new Error('Router: queuePath is required');
|
|
144
|
+
if (!auditPath) throw new Error('Router: auditPath is required');
|
|
145
|
+
if (!llm || typeof llm.stream !== 'function') {
|
|
146
|
+
throw new Error('Router: llm.stream() is required (the promise-style complete() is not the host contract)');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
this.queuePath = queuePath;
|
|
150
|
+
this.auditPath = auditPath;
|
|
151
|
+
this.memoryPath = memoryPath;
|
|
152
|
+
this.llm = llm;
|
|
153
|
+
// 真宿主 llm.stream 必须带 provider/model;允许从 llm 实例上取默认值。
|
|
154
|
+
this.provider = provider ?? llm.provider ?? llm.defaultProvider ?? null;
|
|
155
|
+
this.model = model ?? llm.model ?? llm.defaultModel ?? null;
|
|
156
|
+
this.maxTokens = maxTokens;
|
|
157
|
+
this.callMaxTokens = Math.max(1, Math.min(callMaxTokens ?? 1024, maxTokens));
|
|
158
|
+
this.maxTicks = maxTicks;
|
|
159
|
+
this.maxTasksPerTick = maxTasksPerTick;
|
|
160
|
+
this.maxConsecutiveErrors = maxConsecutiveErrors;
|
|
161
|
+
this.callTimeoutMs = callTimeoutMs;
|
|
162
|
+
this.stopTimeoutMs = stopTimeoutMs;
|
|
163
|
+
this.stopFile = stopFile;
|
|
164
|
+
this.runId = runId;
|
|
165
|
+
this.now = now;
|
|
166
|
+
this.logger = logger;
|
|
167
|
+
this.retryOptions = {
|
|
168
|
+
maxAttempts: 3,
|
|
169
|
+
initialDelayMs: 500,
|
|
170
|
+
maxDelayMs: 10000,
|
|
171
|
+
jitterRatio: 0.1,
|
|
172
|
+
...retry,
|
|
173
|
+
};
|
|
174
|
+
this.heartbeatMs = heartbeatMs;
|
|
175
|
+
this.ledgerPath = ledgerPath ?? path.join(path.dirname(queuePath), 'budget.ledger.jsonl');
|
|
176
|
+
this.ledgerLockTimeoutMs = ledgerLockTimeoutMs;
|
|
177
|
+
// 外部锚:独立文件、只追加 hash 链。随包之外(只读目录 / 外部 checkpoint)是本部署的降级说明。
|
|
178
|
+
this.anchorPath = anchorPath ?? `${this.ledgerPath}.anchor.jsonl`;
|
|
179
|
+
this.allowMissingAnchor = Boolean(allowMissingAnchor);
|
|
180
|
+
this.reservationLeaseMs = reservationLeaseMs;
|
|
181
|
+
this.ctx = ctx;
|
|
182
|
+
this.agents = agents;
|
|
183
|
+
this.agentOptions = agentOptions;
|
|
184
|
+
this.agentSetup = agentSetup;
|
|
185
|
+
this.sessionId = sessionId;
|
|
186
|
+
|
|
187
|
+
this.queue = new TaskQueue({ file: queuePath, maxTasks: maxQueuedTasks, maxBytes: maxQueueBytes });
|
|
188
|
+
this.memory = memoryPath ? new MemoryReader({ file: memoryPath }) : null;
|
|
189
|
+
this.audit = new AuditLog({
|
|
190
|
+
file: auditPath,
|
|
191
|
+
runId,
|
|
192
|
+
now,
|
|
193
|
+
maxBytes: auditMaxBytes,
|
|
194
|
+
maxRotations: auditMaxRotations,
|
|
195
|
+
});
|
|
196
|
+
this.ledger = new BudgetLedger({
|
|
197
|
+
file: this.ledgerPath,
|
|
198
|
+
runId,
|
|
199
|
+
maxTokens,
|
|
200
|
+
lockTimeoutMs: ledgerLockTimeoutMs,
|
|
201
|
+
now,
|
|
202
|
+
reservationLeaseMs,
|
|
203
|
+
});
|
|
204
|
+
this.anchor = new AnchorLog({ file: this.anchorPath, now });
|
|
205
|
+
|
|
206
|
+
this.state = 'idle';
|
|
207
|
+
this.busy = false;
|
|
208
|
+
this.seen = new Set();
|
|
209
|
+
this.tokensUsed = 0;
|
|
210
|
+
this.reservedTokens = 0;
|
|
211
|
+
this.ticks = 0;
|
|
212
|
+
this.processed = 0;
|
|
213
|
+
this.denied = 0;
|
|
214
|
+
this.errors = 0;
|
|
215
|
+
this.deadLettered = 0;
|
|
216
|
+
this.consecutiveErrors = 0;
|
|
217
|
+
this.stopReason = null;
|
|
218
|
+
this.alreadyStopped = false;
|
|
219
|
+
this.started = false;
|
|
220
|
+
this.lastError = null;
|
|
221
|
+
this.lastMessages = null;
|
|
222
|
+
this.startup = null;
|
|
223
|
+
|
|
224
|
+
this.#controller = new AbortController();
|
|
225
|
+
this.#inflight = new Set();
|
|
226
|
+
this.#reservations = new Map();
|
|
227
|
+
this.#finalized = false;
|
|
228
|
+
this.#finalResult = null;
|
|
229
|
+
this.#auditBroken = false;
|
|
230
|
+
this.#timerDispose = null;
|
|
231
|
+
this.#disposed = false;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
#controller;
|
|
235
|
+
#inflight;
|
|
236
|
+
#reservations;
|
|
237
|
+
#finalized;
|
|
238
|
+
#finalResult;
|
|
239
|
+
#auditBroken;
|
|
240
|
+
#timerDispose;
|
|
241
|
+
#disposed;
|
|
242
|
+
|
|
243
|
+
get signal() {
|
|
244
|
+
return this.#controller.signal;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
get budget() {
|
|
248
|
+
return {
|
|
249
|
+
maxTokens: this.maxTokens,
|
|
250
|
+
callMaxTokens: this.callMaxTokens,
|
|
251
|
+
tokensUsed: this.tokensUsed,
|
|
252
|
+
reservedTokens: this.reservedTokens,
|
|
253
|
+
remaining: Math.max(0, this.maxTokens - this.tokensUsed - this.reservedTokens),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
get auditBroken() {
|
|
258
|
+
return this.#auditBroken;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 启动:从账本恢复预算、续 seq、写 router.start。
|
|
263
|
+
* 审计/账本损坏不 throw,返回 {ok:false, code}。
|
|
264
|
+
*/
|
|
265
|
+
start() {
|
|
266
|
+
if (this.#disposed) return { ok: false, code: 'E_DISPOSED', alreadyRunning: false, replayed: 0 };
|
|
267
|
+
if (this.state === 'running' || this.state === 'stopping') {
|
|
268
|
+
return { ok: true, alreadyRunning: true, replayed: 0, resumedTokens: this.tokensUsed + this.reservedTokens };
|
|
269
|
+
}
|
|
270
|
+
if (this.state === 'stopped') {
|
|
271
|
+
return { ok: false, code: 'E_STOPPED', alreadyRunning: false, replayed: 0, state: this.state };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (!this.provider || !this.model) {
|
|
275
|
+
this.state = 'stopped';
|
|
276
|
+
this.stopReason = 'no_provider';
|
|
277
|
+
this.lastError = {
|
|
278
|
+
code: 'E_NO_PROVIDER',
|
|
279
|
+
message: `Router needs provider/model before start (provider=${String(this.provider)}, model=${String(this.model)})`,
|
|
280
|
+
};
|
|
281
|
+
return {
|
|
282
|
+
ok: false,
|
|
283
|
+
code: 'E_NO_PROVIDER',
|
|
284
|
+
missing: [...(this.provider ? [] : ['provider']), ...(this.model ? [] : ['model'])],
|
|
285
|
+
alreadyRunning: false,
|
|
286
|
+
replayed: 0,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// P0-2/P0-3:先修崩溃留下的半行尾,再回收「pid 已死 / 租约过期」的预留。
|
|
291
|
+
// 这两步必须在读账本之前,否则半行尾会被当成 CORRUPT、死预留会占着预算。
|
|
292
|
+
let repaired = { ok: true, repaired: false };
|
|
293
|
+
let reclaimed = { released: 0, freedTokens: 0, items: [] };
|
|
294
|
+
try {
|
|
295
|
+
repaired = this.ledger.repairTail();
|
|
296
|
+
reclaimed = this.ledger.reclaimDead({ now: Date.now() });
|
|
297
|
+
} catch (error) {
|
|
298
|
+
this.state = 'stopped';
|
|
299
|
+
this.lastError = { code: error?.code ?? 'E_BUDGET_WRITE', message: error.message };
|
|
300
|
+
this.stopReason = this.lastError.code === 'E_LEDGER_TAMPERED' ? 'ledger_tampered' : 'ledger_repair_failed';
|
|
301
|
+
return {
|
|
302
|
+
ok: false,
|
|
303
|
+
code: this.lastError.code,
|
|
304
|
+
message: error.message,
|
|
305
|
+
chainBreaks: Array.isArray(error?.chainBreaks) ? error.chainBreaks.length : 0,
|
|
306
|
+
alreadyRunning: false,
|
|
307
|
+
replayed: 0,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
let read = {
|
|
312
|
+
records: [],
|
|
313
|
+
badLines: 0,
|
|
314
|
+
unsigned: 0,
|
|
315
|
+
truncated: 0,
|
|
316
|
+
tamperedLines: 0,
|
|
317
|
+
chainBreaks: [],
|
|
318
|
+
badLineDetails: [],
|
|
319
|
+
};
|
|
320
|
+
try {
|
|
321
|
+
read = readAudit(this.auditPath, { maxRotations: this.audit.maxRotations });
|
|
322
|
+
} catch (error) {
|
|
323
|
+
this.state = 'stopped';
|
|
324
|
+
this.stopReason = 'audit_read_failed';
|
|
325
|
+
this.lastError = { code: 'E_AUDIT_READ', message: error.message };
|
|
326
|
+
return { ok: false, code: 'E_AUDIT_READ', message: error.message, alreadyRunning: false, replayed: 0 };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// P0-4:审计是证据链。整行删除 / seq 跳号 / hash 链断 = 篡改,fail-closed。
|
|
330
|
+
// 无换行的半行尾是崩溃残留(truncated),不算篡改,交给账本对账兜底。
|
|
331
|
+
const auditChainBreaks = read.chainBreaks?.length ?? 0;
|
|
332
|
+
const auditTamperedLines = read.tamperedLines ?? 0;
|
|
333
|
+
if (auditChainBreaks > 0 || auditTamperedLines > 0) {
|
|
334
|
+
this.state = 'stopped';
|
|
335
|
+
this.stopReason = 'ledger_tampered';
|
|
336
|
+
this.lastError = {
|
|
337
|
+
code: 'E_LEDGER_TAMPERED',
|
|
338
|
+
message: `audit evidence chain is broken (${auditChainBreaks} chain break(s), ${auditTamperedLines} tampered line(s))`,
|
|
339
|
+
};
|
|
340
|
+
return {
|
|
341
|
+
ok: false,
|
|
342
|
+
code: 'E_LEDGER_TAMPERED',
|
|
343
|
+
chainBreaks: auditChainBreaks,
|
|
344
|
+
tamperedLines: auditTamperedLines,
|
|
345
|
+
alreadyRunning: false,
|
|
346
|
+
replayed: 0,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
let snapshot;
|
|
351
|
+
try {
|
|
352
|
+
snapshot = this.ledger.snapshot();
|
|
353
|
+
} catch (error) {
|
|
354
|
+
this.state = 'stopped';
|
|
355
|
+
this.stopReason = 'ledger_read_failed';
|
|
356
|
+
this.lastError = { code: 'E_BUDGET_READ', message: error.message };
|
|
357
|
+
return { ok: false, code: 'E_BUDGET_READ', message: error.message, alreadyRunning: false, replayed: 0 };
|
|
358
|
+
}
|
|
359
|
+
if ((snapshot.chainBreaks?.length ?? 0) > 0) {
|
|
360
|
+
this.state = 'stopped';
|
|
361
|
+
this.stopReason = 'ledger_tampered';
|
|
362
|
+
this.lastError = {
|
|
363
|
+
code: 'E_LEDGER_TAMPERED',
|
|
364
|
+
message: `budget ledger hash chain is broken (${snapshot.chainBreaks.length} break(s))`,
|
|
365
|
+
};
|
|
366
|
+
return {
|
|
367
|
+
ok: false,
|
|
368
|
+
code: 'E_LEDGER_TAMPERED',
|
|
369
|
+
chainBreaks: snapshot.chainBreaks.length,
|
|
370
|
+
alreadyRunning: false,
|
|
371
|
+
replayed: 0,
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
if (snapshot.badLines > 0) {
|
|
375
|
+
this.state = 'stopped';
|
|
376
|
+
this.stopReason = 'ledger_corrupt';
|
|
377
|
+
this.lastError = { code: 'E_BUDGET_CORRUPT', message: `budget ledger has ${snapshot.badLines} bad record(s)` };
|
|
378
|
+
return {
|
|
379
|
+
ok: false,
|
|
380
|
+
code: 'E_BUDGET_CORRUPT',
|
|
381
|
+
badLines: snapshot.badLines,
|
|
382
|
+
alreadyRunning: false,
|
|
383
|
+
replayed: 0,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const auditUsage = foldAuditUsage(read.records);
|
|
388
|
+
let mismatch = null;
|
|
389
|
+
let adopted = false;
|
|
390
|
+
|
|
391
|
+
try {
|
|
392
|
+
if (snapshot.records === 0) {
|
|
393
|
+
// 只有旧审计(或根本没有历史):先 fail-closed,再 bootstrap。
|
|
394
|
+
if (read.badLines > 0) {
|
|
395
|
+
this.state = 'stopped';
|
|
396
|
+
this.stopReason = 'audit_corrupt';
|
|
397
|
+
this.lastError = {
|
|
398
|
+
code: 'E_AUDIT_CORRUPT',
|
|
399
|
+
message: `audit has ${read.badLines} bad line(s) and no budget ledger to reconcile against`,
|
|
400
|
+
};
|
|
401
|
+
return {
|
|
402
|
+
ok: false,
|
|
403
|
+
code: 'E_AUDIT_CORRUPT',
|
|
404
|
+
badLines: read.badLines,
|
|
405
|
+
truncated: read.truncated,
|
|
406
|
+
alreadyRunning: false,
|
|
407
|
+
replayed: 0,
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
if (auditUsage.used > 0) {
|
|
411
|
+
const adopt = this.ledger.adopt({ used: auditUsage.used, reason: 'audit_bootstrap' });
|
|
412
|
+
if (!adopt.ok) throw new Error(`budget ledger adopt failed: ${adopt.code}`);
|
|
413
|
+
adopted = true;
|
|
414
|
+
}
|
|
415
|
+
snapshot = this.ledger.snapshot();
|
|
416
|
+
} else if (auditUsage.settledUsed !== snapshot.used) {
|
|
417
|
+
// 账本说花了 X、审计说花了 Y,且两者都在(不是 bootstrap)—— 必有一方被删/被改。
|
|
418
|
+
// 这是 P0-4 的「账本/审计不一致 fail-closed」:不再只记 mismatch 继续跑。
|
|
419
|
+
this.state = 'stopped';
|
|
420
|
+
this.stopReason = 'ledger_tampered';
|
|
421
|
+
this.lastError = {
|
|
422
|
+
code: 'E_LEDGER_TAMPERED',
|
|
423
|
+
message: `audit settles ${auditUsage.settledUsed} token(s) but ledger records ${snapshot.used}`,
|
|
424
|
+
};
|
|
425
|
+
return {
|
|
426
|
+
ok: false,
|
|
427
|
+
code: 'E_LEDGER_TAMPERED',
|
|
428
|
+
auditUsed: auditUsage.settledUsed,
|
|
429
|
+
ledgerUsed: snapshot.used,
|
|
430
|
+
alreadyRunning: false,
|
|
431
|
+
replayed: 0,
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
} catch (error) {
|
|
435
|
+
this.state = 'stopped';
|
|
436
|
+
this.stopReason = 'ledger_init_failed';
|
|
437
|
+
this.lastError = { code: error?.code ?? 'E_BUDGET_WRITE', message: error.message };
|
|
438
|
+
return { ok: false, code: this.lastError.code, message: error.message, alreadyRunning: false, replayed: 0 };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// D:外部锚。账本和审计是两条可被「有写权限者」一起重算的 hash 链;
|
|
442
|
+
// 锚是独立文件里的 checkpoint(只追加、带自己的 hash 链),跨进程/重启保留。
|
|
443
|
+
// 单机边界:能同时改账本、审计和锚的攻击者仍可伪造,故生产应把锚放到只读目录/外部
|
|
444
|
+
// checkpoint;这里给出 anchorPath 接线,并用「删锚 + 有历史」判 E_ANCHOR_MISSING。
|
|
445
|
+
let anchorCheck = { ok: true, anchored: false, reason: 'no_anchor' };
|
|
446
|
+
try {
|
|
447
|
+
this.anchor.repairTail();
|
|
448
|
+
anchorCheck = verifyAnchor(this.anchor.read().records, {
|
|
449
|
+
ledgerRecords: readLedger(this.ledgerPath).records,
|
|
450
|
+
ledgerState: snapshot,
|
|
451
|
+
auditRecords: read.records,
|
|
452
|
+
auditSettled: auditUsage.settledUsed,
|
|
453
|
+
auditFile: this.auditPath,
|
|
454
|
+
});
|
|
455
|
+
} catch (error) {
|
|
456
|
+
this.state = 'stopped';
|
|
457
|
+
this.stopReason = 'anchor_read_failed';
|
|
458
|
+
this.lastError = { code: error?.code ?? 'E_ANCHOR_READ', message: error.message };
|
|
459
|
+
return { ok: false, code: this.lastError.code, message: error.message, alreadyRunning: false, replayed: 0 };
|
|
460
|
+
}
|
|
461
|
+
if (!anchorCheck.ok) {
|
|
462
|
+
this.state = 'stopped';
|
|
463
|
+
this.stopReason = 'ledger_tampered';
|
|
464
|
+
this.lastError = {
|
|
465
|
+
code: 'E_LEDGER_TAMPERED',
|
|
466
|
+
message: `budget anchor mismatch (${anchorCheck.reason}): ledger/audit were rewritten outside the anchored prefix`,
|
|
467
|
+
};
|
|
468
|
+
return {
|
|
469
|
+
ok: false,
|
|
470
|
+
code: 'E_LEDGER_TAMPERED',
|
|
471
|
+
anchorReason: anchorCheck.reason,
|
|
472
|
+
alreadyRunning: false,
|
|
473
|
+
replayed: 0,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
const hadRouterHistory = read.records.some((rec) => rec.kind === 'router.start');
|
|
477
|
+
if (!anchorCheck.anchored && !this.allowMissingAnchor && hadRouterHistory) {
|
|
478
|
+
this.state = 'stopped';
|
|
479
|
+
this.stopReason = 'anchor_missing';
|
|
480
|
+
this.lastError = {
|
|
481
|
+
code: 'E_ANCHOR_MISSING',
|
|
482
|
+
message: 'budget anchor file is missing although this directory has Router history (delete-anchor attack)',
|
|
483
|
+
};
|
|
484
|
+
return { ok: false, code: 'E_ANCHOR_MISSING', alreadyRunning: false, replayed: 0 };
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const seen = new Set();
|
|
488
|
+
for (const rec of read.records) {
|
|
489
|
+
if (['action', 'action.denied', 'task.denied', 'task.error'].includes(rec.kind)
|
|
490
|
+
&& typeof rec.task_id === 'string') {
|
|
491
|
+
seen.add(rec.task_id);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
this.seen = seen;
|
|
495
|
+
this.tokensUsed = snapshot.used;
|
|
496
|
+
this.reservedTokens = snapshot.reserved;
|
|
497
|
+
this.startup = {
|
|
498
|
+
adopted,
|
|
499
|
+
auditBadLines: read.badLines,
|
|
500
|
+
auditUnsigned: read.unsigned,
|
|
501
|
+
mismatch,
|
|
502
|
+
anchor: anchorCheck.anchored ? 'verified' : 'none',
|
|
503
|
+
reclaimed: { released: reclaimed.released, freedTokens: reclaimed.freedTokens },
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
try {
|
|
507
|
+
this.audit.open();
|
|
508
|
+
} catch (error) {
|
|
509
|
+
this.state = 'stopped';
|
|
510
|
+
this.stopReason = 'audit_open_failed';
|
|
511
|
+
this.lastError = { code: 'E_AUDIT_OPEN', message: error.message };
|
|
512
|
+
return { ok: false, code: 'E_AUDIT_OPEN', message: error.message, alreadyRunning: false, replayed: 0 };
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
this.state = 'running';
|
|
516
|
+
this.started = true;
|
|
517
|
+
try {
|
|
518
|
+
this.#emit('router.start', {
|
|
519
|
+
resumed_tokens_used: snapshot.used,
|
|
520
|
+
resumed_tokens_reserved: snapshot.reserved,
|
|
521
|
+
max_tokens: this.maxTokens,
|
|
522
|
+
call_max_tokens: this.callMaxTokens,
|
|
523
|
+
replayed: seen.size,
|
|
524
|
+
bad_lines: read.badLines,
|
|
525
|
+
audit_unsigned: read.unsigned,
|
|
526
|
+
ledger: this.ledgerPath,
|
|
527
|
+
adopted_from_audit: adopted,
|
|
528
|
+
reclaimed_reservations: reclaimed.released,
|
|
529
|
+
provider: this.provider,
|
|
530
|
+
model: this.model,
|
|
531
|
+
anchor: anchorCheck.anchored ? 'verified' : 'none',
|
|
532
|
+
});
|
|
533
|
+
if (reclaimed.released > 0) {
|
|
534
|
+
this.#emit('budget.reclaim', {
|
|
535
|
+
released: reclaimed.released,
|
|
536
|
+
freed_tokens: reclaimed.freedTokens,
|
|
537
|
+
items: reclaimed.items.slice(0, 10),
|
|
538
|
+
reason: 'startup',
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
if (repaired.repaired) {
|
|
542
|
+
// 半行尾修复也是证据:没有它,test「只删 start 的 repairTail」无法红。
|
|
543
|
+
this.#emit('budget.repair', {
|
|
544
|
+
file: this.ledgerPath,
|
|
545
|
+
repaired: true,
|
|
546
|
+
reason: 'startup_tail_repair',
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
if (read.badLines > 0) {
|
|
550
|
+
this.#emit('audit.corrupt', {
|
|
551
|
+
bad_lines: read.badLines,
|
|
552
|
+
truncated: read.truncated,
|
|
553
|
+
items: read.badLineDetails.slice(0, 5),
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
if (mismatch) this.#emit('audit.replay_mismatch', mismatch);
|
|
557
|
+
// 启动即打一个 checkpoint:锚缺失时也能从第一次运行起留下外部证据。
|
|
558
|
+
this.#sealAnchor();
|
|
559
|
+
} catch (error) {
|
|
560
|
+
return this.#failSafe(error);
|
|
561
|
+
}
|
|
562
|
+
this.#installTimer();
|
|
563
|
+
return {
|
|
564
|
+
ok: true,
|
|
565
|
+
alreadyRunning: false,
|
|
566
|
+
replayed: seen.size,
|
|
567
|
+
resumedTokens: snapshot.used + snapshot.reserved,
|
|
568
|
+
tokensUsed: snapshot.used,
|
|
569
|
+
reservedTokens: snapshot.reserved,
|
|
570
|
+
badLines: read.badLines,
|
|
571
|
+
adopted,
|
|
572
|
+
anchor: anchorCheck.anchored ? 'verified' : 'none',
|
|
573
|
+
reclaimed,
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* 跑一个 tick。永不 reject:任何内部异常都转成 fail-safe 结果。
|
|
579
|
+
* 并发调用只让第一个跑,其余立即 E_BUSY。
|
|
580
|
+
*/
|
|
581
|
+
async tick() {
|
|
582
|
+
if (this.state !== 'running') {
|
|
583
|
+
return {
|
|
584
|
+
ok: false,
|
|
585
|
+
code: 'E_NOT_RUNNING',
|
|
586
|
+
state: this.state,
|
|
587
|
+
processed: 0,
|
|
588
|
+
denied: 0,
|
|
589
|
+
errors: 0,
|
|
590
|
+
tokensUsed: this.tokensUsed,
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
if (this.stopFile && fs.existsSync(this.stopFile)) {
|
|
594
|
+
const stopped = await this.stop('stop_file');
|
|
595
|
+
return {
|
|
596
|
+
ok: true,
|
|
597
|
+
stop: 'stop_file',
|
|
598
|
+
state: this.state,
|
|
599
|
+
auditBroken: stopped.ok === false,
|
|
600
|
+
processed: 0,
|
|
601
|
+
denied: 0,
|
|
602
|
+
errors: 0,
|
|
603
|
+
tokensUsed: this.tokensUsed,
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
if (this.busy) {
|
|
607
|
+
return {
|
|
608
|
+
ok: false,
|
|
609
|
+
code: 'E_BUSY',
|
|
610
|
+
state: this.state,
|
|
611
|
+
processed: 0,
|
|
612
|
+
denied: 0,
|
|
613
|
+
errors: 0,
|
|
614
|
+
tokensUsed: this.tokensUsed,
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
this.busy = true;
|
|
619
|
+
const controller = new AbortController();
|
|
620
|
+
const unlink = this.#linkAbort(this.#controller.signal, controller);
|
|
621
|
+
const tickNo = this.ticks + 1;
|
|
622
|
+
const promise = this.#runTick(tickNo, controller.signal);
|
|
623
|
+
this.#inflight.add(promise);
|
|
624
|
+
let result;
|
|
625
|
+
try {
|
|
626
|
+
result = await promise;
|
|
627
|
+
} catch (error) {
|
|
628
|
+
result = this.#failSafe(error);
|
|
629
|
+
} finally {
|
|
630
|
+
this.#inflight.delete(promise);
|
|
631
|
+
this.busy = false;
|
|
632
|
+
unlink();
|
|
633
|
+
if (this.state === 'stopping' && this.#inflight.size === 0) {
|
|
634
|
+
await this.#finalizeStop();
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
return result;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
async #runTick(tickNo, signal) {
|
|
641
|
+
this.ticks = tickNo;
|
|
642
|
+
const res = {
|
|
643
|
+
ok: true,
|
|
644
|
+
tick: tickNo,
|
|
645
|
+
processed: 0,
|
|
646
|
+
denied: 0,
|
|
647
|
+
errors: 0,
|
|
648
|
+
stop: false,
|
|
649
|
+
tokensUsed: this.tokensUsed,
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
if (tickNo > this.maxTicks) {
|
|
653
|
+
this.#beginStop('max_ticks');
|
|
654
|
+
return { ...res, stop: 'max_ticks', tokensUsed: this.tokensUsed };
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// P0-2:长驻进程也要回收——上一个 tick 崩溃的兄弟进程留下的预留不能一直占着预算。
|
|
658
|
+
this.#reclaimDeadReservations();
|
|
659
|
+
|
|
660
|
+
this.#emit('tick.start', {
|
|
661
|
+
tick: tickNo,
|
|
662
|
+
tokens_used: this.tokensUsed,
|
|
663
|
+
tokens_reserved: this.reservedTokens,
|
|
664
|
+
tokens_remaining: Math.max(0, this.maxTokens - this.tokensUsed - this.reservedTokens),
|
|
665
|
+
});
|
|
666
|
+
|
|
667
|
+
const memory = this.memory?.read() ?? { source: 'none', facts: [], error: null };
|
|
668
|
+
this.#emit('memory.read', {
|
|
669
|
+
source: memory.source,
|
|
670
|
+
facts: Array.isArray(memory.facts) ? memory.facts.length : 0,
|
|
671
|
+
error: memory.error ?? null,
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
const pending = this.queue.pending(this.seen);
|
|
675
|
+
if (pending.invalid.length > 0) {
|
|
676
|
+
this.#emit('queue.invalid', { count: pending.invalid.length, items: pending.invalid.slice(0, 5) });
|
|
677
|
+
}
|
|
678
|
+
if (pending.duplicates.length > 0) {
|
|
679
|
+
this.#emit('queue.duplicates', { count: pending.duplicates.length });
|
|
680
|
+
}
|
|
681
|
+
if (pending.capacity?.full) {
|
|
682
|
+
this.#emit('queue.full', pending.capacity);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
const tasks = pending.tasks.slice(0, this.maxTasksPerTick);
|
|
686
|
+
if (tasks.length === 0) {
|
|
687
|
+
this.#emit('tick.idle', { tick: tickNo });
|
|
688
|
+
return { ...res, tokensUsed: this.tokensUsed };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
for (const task of tasks) {
|
|
692
|
+
if (signal?.aborted) {
|
|
693
|
+
res.stop = 'aborted';
|
|
694
|
+
break;
|
|
695
|
+
}
|
|
696
|
+
if (this.seen.has(task.id)) continue;
|
|
697
|
+
|
|
698
|
+
if (isRecursiveTask(task)) {
|
|
699
|
+
this.denied += 1;
|
|
700
|
+
res.denied += 1;
|
|
701
|
+
this.seen.add(task.id);
|
|
702
|
+
this.#emit('task.denied', {
|
|
703
|
+
task_id: task.id,
|
|
704
|
+
reason: 'recursion',
|
|
705
|
+
origin: task.origin ?? null,
|
|
706
|
+
depth: task.depth ?? 0,
|
|
707
|
+
});
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
const reservation = this.#reserveBudget(task, tickNo);
|
|
712
|
+
if (!reservation.ok) {
|
|
713
|
+
res.ok = false;
|
|
714
|
+
res.stop = reservation.stop;
|
|
715
|
+
res.code = 'E_BUDGET_EXCEEDED';
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
let call;
|
|
720
|
+
try {
|
|
721
|
+
call = await this.#callModel(task, reservation.reserved, memory, signal);
|
|
722
|
+
} catch (error) {
|
|
723
|
+
this.#releaseReservation(reservation);
|
|
724
|
+
throw error;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
const settled = this.#settleBudget(task, reservation, call);
|
|
728
|
+
if (settled.stop) {
|
|
729
|
+
res.stop = settled.stop;
|
|
730
|
+
if (settled.code) res.code = settled.code;
|
|
731
|
+
break;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
if (call.aborted) {
|
|
735
|
+
this.#beginStop('aborted');
|
|
736
|
+
res.stop = 'aborted';
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
if (!call.ok) {
|
|
741
|
+
this.errors += 1;
|
|
742
|
+
res.errors += 1;
|
|
743
|
+
this.consecutiveErrors += 1;
|
|
744
|
+
this.seen.add(task.id);
|
|
745
|
+
this.#emit('task.error', {
|
|
746
|
+
task_id: task.id,
|
|
747
|
+
code: call.failure?.code ?? 'E_LLM',
|
|
748
|
+
message: call.failure?.message ?? 'llm call failed',
|
|
749
|
+
attempts: call.attempts ?? 0,
|
|
750
|
+
});
|
|
751
|
+
if (this.consecutiveErrors >= this.maxConsecutiveErrors) {
|
|
752
|
+
this.#beginStop('error_streak');
|
|
753
|
+
res.stop = 'error_streak';
|
|
754
|
+
break;
|
|
755
|
+
}
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
this.consecutiveErrors = 0;
|
|
760
|
+
const action = parseAction(call.text) ?? { type: 'noop' };
|
|
761
|
+
const type = action?.type;
|
|
762
|
+
|
|
763
|
+
if (recursiveAction(type)) {
|
|
764
|
+
this.denied += 1;
|
|
765
|
+
res.denied += 1;
|
|
766
|
+
this.seen.add(task.id);
|
|
767
|
+
this.#emit('action.denied', {
|
|
768
|
+
task_id: task.id,
|
|
769
|
+
reason: 'recursion',
|
|
770
|
+
action,
|
|
771
|
+
});
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
if (!DEFAULT_ALLOWED_ACTIONS.includes(type)) {
|
|
776
|
+
this.denied += 1;
|
|
777
|
+
res.denied += 1;
|
|
778
|
+
this.seen.add(task.id);
|
|
779
|
+
this.#emit('action.denied', {
|
|
780
|
+
task_id: task.id,
|
|
781
|
+
reason: 'action_not_allowed',
|
|
782
|
+
action,
|
|
783
|
+
});
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
this.processed += 1;
|
|
788
|
+
res.processed += 1;
|
|
789
|
+
this.seen.add(task.id);
|
|
790
|
+
this.#emit('action', {
|
|
791
|
+
task_id: task.id,
|
|
792
|
+
action,
|
|
793
|
+
attempts: call.attempts ?? 1,
|
|
794
|
+
usage: call.usage ?? null,
|
|
795
|
+
text: typeof call.text === 'string' ? call.text.slice(0, 500) : '',
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
res.tokensUsed = this.tokensUsed;
|
|
800
|
+
if (!res.stop && this.state === 'stopping') res.stop = this.stopReason ?? 'stopping';
|
|
801
|
+
return res;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
#reserveBudget(task, tickNo) {
|
|
805
|
+
// B:预留必须覆盖整条重试链,否则第 2 次 attempt 的 30 会因为「只预留 30」被 clamp。
|
|
806
|
+
const maxAttempts = Math.max(1, Number(this.retryOptions.maxAttempts) || 1);
|
|
807
|
+
const reservedTokens = this.callMaxTokens * maxAttempts;
|
|
808
|
+
let result;
|
|
809
|
+
try {
|
|
810
|
+
result = this.ledger.reserve({
|
|
811
|
+
taskId: task.id,
|
|
812
|
+
tokens: reservedTokens,
|
|
813
|
+
owner: this.runId,
|
|
814
|
+
tick: tickNo,
|
|
815
|
+
leaseMs: this.reservationLeaseMs,
|
|
816
|
+
});
|
|
817
|
+
} catch (error) {
|
|
818
|
+
throw error;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
if (!result.ok) {
|
|
822
|
+
this.#emit('budget.exceeded', {
|
|
823
|
+
task_id: task.id,
|
|
824
|
+
needed: reservedTokens,
|
|
825
|
+
remaining: result.remaining,
|
|
826
|
+
tokens_used: result.used,
|
|
827
|
+
tokens_reserved: result.reserved,
|
|
828
|
+
call_max_tokens: this.callMaxTokens,
|
|
829
|
+
max_attempts: maxAttempts,
|
|
830
|
+
});
|
|
831
|
+
this.#beginStop('budget_exceeded');
|
|
832
|
+
return { ok: false, stop: 'budget_exceeded' };
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
this.tokensUsed = result.used;
|
|
836
|
+
this.reservedTokens = result.reserved;
|
|
837
|
+
const reservation = {
|
|
838
|
+
id: result.id,
|
|
839
|
+
reserved: reservedTokens,
|
|
840
|
+
taskId: task.id,
|
|
841
|
+
settled: false,
|
|
842
|
+
};
|
|
843
|
+
this.#reservations.set(reservation.id, reservation);
|
|
844
|
+
|
|
845
|
+
try {
|
|
846
|
+
this.#emit('budget.reserve', {
|
|
847
|
+
tick: tickNo,
|
|
848
|
+
task_id: task.id,
|
|
849
|
+
reservation_id: reservation.id,
|
|
850
|
+
budgetReserved: reservation.reserved,
|
|
851
|
+
tokens_used: result.used,
|
|
852
|
+
tokens_remaining: result.remaining,
|
|
853
|
+
tokens_reserved: result.reserved,
|
|
854
|
+
call_max_tokens: this.callMaxTokens,
|
|
855
|
+
max_attempts: maxAttempts,
|
|
856
|
+
});
|
|
857
|
+
} catch (error) {
|
|
858
|
+
this.#releaseReservation(reservation);
|
|
859
|
+
throw error;
|
|
860
|
+
}
|
|
861
|
+
return { ok: true, ...reservation };
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
#settleBudget(task, reservation, call) {
|
|
865
|
+
const usage = call?.usage ?? null;
|
|
866
|
+
const rawTotal = usage?.totalTokens;
|
|
867
|
+
// 缺失 usage 按 0 处理;任何字段负数 / NaN / Infinity 都视为协议错误(F4/F12)。
|
|
868
|
+
// attempt 级 invalid(retry 累加时发现某次是 NaN/-20)也 fail-closed。
|
|
869
|
+
let fieldsValid = true;
|
|
870
|
+
if (usage !== null) {
|
|
871
|
+
if (typeof usage !== 'object' || usage.invalid) {
|
|
872
|
+
fieldsValid = false;
|
|
873
|
+
} else {
|
|
874
|
+
for (const field of ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'totalTokens']) {
|
|
875
|
+
const value = usage[field];
|
|
876
|
+
if (value === undefined || value === null) continue;
|
|
877
|
+
if (!Number.isFinite(Number(value)) || Number(value) < 0) fieldsValid = false;
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
const usageValid = usage === null ? true : (fieldsValid && !call?.invalidUsage);
|
|
882
|
+
// F5:重试链上「前一次合法花费」必须入账。retryOnFailure 已把非法 attempt 整次剔除、
|
|
883
|
+
// 且累计值单调不减,所以 invalidUsage 时 usage 里只剩已确认的合法用量(单次 NaN/-5 → 0)。
|
|
884
|
+
const accumulatedValid = usage !== null && Number.isFinite(Number(rawTotal)) && Number(rawTotal) >= 0;
|
|
885
|
+
const requested = usage === null ? 0 : (usageValid || call?.invalidUsage) && accumulatedValid ? Number(rawTotal) : 0;
|
|
886
|
+
|
|
887
|
+
// P0-1:settle 只记「预留内且不超硬上限」的部分。多出来的 token 拒绝入账,
|
|
888
|
+
// 但必须留下审计(requested/rejected),并让 Router 停下——不能像旧版那样先记 120 再报 overshoot。
|
|
889
|
+
let snapshot;
|
|
890
|
+
try {
|
|
891
|
+
snapshot = this.ledger.settle({ id: reservation.id, tokens: requested });
|
|
892
|
+
} catch (error) {
|
|
893
|
+
this.#releaseReservation(reservation);
|
|
894
|
+
throw error;
|
|
895
|
+
}
|
|
896
|
+
reservation.settled = true;
|
|
897
|
+
this.#reservations.delete(reservation.id);
|
|
898
|
+
|
|
899
|
+
if (snapshot.ok === false && snapshot.code === 'E_BUDGET_UNKNOWN_RESERVATION') {
|
|
900
|
+
this.lastError = {
|
|
901
|
+
code: snapshot.code,
|
|
902
|
+
message: `reservation ${reservation.id} is not active in the budget ledger`,
|
|
903
|
+
};
|
|
904
|
+
this.#emit('budget.settle_failed', {
|
|
905
|
+
task_id: task.id,
|
|
906
|
+
reservation_id: reservation.id,
|
|
907
|
+
code: snapshot.code,
|
|
908
|
+
});
|
|
909
|
+
this.#beginStop('ledger_unknown_reservation');
|
|
910
|
+
return { stop: 'ledger_unknown_reservation', code: snapshot.code };
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
const applied = Number.isFinite(snapshot.applied) ? snapshot.applied : requested;
|
|
914
|
+
const rejected = Number.isFinite(snapshot.rejected) ? snapshot.rejected : 0;
|
|
915
|
+
this.tokensUsed = snapshot.used;
|
|
916
|
+
this.reservedTokens = snapshot.reserved;
|
|
917
|
+
|
|
918
|
+
this.#emit('budget.settle', {
|
|
919
|
+
task_id: task.id,
|
|
920
|
+
reservation_id: reservation.id,
|
|
921
|
+
budgetReserved: reservation.reserved,
|
|
922
|
+
actual_tokens: applied,
|
|
923
|
+
requested_tokens: requested,
|
|
924
|
+
rejected_tokens: rejected,
|
|
925
|
+
usage,
|
|
926
|
+
usage_valid: usageValid,
|
|
927
|
+
tokens_total: this.tokensUsed,
|
|
928
|
+
tokens_used: this.tokensUsed,
|
|
929
|
+
});
|
|
930
|
+
// settle 之后立刻把「账本+审计到哪了」钉进锚,崩溃也不会留下无锚窗口。
|
|
931
|
+
this.#sealAnchor();
|
|
932
|
+
|
|
933
|
+
if (!usageValid) {
|
|
934
|
+
this.#emit('budget.usage_invalid', {
|
|
935
|
+
task_id: task.id,
|
|
936
|
+
code: 'E_USAGE_INVALID',
|
|
937
|
+
usage,
|
|
938
|
+
applied_tokens: applied,
|
|
939
|
+
});
|
|
940
|
+
this.lastError = { code: 'E_USAGE_INVALID', message: 'llm returned a negative or non-finite usage' };
|
|
941
|
+
this.#deadLetter(task, { reason: 'usage_invalid', code: 'E_USAGE_INVALID', tokens: applied });
|
|
942
|
+
this.#beginStop('usage_invalid');
|
|
943
|
+
return { stop: 'usage_invalid' };
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
if (snapshot.ok === false && snapshot.code === 'E_BUDGET_OVERSHOOT') {
|
|
947
|
+
this.lastError = {
|
|
948
|
+
code: snapshot.code,
|
|
949
|
+
message: `usage ${requested} exceeded the reservation (${reservation.reserved}) or the hard cap; ${rejected} token(s) rejected`,
|
|
950
|
+
};
|
|
951
|
+
this.#emit('budget.overshoot', {
|
|
952
|
+
task_id: task.id,
|
|
953
|
+
budgetReserved: reservation.reserved,
|
|
954
|
+
actual_tokens: requested,
|
|
955
|
+
applied_tokens: applied,
|
|
956
|
+
rejected_tokens: rejected,
|
|
957
|
+
tokens_total: this.tokensUsed,
|
|
958
|
+
});
|
|
959
|
+
// C:停机前落死信,重启后这条任务不会再被当成未处理而重跑一遍。
|
|
960
|
+
this.#deadLetter(task, { reason: 'budget_overshoot', code: 'E_BUDGET_OVERSHOOT', tokens: applied });
|
|
961
|
+
this.#beginStop('budget_overshoot');
|
|
962
|
+
return { stop: 'budget_overshoot', code: 'E_BUDGET_OVERSHOOT' };
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
if (call?.attemptOverflow) {
|
|
966
|
+
// B:单次 attempt 超过 callMaxTokens 是硬边界,即使总额还在整段预留内也必须 fail 任务。
|
|
967
|
+
this.lastError = {
|
|
968
|
+
code: 'E_USAGE_OVER_CALL_MAX',
|
|
969
|
+
message: `a single attempt reported more than callMaxTokens (${this.callMaxTokens}); task failed after billing ${applied}`,
|
|
970
|
+
};
|
|
971
|
+
this.#emit('budget.attempt_overflow', {
|
|
972
|
+
task_id: task.id,
|
|
973
|
+
call_max_tokens: this.callMaxTokens,
|
|
974
|
+
actual_tokens: applied,
|
|
975
|
+
requested_tokens: requested,
|
|
976
|
+
tokens_total: this.tokensUsed,
|
|
977
|
+
});
|
|
978
|
+
this.#deadLetter(task, { reason: 'attempt_usage_overflow', code: 'E_USAGE_OVER_CALL_MAX', tokens: applied });
|
|
979
|
+
this.#beginStop('usage_overflow');
|
|
980
|
+
return { stop: 'usage_overflow', code: 'E_USAGE_OVER_CALL_MAX' };
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
if (call?.stopReason) {
|
|
984
|
+
if (call.failure && ['NO_ADAPTER', 'MISSING_CREDENTIAL'].includes(call.failure.code)) {
|
|
985
|
+
this.#emit('llm.diagnostic', {
|
|
986
|
+
task_id: task.id,
|
|
987
|
+
code: call.failure.code,
|
|
988
|
+
message: call.failure.message,
|
|
989
|
+
provider: this.provider,
|
|
990
|
+
model: this.model,
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
this.#emit('llm.stop', {
|
|
994
|
+
task_id: task.id,
|
|
995
|
+
code: call.failure?.code ?? null,
|
|
996
|
+
stop_reason: call.stopReason,
|
|
997
|
+
});
|
|
998
|
+
this.#beginStop(call.stopReason);
|
|
999
|
+
return { stop: call.stopReason };
|
|
1000
|
+
}
|
|
1001
|
+
return {};
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* C:停机路径上的任务必须落死信(seen),否则重启后同一条任务会被重新调度、
|
|
1006
|
+
* 再花一遍钱。审计里的 task.error 就是重启时的 seen 来源。
|
|
1007
|
+
*/
|
|
1008
|
+
#deadLetter(task, { reason, code, tokens = 0 }) {
|
|
1009
|
+
if (!task || typeof task.id !== 'string') return;
|
|
1010
|
+
if (this.seen.has(task.id)) return;
|
|
1011
|
+
this.seen.add(task.id);
|
|
1012
|
+
this.deadLettered += 1;
|
|
1013
|
+
this.#emit('task.error', {
|
|
1014
|
+
task_id: task.id,
|
|
1015
|
+
code,
|
|
1016
|
+
message: `task dead-lettered: ${reason}; it will not be retried after restart`,
|
|
1017
|
+
reason,
|
|
1018
|
+
dead_letter: true,
|
|
1019
|
+
tokens: Number.isFinite(tokens) ? tokens : 0,
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** 把当前账本/审计位置钉进独立锚文件(D)。 */
|
|
1024
|
+
#sealAnchor() {
|
|
1025
|
+
const snapshot = this.ledger.snapshot();
|
|
1026
|
+
const auditRead = readAudit(this.auditPath, { maxRotations: this.audit.maxRotations });
|
|
1027
|
+
const last = auditRead.records[auditRead.records.length - 1] ?? null;
|
|
1028
|
+
const usage = foldAuditUsage(auditRead.records);
|
|
1029
|
+
return this.anchor.seal({
|
|
1030
|
+
ledger: {
|
|
1031
|
+
seq: snapshot.seq,
|
|
1032
|
+
lastHash: snapshot.lastHash,
|
|
1033
|
+
used: snapshot.used,
|
|
1034
|
+
reserved: snapshot.reserved,
|
|
1035
|
+
},
|
|
1036
|
+
audit: {
|
|
1037
|
+
file: this.auditPath,
|
|
1038
|
+
seq: last?.seq ?? 0,
|
|
1039
|
+
lastHash: last?.hash ?? null,
|
|
1040
|
+
settledUsed: usage.settledUsed,
|
|
1041
|
+
records: auditRead.records.length,
|
|
1042
|
+
},
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
#releaseReservation(reservation) {
|
|
1047
|
+
if (!reservation || reservation.settled) return;
|
|
1048
|
+
reservation.settled = true;
|
|
1049
|
+
this.#reservations.delete(reservation.id);
|
|
1050
|
+
try {
|
|
1051
|
+
const snapshot = this.ledger.release({ id: reservation.id });
|
|
1052
|
+
this.tokensUsed = snapshot.used;
|
|
1053
|
+
this.reservedTokens = snapshot.reserved;
|
|
1054
|
+
} catch {
|
|
1055
|
+
// 账本写失败时不要报一个假的“已释放”;tick 会走 fail-safe 停下。
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/**
|
|
1060
|
+
* P0-2:回收「pid 已死」或「租约过期」的 active 预留。
|
|
1061
|
+
* 每个 tick 都跑一次——长驻 Router 也要能接管兄弟进程崩溃后留下的预算。
|
|
1062
|
+
* 账本链被篡改时向上抛(fail-closed);其它账本 IO 错误不阻断本次 tick。
|
|
1063
|
+
*/
|
|
1064
|
+
#reclaimDeadReservations() {
|
|
1065
|
+
let snapshot;
|
|
1066
|
+
try {
|
|
1067
|
+
snapshot = this.ledger.reclaimDead({ now: Date.now() });
|
|
1068
|
+
} catch (error) {
|
|
1069
|
+
if (error?.code === 'E_LEDGER_TAMPERED') throw error;
|
|
1070
|
+
return null;
|
|
1071
|
+
}
|
|
1072
|
+
if (snapshot.released > 0) {
|
|
1073
|
+
this.tokensUsed = snapshot.used;
|
|
1074
|
+
this.reservedTokens = snapshot.reserved;
|
|
1075
|
+
this.#emit('budget.reclaim', {
|
|
1076
|
+
released: snapshot.released,
|
|
1077
|
+
freed_tokens: snapshot.freedTokens,
|
|
1078
|
+
items: snapshot.items.slice(0, 10),
|
|
1079
|
+
reason: 'tick',
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
return snapshot;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
async #callModel(task, reserved, memory, signal) {
|
|
1086
|
+
const system = memoryToSystemPrompt(memory.facts ?? []);
|
|
1087
|
+
const prompt = `Task ${task.id} (${task.type})\n${JSON.stringify(task.payload ?? {})}`;
|
|
1088
|
+
const messages = buildMessages({ system, prompt });
|
|
1089
|
+
this.lastMessages = messages;
|
|
1090
|
+
|
|
1091
|
+
const result = await retryOnFailure(
|
|
1092
|
+
(attempt) => this.#callOnce({ task, reserved, messages, signal, attempt }),
|
|
1093
|
+
{
|
|
1094
|
+
...this.retryOptions,
|
|
1095
|
+
signal,
|
|
1096
|
+
onRetry: ({ attempt, code, delayMs }) => {
|
|
1097
|
+
this.#emit('llm.retry', {
|
|
1098
|
+
task_id: task.id,
|
|
1099
|
+
attempt,
|
|
1100
|
+
code,
|
|
1101
|
+
delay_ms: delayMs,
|
|
1102
|
+
});
|
|
1103
|
+
},
|
|
1104
|
+
},
|
|
1105
|
+
);
|
|
1106
|
+
|
|
1107
|
+
if (result.invalidUsage) {
|
|
1108
|
+
return {
|
|
1109
|
+
ok: false,
|
|
1110
|
+
aborted: false,
|
|
1111
|
+
invalidUsage: true,
|
|
1112
|
+
failure: null,
|
|
1113
|
+
usage: result.usage ?? null,
|
|
1114
|
+
attempts: result.attempts,
|
|
1115
|
+
attemptOverflow: result.attemptOverflow === true,
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
if (result.aborted) {
|
|
1119
|
+
return {
|
|
1120
|
+
ok: false,
|
|
1121
|
+
aborted: true,
|
|
1122
|
+
failure: result.failure,
|
|
1123
|
+
usage: result.usage ?? result.result?.usage,
|
|
1124
|
+
attempts: result.attempts,
|
|
1125
|
+
attemptOverflow: result.attemptOverflow === true,
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
if (result.failure) {
|
|
1129
|
+
return {
|
|
1130
|
+
ok: false,
|
|
1131
|
+
aborted: false,
|
|
1132
|
+
failure: result.failure,
|
|
1133
|
+
usage: result.usage ?? result.result?.usage,
|
|
1134
|
+
attempts: result.attempts,
|
|
1135
|
+
attemptOverflow: result.attemptOverflow === true,
|
|
1136
|
+
stopReason: result.stopReason,
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
return {
|
|
1140
|
+
ok: true,
|
|
1141
|
+
text: result.text,
|
|
1142
|
+
usage: result.usage,
|
|
1143
|
+
finish: result.finish,
|
|
1144
|
+
attempts: result.attempts,
|
|
1145
|
+
attemptOverflow: result.attemptOverflow === true,
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
async #callOnce({ task, reserved, messages, signal, attempt }) {
|
|
1150
|
+
const callController = new AbortController();
|
|
1151
|
+
const unlink = this.#linkAbort(signal, callController);
|
|
1152
|
+
let timedOut = false;
|
|
1153
|
+
const timer = setTimeout(() => {
|
|
1154
|
+
timedOut = true;
|
|
1155
|
+
callController.abort('timeout');
|
|
1156
|
+
}, this.callTimeoutMs);
|
|
1157
|
+
timer.unref?.();
|
|
1158
|
+
|
|
1159
|
+
try {
|
|
1160
|
+
// 真宿主(dsh-llm README:50-57)要求 provider + model;缺了就是 NO_ADAPTER。
|
|
1161
|
+
const stream = this.llm.stream({
|
|
1162
|
+
provider: this.provider,
|
|
1163
|
+
model: this.model,
|
|
1164
|
+
messages,
|
|
1165
|
+
task,
|
|
1166
|
+
signal: callController.signal,
|
|
1167
|
+
// 单次调用只允许 callMaxTokens;整段预留覆盖 maxAttempts 次,不能让一次 attempt 吃掉全部。
|
|
1168
|
+
maxTokens: this.callMaxTokens,
|
|
1169
|
+
attempt,
|
|
1170
|
+
});
|
|
1171
|
+
const result = await consumeStream(stream, {
|
|
1172
|
+
signal: callController.signal,
|
|
1173
|
+
returnTimeoutMs: Math.max(50, Math.min(this.callTimeoutMs, 200)),
|
|
1174
|
+
});
|
|
1175
|
+
const withOverflow = (r) => {
|
|
1176
|
+
const total = Number(r?.usage?.totalTokens);
|
|
1177
|
+
return { ...r, attemptOverflow: Number.isFinite(total) && total > this.callMaxTokens };
|
|
1178
|
+
};
|
|
1179
|
+
if (timedOut && !result.finished && !signal?.aborted) {
|
|
1180
|
+
return withOverflow({
|
|
1181
|
+
failure: { code: 'TIMEOUT', message: `llm call timed out after ${this.callTimeoutMs}ms` },
|
|
1182
|
+
usage: result.usage,
|
|
1183
|
+
aborted: false,
|
|
1184
|
+
result,
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
return withOverflow(result);
|
|
1188
|
+
} finally {
|
|
1189
|
+
clearTimeout(timer);
|
|
1190
|
+
unlink();
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* 停止:先 abort,再等在飞 tick 到边界(带超时),超时强制释放预留,最后关审计。
|
|
1196
|
+
* 幂等;router.stop 写不进去时返回 ok:false + E_AUDIT_WRITE。
|
|
1197
|
+
*/
|
|
1198
|
+
async stop(reason = 'manual') {
|
|
1199
|
+
if (this.state === 'stopped' || this.#disposed) {
|
|
1200
|
+
return {
|
|
1201
|
+
ok: true,
|
|
1202
|
+
alreadyStopped: true,
|
|
1203
|
+
state: this.state,
|
|
1204
|
+
stopReason: this.stopReason,
|
|
1205
|
+
processed: this.processed,
|
|
1206
|
+
denied: this.denied,
|
|
1207
|
+
errors: this.errors,
|
|
1208
|
+
tokensUsed: this.tokensUsed,
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
const wasStopping = this.state === 'stopping';
|
|
1212
|
+
this.#beginStop(reason);
|
|
1213
|
+
const timedOut = await this.#awaitInflight(this.stopTimeoutMs);
|
|
1214
|
+
let released = 0;
|
|
1215
|
+
if (timedOut) {
|
|
1216
|
+
try {
|
|
1217
|
+
const snapshot = this.ledger.releaseOwner({ owner: this.runId });
|
|
1218
|
+
released = snapshot.released;
|
|
1219
|
+
this.tokensUsed = snapshot.used;
|
|
1220
|
+
this.reservedTokens = snapshot.reserved;
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
this.lastError = { code: error?.code ?? 'E_BUDGET_WRITE', message: error.message };
|
|
1223
|
+
}
|
|
1224
|
+
for (const reservation of this.#reservations.values()) reservation.settled = true;
|
|
1225
|
+
this.#reservations.clear();
|
|
1226
|
+
// 僵尸 tick 不再阻塞 busy,也不再占着 stop() 的返回值。
|
|
1227
|
+
this.busy = false;
|
|
1228
|
+
try {
|
|
1229
|
+
this.audit.append('stop.timeout', { ms: this.stopTimeoutMs, released });
|
|
1230
|
+
} catch {
|
|
1231
|
+
this.#auditBroken = true;
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
const finalized = await this.#finalizeStop();
|
|
1235
|
+
return {
|
|
1236
|
+
ok: finalized.ok,
|
|
1237
|
+
code: finalized.code,
|
|
1238
|
+
alreadyStopped: wasStopping,
|
|
1239
|
+
state: this.state,
|
|
1240
|
+
stopReason: this.stopReason,
|
|
1241
|
+
timedOut,
|
|
1242
|
+
released,
|
|
1243
|
+
auditBroken: this.#auditBroken,
|
|
1244
|
+
processed: this.processed,
|
|
1245
|
+
denied: this.denied,
|
|
1246
|
+
errors: this.errors,
|
|
1247
|
+
tokensUsed: this.tokensUsed,
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
async dispose() {
|
|
1252
|
+
if (this.#disposed) return { ok: true, alreadyDisposed: true };
|
|
1253
|
+
let stop = null;
|
|
1254
|
+
if (this.started && this.state !== 'stopped') {
|
|
1255
|
+
stop = await this.stop('dispose');
|
|
1256
|
+
} else {
|
|
1257
|
+
this.#timerDispose?.();
|
|
1258
|
+
this.#timerDispose = null;
|
|
1259
|
+
try { this.audit.close(); } catch { /* best effort */ }
|
|
1260
|
+
this.state = 'disposed';
|
|
1261
|
+
}
|
|
1262
|
+
try { this.ledger.releaseOwner({ owner: this.runId }); } catch { /* best effort */ }
|
|
1263
|
+
this.#disposed = true;
|
|
1264
|
+
this.state = 'disposed';
|
|
1265
|
+
return { ok: true, alreadyDisposed: false, stop };
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/** 需要真实 agent 路径时显式调用;Router 的普通 tick 不隐式创建 agent。 */
|
|
1269
|
+
async runInAgent(task, { prompt = null, setup = null, timeoutMs = 5000 } = {}) {
|
|
1270
|
+
if (!this.agents) {
|
|
1271
|
+
return { ok: false, code: 'E_NO_AGENTS', message: 'Router was constructed without ctx.agents' };
|
|
1272
|
+
}
|
|
1273
|
+
return runAgentTask({
|
|
1274
|
+
agents: this.agents,
|
|
1275
|
+
prompt: prompt ?? `Task ${task.id} (${task.type})\n${JSON.stringify(task.payload ?? {})}`,
|
|
1276
|
+
setup: setup ?? this.agentSetup,
|
|
1277
|
+
agentOptions: this.agentOptions,
|
|
1278
|
+
sessionId: this.sessionId ?? `${this.runId}-${task.id}`,
|
|
1279
|
+
signal: this.#controller.signal,
|
|
1280
|
+
timeoutMs,
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
result() {
|
|
1285
|
+
return {
|
|
1286
|
+
ok: this.state === 'running',
|
|
1287
|
+
state: this.state,
|
|
1288
|
+
runId: this.runId,
|
|
1289
|
+
stop: this.stopReason,
|
|
1290
|
+
tick: this.ticks,
|
|
1291
|
+
processed: this.processed,
|
|
1292
|
+
denied: this.denied,
|
|
1293
|
+
errors: this.errors,
|
|
1294
|
+
tokensUsed: this.tokensUsed,
|
|
1295
|
+
busy: this.busy,
|
|
1296
|
+
budget: this.budget,
|
|
1297
|
+
lastError: this.lastError,
|
|
1298
|
+
auditBroken: this.#auditBroken,
|
|
1299
|
+
provider: this.provider,
|
|
1300
|
+
model: this.model,
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
modelessResult() {
|
|
1305
|
+
return this.result();
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
#linkAbort(parent, target) {
|
|
1309
|
+
if (parent.aborted) {
|
|
1310
|
+
target.abort(parent.reason);
|
|
1311
|
+
return () => {};
|
|
1312
|
+
}
|
|
1313
|
+
const onAbort = () => target.abort(parent.reason);
|
|
1314
|
+
parent.addEventListener('abort', onAbort, { once: true });
|
|
1315
|
+
return () => parent.removeEventListener('abort', onAbort);
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
#beginStop(reason) {
|
|
1319
|
+
if (this.state === 'stopped') return;
|
|
1320
|
+
if (!this.stopReason) this.stopReason = reason;
|
|
1321
|
+
if (this.state === 'running') this.state = 'stopping';
|
|
1322
|
+
this.#controller.abort(reason);
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
async #awaitInflight(timeoutMs) {
|
|
1326
|
+
if (this.#inflight.size === 0) return false;
|
|
1327
|
+
let timedOut = false;
|
|
1328
|
+
let timer;
|
|
1329
|
+
const timeout = new Promise((resolve) => {
|
|
1330
|
+
timer = setTimeout(() => {
|
|
1331
|
+
timedOut = true;
|
|
1332
|
+
resolve();
|
|
1333
|
+
}, timeoutMs);
|
|
1334
|
+
// E:这里绝不能 unref。裸进程中唯一的 ref 可能就是这颗定时器;
|
|
1335
|
+
// unref 之后 event loop 会提前退出,race 永远等不到 resolve(旧实现会挂住)。
|
|
1336
|
+
});
|
|
1337
|
+
await Promise.race([Promise.allSettled([...this.#inflight]), timeout]);
|
|
1338
|
+
clearTimeout(timer);
|
|
1339
|
+
return timedOut;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
async #finalizeStop() {
|
|
1343
|
+
if (this.#finalized) return this.#finalResult ?? { ok: true };
|
|
1344
|
+
this.#finalized = true;
|
|
1345
|
+
this.state = 'stopped';
|
|
1346
|
+
this.alreadyStopped = true;
|
|
1347
|
+
let ok = true;
|
|
1348
|
+
let code;
|
|
1349
|
+
if (this.started) {
|
|
1350
|
+
try {
|
|
1351
|
+
this.audit.append('router.stop', {
|
|
1352
|
+
reason: this.stopReason,
|
|
1353
|
+
processed: this.processed,
|
|
1354
|
+
denied: this.denied,
|
|
1355
|
+
errors: this.errors,
|
|
1356
|
+
tokens_used: this.tokensUsed,
|
|
1357
|
+
});
|
|
1358
|
+
} catch (error) {
|
|
1359
|
+
// P12:stop 都写不进审计时不能 ok:true。状态仍然是 stopped。
|
|
1360
|
+
this.#auditBroken = true;
|
|
1361
|
+
ok = false;
|
|
1362
|
+
code = 'E_AUDIT_WRITE';
|
|
1363
|
+
this.lastError = { code, message: `cannot append router.stop: ${error.message}` };
|
|
1364
|
+
}
|
|
1365
|
+
if (ok) {
|
|
1366
|
+
try {
|
|
1367
|
+
// 停机封口:最后一次 checkpoint 覆盖 router.stop,重启时从锚校验整段历史。
|
|
1368
|
+
this.#sealAnchor();
|
|
1369
|
+
} catch (error) {
|
|
1370
|
+
ok = false;
|
|
1371
|
+
code = error?.code ?? 'E_ANCHOR_WRITE';
|
|
1372
|
+
this.lastError = { code, message: `cannot seal budget anchor: ${error.message}` };
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
try { this.audit.close(); } catch { /* best effort */ }
|
|
1377
|
+
this.#timerDispose?.();
|
|
1378
|
+
this.#timerDispose = null;
|
|
1379
|
+
this.#finalResult = { ok, code };
|
|
1380
|
+
return this.#finalResult;
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
#failSafe(error) {
|
|
1384
|
+
const code = error?.code ?? 'E_TICK';
|
|
1385
|
+
this.lastError = { code, message: error?.message ?? String(error) };
|
|
1386
|
+
this.#auditBroken = true;
|
|
1387
|
+
this.#beginStop(code === 'E_AUDIT_WRITE' ? 'audit_failed' : 'tick_crashed');
|
|
1388
|
+
this.state = 'stopped';
|
|
1389
|
+
try {
|
|
1390
|
+
const snapshot = this.ledger.releaseOwner({ owner: this.runId });
|
|
1391
|
+
this.tokensUsed = snapshot.used;
|
|
1392
|
+
this.reservedTokens = snapshot.reserved;
|
|
1393
|
+
} catch { /* ledger might itself be broken */ }
|
|
1394
|
+
this.#reservations.clear();
|
|
1395
|
+
this.busy = false;
|
|
1396
|
+
try { this.audit.close(); } catch { /* best effort */ }
|
|
1397
|
+
this.#timerDispose?.();
|
|
1398
|
+
this.#timerDispose = null;
|
|
1399
|
+
return {
|
|
1400
|
+
ok: false,
|
|
1401
|
+
code,
|
|
1402
|
+
message: this.lastError.message,
|
|
1403
|
+
state: this.state,
|
|
1404
|
+
stop: this.stopReason,
|
|
1405
|
+
processed: this.processed,
|
|
1406
|
+
denied: this.denied,
|
|
1407
|
+
errors: this.errors,
|
|
1408
|
+
tokensUsed: this.tokensUsed,
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
#emit(kind, data = {}) {
|
|
1413
|
+
if (this.#auditBroken) {
|
|
1414
|
+
const error = new Error('audit is broken; refusing to continue without an evidence trail');
|
|
1415
|
+
error.code = 'E_AUDIT_WRITE';
|
|
1416
|
+
throw error;
|
|
1417
|
+
}
|
|
1418
|
+
try {
|
|
1419
|
+
this.audit.append(kind, data);
|
|
1420
|
+
} catch (cause) {
|
|
1421
|
+
this.#auditBroken = true;
|
|
1422
|
+
const error = new Error(`audit append failed: ${cause.message}`);
|
|
1423
|
+
error.code = 'E_AUDIT_WRITE';
|
|
1424
|
+
error.cause = cause;
|
|
1425
|
+
throw error;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
#installTimer() {
|
|
1430
|
+
if (!Number.isFinite(this.heartbeatMs) || this.heartbeatMs <= 0) return;
|
|
1431
|
+
let installed = null;
|
|
1432
|
+
const install = () => {
|
|
1433
|
+
const timer = setInterval(() => {
|
|
1434
|
+
if (this.state !== 'running') return;
|
|
1435
|
+
try {
|
|
1436
|
+
this.#emit('router.heartbeat', { tokensUsed: this.tokensUsed, tick: this.ticks });
|
|
1437
|
+
} catch (error) {
|
|
1438
|
+
this.#failSafe(error);
|
|
1439
|
+
}
|
|
1440
|
+
}, this.heartbeatMs);
|
|
1441
|
+
timer.unref?.();
|
|
1442
|
+
installed = () => clearInterval(timer);
|
|
1443
|
+
return installed;
|
|
1444
|
+
};
|
|
1445
|
+
try {
|
|
1446
|
+
if (typeof this.ctx?.effect === 'function') {
|
|
1447
|
+
// 宿主 effect 契约在不同版本里可能是「返回 disposer」或「调用 fn 并用其
|
|
1448
|
+
// 返回值做清理」;两条都接住,避免定时器泄漏。
|
|
1449
|
+
const ret = this.ctx.effect(install);
|
|
1450
|
+
this.#timerDispose = typeof ret === 'function' ? ret : installed;
|
|
1451
|
+
if (!this.#timerDispose) this.#timerDispose = install();
|
|
1452
|
+
} else {
|
|
1453
|
+
this.#timerDispose = install();
|
|
1454
|
+
}
|
|
1455
|
+
} catch (error) {
|
|
1456
|
+
this.#failSafe(error);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
}
|