@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.
Files changed (331) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +21 -0
  3. package/QUICKSTART.md +362 -0
  4. package/README.en.md +64 -0
  5. package/README.md +256 -2
  6. package/SPEC.md +211 -0
  7. package/build-info.json +1665 -0
  8. package/cordis.patch.yml +208 -0
  9. package/docs/A1-MIGRATION.md +75 -0
  10. package/docs/ANSWER-GUARD.md +92 -0
  11. package/docs/ARCHITECTURE.md +128 -0
  12. package/docs/AUTO-RECALL-WIRING.md +115 -0
  13. package/docs/AUTO-RECALL.md +237 -0
  14. package/docs/CONCEPTS.md +143 -0
  15. package/docs/CONFIG.md +839 -0
  16. package/docs/ERRORS.md +271 -0
  17. package/docs/FAQ.md +186 -0
  18. package/docs/FEATURES.md +579 -0
  19. package/docs/INDEX-FRESHNESS.md +21 -0
  20. package/docs/METRICS.md +244 -0
  21. package/docs/MIGRATION-1.6.0.md +220 -0
  22. package/docs/OPERATIONS.md +439 -0
  23. package/docs/PANEL-INTEGRATION.md +190 -0
  24. package/docs/PRIVACY.md +88 -0
  25. package/docs/QUICKSTART.md +155 -0
  26. package/docs/RAW-INDEX-POLICY.md +7 -0
  27. package/docs/README.en.md +48 -0
  28. package/docs/RESIDENT-WATCHER.md +90 -0
  29. package/docs/SESSION-WATCH.md +214 -0
  30. package/docs/TOOLS.md +184 -0
  31. package/docs/TROUBLESHOOTING.md +329 -0
  32. package/icon.svg +11 -0
  33. package/lib/client.js +436 -0
  34. package/locale/en.json +6 -0
  35. package/locale/zh.json +6 -0
  36. package/package.json +163 -4
  37. package/runbook.md +343 -0
  38. package/scripts/archive-digest-build.mjs +668 -0
  39. package/scripts/auto-truncate-run.ps1 +752 -0
  40. package/scripts/backfill-auto-cards.mjs +98 -0
  41. package/scripts/edges-build.mjs +1003 -0
  42. package/scripts/index-maintain.mjs +39 -0
  43. package/scripts/index-reconcile.mjs +49 -0
  44. package/scripts/index-status.mjs +28 -0
  45. package/scripts/install-resident-watcher.ps1 +15 -0
  46. package/scripts/install-session-watch.ps1 +332 -0
  47. package/scripts/install-surgery-task.ps1 +174 -0
  48. package/scripts/lib/auto-truncate-run.ps1 +512 -0
  49. package/scripts/lib/session-watch-fixture.mjs +207 -0
  50. package/scripts/longlive-doctor.mjs +578 -0
  51. package/scripts/metrics-read.mjs +79 -0
  52. package/scripts/metrics-sample.mjs +215 -0
  53. package/scripts/migrate-180.mjs +163 -0
  54. package/scripts/migrate-200.mjs +8 -0
  55. package/scripts/migrate-a1-legacy.mjs +62 -0
  56. package/scripts/migrate-lifecycle.mjs +157 -0
  57. package/scripts/pack.mjs +392 -0
  58. package/scripts/recall-index-build.mjs +128 -0
  59. package/scripts/recall-links-build.mjs +420 -0
  60. package/scripts/rescore-cards.mjs +36 -0
  61. package/scripts/resident-watcher-status.ps1 +15 -0
  62. package/scripts/resident-watcher.ps1 +643 -0
  63. package/scripts/session-watch-drill.mjs +553 -0
  64. package/scripts/session-watch-status.ps1 +146 -0
  65. package/scripts/session-watch.mjs +1367 -0
  66. package/scripts/surgery-inspect.mjs +122 -0
  67. package/scripts/surgery-run.cmd +34 -0
  68. package/scripts/truncate-cli.mjs +279 -0
  69. package/scripts/unattended-surgery.ps1 +1019 -0
  70. package/scripts/uninstall-resident-watcher.ps1 +15 -0
  71. package/scripts/uninstall-session-watch.ps1 +192 -0
  72. package/scripts/verify-card-anchors.mjs +138 -0
  73. package/scripts/watch-loop.ps1 +916 -0
  74. package/src/actions/audit.js +125 -0
  75. package/src/actions/evidence.js +122 -0
  76. package/src/actions/fs.js +162 -0
  77. package/src/activity/index.js +873 -0
  78. package/src/activity/model.js +351 -0
  79. package/src/activity/store.js +786 -0
  80. package/src/activity/summary.js +180 -0
  81. package/src/activity/thinking.js +191 -0
  82. package/src/adapters/constants.js +11 -0
  83. package/src/adapters/engram/data/aliases.json +51 -0
  84. package/src/adapters/engram/data/policy.json +8 -0
  85. package/src/adapters/engram/data/routing-rules.json +546 -0
  86. package/src/adapters/engram/index.js +278 -0
  87. package/src/adapters/registry.js +315 -0
  88. package/src/answer/audit.js +238 -0
  89. package/src/answer/claim-guard.mjs +234 -0
  90. package/src/answer/evidence.js +30 -0
  91. package/src/answer/guard.js +1370 -0
  92. package/src/answer/index.js +1086 -0
  93. package/src/answer/query.js +111 -0
  94. package/src/answer/second-hop.mjs +101 -0
  95. package/src/auto-truncate-status.js +164 -0
  96. package/src/auto-truncate.js +1181 -0
  97. package/src/autoprocedure/candidate.js +342 -0
  98. package/src/autoprocedure/config.js +122 -0
  99. package/src/autoprocedure/evidence.js +345 -0
  100. package/src/autoprocedure/index.js +83 -0
  101. package/src/autoprocedure/ledger.js +329 -0
  102. package/src/autoprocedure/lint.js +232 -0
  103. package/src/autoprocedure/llm.js +409 -0
  104. package/src/autoprocedure/locks.js +102 -0
  105. package/src/autoprocedure/paths.js +39 -0
  106. package/src/autoprocedure/privacy.js +87 -0
  107. package/src/autoprocedure/rules.js +288 -0
  108. package/src/autoprocedure/runtime.js +718 -0
  109. package/src/autoprocedure/session-reader.js +328 -0
  110. package/src/backup.js +310 -0
  111. package/src/bus/bus.mjs +1446 -0
  112. package/src/codec.js +269 -0
  113. package/src/compaction/cut-engine.js +44 -0
  114. package/src/compaction/engine-core.js +1237 -0
  115. package/src/compaction/entry.js +228 -0
  116. package/src/compaction.js +230 -0
  117. package/src/conclusion.js +366 -0
  118. package/src/config.js +835 -0
  119. package/src/d6/runtime.js +517 -0
  120. package/src/d6/surface.js +181 -0
  121. package/src/deps.js +189 -0
  122. package/src/engine-status.js +141 -0
  123. package/src/features.js +1035 -0
  124. package/src/handoff/index.js +1077 -0
  125. package/src/handoff/model.js +1058 -0
  126. package/src/handoff/store.js +1233 -0
  127. package/src/heartbeat.js +385 -0
  128. package/src/home.js +16 -0
  129. package/src/host-version.js +280 -0
  130. package/src/hot-truncate-diag.js +98 -0
  131. package/src/identity/card-marker.js +281 -0
  132. package/src/identity/handover.js +845 -0
  133. package/src/identity/index.js +337 -0
  134. package/src/identity/inject-position.js +133 -0
  135. package/src/identity/writeback.js +344 -0
  136. package/src/identity.js +118 -0
  137. package/src/index.js +647 -0
  138. package/src/lifecycle/gap-clocks.js +364 -0
  139. package/src/lifecycle/index.js +269 -0
  140. package/src/lifecycle/proactive.js +1426 -0
  141. package/src/live-target.js +212 -0
  142. package/src/live.js +1603 -0
  143. package/src/log-rotation.js +153 -0
  144. package/src/memory/a1-migration.js +190 -0
  145. package/src/memory/activity-capture.js +229 -0
  146. package/src/memory/anchor-fallback.js +116 -0
  147. package/src/memory/anchors.js +194 -0
  148. package/src/memory/archive-cold-state.mjs +794 -0
  149. package/src/memory/archive-staging.mjs +305 -0
  150. package/src/memory/archive.mjs +415 -0
  151. package/src/memory/audit-records.js +222 -0
  152. package/src/memory/auto-cards.js +441 -0
  153. package/src/memory/capture-host.js +297 -0
  154. package/src/memory/capture.js +496 -0
  155. package/src/memory/card-anchors.js +203 -0
  156. package/src/memory/card-priority.js +110 -0
  157. package/src/memory/cards.js +425 -0
  158. package/src/memory/catchup.mjs +534 -0
  159. package/src/memory/conclusion-distill.js +381 -0
  160. package/src/memory/conclusion-drafts.js +243 -0
  161. package/src/memory/conflicts.js +1060 -0
  162. package/src/memory/consolidate.js +834 -0
  163. package/src/memory/decay.js +311 -0
  164. package/src/memory/distill.js +485 -0
  165. package/src/memory/event-index.js +1826 -0
  166. package/src/memory/evidence-chain.js +295 -0
  167. package/src/memory/evidence.js +213 -0
  168. package/src/memory/filter-runner.js +555 -0
  169. package/src/memory/filter.js +1035 -0
  170. package/src/memory/forget-v2.js +680 -0
  171. package/src/memory/forget.js +531 -0
  172. package/src/memory/frames-activation.js +249 -0
  173. package/src/memory/frontmatter.js +454 -0
  174. package/src/memory/fts-query.js +342 -0
  175. package/src/memory/governance.js +604 -0
  176. package/src/memory/index-freshness.js +234 -0
  177. package/src/memory/index.js +435 -0
  178. package/src/memory/l2-gate.js +169 -0
  179. package/src/memory/land.mjs +743 -0
  180. package/src/memory/lifecycle.js +235 -0
  181. package/src/memory/lock.js +121 -0
  182. package/src/memory/maintenance.js +1149 -0
  183. package/src/memory/manifest.js +245 -0
  184. package/src/memory/memory-health.mjs +607 -0
  185. package/src/memory/migrate-200.js +1681 -0
  186. package/src/memory/migrate-lifecycle.js +1808 -0
  187. package/src/memory/migrate.js +139 -0
  188. package/src/memory/paths.js +229 -0
  189. package/src/memory/procedure-candidate.mjs +377 -0
  190. package/src/memory/procedure.js +982 -0
  191. package/src/memory/prospective-memory.mjs +362 -0
  192. package/src/memory/provenance.js +119 -0
  193. package/src/memory/recall-feedback.mjs +406 -0
  194. package/src/memory/recall-v2.js +218 -0
  195. package/src/memory/recall.js +357 -0
  196. package/src/memory/reconcile.js +265 -0
  197. package/src/memory/records.js +433 -0
  198. package/src/memory/reinforce.js +281 -0
  199. package/src/memory/retention.js +162 -0
  200. package/src/memory/review.js +124 -0
  201. package/src/memory/state.js +279 -0
  202. package/src/memory/tiers.js +168 -0
  203. package/src/memory/topic-phrases.js +73 -0
  204. package/src/memory/trust.js +97 -0
  205. package/src/memory/turn-budget.mjs +290 -0
  206. package/src/memory/version-chain.js +264 -0
  207. package/src/memory/wake-bridge.mjs +2999 -0
  208. package/src/memory/wal.js +137 -0
  209. package/src/memory/working-frame.js +779 -0
  210. package/src/metrics/classify.mjs +191 -0
  211. package/src/metrics/estimate.mjs +108 -0
  212. package/src/metrics/index.mjs +204 -0
  213. package/src/metrics/measure.mjs +462 -0
  214. package/src/metrics/prestep-latency.mjs +307 -0
  215. package/src/metrics/store.mjs +264 -0
  216. package/src/original.js +294 -0
  217. package/src/policy/threshold-policy.js +224 -0
  218. package/src/policy-profile.js +463 -0
  219. package/src/recall/anaphora.mjs +87 -0
  220. package/src/recall/archive-config.mjs +130 -0
  221. package/src/recall/archive-fallback.mjs +390 -0
  222. package/src/recall/archive-search.mjs +428 -0
  223. package/src/recall/archive-state.mjs +588 -0
  224. package/src/recall/brain.mjs +501 -0
  225. package/src/recall/cards.mjs +202 -0
  226. package/src/recall/current-line.mjs +110 -0
  227. package/src/recall/edges.js +398 -0
  228. package/src/recall/embedding.mjs +698 -0
  229. package/src/recall/entities.mjs +112 -0
  230. package/src/recall/explain.mjs +443 -0
  231. package/src/recall/force-policy.mjs +138 -0
  232. package/src/recall/gate-log.mjs +280 -0
  233. package/src/recall/gate-metrics.mjs +191 -0
  234. package/src/recall/index.js +1337 -0
  235. package/src/recall/inject-order.mjs +279 -0
  236. package/src/recall/link-recall.mjs +183 -0
  237. package/src/recall/links.mjs +696 -0
  238. package/src/recall/privacy.mjs +208 -0
  239. package/src/recall/recall-core.mjs +810 -0
  240. package/src/recall/shared-visibility.js +302 -0
  241. package/src/recall/time-normalizer.mjs +196 -0
  242. package/src/recall/turn-budget-inject.mjs +154 -0
  243. package/src/retention/cold-gate.mjs +146 -0
  244. package/src/retention/config.js +163 -0
  245. package/src/retention/index.js +801 -0
  246. package/src/role/activation.js +191 -0
  247. package/src/role/attention.js +318 -0
  248. package/src/role/base.js +36 -0
  249. package/src/role/channels.js +423 -0
  250. package/src/role/index.js +425 -0
  251. package/src/role/interfaces.js +115 -0
  252. package/src/role/personality.js +370 -0
  253. package/src/role/readers.js +151 -0
  254. package/src/role/relationships.js +477 -0
  255. package/src/role/store.js +202 -0
  256. package/src/role/writeprotect.js +373 -0
  257. package/src/router/aliases.json +182 -0
  258. package/src/router/background/agent-runner.mjs +239 -0
  259. package/src/router/background/anchor.mjs +323 -0
  260. package/src/router/background/audit.mjs +337 -0
  261. package/src/router/background/budget-ledger.mjs +648 -0
  262. package/src/router/background/host-sim.mjs +451 -0
  263. package/src/router/background/index.mjs +81 -0
  264. package/src/router/background/memory.mjs +63 -0
  265. package/src/router/background/mock-llm.mjs +203 -0
  266. package/src/router/background/queue.mjs +224 -0
  267. package/src/router/background/retry.mjs +255 -0
  268. package/src/router/background/router.mjs +1459 -0
  269. package/src/router/background/stream.mjs +276 -0
  270. package/src/router/background/tool-policy.mjs +255 -0
  271. package/src/router/design-headings.json +221 -0
  272. package/src/router/face/config.mjs +155 -0
  273. package/src/router/face/context.mjs +284 -0
  274. package/src/router/face/face.mjs +466 -0
  275. package/src/router/face/identity.mjs +130 -0
  276. package/src/router/face/index.mjs +65 -0
  277. package/src/router/face/journal.mjs +119 -0
  278. package/src/router/face/llm.mjs +252 -0
  279. package/src/router/face/outbox.mjs +153 -0
  280. package/src/router/face/paths.mjs +54 -0
  281. package/src/router/judge.mjs +987 -0
  282. package/src/router/policies/generic.json +131 -0
  283. package/src/router/route.js +1766 -0
  284. package/src/router/router.mjs +535 -0
  285. package/src/router/routing-rules.json +816 -0
  286. package/src/router/run-sim.mjs +530 -0
  287. package/src/router/runtime.js +569 -0
  288. package/src/router/service/apply.mjs +1218 -0
  289. package/src/router/service/board.mjs +712 -0
  290. package/src/router/service/caller.mjs +131 -0
  291. package/src/router/service/config.mjs +361 -0
  292. package/src/router/service/context.mjs +314 -0
  293. package/src/router/service/hint.mjs +668 -0
  294. package/src/router/service/lease.mjs +494 -0
  295. package/src/router/service/live.mjs +251 -0
  296. package/src/router/service/lock.mjs +550 -0
  297. package/src/router/service/merge.mjs +255 -0
  298. package/src/router/service/model-resolve.mjs +350 -0
  299. package/src/router/service/paths.mjs +168 -0
  300. package/src/router/service/proposals.mjs +1461 -0
  301. package/src/router/service/queue.mjs +477 -0
  302. package/src/router/service/reconcile.mjs +271 -0
  303. package/src/router/service/service.mjs +2998 -0
  304. package/src/router/service/sources.mjs +352 -0
  305. package/src/router/service/status.mjs +520 -0
  306. package/src/router/service/store.mjs +476 -0
  307. package/src/router/service/ticklock.mjs +239 -0
  308. package/src/router/service/tokens.mjs +95 -0
  309. package/src/router/service/tools.mjs +248 -0
  310. package/src/router/service/wake.mjs +544 -0
  311. package/src/router/service/wal.mjs +685 -0
  312. package/src/router/shadow.mjs +821 -0
  313. package/src/surgery-recovery.js +1909 -0
  314. package/src/tool-output.js +485 -0
  315. package/src/tools.js +3262 -0
  316. package/src/truncate-visible.js +2416 -0
  317. package/src/truncate.js +999 -0
  318. package/src/ui/actions.js +1312 -0
  319. package/src/ui/flags.js +259 -0
  320. package/src/ui/panel-api.js +371 -0
  321. package/src/ui/panel-auth.js +251 -0
  322. package/src/ui/panel-integrity.js +243 -0
  323. package/src/ui/routes-readonly.js +759 -0
  324. package/src/ui/routes.js +284 -0
  325. package/src/util/append-store.js +368 -0
  326. package/src/util/local-day.js +30 -0
  327. package/src/util/redact.js +227 -0
  328. package/src/util/stale-locks.js +148 -0
  329. package/src/version.js +99 -0
  330. package/test/fixtures/pre-step-container.mjs +100 -0
  331. package/test/p1_probe.mjs +97 -0
