@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,485 @@
1
+ // D2 — trim oversized tool results before they reach the context.
2
+ //
3
+ // Seam: the host's `tools/post-execute` waterfall (Cordis). The host runs it
4
+ // after a tool has produced its content and before that content is appended to
5
+ // the session log (`@deepseek-ai/dsh-tools` lib/pipeline.js `postExecute` →
6
+ // `commit` → `session.append('tool/result', …)`), so a replacement returned
7
+ // here is exactly what the model sees and what the log keeps. No history
8
+ // rewriting, no second pass over the context.
9
+ //
10
+ // Contract with D3: the archive lands at the D3 convention
11
+ // `<memoryRoot>/.longlive/tool-output/<turn>/<id>.txt`
12
+ // with `<id>` = `archiveFileName({kind:'tool', toolCallId})`, i.e. the same
13
+ // toolCallId that `session_original` uses to plan a path. D3 never writes it;
14
+ // D2 does, and both agree on the name.
15
+ //
16
+ // Safety envelope:
17
+ // - ON by default (1.8.0 behavior): `d2.enabled !== false` mounts the listener;
18
+ // an explicit `d2.enabled: false` is the kill switch and mounts nothing;
19
+ // - fail-open: every failure keeps the untouched decision and never throws
20
+ // out of the hook (a broken trim must not break a turn);
21
+ // - the privacy gate (`privacyScan`) scans the FULL text before anything is
22
+ // written; a hit writes nothing and leaves a placeholder;
23
+ // - write-before-replace: the archive is renamed into place before the
24
+ // content is swapped, so a path printed in the context always resolves.
25
+ //
26
+ // Ordering note: this listener does NOT use `{prepend:true}`. It runs after
27
+ // other post-execute policies (notably `@deepseek-ai/dsh-spill-policy`) and its
28
+ // decision is the final one, while `result.content` — read before `next()`
29
+ // resolves — is still the untrimmed tool output.
30
+
31
+ import fs from 'node:fs';
32
+ import path from 'node:path';
33
+
34
+ import { archiveFileName, textOfParts } from './original.js';
35
+ import { privacyScan } from './recall/privacy.mjs';
36
+ import { scrubText, redactionMetadata } from './util/redact.js';
37
+
38
+ export const D2_DEFAULTS = Object.freeze({
39
+ // Default ON to match deployed 1.8.0 behavior and the config schema; only an
40
+ // explicit `d2.enabled: false` (or the features-level kill switch) disables.
41
+ enabled: true,
42
+ maxInlineChars: 4096,
43
+ headRatio: 0.6,
44
+ skipTools: Object.freeze(['read']),
45
+ trimErrors: false,
46
+ });
47
+ export const D2_MIN_MAX_INLINE_CHARS = 64;
48
+ export const D2_MAX_MAX_INLINE_CHARS = 1_000_000;
49
+
50
+ /** S1: tool-output 落盘的 TTL/scrub 默认值(删除执行归 S5 retention)。 */
51
+ export const TOOL_OUTPUT_DEFAULTS = Object.freeze({
52
+ redact: true,
53
+ retentionDays: 90,
54
+ });
55
+ export const TOOL_OUTPUT_META_SCHEMA = 'tool-output-meta/v1';
56
+
57
+ /** Normalise the top-level `toolOutput` config block; bad values fall back. */
58
+ export function normalizeToolOutputConfig(raw) {
59
+ const source = raw && typeof raw === 'object' ? raw : {};
60
+ const retentionDays = Number(source.retentionDays);
61
+ return {
62
+ redact: source.redact !== false,
63
+ retentionDays: Number.isInteger(retentionDays) && retentionDays > 0 && retentionDays <= 3650
64
+ ? retentionDays
65
+ : TOOL_OUTPUT_DEFAULTS.retentionDays,
66
+ };
67
+ }
68
+
69
+ /** Where D2 keeps tool output for a memory root (D3's convention). */
70
+ export function toolOutputRoot(memoryRoot) {
71
+ return path.join(String(memoryRoot ?? ''), '.longlive', 'tool-output');
72
+ }
73
+
74
+ /** `<memoryRoot>/.longlive/tool-output/<turn>` — the directory D3 plans too. */
75
+ export function toolOutputDir(memoryRoot, turn) {
76
+ return path.join(toolOutputRoot(memoryRoot), String(turn));
77
+ }
78
+
79
+ function clampNumber(value, fallback, min, max) {
80
+ const n = Number(value);
81
+ if (!Number.isFinite(n)) return fallback;
82
+ return Math.min(max, Math.max(min, n));
83
+ }
84
+
85
+ /**
86
+ * Normalise `config.d2`. Missing config means default ON (1.8.0 behavior);
87
+ * only an explicit boolean `false` is the kill switch. Unknown/invalid values
88
+ * for budgets fall back to the defaults instead of failing activation.
89
+ */
90
+ export function normalizeD2Config(raw) {
91
+ const source = raw && typeof raw === 'object' ? raw : {};
92
+ const skipTools = Array.isArray(source.skipTools)
93
+ ? source.skipTools.filter((name) => typeof name === 'string' && name !== '')
94
+ : [...D2_DEFAULTS.skipTools];
95
+ return {
96
+ enabled: source.enabled !== false,
97
+ maxInlineChars: Math.round(clampNumber(
98
+ source.maxInlineChars,
99
+ D2_DEFAULTS.maxInlineChars,
100
+ D2_MIN_MAX_INLINE_CHARS,
101
+ D2_MAX_MAX_INLINE_CHARS,
102
+ )),
103
+ headRatio: clampNumber(source.headRatio, D2_DEFAULTS.headRatio, 0.2, 0.8),
104
+ skipTools,
105
+ trimErrors: source.trimErrors === true,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Split `text` into an inline head and tail of at most `maxInlineChars`
111
+ * characters (head ≈ `headRatio`). Never splits a surrogate pair, so an emoji
112
+ * on the boundary cannot become a lone half. Returns `trimmed:false` when the
113
+ * text already fits.
114
+ */
115
+ export function splitHeadTail(text, maxInlineChars, headRatio = D2_DEFAULTS.headRatio) {
116
+ const source = String(text ?? '');
117
+ const budget = Math.max(1, Math.round(Number(maxInlineChars) || D2_DEFAULTS.maxInlineChars));
118
+ if (source.length <= budget) {
119
+ return { head: source, tail: '', headChars: source.length, tailChars: 0, omittedChars: 0, trimmed: false };
120
+ }
121
+ const headBudget = Math.max(1, Math.min(budget - 1, Math.round(budget * clampNumber(headRatio, 0.6, 0.2, 0.8))));
122
+ const tailBudget = Math.max(0, budget - headBudget);
123
+
124
+ let head = source.slice(0, headBudget);
125
+ if (head.length > 0 && /[\uD800-\uDBFF]/.test(head[head.length - 1])) head = head.slice(0, -1);
126
+ let tail = tailBudget > 0 ? source.slice(source.length - tailBudget) : '';
127
+ if (tail.length > 0 && /[\uDC00-\uDFFF]/.test(tail[0])) tail = tail.slice(1);
128
+
129
+ return {
130
+ head,
131
+ tail,
132
+ headChars: head.length,
133
+ tailChars: tail.length,
134
+ omittedChars: source.length - head.length - tail.length,
135
+ trimmed: true,
136
+ };
137
+ }
138
+
139
+ /** The single context line that replaces an archived tool output. */
140
+ export function formatD2Notice({
141
+ chars,
142
+ inlineChars,
143
+ bytes,
144
+ file,
145
+ turn,
146
+ callId,
147
+ toolName,
148
+ }) {
149
+ const name = toolName ? ` (${toolName})` : '';
150
+ const turnHint = Number.isInteger(turn)
151
+ ? ` or session_original(turn=${turn}, toolCallId=${JSON.stringify(callId)})`
152
+ : '';
153
+ return `[D2] tool output${name} trimmed: ${chars} chars → ${inlineChars} inline. ` +
154
+ `Full output (${bytes} bytes) saved at ${file} — read it back with read(path)${turnHint}.`;
155
+ }
156
+
157
+ /** The placeholder left when the privacy gate refuses to archive. */
158
+ export function formatD2PrivacyNotice({ chars, toolName, reasons }) {
159
+ const name = toolName ? ` from ${toolName}` : '';
160
+ const why = Array.isArray(reasons) && reasons.length > 0 ? ` (${reasons.join(', ')})` : '';
161
+ return `[D2] tool output${name} withheld: ${chars} chars matched the privacy gate${why}. ` +
162
+ 'Nothing was written to disk and the text is not shown here.';
163
+ }
164
+
165
+ function warn(logger, message, error) {
166
+ try {
167
+ if (typeof logger?.warn === 'function') logger.warn(`${message}: ${error?.message ?? error}`);
168
+ else if (typeof logger === 'function') logger(`${message}: ${error?.message ?? error}`);
169
+ } catch {
170
+ /* logging a failure must not create one */
171
+ }
172
+ }
173
+
174
+ /**
175
+ * The turn a tool call belongs to.
176
+ *
177
+ * `exec` carries no turn (0.2.2 `createExecution`), so ask the `agents`
178
+ * service's turnBoundary projection (O(1)); if that service or its projection
179
+ * is unavailable, scan the session log backwards for the latest `turn/start`.
180
+ * Returning null is safe: the caller keeps the original content.
181
+ */
182
+ export function currentTurnOf(ctx, exec) {
183
+ const session = exec?.agent?.session;
184
+ if (!session) return null;
185
+ try {
186
+ const agents = typeof ctx?.get === 'function' ? ctx.get('agents') : null;
187
+ const boundary = agents?.turnBoundaryOf?.(session);
188
+ if (Number.isInteger(boundary?.lastTurn) && boundary.lastTurn >= 1) return boundary.lastTurn;
189
+ } catch {
190
+ /* projection unavailable — fall through to the log scan */
191
+ }
192
+ try {
193
+ const length = Number(session.seq);
194
+ for (let seq = (Number.isInteger(length) ? length : 0) - 1; seq >= 0; seq -= 1) {
195
+ const event = session.eventAt(seq);
196
+ if (event?.type === 'turn/start' && Number.isInteger(event?.data?.turn)) return event.data.turn;
197
+ }
198
+ } catch {
199
+ /* unreadable log — no turn */
200
+ }
201
+ return null;
202
+ }
203
+
204
+ /** Merge every text part into one string and replace them with `text`. */
205
+ export function replaceTextParts(content, text) {
206
+ const parts = Array.isArray(content) ? content : [];
207
+ const out = [];
208
+ let placed = false;
209
+ for (const part of parts) {
210
+ if (part && part.type === 'text' && typeof part.text === 'string') {
211
+ if (!placed) {
212
+ out.push({ ...part, text });
213
+ placed = true;
214
+ }
215
+ continue;
216
+ }
217
+ if (part) out.push(part);
218
+ }
219
+ if (!placed) out.unshift({ type: 'text', text });
220
+ return out;
221
+ }
222
+
223
+ /** Atomic archive write: tmp file next to the target, then rename. */
224
+ function writeArchiveAtomic(dir, file, text) {
225
+ fs.mkdirSync(dir, { recursive: true });
226
+ const tmp = `${file}.tmp-${process.pid}-${Date.now().toString(36)}`;
227
+ try {
228
+ fs.writeFileSync(tmp, text, 'utf8');
229
+ fs.renameSync(tmp, file);
230
+ } catch (error) {
231
+ try {
232
+ fs.unlinkSync(tmp);
233
+ } catch {
234
+ /* the tmp file may not exist yet */
235
+ }
236
+ throw error;
237
+ }
238
+ }
239
+
240
+ /** Atomic sidecar metadata write (never throws: metadata loss must not fail the archive). */
241
+ function writeArchiveMetaAtomic(dir, file, meta) {
242
+ const target = `${file}.meta.json`;
243
+ const tmp = `${target}.tmp-${process.pid}-${Date.now().toString(36)}`;
244
+ try {
245
+ fs.mkdirSync(dir, { recursive: true });
246
+ fs.writeFileSync(tmp, `${JSON.stringify(meta, null, 2)}\n`, 'utf8');
247
+ fs.renameSync(tmp, target);
248
+ return { ok: true, file: target };
249
+ } catch (error) {
250
+ try { fs.unlinkSync(tmp); } catch { /* best effort */ }
251
+ return { ok: false, file: target, error: String(error?.message ?? error) };
252
+ }
253
+ }
254
+
255
+ /**
256
+ * The whole decision, one call. Pure over its inputs except the injected
257
+ * `scan` / `writeArchive` / `now`, which is what makes the five acceptance
258
+ * cases testable with a fake host.
259
+ *
260
+ * Returns `{action, decision}` where `decision` is always a valid
261
+ * `tools/post-execute` accept decision. `action` is one of
262
+ * `off | keep | small | trimmed | privacy | error`.
263
+ */
264
+ export function decideToolOutputTrim({
265
+ exec,
266
+ result,
267
+ decision,
268
+ settings,
269
+ memoryRoot,
270
+ turn,
271
+ scan = privacyScan,
272
+ writeArchive = writeArchiveAtomic,
273
+ writeMeta = writeArchiveMetaAtomic,
274
+ nextIndex = () => 0,
275
+ now = () => new Date(),
276
+ }) {
277
+ if (!settings?.enabled) return { action: 'off', decision };
278
+ if (!decision || decision.kind !== 'accept') return { action: 'keep', decision };
279
+ // Another policy already replaced the value (e.g. a structured tool result):
280
+ // D2 only ever rewrites text content.
281
+ if (Object.hasOwn(decision, 'value')) return { action: 'keep', decision };
282
+ if (exec?.parent) return { action: 'keep', decision };
283
+ const toolName = typeof exec?.name === 'string' ? exec.name : '';
284
+ if (settings.skipTools.includes(toolName)) return { action: 'keep', decision };
285
+ if (settings.trimErrors !== true && result?.isError === true) return { action: 'keep', decision };
286
+
287
+ const content = result?.content;
288
+ if (!Array.isArray(content)) return { action: 'keep', decision };
289
+ const { text } = textOfParts(content);
290
+ if (text === '') return { action: 'keep', decision };
291
+ if (text.length <= settings.maxInlineChars) return { action: 'small', decision };
292
+
293
+ const callId = typeof exec?.callId === 'string' && exec.callId !== ''
294
+ ? exec.callId
295
+ : (typeof exec?.rootCallId === 'string' ? exec.rootCallId : '');
296
+ const chars = text.length;
297
+ const bytes = Buffer.byteLength(text, 'utf8');
298
+
299
+ // Privacy gate first: a match must not write anything, not even a tmp file.
300
+ const verdict = scan(text);
301
+ if (verdict && verdict.verdict !== 'none') {
302
+ const placeholder = formatD2PrivacyNotice({ chars, toolName, reasons: verdict.reasons });
303
+ return {
304
+ action: 'privacy',
305
+ decision: { ...decision, content: replaceTextParts(content, placeholder) },
306
+ };
307
+ }
308
+
309
+ if (!Number.isInteger(turn) || turn < 1 || !memoryRoot) return { action: 'keep', decision };
310
+
311
+ const seq = nextIndex();
312
+ const dir = toolOutputDir(memoryRoot, turn);
313
+ const file = path.join(dir, archiveFileName({ kind: 'tool', toolCallId: callId || null, seq }));
314
+
315
+ // S1: 凭据类 scrub 先于落盘;原文 sha256 / 长度 / 命中类型写进 sidecar
316
+ // `<archive>.meta.json`,TTL 元数据留给 S5 retention 使用(本层不删除)。
317
+ const retentionDays = Number.isInteger(settings.retentionDays) && settings.retentionDays > 0
318
+ ? settings.retentionDays
319
+ : TOOL_OUTPUT_DEFAULTS.retentionDays;
320
+ const scrubbed = scrubText(text, { enabled: settings.redact !== false });
321
+ writeArchive(dir, file, scrubbed.text);
322
+ const at = (() => {
323
+ try {
324
+ const value = typeof now === 'function' ? now() : now;
325
+ const date = value instanceof Date ? value : new Date(value);
326
+ return Number.isNaN(date.getTime()) ? new Date().toISOString() : date.toISOString();
327
+ } catch {
328
+ return new Date().toISOString();
329
+ }
330
+ })();
331
+ const meta = {
332
+ ...redactionMetadata(scrubbed, { retentionDays, at }),
333
+ schema: TOOL_OUTPUT_META_SCHEMA,
334
+ turn,
335
+ callId: callId || null,
336
+ toolName: toolName || null,
337
+ originalBytes: bytes,
338
+ at,
339
+ };
340
+ const metaWritten = (() => {
341
+ try {
342
+ return writeMeta(dir, file, meta);
343
+ } catch (error) {
344
+ return { ok: false, error: String(error?.message ?? error) };
345
+ }
346
+ })();
347
+
348
+ const { head, tail, headChars, tailChars, omittedChars } = splitHeadTail(
349
+ scrubbed.text,
350
+ settings.maxInlineChars,
351
+ settings.headRatio,
352
+ );
353
+ const notice = formatD2Notice({
354
+ chars,
355
+ inlineChars: headChars + tailChars,
356
+ bytes,
357
+ file,
358
+ turn,
359
+ callId,
360
+ toolName,
361
+ });
362
+ const inline = [head, notice, tail].filter((part) => part !== '').join('\n\n');
363
+ return {
364
+ action: 'trimmed',
365
+ info: {
366
+ chars, bytes, file, turn, headChars, tailChars, omittedChars, inlineChars: inline.length,
367
+ redacted: scrubbed.changed,
368
+ redactionHits: scrubbed.hits,
369
+ originalSha256: scrubbed.originalSha256,
370
+ retentionDays,
371
+ metaFile: `${file}.meta.json`,
372
+ metaWritten: metaWritten?.ok === true,
373
+ },
374
+ decision: { ...decision, content: replaceTextParts(content, inline) },
375
+ };
376
+ }
377
+
378
+ /**
379
+ * Build the `tools/post-execute` listener. The listener is fail-open by
380
+ * construction: `next()` is always honoured, and every internal failure
381
+ * returns whatever the next policy decided.
382
+ */
383
+ export function createTrimHandler({
384
+ settings,
385
+ memoryRoot,
386
+ logger = null,
387
+ currentTurn = (exec) => currentTurnOf(null, exec),
388
+ nextIndex = () => 0,
389
+ scan = privacyScan,
390
+ writeArchive = writeArchiveAtomic,
391
+ writeMeta = writeArchiveMetaAtomic,
392
+ now = () => new Date(),
393
+ onTrimmed = null,
394
+ } = {}) {
395
+ return async function trimToolResult(exec, result, next) {
396
+ let decision;
397
+ try {
398
+ decision = await next();
399
+ } catch (error) {
400
+ warn(logger, 'tool-output trim: next() failed', error);
401
+ throw error;
402
+ }
403
+ try {
404
+ const outcome = decideToolOutputTrim({
405
+ exec,
406
+ result,
407
+ decision,
408
+ settings,
409
+ memoryRoot,
410
+ turn: currentTurn(exec),
411
+ scan,
412
+ writeArchive,
413
+ writeMeta,
414
+ now,
415
+ nextIndex,
416
+ });
417
+ if (outcome.action === 'trimmed' && typeof onTrimmed === 'function') {
418
+ try {
419
+ onTrimmed(outcome.info);
420
+ } catch {
421
+ /* an observer must not break the hook */
422
+ }
423
+ }
424
+ return outcome.decision;
425
+ } catch (error) {
426
+ warn(logger, 'tool-output trim failed; keeping the inline output', error);
427
+ return decision;
428
+ }
429
+ };
430
+ }
431
+
432
+ /**
433
+ * Mount D2 on a Cordis-like context. Returns a small status object; the
434
+ * listener is disposed with the plugin scope when the context supports
435
+ * `ctx.effect`.
436
+ */
437
+ export function registerToolOutputTrim(ctx, config, { memoryRoot = null, logger = null } = {}) {
438
+ const toolCfg = normalizeToolOutputConfig(config?.toolOutput);
439
+ const settings = {
440
+ ...normalizeD2Config(config?.d2),
441
+ redact: toolCfg.redact,
442
+ retentionDays: toolCfg.retentionDays,
443
+ };
444
+ if (!settings.enabled) return { enabled: false, registered: false, settings };
445
+ if (!memoryRoot) {
446
+ warn(logger ?? ctx?.logger, 'tool-output trim enabled but memoryRoot is unset — not registered');
447
+ return { enabled: true, registered: false, settings, reason: 'E_MEMORY_ROOT_UNSET' };
448
+ }
449
+ if (typeof ctx?.on !== 'function') {
450
+ return { enabled: true, registered: false, settings, reason: 'E_NO_HOOK_SEAM' };
451
+ }
452
+
453
+ let counter = 0;
454
+ const handler = createTrimHandler({
455
+ settings,
456
+ memoryRoot,
457
+ logger: logger ?? ctx?.logger,
458
+ currentTurn: (exec) => currentTurnOf(ctx, exec),
459
+ nextIndex: () => (counter += 1),
460
+ });
461
+
462
+ let dispose = null;
463
+ try {
464
+ dispose = ctx.on('tools/post-execute', handler);
465
+ } catch (error) {
466
+ warn(logger ?? ctx?.logger, 'tool-output trim could not listen on tools/post-execute', error);
467
+ return { enabled: true, registered: false, settings, reason: 'E_HOOK_FAILED' };
468
+ }
469
+ if (typeof dispose === 'function' && typeof ctx?.effect === 'function') {
470
+ try {
471
+ ctx.effect(() => () => dispose(), 'longlive.tool-output');
472
+ } catch {
473
+ /* fake context without an effect scope: listener lives with the plugin */
474
+ }
475
+ }
476
+ try {
477
+ ctx?.logger?.info?.(
478
+ `longlive D2: tool output trim on — >${settings.maxInlineChars} chars archived to ` +
479
+ `${toolOutputRoot(memoryRoot)} (head ${Math.round(settings.headRatio * 100)}%)`,
480
+ );
481
+ } catch {
482
+ /* logging must not fail activation */
483
+ }
484
+ return { enabled: true, registered: true, settings, dispose, archiveRoot: toolOutputRoot(memoryRoot) };
485
+ }