@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,191 @@
1
+ /**
2
+ * D1 — classify one model-visible message into a working-set layer.
3
+ *
4
+ * Layers:
5
+ * fixed system prompt + tool schemas + host-injected context
6
+ * (agent instructions, runtime context, skill catalog, external
7
+ * memory plugin injection, time context, developer/tool-registry messages)
8
+ * recent real conversation inside the keepTurns window
9
+ * recall auto-recall injection (`【自动想起】`)
10
+ * conclusion boot card (`【开机卡】`) or a future board lastConclusion
11
+ *
12
+ * Everything that is real conversation but older than the window is
13
+ * `carried` — it stays in the request today because D2/D3 trimming is not
14
+ * implemented, and the ledger must show that honestly.
15
+ */
16
+
17
+ import { classificationPluginLabels } from '../adapters/registry.js';
18
+
19
+ // 2.0.0 起 auto-recall 注入块头是 `【自动想起 · recallId=…】`(零命中同头),
20
+ // 这里只保留前缀,继续兼容历史 `【自动想起】` 正文标记。
21
+ export const RECALL_HEADER = '【自动想起';
22
+ export const CONCLUSION_HEADER = '【开机卡】';
23
+
24
+ /**
25
+ * Host-injected user messages that are prompt scaffolding, not conversation.
26
+ * Keep this list explicit: an unknown `source.kind` is treated as fixed only
27
+ * when it is clearly host-owned, so a new host notification cannot silently
28
+ * inflate the fixed layer.
29
+ */
30
+ export const FIXED_SOURCE_KINDS = new Set([
31
+ 'agent-instructions',
32
+ 'runtime-context',
33
+ 'skill-catalog',
34
+ ...classificationPluginLabels(),
35
+ 'time-context',
36
+ ]);
37
+
38
+ /** Host/user messages that belong to the conversation stream. */
39
+ export const CONVERSATION_SOURCE_KINDS = new Set([
40
+ 'user',
41
+ 'archive-card',
42
+ 'agent-message',
43
+ 'subagent-settled',
44
+ 'user-approval',
45
+ ]);
46
+
47
+ /** Return the message carried by a session event. */
48
+ export function messageOfEvent(event) {
49
+ const data = event === null || typeof event !== 'object' ? null : event.data;
50
+ if (data === null || typeof data !== 'object') return null;
51
+ if (data.message !== null && typeof data.message === 'object') return data.message;
52
+ // `user/message` stores the message itself as the event data (no wrapper).
53
+ if (typeof data.role === 'string') return data;
54
+ return null;
55
+ }
56
+
57
+ export function sourceKindOf(message) {
58
+ const source = message === null || typeof message !== 'object' ? null : message.source;
59
+ return source !== null && typeof source === 'object' && typeof source.kind === 'string'
60
+ ? source.kind
61
+ : '';
62
+ }
63
+
64
+ /** First non-empty line, trimmed; '' for non-strings. */
65
+ export function firstLine(text) {
66
+ if (typeof text !== 'string' || text === '') return '';
67
+ for (const line of text.split(/\r?\n/)) {
68
+ const trimmed = line.trim();
69
+ if (trimmed !== '') return trimmed;
70
+ }
71
+ return '';
72
+ }
73
+
74
+ /**
75
+ * The injection source shape is shared by the boot card and auto-recall
76
+ * (`session-reference` / `recall`), so the first line is the discriminator.
77
+ */
78
+ export function isRecallText(text) {
79
+ return firstLine(text).startsWith(RECALL_HEADER);
80
+ }
81
+
82
+ export function isConclusionText(text) {
83
+ return firstLine(text).startsWith(CONCLUSION_HEADER);
84
+ }
85
+
86
+ /**
87
+ * Classify one message.
88
+ * @returns {'fixed'|'recall'|'conclusion'|'conversation'|'unknown'}
89
+ * Callers use `conversation` plus the message turn to decide recent/carried.
90
+ */
91
+ export function classifyMessage(message) {
92
+ if (message === null || typeof message !== 'object') return 'unknown';
93
+ const role = typeof message.role === 'string' ? message.role : '';
94
+ if (role === 'system' || role === 'developer') return 'fixed';
95
+ if (role === 'assistant' || role === 'tool') return 'conversation';
96
+ if (role !== 'user') return 'unknown';
97
+
98
+ const kind = sourceKindOf(message);
99
+ const text = typeof message.content === 'string'
100
+ ? message.content
101
+ : Array.isArray(message.content)
102
+ ? message.content
103
+ .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
104
+ .map((block) => block.text)
105
+ .join('\n')
106
+ : '';
107
+
108
+ if (kind === 'plugin:dsh-auto-recall' || isRecallText(text)) return 'recall';
109
+ if (kind === 'plugin:dsh-identity-router' || isConclusionText(text)) return 'conclusion';
110
+ if (FIXED_SOURCE_KINDS.has(kind)) return 'fixed';
111
+ if (CONVERSATION_SOURCE_KINDS.has(kind)) return 'conversation';
112
+ // An unknown host-owned source (has a kind but is not the real user) is
113
+ // prompt scaffolding rather than conversation. This keeps total honest
114
+ // when the harness adds a new injection type.
115
+ if (kind !== '') return 'fixed';
116
+ const source = message.source;
117
+ if (source !== null && typeof source === 'object'
118
+ && (source.sections !== undefined || typeof source.form === 'string')) {
119
+ return 'fixed';
120
+ }
121
+ return 'conversation';
122
+ }
123
+
124
+ /**
125
+ * Parse recall card ids from the rendered injection body.
126
+ *
127
+ * Rendered form (one per line):
128
+ * - 《Card title》(topics/card.md · 相关度 1.72)
129
+ *
130
+ * References are empty in the live payload, so text parsing is the reliable
131
+ * path; `message.source.references` is used first when present.
132
+ */
133
+ export function recallIdsFromText(text) {
134
+ if (typeof text !== 'string' || text === '') return [];
135
+ const out = [];
136
+ const re = /^[-*]\s*《([^》\n]{1,200})》\s*[((]([^))\n]{1,500})[))]/gm;
137
+ let match = re.exec(text);
138
+ while (match !== null) {
139
+ const title = match[1].trim();
140
+ const rawPath = match[2].trim();
141
+ const cardPath = rawPath.split(/\s*[·|]\s*/)[0].replace(/`/g, '').trim();
142
+ if (cardPath !== '' || title !== '') out.push({ title, path: cardPath });
143
+ match = re.exec(text);
144
+ }
145
+ return dedupeIds(out);
146
+ }
147
+
148
+ /** Card ids carried by one message: source.references first, text second. */
149
+ export function recallIdsFromMessage(message) {
150
+ if (message === null || typeof message !== 'object') return [];
151
+ const source = message.source;
152
+ const refs = source !== null && typeof source === 'object' ? source.references : null;
153
+ if (Array.isArray(refs) && refs.length > 0) {
154
+ const ids = [];
155
+ for (const ref of refs) {
156
+ if (typeof ref === 'string' && ref.trim() !== '') ids.push({ title: '', path: ref.trim() });
157
+ else if (ref !== null && typeof ref === 'object') {
158
+ const cardPath = typeof ref.path === 'string' ? ref.path.trim() : '';
159
+ const title = typeof ref.title === 'string' ? ref.title.trim() : '';
160
+ if (cardPath !== '' || title !== '') ids.push({ title, path: cardPath });
161
+ }
162
+ }
163
+ const deduped = dedupeIds(ids);
164
+ if (deduped.length > 0) return deduped;
165
+ }
166
+ const text = typeof message.content === 'string'
167
+ ? message.content
168
+ : Array.isArray(message.content)
169
+ ? message.content
170
+ .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
171
+ .map((block) => block.text)
172
+ .join('\n')
173
+ : '';
174
+ return recallIdsFromText(text);
175
+ }
176
+
177
+ /** Stable dedupe: path when present, otherwise title. */
178
+ export function dedupeIds(ids) {
179
+ const seen = new Set();
180
+ const out = [];
181
+ for (const id of Array.isArray(ids) ? ids : []) {
182
+ if (id === null || typeof id !== 'object') continue;
183
+ const title = typeof id.title === 'string' ? id.title : '';
184
+ const cardPath = typeof id.path === 'string' ? id.path : '';
185
+ const key = cardPath !== '' ? `p:${cardPath}` : `t:${title}`;
186
+ if (key === 'p:' || key === 't:' || seen.has(key)) continue;
187
+ seen.add(key);
188
+ out.push({ title, path: cardPath });
189
+ }
190
+ return out;
191
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * D1/D4 — token estimation primitives.
3
+ *
4
+ * The harness does not hand plugins a tokenizer. Every layer number in the
5
+ * ledger is therefore an ESTIMATE unless the provider usage is attached:
6
+ *
7
+ * tokens = ceil(CJK_chars * 1 + other_chars / 3.5)
8
+ *
9
+ * That is the baseline documented in `docs/METRICS.md`. The ledger keeps the
10
+ * raw value and a calibration factor so the operator can see both the
11
+ * documented estimate and the factor-corrected forecast.
12
+ *
13
+ * No imports: this file is pure and directly unit-testable.
14
+ */
15
+
16
+ export const ESTIMATOR_ID = 'cjk*1+other/3.5';
17
+ export const CHARS_PER_TOKEN = 3.5;
18
+
19
+ // CJK Unified Ideographs (+ Ext A), compatibility ideographs, CJK punctuation
20
+ // and full-width forms, kana and hangul. This matches the intent of the
21
+ // existing recall estimator while keeping the documented /3.5 divisor.
22
+ const CJK_RE = /[\u2E80-\u9FFF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u3040-\u30FF\uAC00-\uD7AF]/g;
23
+
24
+ /** Count CJK code points (non-overlapping, surrogate-safe enough for BMP). */
25
+ export function countCjk(text) {
26
+ if (typeof text !== 'string' || text === '') return 0;
27
+ const matches = text.match(CJK_RE);
28
+ return matches === null ? 0 : matches.length;
29
+ }
30
+
31
+ /**
32
+ * Estimate tokens for one string.
33
+ * Empty / non-string / nullish input is 0, never NaN.
34
+ */
35
+ export function estimateTokens(text) {
36
+ if (typeof text !== 'string' || text.length === 0) return 0;
37
+ const cjk = countCjk(text);
38
+ const other = text.length - cjk;
39
+ return Math.ceil(cjk + other / CHARS_PER_TOKEN);
40
+ }
41
+
42
+ /**
43
+ * Text of a model-visible content value.
44
+ *
45
+ * `reasoning` blocks are intentionally ignored: they are model-internal and
46
+ * are not part of the measured request on this provider. Tool calls do count
47
+ * because their name + arguments are serialized into the request.
48
+ */
49
+ export function contentText(content) {
50
+ if (typeof content === 'string') return content;
51
+ if (!Array.isArray(content)) return '';
52
+ const parts = [];
53
+ for (const block of content) {
54
+ if (block === null || typeof block !== 'object') continue;
55
+ switch (block.type) {
56
+ case 'text':
57
+ if (typeof block.text === 'string') parts.push(block.text);
58
+ break;
59
+ case 'tool-call': {
60
+ const name = typeof block.name === 'string' ? block.name : '';
61
+ const args = typeof block.arguments === 'string'
62
+ ? block.arguments
63
+ : block.arguments === undefined ? '' : JSON.stringify(block.arguments);
64
+ parts.push(`${name}${args}`);
65
+ break;
66
+ }
67
+ case 'tool-result':
68
+ if (typeof block.text === 'string') parts.push(block.text);
69
+ break;
70
+ default:
71
+ // reasoning / image / unknown blocks do not contribute here.
72
+ break;
73
+ }
74
+ }
75
+ return parts.join('\n');
76
+ }
77
+
78
+ /** Text of one surface message (role is irrelevant). */
79
+ export function messageText(message) {
80
+ if (message === null || typeof message !== 'object') return '';
81
+ return contentText(message.content);
82
+ }
83
+
84
+ /**
85
+ * Estimate one message. A non-empty message carries a small role/envelope
86
+ * overhead (4 tokens) so a request with many tiny turns is not undercounted.
87
+ */
88
+ export function estimateMessageTokens(message) {
89
+ const text = messageText(message);
90
+ if (text === '') return 0;
91
+ return 4 + estimateTokens(text);
92
+ }
93
+
94
+ /**
95
+ * Estimate a tool-schema array. The host serializes the canonical header's
96
+ * `tools` value as JSON into the request, so JSON length is the right proxy.
97
+ */
98
+ export function estimateToolsTokens(tools) {
99
+ if (!Array.isArray(tools) || tools.length === 0) return 0;
100
+ let json;
101
+ try {
102
+ json = JSON.stringify(tools);
103
+ } catch {
104
+ return 0;
105
+ }
106
+ if (typeof json !== 'string' || json.length === 0) return 0;
107
+ return 4 + estimateTokens(json);
108
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * D1/D4 — live recorder.
3
+ *
4
+ * Registered from `src/index.js` after the opt-in features. It listens on
5
+ * `session/event`, and on every `turn/end` appends one row to
6
+ * `<memoryRoot>/.longlive/metrics/turns.jsonl`.
7
+ *
8
+ * Hard rules:
9
+ * - measure only: no trimming, no rewriting, no errors leaking into a turn;
10
+ * - the final request is reconstructed at the last assistant usage event,
11
+ * using the same Surface fold as the rest of the plugin;
12
+ * - if the host gives no usage, the row still records estimates and
13
+ * `reconciliation.available=false`.
14
+ */
15
+
16
+ import {
17
+ measureTurn,
18
+ normalizeMetricsConfig,
19
+ clampFactor,
20
+ DEFAULT_FACTOR,
21
+ } from './measure.mjs';
22
+ import {
23
+ appendTurnRow,
24
+ readCalibration,
25
+ writeCalibration,
26
+ readLastConclusion,
27
+ ledgerPath,
28
+ readPrestepLedger,
29
+ readPrestepSummary,
30
+ } from './store.mjs';
31
+ import {
32
+ configurePrestepLatency,
33
+ finalizePrestepTurn,
34
+ } from './prestep-latency.mjs';
35
+
36
+ /** The message events whose Surface fold is the request. */
37
+ export function snapshotSessionEvents(session) {
38
+ if (session !== null && typeof session === 'object' && typeof session.snapshotEvents === 'function') {
39
+ try {
40
+ const events = session.snapshotEvents();
41
+ if (Array.isArray(events)) return events;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+ if (session !== null && typeof session === 'object' && Array.isArray(session.events)) {
47
+ return session.events;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ /** Last assistant message for `turn` carrying provider usage. */
53
+ export function findUsageEvent(events, turn) {
54
+ let found = null;
55
+ for (const event of Array.isArray(events) ? events : []) {
56
+ if (event?.type !== 'assistant/message') continue;
57
+ if (!Number.isInteger(event.data?.turn) || event.data.turn !== turn) continue;
58
+ if (event.data.usage === null || typeof event.data.usage !== 'object') continue;
59
+ found = event;
60
+ }
61
+ return found;
62
+ }
63
+
64
+ /** Latest request header at or before `cutSeq`. */
65
+ export function findRequestHeader(events, cutSeq = Number.POSITIVE_INFINITY) {
66
+ let header = null;
67
+ for (const event of Array.isArray(events) ? events : []) {
68
+ if (!Number.isInteger(event?.seq) || event.seq >= cutSeq) continue;
69
+ if (event.type === 'request/header' && event.data?.header !== null && typeof event.data.header === 'object') {
70
+ header = event.data.header;
71
+ }
72
+ }
73
+ return header;
74
+ }
75
+
76
+ function sessionIdOf(session, event) {
77
+ if (session !== null && typeof session === 'object') {
78
+ if (typeof session.id === 'string' && session.id !== '') return session.id;
79
+ if (typeof session.sessionId === 'string' && session.sessionId !== '') return session.sessionId;
80
+ }
81
+ if (typeof event?.data?.sessionId === 'string' && event.data.sessionId !== '') return event.data.sessionId;
82
+ return '';
83
+ }
84
+
85
+ /**
86
+ * Register the recorder. Returns a small handle for tests.
87
+ *
88
+ * @param {object} ctx host context (needs `on`)
89
+ * @param {object} config plugin config
90
+ * @param {{memoryRoot?:string|null, now?:()=>Date, appendRow?:Function}} [deps]
91
+ */
92
+ export function registerMetrics(ctx, config, deps = {}) {
93
+ const cfg = normalizeMetricsConfig(config);
94
+ const memoryRoot = typeof deps.memoryRoot === 'string' && deps.memoryRoot.trim() !== ''
95
+ ? deps.memoryRoot
96
+ : '';
97
+ // B3: pre-step latency attribution is gated by the same metrics switch; when the
98
+ // recorder is off every phase helper is a no-op (zero disk IO, zero behavior change).
99
+ const nowFn = typeof deps.now === 'function' ? deps.now : () => new Date();
100
+ configurePrestepLatency({
101
+ enabled: cfg.enabled === true && memoryRoot !== '' && ctx !== null && typeof ctx === 'object',
102
+ memoryRoot,
103
+ now: nowFn,
104
+ });
105
+ if (cfg.enabled !== true) return { enabled: false, reason: 'disabled' };
106
+ if (memoryRoot === '') return { enabled: false, reason: 'memory-root-unset' };
107
+ if (ctx === null || typeof ctx !== 'object' || typeof ctx.on !== 'function') {
108
+ return { enabled: false, reason: 'no-ctx' };
109
+ }
110
+
111
+ const now = nowFn;
112
+ const append = typeof deps.appendRow === 'function'
113
+ ? deps.appendRow
114
+ : (row) => appendTurnRow(row, { memoryRoot });
115
+ const seen = new Set();
116
+
117
+ const onSessionEvent = (session, event) => {
118
+ try {
119
+ if (event?.type !== 'turn/end') return;
120
+ const turn = event.data?.turn;
121
+ if (!Number.isInteger(turn) || turn < 0) return;
122
+ const sessionId = sessionIdOf(session, event);
123
+ const key = `${sessionId}:${turn}`;
124
+ if (seen.has(key)) return;
125
+ seen.add(key);
126
+ if (seen.size > 8192) seen.clear();
127
+
128
+ // B3 fallback: if no outer pre-step handler finalized this turn (e.g.
129
+ // answer-guard disabled), flush whatever phases were collected. Idempotent.
130
+ try { finalizePrestepTurn(sessionId, turn, { memoryRoot }); } catch { /* never breaks */ }
131
+
132
+ const events = snapshotSessionEvents(session);
133
+ if (!Array.isArray(events)) return;
134
+
135
+ const usageEvent = findUsageEvent(events, turn);
136
+ const cutSeq = usageEvent ? usageEvent.seq : Number.POSITIVE_INFINITY;
137
+ const requestEvents = Number.isFinite(cutSeq)
138
+ ? events.filter((item) => !Number.isInteger(item?.seq) || item.seq < cutSeq)
139
+ : events;
140
+ const explicitHeader = session !== null && typeof session === 'object' && typeof session.requestHeader === 'function'
141
+ ? session.requestHeader()
142
+ : null;
143
+ const requestHeader = explicitHeader !== null && typeof explicitHeader === 'object'
144
+ ? explicitHeader
145
+ : findRequestHeader(events, cutSeq);
146
+
147
+ const calibration = readCalibration(memoryRoot);
148
+ const factor = clampFactor(calibration.factor ?? DEFAULT_FACTOR);
149
+ const row = measureTurn({
150
+ events: requestEvents,
151
+ turn,
152
+ sessionId,
153
+ requestHeader,
154
+ config: { ...cfg, keepTurns: cfg.keepTurns },
155
+ actualUsage: usageEvent?.data?.usage ?? null,
156
+ lastConclusion: readLastConclusion({ memoryRoot, sessionId }),
157
+ factor,
158
+ calibrationSamples: calibration.samples ?? 0,
159
+ now: now(),
160
+ source: 'live',
161
+ });
162
+
163
+ const written = append(row);
164
+ if (written?.ok !== true) return;
165
+
166
+ const actualInput = row?.reconciliation?.actualInput;
167
+ const rawTotal = row?.raw?.total;
168
+ if (Number.isFinite(actualInput) && actualInput > 0 && Number.isFinite(rawTotal) && rawTotal > 0) {
169
+ const rawSum = (calibration.rawSum ?? 0) + rawTotal;
170
+ const actualSum = (calibration.actualSum ?? 0) + actualInput;
171
+ writeCalibration(memoryRoot, {
172
+ factor: actualSum / rawSum,
173
+ samples: (calibration.samples ?? 0) + 1,
174
+ rawSum,
175
+ actualSum,
176
+ keepTurns: cfg.keepTurns,
177
+ updatedAt: row.at,
178
+ });
179
+ }
180
+ } catch {
181
+ // Metrics must never break a turn. A missing row is visible in the
182
+ // ledger; a thrown error here is not.
183
+ }
184
+ };
185
+
186
+ let dispose = null;
187
+ try {
188
+ const result = ctx.on('session/event', onSessionEvent);
189
+ if (typeof result === 'function') dispose = result;
190
+ } catch {
191
+ return { enabled: false, reason: 'register-failed' };
192
+ }
193
+
194
+ return {
195
+ enabled: true,
196
+ memoryRoot,
197
+ ledgerPath: ledgerPath(memoryRoot),
198
+ prestepPath: readPrestepLedger({ memoryRoot, limit: 1 }).path,
199
+ prestepSummary: () => readPrestepSummary({ memoryRoot }),
200
+ config: cfg,
201
+ onSessionEvent,
202
+ dispose,
203
+ };
204
+ }