@@ -0,0 +1,203 @@
1
+ // mock-llm.mjs — 确定性 mock 模型(无网络、无凭据)
2
+ //
3
+ // 形状对齐宿主 ctx.llm.stream()(_hostsrc/dsh-llm README:47-57 / :93):
4
+ // - 返回 AsyncIterable<StreamChunk>,不是 Promise<{text, action}>;
5
+ // - messages 的 content 必须是 block 数组;
6
+ // - 块序列:block-start -> text-delta* -> usage -> finish;
7
+ // - 失败也是 finish,reason = { kind:'error', failure:{code,...} };
8
+ // - abort 走 finish,reason = { kind:'aborted', failure:{code:'ABORTED'} };
9
+ // - usage 是 camelCase,totalTokens 显式给出。
10
+ //
11
+ // action 用文本协议传递(真实模型走 tool-call-delta,这里保持可读、可断言):
12
+ // 最后一行是 `ACTION: {"type":"note",...}`,Router 解析它。
13
+
14
+ import { normalizeUsage } from './stream.mjs';
15
+
16
+ export class MockLlmError extends Error {
17
+ constructor(message, code, extra = {}) {
18
+ super(message);
19
+ this.name = 'MockLlmError';
20
+ this.code = code;
21
+ Object.assign(this, extra);
22
+ }
23
+ }
24
+
25
+ function sleep(ms, signal) {
26
+ if (!ms || ms <= 0) return Promise.resolve();
27
+ return new Promise((resolve) => {
28
+ const timer = setTimeout(done, ms);
29
+ timer.unref?.();
30
+ function done() {
31
+ signal?.removeEventListener?.('abort', done);
32
+ resolve();
33
+ }
34
+ signal?.addEventListener?.('abort', done, { once: true });
35
+ });
36
+ }
37
+
38
+ /** 宿主只接受 block 数组;mock 也照此校验,避免测试掩盖契约错误。 */
39
+ export function assertBlockMessages(messages) {
40
+ if (!Array.isArray(messages) || messages.length === 0) {
41
+ throw new MockLlmError('messages must be a non-empty array', 'E_MOCK_BAD_MESSAGES');
42
+ }
43
+ for (const message of messages) {
44
+ if (!message || typeof message.role !== 'string' || !Array.isArray(message.content)) {
45
+ throw new MockLlmError('each message.content must be a block array', 'E_MOCK_BAD_MESSAGES');
46
+ }
47
+ for (const block of message.content) {
48
+ if (!block || typeof block.type !== 'string') {
49
+ throw new MockLlmError('message content blocks need a type', 'E_MOCK_BAD_MESSAGES');
50
+ }
51
+ }
52
+ }
53
+ }
54
+
55
+ function usageFrom(raw) {
56
+ const normalized = normalizeUsage(raw);
57
+ return normalized ?? { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, totalTokens: 0, legacy: false };
58
+ }
59
+
60
+ function failureSpec(value) {
61
+ if (!value) return null;
62
+ if (value === 'crash') return { code: 'MOCK_CRASH', message: 'mock backend crashed' };
63
+ if (typeof value === 'string') return { code: value, message: `mock failure ${value}` };
64
+ if (typeof value === 'object' && typeof value.code === 'string') {
65
+ return { message: `mock failure ${value.code}`, ...value };
66
+ }
67
+ return { code: 'MOCK_CRASH', message: 'mock backend crashed' };
68
+ }
69
+
70
+ export class MockLlm {
71
+ /**
72
+ * @param {object} options
73
+ * @param {object|Function} [options.usage] {inputTokens,outputTokens} 或 (task)=>usage
74
+ * @param {Map<string, string|object>} [options.failOn] 任务 id/type/'*' -> code 或 {code,times,...}
75
+ * @param {number|Function} [options.delayMs]
76
+ * @param {Function|string} [options.text] 自定义正文
77
+ * @param {Function} [options.actionFor] (task)=>action
78
+ * @param {string} [options.finishKind='stop']
79
+ */
80
+ constructor({
81
+ usage = { inputTokens: 120, outputTokens: 30 },
82
+ failOn = new Map(),
83
+ delayMs = 0,
84
+ text = null,
85
+ actionFor = null,
86
+ finishKind = 'stop',
87
+ provider = 'mock',
88
+ model = 'mock-1',
89
+ } = {}) {
90
+ this.provider = provider;
91
+ this.model = model;
92
+ this.usage = usage;
93
+ this.failOn = failOn;
94
+ this.delayMs = delayMs;
95
+ this.text = text;
96
+ this.actionFor = actionFor;
97
+ this.finishKind = finishKind;
98
+ this.calls = 0;
99
+ this.attempts = new Map();
100
+ this.lastRequest = null;
101
+ this.requests = [];
102
+ }
103
+
104
+ #failureFor(task, key) {
105
+ if (!key) return null;
106
+ const spec = failureSpec(this.failOn.get(key));
107
+ if (!spec) return null;
108
+ const attempt = (this.attempts.get(key) ?? 0) + 1;
109
+ this.attempts.set(key, attempt);
110
+ if (Number.isInteger(spec.times) && attempt > spec.times) return null;
111
+ if (Number.isInteger(spec.skipTimes) && attempt <= spec.skipTimes) return null;
112
+ return spec;
113
+ }
114
+
115
+ #action(task) {
116
+ if (typeof this.actionFor === 'function') return this.actionFor(task);
117
+ return { type: 'note', task_id: task?.id ?? null, note: `mock: ${task?.id ?? 'unknown'}` };
118
+ }
119
+
120
+ #text(task, action) {
121
+ if (typeof this.text === 'function') return this.text(task, action);
122
+ if (typeof this.text === 'string' && this.text.length > 0) {
123
+ return `${this.text}\nACTION: ${JSON.stringify(action)}`;
124
+ }
125
+ return `mock: 处理 ${task?.id ?? 'unknown'}\nACTION: ${JSON.stringify(action)}`;
126
+ }
127
+
128
+ /**
129
+ * 真实签名的核心:返回 AsyncIterable,而不是 Promise。
130
+ * @returns {AsyncGenerator<object>}
131
+ */
132
+ async *stream({ messages, task, signal, maxTokens } = {}) {
133
+ this.calls += 1;
134
+ this.lastRequest = { messages, task, maxTokens, signal };
135
+ this.requests.push(this.lastRequest);
136
+ assertBlockMessages(messages);
137
+
138
+ const key = task?.id ?? task?.type ?? null;
139
+ const failure = this.#failureFor(task, key);
140
+ const delay = typeof this.delayMs === 'function' ? this.delayMs(task) : this.delayMs;
141
+
142
+ if (signal?.aborted) {
143
+ yield {
144
+ type: 'finish',
145
+ reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'aborted before stream' } },
146
+ };
147
+ return;
148
+ }
149
+
150
+ if (delay > 0) {
151
+ await sleep(delay, signal);
152
+ if (signal?.aborted) {
153
+ yield {
154
+ type: 'finish',
155
+ reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'aborted during delay' } },
156
+ };
157
+ return;
158
+ }
159
+ }
160
+
161
+ yield { type: 'block-start', index: 0, blockType: 'text' };
162
+
163
+ if (failure) {
164
+ // 失败也可以带 usage(真适配器会在 finish 前报已消耗量);重试累计需要它。
165
+ if (failure.usage) {
166
+ yield { type: 'usage', usage: usageFrom(failure.usage) };
167
+ }
168
+ // 失败可以是到达 finish 才暴露;真实适配器也允许先有 block-start。
169
+ yield {
170
+ type: 'finish',
171
+ reason: {
172
+ kind: 'error',
173
+ failure: {
174
+ code: failure.code,
175
+ message: failure.message,
176
+ providerRetryAfterMs: failure.providerRetryAfterMs,
177
+ status: failure.status,
178
+ },
179
+ },
180
+ };
181
+ return;
182
+ }
183
+
184
+ const action = this.#action(task);
185
+ const text = this.#text(task, action);
186
+ const split = text.length > 1 ? Math.ceil(text.length / 2) : text.length;
187
+ for (const delta of [text.slice(0, split), text.slice(split)].filter(Boolean)) {
188
+ if (signal?.aborted) {
189
+ yield {
190
+ type: 'finish',
191
+ reason: { kind: 'aborted', failure: { code: 'ABORTED', message: 'aborted mid-text' } },
192
+ };
193
+ return;
194
+ }
195
+ yield { type: 'text-delta', index: 0, text: delta };
196
+ }
197
+
198
+ const rawUsage = typeof this.usage === 'function' ? this.usage(task) : this.usage;
199
+ const usage = usageFrom(rawUsage);
200
+ yield { type: 'usage', usage };
201
+ yield { type: 'finish', reason: { kind: this.finishKind } };
202
+ }
203
+ }
@@ -0,0 +1,224 @@
1
+ // queue.mjs — 任务队列(JSONL)
2
+ //
3
+ // 写路径与读路径分离:
4
+ // - read()/pending() 给 Router 的 tick 用,永远只读;
5
+ // - append 只通过队列自己签发的 writer capability 暴露,插件把 writer 交给
6
+ // 「可信生产者」(用户输入 / 宿主调度器),后台 agent 拿不到。
7
+ // capability 是逻辑隔离,不是 OS 权限隔离;真正的隔离靠后台 agent 的工具面
8
+ // 没有 fs 写工具(见 tool-policy.mjs)。
9
+ //
10
+ // 去重规则:id 第一次出现者胜;后出现的重复 id 被忽略,并在 read().duplicates
11
+ // 里留下证据。append 遇到已存在 id 返回 {ok:false, code:'E_DUPLICATE'},不写盘。
12
+ //
13
+ // 容量上限(复核 P29):800 条任务曾被无条件收下。现在 append 前同时检查
14
+ // maxTasks / maxBytes,超了返回 E_QUEUE_FULL 且不写盘。id 缓存带文件签名
15
+ // (size+mtime),别的实例追加后本实例会重扫,避免拿过期缓存写出重复 id(P28)。
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+
20
+ /** 任务最小形状:{ id: string, type: string, payload?: object, origin?: string, depth?: number } */
21
+ export function validateTask(raw, index = 0) {
22
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { ok: false, reason: `line ${index}: not an object` };
23
+ if (typeof raw.id !== 'string' || raw.id.length === 0) return { ok: false, reason: `line ${index}: missing id` };
24
+ if (typeof raw.type !== 'string' || raw.type.length === 0) return { ok: false, reason: `line ${index}: missing type` };
25
+ if (raw.payload !== undefined && (raw.payload === null || typeof raw.payload !== 'object')) {
26
+ return { ok: false, reason: `line ${index}: payload must be an object` };
27
+ }
28
+ if (raw.depth !== undefined && (!Number.isInteger(raw.depth) || raw.depth < 0)) {
29
+ return { ok: false, reason: `line ${index}: depth must be a non-negative integer` };
30
+ }
31
+ return { ok: true, task: raw };
32
+ }
33
+
34
+ export const DEFAULT_MAX_TASKS = 500;
35
+ export const DEFAULT_MAX_BYTES = 1024 * 1024;
36
+
37
+ export class TaskQueue {
38
+ constructor({
39
+ file,
40
+ maxTasks = DEFAULT_MAX_TASKS,
41
+ maxBytes = DEFAULT_MAX_BYTES,
42
+ } = {}) {
43
+ if (!file) throw new Error('TaskQueue: file is required');
44
+ this.file = file;
45
+ this.maxTasks = maxTasks;
46
+ this.maxBytes = maxBytes;
47
+ this.ids = null;
48
+ this.loadedSignature = null;
49
+ this.count = 0;
50
+ this.bytes = 0;
51
+ const writer = Object.freeze({ append: (task) => this.#append(task) });
52
+ this.writer = writer;
53
+ }
54
+
55
+ /** 裸 append 一律拒绝:写队列是可信生产者的能力,不是普通调用。 */
56
+ append() {
57
+ const error = new Error('TaskQueue: append() is reserved for the trusted producer; use queue.writer.append(task)');
58
+ error.code = 'E_UNTRUSTED_PRODUCER';
59
+ throw error;
60
+ }
61
+
62
+ #signature() {
63
+ try {
64
+ const stat = fs.statSync(this.file);
65
+ return `${stat.size}:${stat.mtimeMs}`;
66
+ } catch {
67
+ return 'missing';
68
+ }
69
+ }
70
+
71
+ #loadIds() {
72
+ const signature = this.#signature();
73
+ if (this.ids !== null && this.loadedSignature === signature) return this.ids;
74
+ const ids = new Set();
75
+ let count = 0;
76
+ if (fs.existsSync(this.file)) {
77
+ const text = fs.readFileSync(this.file, 'utf8');
78
+ this.bytes = Buffer.byteLength(text);
79
+ let line = 0;
80
+ for (const rawLine of text.split('\n')) {
81
+ line += 1;
82
+ if (rawLine.trim() === '') continue;
83
+ count += 1;
84
+ try {
85
+ const rec = JSON.parse(rawLine);
86
+ const verdict = validateTask(rec, line);
87
+ if (verdict.ok) ids.add(verdict.task.id);
88
+ } catch { /* 坏行不参与 id 集合 */ }
89
+ }
90
+ } else {
91
+ this.bytes = 0;
92
+ }
93
+ this.ids = ids;
94
+ this.count = count;
95
+ this.loadedSignature = signature;
96
+ return ids;
97
+ }
98
+
99
+ /** 当前容量快照(给 read()/审计用)。 */
100
+ capacity() {
101
+ this.#loadIds();
102
+ return {
103
+ maxTasks: this.maxTasks,
104
+ maxBytes: this.maxBytes,
105
+ count: this.count,
106
+ bytes: this.bytes,
107
+ full: this.count >= this.maxTasks || this.bytes >= this.maxBytes,
108
+ };
109
+ }
110
+
111
+ #append(task) {
112
+ const verdict = validateTask(task);
113
+ if (!verdict.ok) return { ok: false, code: 'E_INVALID_TASK', reason: verdict.reason };
114
+ const ids = this.#loadIds();
115
+ if (ids.has(verdict.task.id)) return { ok: false, code: 'E_DUPLICATE', id: verdict.task.id };
116
+
117
+ const line = JSON.stringify(verdict.task) + '\n';
118
+ const lineBytes = Buffer.byteLength(line);
119
+ if (this.count + 1 > this.maxTasks) {
120
+ return {
121
+ ok: false,
122
+ code: 'E_QUEUE_FULL',
123
+ reason: `queue already has ${this.count} task(s); maxTasks is ${this.maxTasks}`,
124
+ maxTasks: this.maxTasks,
125
+ count: this.count,
126
+ };
127
+ }
128
+ if (this.bytes + lineBytes > this.maxBytes) {
129
+ return {
130
+ ok: false,
131
+ code: 'E_QUEUE_FULL',
132
+ reason: `queue is ${this.bytes} byte(s); adding ${lineBytes} would exceed maxBytes ${this.maxBytes}`,
133
+ maxBytes: this.maxBytes,
134
+ bytes: this.bytes,
135
+ };
136
+ }
137
+
138
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
139
+ const fd = fs.openSync(this.file, 'a');
140
+ try {
141
+ fs.writeSync(fd, line);
142
+ fs.fsyncSync(fd);
143
+ } finally {
144
+ fs.closeSync(fd);
145
+ }
146
+ ids.add(verdict.task.id);
147
+ this.count += 1;
148
+ this.bytes += lineBytes;
149
+ this.loadedSignature = this.#signature();
150
+ return { ok: true, task: verdict.task };
151
+ }
152
+
153
+ /**
154
+ * 读全部合法任务;坏行/坏任务进 invalid,重复 id 只保留第一条。
155
+ * 不抛异常(除文件系统本身不可读)。
156
+ */
157
+ read() {
158
+ if (!fs.existsSync(this.file)) {
159
+ return {
160
+ tasks: [],
161
+ invalid: [],
162
+ duplicates: [],
163
+ missing: true,
164
+ total: 0,
165
+ capacity: { maxTasks: this.maxTasks, maxBytes: this.maxBytes, count: 0, bytes: 0, full: false },
166
+ };
167
+ }
168
+ const text = fs.readFileSync(this.file, 'utf8');
169
+ const tasks = [];
170
+ const invalid = [];
171
+ const duplicates = [];
172
+ const seen = new Set();
173
+ text.split('\n').forEach((line, i) => {
174
+ if (line.trim() === '') return;
175
+ let raw;
176
+ try {
177
+ raw = JSON.parse(line);
178
+ } catch (error) {
179
+ invalid.push({ line: i + 1, reason: `json: ${error.message}` });
180
+ return;
181
+ }
182
+ const verdict = validateTask(raw, i + 1);
183
+ if (!verdict.ok) {
184
+ invalid.push({ line: i + 1, reason: verdict.reason });
185
+ return;
186
+ }
187
+ if (seen.has(verdict.task.id)) {
188
+ duplicates.push({ line: i + 1, id: verdict.task.id });
189
+ return;
190
+ }
191
+ seen.add(verdict.task.id);
192
+ tasks.push(verdict.task);
193
+ });
194
+ const bytes = Buffer.byteLength(text);
195
+ const lines = text.split('\n').filter((line) => line.trim() !== '').length;
196
+ return {
197
+ tasks,
198
+ invalid,
199
+ duplicates,
200
+ missing: false,
201
+ total: tasks.length,
202
+ capacity: {
203
+ maxTasks: this.maxTasks,
204
+ maxBytes: this.maxBytes,
205
+ count: lines,
206
+ bytes,
207
+ full: lines >= this.maxTasks || bytes >= this.maxBytes,
208
+ },
209
+ };
210
+ }
211
+
212
+ /** 过滤掉已处理过的任务(seen 来自审计回放)。去重后的第一条先参与处理。 */
213
+ pending(seen = new Set()) {
214
+ const { tasks, invalid, duplicates, missing, total, capacity } = this.read();
215
+ return {
216
+ tasks: tasks.filter((task) => !seen.has(task.id)),
217
+ invalid,
218
+ duplicates,
219
+ missing,
220
+ total,
221
+ capacity,
222
+ };
223
+ }
224
+ }
@@ -0,0 +1,255 @@
1
+ // retry.mjs — 裸 stream 调用方的 RATE_LIMIT 退避 / QUOTA 立刻停
2
+ //
3
+ // 宿主 dsh-llm 自己从不重试(README:93),重试属于 agent 的 failed-step
4
+ // 扩展点(dsh-llm-retry)。Router 后台面不走 agent loop 时,必须自己实现
5
+ // 同样的最小策略:
6
+ // - RATE_LIMIT / SERVER / TIMEOUT / TRANSPORT / EMPTY_RESPONSE:指数退避重试
7
+ // - QUOTA / ACCOUNT_QUOTA:不重试,整个 Router 停(quota_exceeded)
8
+ // - AUTH / INVALID_CREDENTIAL / CONTEXT_WINDOW_EXCEEDED / NO_ADAPTER:不重试
9
+ // - 有副作用之后的调用不重试(idempotent:false)
10
+ // 退避优先使用 failure.providerRetryAfterMs,其次 500ms 起、10s 封顶、±10% 抖动。
11
+
12
+ export const RETRYABLE_CODES = Object.freeze([
13
+ 'EMPTY_RESPONSE',
14
+ 'RATE_LIMIT',
15
+ 'SERVER',
16
+ 'TIMEOUT',
17
+ 'TRANSPORT',
18
+ ]);
19
+
20
+ export const STOP_CODES = Object.freeze(['QUOTA', 'ACCOUNT_QUOTA']);
21
+
22
+ export const FATAL_CODES = Object.freeze([
23
+ 'NO_ADAPTER',
24
+ 'MISSING_CREDENTIAL',
25
+ 'INVALID_CREDENTIAL',
26
+ 'AUTH',
27
+ 'CONTEXT_WINDOW_EXCEEDED',
28
+ ]);
29
+
30
+ export function classifyCode(code) {
31
+ if (RETRYABLE_CODES.includes(code)) return 'retry';
32
+ if (STOP_CODES.includes(code)) return 'stop';
33
+ if (FATAL_CODES.includes(code)) return 'fatal';
34
+ return 'unknown';
35
+ }
36
+
37
+ export function stopReasonFor(code) {
38
+ if (STOP_CODES.includes(code)) return 'quota_exceeded';
39
+ if (FATAL_CODES.includes(code)) {
40
+ if (code === 'CONTEXT_WINDOW_EXCEEDED') return 'context_window_exceeded';
41
+ if (code === 'AUTH' || code === 'INVALID_CREDENTIAL') return 'auth_failed';
42
+ return 'llm_fatal';
43
+ }
44
+ return null;
45
+ }
46
+
47
+ export function computeBackoff({
48
+ attempt,
49
+ initialDelayMs = 500,
50
+ maxDelayMs = 10000,
51
+ jitterRatio = 0.1,
52
+ random = Math.random,
53
+ } = {}) {
54
+ const base = Math.min(maxDelayMs, initialDelayMs * 2 ** Math.max(0, attempt - 1));
55
+ const jitter = base * jitterRatio * (random() * 2 - 1);
56
+ return Math.max(0, Math.min(maxDelayMs, Math.round(base + jitter)));
57
+ }
58
+
59
+ export function sleep(ms, signal) {
60
+ if (!ms || ms <= 0) return Promise.resolve();
61
+ return new Promise((resolve, reject) => {
62
+ if (signal?.aborted) {
63
+ const error = new Error('aborted');
64
+ error.code = 'E_ABORTED';
65
+ reject(error);
66
+ return;
67
+ }
68
+ const timer = setTimeout(() => {
69
+ signal?.removeEventListener?.('abort', onAbort);
70
+ resolve();
71
+ }, ms);
72
+ timer.unref?.();
73
+ function onAbort() {
74
+ clearTimeout(timer);
75
+ const error = new Error('aborted');
76
+ error.code = 'E_ABORTED';
77
+ reject(error);
78
+ }
79
+ signal?.addEventListener?.('abort', onAbort, { once: true });
80
+ });
81
+ }
82
+
83
+ function failureFromError(error) {
84
+ return {
85
+ code: typeof error?.code === 'string' ? error.code : 'E_UNKNOWN',
86
+ message: String(error?.message ?? error),
87
+ providerRetryAfterMs: error?.providerRetryAfterMs,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Retry-After 封顶:provider 给 99999 也不能让后台 tick 睡 100 秒。
93
+ * 单独导出是为了能在不真睡 30s 的测试里断言生产默认值。
94
+ */
95
+ export function capRetryAfter(ms, maxRetryAfterMs = 30000) {
96
+ if (!Number.isFinite(ms)) return null;
97
+ return Math.min(Math.max(0, ms), maxRetryAfterMs);
98
+ }
99
+
100
+ const USAGE_FIELDS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'totalTokens'];
101
+
102
+ /**
103
+ * 累加每一次 attempt 的 usage —— 包括最终失败的那一次。
104
+ * 复核 P26:第一次 attempt 花了 60 后 SERVER 失败,第二次花 30,旧实现只记 30;
105
+ * provider 已经计费 90,预算必须按 90 扣。
106
+ */
107
+ export function addUsage(total, usage) {
108
+ if (!usage || typeof usage !== 'object') return total;
109
+ const next = total ?? {
110
+ inputTokens: 0,
111
+ outputTokens: 0,
112
+ cacheReadTokens: 0,
113
+ cacheWriteTokens: 0,
114
+ totalTokens: 0,
115
+ legacy: false,
116
+ };
117
+ for (const field of USAGE_FIELDS) {
118
+ const value = Number(usage[field]);
119
+ if (Number.isFinite(value)) next[field] += value;
120
+ }
121
+ next.legacy = Boolean(next.legacy || usage.legacy);
122
+ return next;
123
+ }
124
+
125
+ /**
126
+ * 把一次 attempt 的 usage 累加进总数;fail-closed:
127
+ * 任何字段是负数 / NaN / Infinity,整个 attempt 都不入账(不能出现 -20 回冲),
128
+ * 并标记 invalidUsage,让 Router 记 0 或只记之前已确认的合法用量后停机。
129
+ *
130
+ * @returns {{usage:object, invalid:boolean}}
131
+ */
132
+ export function accumulateUsage(total, usage) {
133
+ const base = total ?? {
134
+ inputTokens: 0,
135
+ outputTokens: 0,
136
+ cacheReadTokens: 0,
137
+ cacheWriteTokens: 0,
138
+ totalTokens: 0,
139
+ legacy: false,
140
+ };
141
+ if (!usage || typeof usage !== 'object') return { usage: base, invalid: false };
142
+
143
+ let invalid = Boolean(usage.invalid);
144
+ for (const field of USAGE_FIELDS) {
145
+ const raw = usage[field];
146
+ if (raw === undefined || raw === null) continue;
147
+ const value = Number(raw);
148
+ if (!Number.isFinite(value) || value < 0) invalid = true;
149
+ }
150
+ if (invalid) return { usage: base, invalid: true };
151
+
152
+ const next = { ...base };
153
+ for (const field of USAGE_FIELDS) {
154
+ const raw = usage[field];
155
+ if (raw === undefined || raw === null) continue;
156
+ next[field] += Number(raw);
157
+ }
158
+ next.legacy = Boolean(next.legacy || usage.legacy);
159
+ // 单调不减:即使上游传了负的差额,也绝不把累计值改小。
160
+ for (const field of USAGE_FIELDS) {
161
+ next[field] = Math.max(next[field], base[field] ?? 0);
162
+ }
163
+ return { usage: next, invalid: false };
164
+ }
165
+
166
+ /**
167
+ * 调用一次可能失败的异步操作;失败按 code 分类决定是否重试。
168
+ * call(attempt) 返回 { failure } 表示失败,返回其它对象表示成功。
169
+ * 抛出的异常按 error.code 分类;AbortError 立即返回 aborted。
170
+ *
171
+ * @returns {Promise<object>} 最后一次结果 + { attempts, retryExhausted?, stopReason? }
172
+ */
173
+ export async function retryOnFailure(call, {
174
+ maxAttempts = 3,
175
+ initialDelayMs = 500,
176
+ maxDelayMs = 10000,
177
+ jitterRatio = 0.1,
178
+ random = Math.random,
179
+ signal,
180
+ onRetry,
181
+ idempotent = true,
182
+ maxRetryAfterMs = 30000,
183
+ } = {}) {
184
+ let attempt = 0;
185
+ let usageTotal = null;
186
+ let attemptOverflow = false;
187
+ while (true) {
188
+ if (signal?.aborted) {
189
+ return { failure: { code: 'E_ABORTED', message: 'aborted' }, aborted: true, attempts: attempt, usage: usageTotal };
190
+ }
191
+ attempt += 1;
192
+
193
+ let result;
194
+ try {
195
+ result = await call(attempt);
196
+ } catch (error) {
197
+ if (error?.name === 'AbortError' || error?.code === 'ABORTED' || signal?.aborted) {
198
+ return { failure: { code: 'E_ABORTED', message: 'aborted' }, aborted: true, attempts: attempt, usage: usageTotal };
199
+ }
200
+ result = { failure: failureFromError(error) };
201
+ }
202
+
203
+ // 单次 attempt 的 usage 超过 callMaxTokens 也记下来;即使总和还在整段预留内,
204
+ // 也必须 fail 任务(B:每次 attempt 上限是硬边界,不能靠「总额没超」混过去)。
205
+ if (result?.attemptOverflow) attemptOverflow = true;
206
+
207
+ const accumulated = accumulateUsage(usageTotal, result?.usage ?? result?.result?.usage);
208
+ usageTotal = accumulated.usage;
209
+ if (accumulated.invalid) {
210
+ // P0/F5/F12:某次 attempt 的 usage 非法时立即 fail-closed,不重试、不回冲。
211
+ return {
212
+ ...(result ?? {}),
213
+ ok: false,
214
+ failure: null,
215
+ usage: usageTotal,
216
+ attempts: attempt,
217
+ invalidUsage: true,
218
+ attemptOverflow,
219
+ retryExhausted: false,
220
+ };
221
+ }
222
+
223
+ if (!result || !result.failure) {
224
+ return { ...(result ?? {}), usage: usageTotal, attempts: attempt, attemptOverflow };
225
+ }
226
+
227
+ const code = result.failure.code ?? 'E_UNKNOWN';
228
+ const kind = classifyCode(code);
229
+
230
+ if (kind === 'stop' || kind === 'fatal') {
231
+ return {
232
+ ...result,
233
+ usage: usageTotal,
234
+ attempts: attempt,
235
+ attemptOverflow,
236
+ retryExhausted: false,
237
+ stopReason: stopReasonFor(code),
238
+ };
239
+ }
240
+
241
+ if (kind !== 'retry' || !idempotent || attempt >= maxAttempts) {
242
+ return { ...result, usage: usageTotal, attempts: attempt, attemptOverflow, retryExhausted: kind === 'retry' };
243
+ }
244
+
245
+ const delayMs = Number.isFinite(result.failure.providerRetryAfterMs)
246
+ ? capRetryAfter(result.failure.providerRetryAfterMs, maxRetryAfterMs)
247
+ : computeBackoff({ attempt, initialDelayMs, maxDelayMs, jitterRatio, random });
248
+ onRetry?.({ attempt, code, delayMs });
249
+ try {
250
+ await sleep(delayMs, signal);
251
+ } catch {
252
+ return { failure: { code: 'E_ABORTED', message: 'aborted' }, aborted: true, attempts: attempt, usage: usageTotal };
253
+ }
254
+ }
255
+ }