@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,873 @@
1
+ // activity/index.js — shared-brain activity stream wiring (1.6.1, event-level).
2
+ //
3
+ // Producer: `session/event` writes into <memoryRoot>/.longlive/board/activity.jsonl.
4
+ // - `tool/call` (and `tool/result` with isError) refresh this turn's 「最近动作」
5
+ // row immediately, as 「工具:目标」 (e.g. 「pwsh:libtv 锚图 S08-S10」), so a
6
+ // sibling session sees a >10-minute turn while it is still running. Same-key
7
+ // refreshes are throttled to ≤1 write/10s; a merge bumps the row's `seq`
8
+ // (touchSeq) so the injection cursor below actually sees the refresh.
9
+ // - `turn/end` writes the local-rule conclusion row (user gist · assistant
10
+ // conclusion · latest tool action, ≤140 chars) as before.
11
+ // No model call, no session-log scan, no tool invocation.
12
+ //
13
+ // Consumer: `agent/pre-step` (step 1) → inject only rows with seq greater than
14
+ // this session's lastSeenSeq, other sessions only, at most `maxItems` rows and
15
+ // at most `injectMaxChars` characters (header/footer included). No rows means
16
+ // no write — zero token cost. Because every event-level refresh bumps seq, the
17
+ // cursor never gets stuck behind a long turn's first row.
18
+ //
19
+ // 1.8.8 M3 — 24h recap: on a new session's first step (or once the session's own
20
+ // last recap is older than `retainHours`), inject one extra ≤400-char block
21
+ // covering the ≤3 other sessions that were active in the window, each with its
22
+ // newest conclusion/action row (kind + text + seq + age). The block is rendered
23
+ // by summary.js from existing board rows only: no model call, no invented
24
+ // conclusions, and every line points at a seq that can still be found in
25
+ // activity.jsonl or the monthly archive. Unread line injection is unchanged.
26
+ //
27
+ // Failure policy: every path is wrapped; a broken board, a missing lock, a
28
+ // privacy verdict or a host without @deepseek-ai/dsh-llm just skips this
29
+ // feature. A turn is never blocked by the activity stream.
30
+
31
+ import path from 'node:path';
32
+
33
+ import { isUserAuthoredMessage } from '../truncate-visible.js';
34
+ import {
35
+ assertInjectionSource,
36
+ injectionSource,
37
+ insertionIndex,
38
+ isHumanMessage,
39
+ textOfMessage,
40
+ } from '../identity/inject-position.js';
41
+ import { privacyScan as defaultPrivacyScan } from '../recall/privacy.mjs';
42
+ import { startPrestepPhase, notePrestepDegrade } from '../metrics/prestep-latency.mjs';
43
+ import {
44
+ ACTIVITY_HINT_MARK,
45
+ ACTIVITY_REFRESH_THROTTLE_MS,
46
+ buildActivityKey,
47
+ buildActivityText,
48
+ buildToolActivityText,
49
+ charLength,
50
+ classifyKind,
51
+ clip,
52
+ oneLine,
53
+ renderActivityHint,
54
+ selectActivities,
55
+ shortSessionId,
56
+ } from './model.js';
57
+ import {
58
+ THINKING_HINT_MARK,
59
+ extractThinkingText,
60
+ isThinkingPayloadSafe,
61
+ renderThinkingHint,
62
+ selectThinkingActivities,
63
+ summarizeThinking,
64
+ } from './thinking.js';
65
+ import {
66
+ ACTIVITY_SUMMARY_MARK,
67
+ ACTIVITY_SUMMARY_MAX_CHARS,
68
+ ACTIVITY_SUMMARY_MAX_SESSIONS,
69
+ isSummaryDue,
70
+ renderActivitySummary,
71
+ selectActivityRecaps,
72
+ } from './summary.js';
73
+ import {
74
+ ACTIVITY_SESSION_RE,
75
+ activityBoardFile,
76
+ createActivityStore,
77
+ readJsonFile,
78
+ writeJsonAtomic,
79
+ } from './store.js';
80
+
81
+ export const ACTIVITY_STATE_VERSION = 1;
82
+ export const ACTIVITY_STATE_DIR = path.join('.longlive', 'bridge');
83
+
84
+ export const ACTIVITY_DEFAULTS = Object.freeze({
85
+ // 1.8.0 product default: real-time shared memory is ON by default; users opt
86
+ // out with an explicit `enabled: false` (never by omission).
87
+ enabled: true,
88
+ injectMaxChars: 300,
89
+ maxItems: 5,
90
+ // 1.8.8 M3: live board window is time-based (24h) with a row-count guard.
91
+ retainHours: 24,
92
+ recentMaxRows: 3200,
93
+ // 1.8.8 M3: recap block budget, independent of injectMaxChars/maxItems.
94
+ summaryMaxChars: 400,
95
+ });
96
+
97
+ function clampInt(value, fallback, min, max) {
98
+ const number = Number(value);
99
+ if (!Number.isFinite(number)) return fallback;
100
+ return Math.min(max, Math.max(min, Math.floor(number)));
101
+ }
102
+
103
+ /** `null`/`undefined` mean "not configured" for the 1.8.8 M3 numeric keys. */
104
+ function configured(value) {
105
+ return value === null || value === undefined ? undefined : value;
106
+ }
107
+
108
+ /** Pure normalizer; the config schema uses the same defaults. */
109
+ export function normalizeActivityConfig(input = {}) {
110
+ const raw = input !== null && typeof input === 'object' ? input : {};
111
+ return {
112
+ // Default ON (1.8.0): only a literal false opts out.
113
+ enabled: raw.enabled !== false,
114
+ injectMaxChars: clampInt(raw.injectMaxChars, ACTIVITY_DEFAULTS.injectMaxChars, 60, 2000),
115
+ maxItems: clampInt(raw.maxItems, ACTIVITY_DEFAULTS.maxItems, 1, 10),
116
+ // M3 defaults keep 1.6.8 behaviour for callers that pass nothing: 24h window,
117
+ // 3200-row guard (1.6.8's 500 was a row cap, not a time window).
118
+ retainHours: clampInt(configured(raw.retainHours), ACTIVITY_DEFAULTS.retainHours, 1, 720),
119
+ recentMaxRows: clampInt(configured(raw.recentMaxRows), ACTIVITY_DEFAULTS.recentMaxRows, 100, 20000),
120
+ summaryMaxChars: clampInt(configured(raw.summaryMaxChars), ACTIVITY_DEFAULTS.summaryMaxChars, 120, ACTIVITY_SUMMARY_MAX_CHARS),
121
+ createUserMessage: typeof raw.createUserMessage === 'function' ? raw.createUserMessage : undefined,
122
+ };
123
+ }
124
+
125
+ export function activityStateFile(memoryRoot, sessionId) {
126
+ return path.join(String(memoryRoot ?? ''), ACTIVITY_STATE_DIR, `${sessionId}.activity.json`);
127
+ }
128
+
129
+ export function emptyActivityState(sessionId) {
130
+ return {
131
+ v: ACTIVITY_STATE_VERSION,
132
+ sessionId,
133
+ lastSeenSeq: 0,
134
+ lastInjectedSeq: 0,
135
+ lastInjectedAt: null,
136
+ injectedTurns: 0,
137
+ // 1.8.8 M3: when this session last received a 24h recap (null = never).
138
+ // Missing on old state files → treated as never, which is the desired
139
+ // migration behaviour (one recap on the next turn, then once per window).
140
+ lastSummaryAt: null,
141
+ resets: 0,
142
+ lastResetAt: null,
143
+ updatedAt: null,
144
+ };
145
+ }
146
+
147
+ export function readActivityState(memoryRoot, sessionId) {
148
+ const read = readJsonFile(activityStateFile(memoryRoot, sessionId));
149
+ const value = read.ok ? read.value : null;
150
+ if (!value || value.v !== ACTIVITY_STATE_VERSION || value.sessionId !== sessionId) {
151
+ return emptyActivityState(sessionId);
152
+ }
153
+ return {
154
+ ...emptyActivityState(sessionId),
155
+ ...value,
156
+ lastSeenSeq: Number.isInteger(value.lastSeenSeq) && value.lastSeenSeq >= 0 ? value.lastSeenSeq : 0,
157
+ lastInjectedSeq: Number.isInteger(value.lastInjectedSeq) && value.lastInjectedSeq >= 0 ? value.lastInjectedSeq : 0,
158
+ injectedTurns: Number.isInteger(value.injectedTurns) && value.injectedTurns >= 0 ? value.injectedTurns : 0,
159
+ resets: Number.isInteger(value.resets) && value.resets >= 0 ? value.resets : 0,
160
+ lastSummaryAt: typeof value.lastSummaryAt === 'string' && value.lastSummaryAt !== '' ? value.lastSummaryAt : null,
161
+ };
162
+ }
163
+
164
+ // Exported for 02-handoff (v4 §5.3): the handoff producer parses the exact same
165
+ // session events as the activity stream, with the same text/tool extraction.
166
+ export function textBlocks(content) {
167
+ if (!Array.isArray(content)) return '';
168
+ const parts = [];
169
+ for (const block of content) {
170
+ if (!block || block.type !== 'text' || typeof block.text !== 'string') continue;
171
+ const text = block.text.trim();
172
+ if (text !== '') parts.push(text);
173
+ }
174
+ return parts.join('\n');
175
+ }
176
+
177
+ export function messageTextOf(event) {
178
+ const data = event?.data ?? {};
179
+ const message = data.message && typeof data.message === 'object' ? data.message : data;
180
+ return textBlocks(message?.content);
181
+ }
182
+
183
+ function sessionIdOfMessage(session, event) {
184
+ const raw = session?.id
185
+ ?? session?.header?.id
186
+ ?? event?.sessionId
187
+ ?? '';
188
+ if (typeof raw !== 'string') return '';
189
+ const id = raw.trim().toLowerCase();
190
+ return ACTIVITY_SESSION_RE.test(id) ? id : '';
191
+ }
192
+
193
+ export function toolSummaryOf(data) {
194
+ const name = oneLine(data?.name ?? 'tool');
195
+ const args = data?.arguments;
196
+ let snippet = '';
197
+ if (typeof args === 'string' && args.trim() !== '') {
198
+ let parsed = null;
199
+ try {
200
+ parsed = JSON.parse(args);
201
+ } catch {
202
+ parsed = null;
203
+ }
204
+ if (parsed && typeof parsed === 'object') {
205
+ for (const key of ['command', 'cmd', 'path', 'file_path', 'query', 'pattern', 'glob', 'description', 'prompt', 'url']) {
206
+ const value = parsed[key];
207
+ if (typeof value === 'string' && value.trim() !== '') {
208
+ snippet = value;
209
+ break;
210
+ }
211
+ }
212
+ }
213
+ if (snippet === '') snippet = args;
214
+ }
215
+ return { name, summary: clip(oneLine(snippet), 44) };
216
+ }
217
+
218
+ function headerOf(payload) {
219
+ const agent = payload?.agent;
220
+ return agent?.session?.header ?? agent?.header ?? payload?.session?.header ?? {};
221
+ }
222
+
223
+ function sessionOf(payload) {
224
+ const agent = payload?.agent;
225
+ return agent?.session ?? payload?.session ?? null;
226
+ }
227
+
228
+ function preStepSessionId(payload) {
229
+ const header = headerOf(payload);
230
+ const agent = payload?.agent;
231
+ const raw = header.id ?? agent?.sessionId ?? sessionOf(payload)?.id ?? payload?.sessionId;
232
+ if (typeof raw !== 'string') return '';
233
+ const id = raw.trim().toLowerCase();
234
+ return ACTIVITY_SESSION_RE.test(id) ? id : '';
235
+ }
236
+
237
+ function normalizeOrigin(value) {
238
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
239
+ }
240
+
241
+ function maxSeqOf(entries) {
242
+ let max = 0;
243
+ for (const entry of Array.isArray(entries) ? entries : []) {
244
+ if (Number.isInteger(entry?.seq) && entry.seq > max) max = entry.seq;
245
+ }
246
+ return max;
247
+ }
248
+
249
+ async function resolveCreateUserMessage(explicit) {
250
+ if (typeof explicit === 'function') return explicit;
251
+ try {
252
+ const mod = await import('@deepseek-ai/dsh-llm');
253
+ return typeof mod?.createUserMessage === 'function' ? mod.createUserMessage : null;
254
+ } catch {
255
+ return null;
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Create the stream object. `enabled` + `memoryRoot` are the only switches;
261
+ * everything else is a budget. Tests drive `onSessionEvent` / `maybeInject`
262
+ * directly, which is the same path the hooks use.
263
+ */
264
+ export function createActivityStream(options = {}) {
265
+ const cfg = normalizeActivityConfig(options);
266
+ // 1.8.0: thinking summaries are an independent, default-off injection switch.
267
+ // The write side also requires it, so off is byte-for-byte the 1.7.4 behaviour.
268
+ const thinkingInjection = options.thinkingInjection === true;
269
+ const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
270
+ ? path.resolve(options.memoryRoot)
271
+ : null;
272
+ const now = typeof options.now === 'function' ? options.now : () => new Date();
273
+ const privacyScan = typeof options.privacyScan === 'function' ? options.privacyScan : defaultPrivacyScan;
274
+ const logger = typeof options.logger === 'function' ? options.logger : () => {};
275
+ const stats = {
276
+ turns: 0,
277
+ events: 0,
278
+ written: 0,
279
+ refreshed: 0,
280
+ merged: 0,
281
+ distilled: 0,
282
+ throttled: 0,
283
+ injected: 0,
284
+ skipped: 0,
285
+ privacy: 0,
286
+ resets: 0,
287
+ errors: 0,
288
+ thinkingWritten: 0,
289
+ thinkingInjected: 0,
290
+ // 1.8.8 M3: how many recap lines were injected / how many turns carried a recap.
291
+ summaryInjected: 0,
292
+ summaryTurns: 0,
293
+ };
294
+ const sessions = new Map();
295
+ // `${sessionId}|${key}` → { at: ms, kind } — 同 key 节流 ≤1 次刷新/10s.
296
+ const refreshes = new Map();
297
+ const disposers = [];
298
+ const store = memoryRoot
299
+ ? createActivityStore({
300
+ memoryRoot,
301
+ now,
302
+ privacyScan,
303
+ retainHours: cfg.retainHours,
304
+ recentMaxRows: cfg.recentMaxRows,
305
+ })
306
+ : null;
307
+ const enabled = cfg.enabled === true && store !== null;
308
+
309
+ function stateFor(sessionId) {
310
+ let state = sessions.get(sessionId);
311
+ if (!state) {
312
+ state = {
313
+ sessionId,
314
+ turn: null,
315
+ userText: '',
316
+ assistantText: '',
317
+ tool: null,
318
+ toolCalls: 0,
319
+ thinkingTurn: null,
320
+ thinkingWritten: false,
321
+ };
322
+ sessions.set(sessionId, state);
323
+ }
324
+ return state;
325
+ }
326
+
327
+ function clearSessionRefreshes(sessionId) {
328
+ const prefix = `${sessionId}|`;
329
+ for (const key of refreshes.keys()) {
330
+ if (key.startsWith(prefix)) refreshes.delete(key);
331
+ }
332
+ }
333
+
334
+ /**
335
+ * Event-level write: one refresh per tool call, as 「工具:目标」.
336
+ *
337
+ * Same-key refreshes are throttled to one per ACTIVITY_REFRESH_THROTTLE_MS —
338
+ * a 12-call burst must not append 12 near-identical rows. A tool error may
339
+ * skip the window once (kind escalation to blocked), after that it throttles
340
+ * like everything else. The store merge bumps `seq`, which is what lets the
341
+ * consumer's seq-only cursor pick the update up.
342
+ */
343
+ function writeToolActivity(state, { isError = false } = {}) {
344
+ const tool = state.tool;
345
+ if (!tool || typeof tool.name !== 'string' || tool.name.trim() === '') {
346
+ return { written: false, reason: 'no-tool' };
347
+ }
348
+ const failed = isError === true || tool.isError === true;
349
+ const text = buildToolActivityText(tool, { isError: failed });
350
+ if (text === '') return { written: false, reason: 'empty' };
351
+ const key = buildActivityKey({
352
+ userText: state.userText,
353
+ assistantText: state.assistantText,
354
+ tool,
355
+ });
356
+ const nowDate = now();
357
+ const nowMs = nowDate.getTime();
358
+ const refreshKey = `${state.sessionId}|${key}`;
359
+ const last = refreshes.get(refreshKey) ?? null;
360
+ const within = last !== null && Number.isFinite(nowMs) && nowMs - last.at < ACTIVITY_REFRESH_THROTTLE_MS;
361
+ const escalating = failed && (last === null || last.kind !== 'blocked');
362
+ if (within && !escalating) {
363
+ stats.throttled += 1;
364
+ return { written: false, reason: 'throttled' };
365
+ }
366
+ const kind = failed ? 'blocked' : classifyKind({ userText: state.userText, tool });
367
+ const result = store.append(
368
+ { sessionId: state.sessionId, kind, text, key, at: nowDate },
369
+ { touchSeq: true, refreshText: true },
370
+ );
371
+ if (!result.ok) {
372
+ if (result.code === 'E_PRIVACY') stats.privacy += 1;
373
+ else stats.errors += 1;
374
+ return { written: false, reason: result.code ?? 'error' };
375
+ }
376
+ refreshes.set(refreshKey, { at: nowMs, kind });
377
+ if (result.action === 'distilled') stats.distilled += 1;
378
+ else if (result.action === 'refreshed') stats.refreshed += 1;
379
+ else if (result.action === 'merged') stats.merged += 1;
380
+ else stats.written += 1;
381
+ return {
382
+ written: true,
383
+ action: result.action,
384
+ seq: result.seq,
385
+ seqBumped: result.seqBumped === true,
386
+ entry: result.entry,
387
+ };
388
+ }
389
+
390
+ function writeTurn(state, reason, turn) {
391
+ let text = buildActivityText({
392
+ userText: state.userText,
393
+ assistantText: state.assistantText,
394
+ tool: state.tool,
395
+ });
396
+ let kind = classifyKind({
397
+ userText: state.userText,
398
+ assistantText: state.assistantText,
399
+ tool: state.tool,
400
+ });
401
+ if (reason === 'failed') {
402
+ kind = 'blocked';
403
+ if (text === '') text = '回合失败(已记录为 blocked)';
404
+ }
405
+ if (text === '') {
406
+ stats.skipped += 1;
407
+ return { written: false, reason: 'empty' };
408
+ }
409
+ const candidate = {
410
+ sessionId: state.sessionId,
411
+ kind,
412
+ text,
413
+ key: buildActivityKey({
414
+ userText: state.userText,
415
+ assistantText: state.assistantText,
416
+ tool: state.tool,
417
+ }),
418
+ at: now(),
419
+ };
420
+ // A conclusion merge also carries new information for sibling sessions:
421
+ // bump seq and let the newest conclusion replace the turn's action text.
422
+ const result = store.append(candidate, { touchSeq: true, refreshText: true });
423
+ if (!result.ok) {
424
+ if (result.code === 'E_PRIVACY') stats.privacy += 1;
425
+ else stats.errors += 1;
426
+ return { written: false, reason: result.code ?? 'error', turn };
427
+ }
428
+ if (result.action === 'distilled') stats.distilled += 1;
429
+ else if (result.action === 'refreshed') stats.refreshed += 1;
430
+ else if (result.action === 'merged') stats.merged += 1;
431
+ else stats.written += 1;
432
+ return { written: true, action: result.action, seqBumped: result.seqBumped === true, entry: result.entry, turn };
433
+ }
434
+
435
+ function onSessionEvent(session, event) {
436
+ if (!enabled) return;
437
+ try {
438
+ const type = event?.type;
439
+ if (typeof type !== 'string') return;
440
+ const sessionId = sessionIdOfMessage(session, event);
441
+ if (type === 'session/disposed') {
442
+ if (sessionId !== '') {
443
+ sessions.delete(sessionId);
444
+ clearSessionRefreshes(sessionId);
445
+ }
446
+ return;
447
+ }
448
+ if (sessionId === '') return;
449
+ const state = stateFor(sessionId);
450
+
451
+ if (type === 'turn/start') {
452
+ const turn = event?.data?.turn;
453
+ state.turn = Number.isInteger(turn) ? turn : state.turn;
454
+ state.userText = '';
455
+ state.assistantText = '';
456
+ state.tool = null;
457
+ state.toolCalls = 0;
458
+ state.thinkingTurn = null;
459
+ state.thinkingWritten = false;
460
+ // A new turn is new information: do not let the previous turn's 10s
461
+ // window swallow its first tool action.
462
+ clearSessionRefreshes(sessionId);
463
+ return;
464
+ }
465
+
466
+ if (type === 'user/message') {
467
+ if (!isUserAuthoredMessage(event)) return;
468
+ const text = messageTextOf(event);
469
+ if (text !== '') state.userText = text;
470
+ return;
471
+ }
472
+
473
+ if (type === 'assistant/message') {
474
+ const data = event?.data ?? {};
475
+ const turn = data.turn;
476
+ if (Number.isInteger(turn) && Number.isInteger(state.turn) && turn !== state.turn) return;
477
+ const text = messageTextOf(event);
478
+ if (text !== '') state.assistantText = text;
479
+ // 1.8.0 thinking summaries: at most one row per session+turn; only when
480
+ // the injection switch is on. Visible reasoning text exists or nothing
481
+ // is written (no model call, no raw log rewrite).
482
+ if (thinkingInjection) {
483
+ const resolvedTurn = Number.isInteger(turn) ? turn : (Number.isInteger(state.turn) ? state.turn : null);
484
+ const alreadyWritten = state.thinkingWritten
485
+ && (state.thinkingTurn === resolvedTurn || resolvedTurn === null);
486
+ if (!alreadyWritten) {
487
+ const summary = summarizeThinking(extractThinkingText(data.message?.content));
488
+ if (summary !== '') {
489
+ const result = store.append(
490
+ {
491
+ sessionId,
492
+ kind: 'thinking',
493
+ text: summary,
494
+ key: `thinking|${resolvedTurn ?? 'turn'}`,
495
+ at: now(),
496
+ turnRef: resolvedTurn,
497
+ charCount: charLength(summary),
498
+ },
499
+ { touchSeq: true, refreshText: false },
500
+ );
501
+ if (result.ok) {
502
+ state.thinkingTurn = resolvedTurn;
503
+ state.thinkingWritten = true;
504
+ stats.thinkingWritten += 1;
505
+ } else if (result.code === 'E_PRIVACY') {
506
+ stats.privacy += 1;
507
+ } else {
508
+ stats.errors += 1;
509
+ }
510
+ }
511
+ }
512
+ }
513
+ return;
514
+ }
515
+
516
+ if (type === 'tool/call') {
517
+ state.toolCalls += 1;
518
+ state.tool = { ...toolSummaryOf(event?.data), isError: false };
519
+ // Event-level write: the sibling session sees the action while the
520
+ // turn is still running (throttled inside writeToolActivity).
521
+ stats.events += 1;
522
+ writeToolActivity(state);
523
+ return;
524
+ }
525
+
526
+ if (type === 'tool/result') {
527
+ const data = event?.data ?? {};
528
+ const message = data.message && typeof data.message === 'object' ? data.message : data;
529
+ const isError = message?.isError === true || data.isError === true;
530
+ if (isError) {
531
+ if (!state.tool && typeof data.name === 'string' && data.name.trim() !== '') {
532
+ state.tool = { ...toolSummaryOf(data), isError: true };
533
+ }
534
+ if (state.tool) {
535
+ state.tool.isError = true;
536
+ stats.events += 1;
537
+ writeToolActivity(state, { isError: true });
538
+ }
539
+ }
540
+ return;
541
+ }
542
+
543
+ if (type === 'turn/end') {
544
+ const turn = event?.data?.turn;
545
+ const reason = normalizeOrigin(event?.data?.reason?.kind);
546
+ const resolved = Number.isInteger(turn) ? turn : state.turn;
547
+ stats.turns += 1;
548
+ if (reason === 'completed' || reason === 'failed') {
549
+ writeTurn(state, reason, resolved);
550
+ } else {
551
+ stats.skipped += 1;
552
+ }
553
+ state.userText = '';
554
+ state.assistantText = '';
555
+ state.tool = null;
556
+ state.toolCalls = 0;
557
+ state.turn = Number.isInteger(resolved) ? resolved : null;
558
+ }
559
+ } catch {
560
+ stats.errors += 1;
561
+ }
562
+ }
563
+
564
+ function skip(reason) {
565
+ stats.skipped += 1;
566
+ return { injected: false, skipped: reason };
567
+ }
568
+
569
+ /**
570
+ * One pre-step attempt. Returns {injected, skipped?, entries?}; never throws.
571
+ */
572
+ async function maybeInject(payload) {
573
+ if (!enabled) return { injected: false, skipped: 'disabled' };
574
+ if (Number(payload?.step) !== 1) return { injected: false, skipped: 'not-step-1' };
575
+ const sessionId = preStepSessionId(payload);
576
+ if (sessionId === '') return skip('no-session');
577
+ if (normalizeOrigin(headerOf(payload).origin) === 'subagent') return skip('subagent');
578
+ const messages = payload?.messages;
579
+ if (!Array.isArray(messages)) return skip('no-messages');
580
+ if (!messages.some((message) => isHumanMessage(message))) return skip('empty-turn');
581
+ if (messages.some((message) => {
582
+ const text = textOfMessage(message);
583
+ return text.includes(ACTIVITY_HINT_MARK)
584
+ || text.includes(THINKING_HINT_MARK)
585
+ || text.includes(ACTIVITY_SUMMARY_MARK);
586
+ })) {
587
+ return { injected: false, skipped: 'turn-already-injected' };
588
+ }
589
+
590
+ const read = store.read();
591
+ if (!read.ok) return skip('board-unreadable');
592
+ const state = readActivityState(memoryRoot, sessionId);
593
+ const nowMs = now().getTime();
594
+ const boardMax = maxSeqOf(read.entries);
595
+ // Board reset (deleted/emptied/replaced-from-backup): the persisted seq-only
596
+ // cursor can sit above every current row, so `seq > lastSeenSeq` would match
597
+ // nothing forever. Falling back to 0 replays the current board instead of
598
+ // stranding the sibling (RE-R15.5). The store's high-water sidecar normally
599
+ // prevents this; this branch is the safety net for legacy/reset boards.
600
+ const resetCursor = boardMax > 0 && state.lastSeenSeq > boardMax;
601
+ if (resetCursor) stats.resets += 1;
602
+ const effectiveSeen = resetCursor ? 0 : state.lastSeenSeq;
603
+ const fresh = selectActivities(read.entries, {
604
+ selfSessionId: sessionId,
605
+ lastSeenSeq: effectiveSeen,
606
+ maxItems: cfg.maxItems,
607
+ });
608
+ // 1.8.0: thinking summaries are selected separately and never mixed into
609
+ // the normal activity lines (the cursor is the same lastSeenSeq).
610
+ const freshThinking = thinkingInjection
611
+ ? selectThinkingActivities(read.entries, {
612
+ selfSessionId: sessionId,
613
+ lastSeenSeq: effectiveSeen,
614
+ maxItems: 5,
615
+ nowMs,
616
+ windowHours: cfg.retainHours,
617
+ })
618
+ : [];
619
+ // 1.8.8 M3: the recap is due on a new session's first step or once the
620
+ // session's own last recap is older than retainHours. It is built only from
621
+ // existing board rows (never from the model), so an empty board simply
622
+ // means no recap — never an invented one.
623
+ const summaryDue = isSummaryDue(state, { nowMs, intervalHours: cfg.retainHours });
624
+ const freshRecaps = summaryDue
625
+ ? selectActivityRecaps(read.entries, {
626
+ nowMs,
627
+ windowHours: cfg.retainHours,
628
+ selfSessionId: sessionId,
629
+ maxSessions: ACTIVITY_SUMMARY_MAX_SESSIONS,
630
+ })
631
+ : [];
632
+ if (fresh.length === 0 && freshThinking.length === 0 && freshRecaps.length === 0) {
633
+ return { injected: false, skipped: 'no-new', reset: resetCursor };
634
+ }
635
+
636
+ const allowed = [];
637
+ for (const item of fresh) {
638
+ try {
639
+ const verdict = privacyScan(item.text);
640
+ if (!verdict || verdict.verdict === 'local_only') {
641
+ stats.privacy += 1;
642
+ continue;
643
+ }
644
+ } catch {
645
+ stats.privacy += 1;
646
+ continue;
647
+ }
648
+ allowed.push(item);
649
+ }
650
+ const allowedThinking = [];
651
+ for (const item of freshThinking) {
652
+ const summary = summarizeThinking(item.text);
653
+ if (summary === '' || !isThinkingPayloadSafe(summary)) {
654
+ stats.privacy += 1;
655
+ continue;
656
+ }
657
+ try {
658
+ const verdict = privacyScan(summary);
659
+ if (!verdict || verdict.verdict === 'local_only') {
660
+ stats.privacy += 1;
661
+ continue;
662
+ }
663
+ } catch {
664
+ stats.privacy += 1;
665
+ continue;
666
+ }
667
+ allowedThinking.push({ ...item, text: summary });
668
+ }
669
+ const allowedRecaps = [];
670
+ for (const item of freshRecaps) {
671
+ try {
672
+ const verdict = privacyScan(item.text);
673
+ if (!verdict || verdict.verdict === 'local_only') {
674
+ stats.privacy += 1;
675
+ continue;
676
+ }
677
+ } catch {
678
+ stats.privacy += 1;
679
+ continue;
680
+ }
681
+ allowedRecaps.push(item);
682
+ }
683
+ if (allowed.length === 0 && allowedThinking.length === 0 && allowedRecaps.length === 0) {
684
+ return { injected: false, skipped: 'privacy' };
685
+ }
686
+
687
+ const parts = [];
688
+ let summarySeqs = [];
689
+ // 1.8.8 M3: recap first — it is the 「其他会话现在在哪」 map; unread lines and
690
+ // thinking follow, so a new session reads context before details.
691
+ if (allowedRecaps.length > 0) {
692
+ const renderedSummary = renderActivitySummary(allowedRecaps, {
693
+ maxChars: cfg.summaryMaxChars,
694
+ nowMs,
695
+ });
696
+ if (renderedSummary.text !== '') {
697
+ parts.push(renderedSummary.text);
698
+ summarySeqs = renderedSummary.seqs;
699
+ }
700
+ }
701
+ if (allowed.length > 0) {
702
+ const rendered = renderActivityHint(allowed, {
703
+ maxChars: cfg.injectMaxChars,
704
+ maxItems: cfg.maxItems,
705
+ nowMs,
706
+ });
707
+ if (rendered.text !== '') parts.push(rendered.text);
708
+ }
709
+ if (allowedThinking.length > 0) {
710
+ const thinkingText = renderThinkingHint(allowedThinking, { maxItems: 5 });
711
+ if (thinkingText !== '') parts.push(thinkingText);
712
+ }
713
+ if (parts.length === 0) return skip('budget-empty');
714
+ const text = parts.join('\n\n');
715
+
716
+ const createUserMessage = await resolveCreateUserMessage(cfg.createUserMessage);
717
+ if (typeof createUserMessage !== 'function') return skip('no-create-user-message');
718
+ let message;
719
+ try {
720
+ message = assertInjectionSource(createUserMessage({
721
+ role: 'user',
722
+ content: [{ type: 'text', text }],
723
+ source: injectionSource(),
724
+ }));
725
+ } catch {
726
+ return skip('create-message-failed');
727
+ }
728
+ const index = insertionIndex(messages);
729
+ if (index <= 0) return skip('no-human-message');
730
+ try {
731
+ messages.splice(index, 0, message);
732
+ } catch {
733
+ return skip('splice-failed');
734
+ }
735
+
736
+ const injectedItems = [...allowed, ...allowedThinking];
737
+ const unreadInjected = injectedItems.length > 0;
738
+ const nowIso = new Date(nowMs).toISOString();
739
+ const nextState = {
740
+ ...state,
741
+ // A summary-only injection must NOT advance the unread cursor: those rows
742
+ // were never shown as lines, so the next turn still needs to deliver them.
743
+ lastSeenSeq: unreadInjected ? Math.max(effectiveSeen, boardMax) : state.lastSeenSeq,
744
+ lastInjectedSeq: unreadInjected ? maxSeqOf(injectedItems) : state.lastInjectedSeq,
745
+ lastInjectedAt: nowIso,
746
+ lastSummaryAt: allowedRecaps.length > 0 ? nowIso : state.lastSummaryAt,
747
+ injectedTurns: state.injectedTurns + 1,
748
+ resets: state.resets + (resetCursor ? 1 : 0),
749
+ lastResetAt: resetCursor ? nowIso : state.lastResetAt,
750
+ updatedAt: nowIso,
751
+ };
752
+ try {
753
+ writeJsonAtomic(activityStateFile(memoryRoot, sessionId), nextState);
754
+ } catch {
755
+ /* state is an optimization; a failed write costs a repeat, not a turn */
756
+ }
757
+ stats.injected += 1;
758
+ stats.thinkingInjected += allowedThinking.length;
759
+ stats.summaryInjected += allowedRecaps.length;
760
+ if (allowedRecaps.length > 0) stats.summaryTurns += 1;
761
+ return {
762
+ injected: true,
763
+ sessionId,
764
+ chars: charLength(text),
765
+ reset: resetCursor,
766
+ items: injectedItems.map((item) => ({ seq: item.seq, sessionId: item.sessionId, kind: item.kind })),
767
+ thinkingItems: allowedThinking.length,
768
+ summary: allowedRecaps.length > 0,
769
+ summaryItems: allowedRecaps.length,
770
+ summarySeqs,
771
+ text,
772
+ };
773
+ }
774
+
775
+ function install(ctx) {
776
+ if (!enabled || !ctx || typeof ctx.on !== 'function') return false;
777
+ try {
778
+ const dispose = ctx.on('session/event', (session, event) => onSessionEvent(session, event));
779
+ if (typeof dispose === 'function') disposers.push(dispose);
780
+ } catch (error) {
781
+ stats.errors += 1;
782
+ logger(`[activity] session/event 监听注册失败:${error?.code ?? error?.message ?? error}`);
783
+ }
784
+ try {
785
+ const dispose = ctx.on('agent/pre-step', async (payload, next) => {
786
+ // B3: shared phase = shared-brain injection only (timing only).
787
+ const sessionId = preStepSessionId(payload);
788
+ const phase = startPrestepPhase(sessionId, payload?.turn, 'shared');
789
+ try {
790
+ await maybeInject(payload);
791
+ } catch {
792
+ stats.errors += 1;
793
+ notePrestepDegrade(sessionId, payload?.turn, { kind: 'error', phase: 'shared', detail: 'E_ACTIVITY_PRE_STEP' });
794
+ } finally {
795
+ phase.end();
796
+ }
797
+ return typeof next === 'function' ? next() : undefined;
798
+ });
799
+ if (typeof dispose === 'function') disposers.push(dispose);
800
+ } catch (error) {
801
+ stats.errors += 1;
802
+ logger(`[activity] agent/pre-step 监听注册失败:${error?.code ?? error?.message ?? error}`);
803
+ }
804
+ return true;
805
+ }
806
+
807
+ function dispose() {
808
+ while (disposers.length > 0) {
809
+ const disposer = disposers.pop();
810
+ try {
811
+ disposer();
812
+ } catch {
813
+ /* already disposed */
814
+ }
815
+ }
816
+ sessions.clear();
817
+ refreshes.clear();
818
+ }
819
+
820
+ return {
821
+ enabled,
822
+ memoryRoot,
823
+ config: { ...cfg, thinkingInjection },
824
+ stats,
825
+ store,
826
+ install,
827
+ dispose,
828
+ onSessionEvent,
829
+ maybeInject,
830
+ readState: (sessionId) => (enabled ? readActivityState(memoryRoot, sessionId) : emptyActivityState(sessionId)),
831
+ boardFile: store?.boardFile ?? null,
832
+ };
833
+ }
834
+
835
+ /**
836
+ * Register the two hooks for the feature switch. A disabled stream registers
837
+ * nothing and touches no file; a broken registration is a warning only.
838
+ */
839
+ export function registerActivityStream(ctx, cfg = {}, options = {}) {
840
+ const stream = createActivityStream({
841
+ enabled: cfg.enabled !== false,
842
+ memoryRoot: options.memoryRoot,
843
+ injectMaxChars: cfg.injectMaxChars,
844
+ maxItems: cfg.maxItems,
845
+ retainHours: cfg.retainHours,
846
+ recentMaxRows: cfg.recentMaxRows,
847
+ summaryMaxChars: cfg.summaryMaxChars,
848
+ thinkingInjection: cfg.thinkingInjection === true,
849
+ createUserMessage: cfg.createUserMessage,
850
+ now: options.now,
851
+ privacyScan: options.privacyScan,
852
+ logger: options.logger,
853
+ });
854
+ if (!stream.enabled) return stream;
855
+ stream.install(ctx);
856
+ if (typeof ctx?.effect === 'function') {
857
+ try {
858
+ ctx.effect(() => () => stream.dispose(), 'longlive.shared-brain-activity');
859
+ } catch {
860
+ /* a fake context may not own an effect scope */
861
+ }
862
+ }
863
+ return stream;
864
+ }
865
+
866
+ export { ACTIVITY_HINT_MARK, ACTIVITY_REFRESH_THROTTLE_MS, shortSessionId, activityBoardFile };
867
+ export { THINKING_HINT_MARK, THINKING_KIND, THINKING_LINE_MAX, THINKING_MAX_ITEMS } from './thinking.js';
868
+ export {
869
+ ACTIVITY_SUMMARY_END,
870
+ ACTIVITY_SUMMARY_MARK,
871
+ ACTIVITY_SUMMARY_MAX_CHARS,
872
+ ACTIVITY_SUMMARY_MAX_SESSIONS,
873
+ } from './summary.js';