@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,294 @@
1
+ // D3 — fetch the original text of one turn from a session log.
2
+ //
3
+ // This module is pure over parsed session events: it attributes events to
4
+ // turns, turns them into addressable items, selects the requested item, joins
5
+ // the selection and slices it on UTF-8 boundaries. Reading the log, resolving
6
+ // the session path, the privacy gate and the memory root stay in tools.js.
7
+ //
8
+ // Item kinds:
9
+ // message user/message and assistant/message (text parts only; reasoning is
10
+ // deliberately never returned)
11
+ // tool tool/result text parts (tool output)
12
+ // call tool/call arguments (opt-in; arguments may be sensitive)
13
+ //
14
+ // The per-turn indexes are stable and 0-based:
15
+ // messageIndex counts user + assistant messages in seq order
16
+ // toolIndex counts tool results in seq order
17
+ // callIndex counts tool calls in seq order
18
+ //
19
+ // system/message and developer/message are not exposed at all: D3 is about
20
+ // conversation and tool output, and the system prompt has no business being
21
+ // fetched through a session reader.
22
+
23
+ const MESSAGE_TYPES = new Set(['user/message', 'assistant/message']);
24
+
25
+ export const ORIGINAL_KINDS = Object.freeze(['tool', 'message', 'call', 'all']);
26
+
27
+ function asArray(value) {
28
+ return Array.isArray(value) ? value : [];
29
+ }
30
+
31
+ /** Join the text parts of a content array; non-text parts are counted, not copied. */
32
+ export function textOfParts(content) {
33
+ const texts = [];
34
+ let nonTextParts = 0;
35
+ for (const part of asArray(content)) {
36
+ if (part && part.type === 'text' && typeof part.text === 'string') {
37
+ texts.push(part.text);
38
+ } else if (part) {
39
+ nonTextParts += 1;
40
+ }
41
+ }
42
+ return { text: texts.join('\n'), nonTextParts };
43
+ }
44
+
45
+ function itemBase(event, data) {
46
+ return {
47
+ seq: event?.seq,
48
+ time: event?.time ?? null,
49
+ step: Number.isInteger(data?.step) ? data.step : null,
50
+ };
51
+ }
52
+
53
+ function messageItem(event, role) {
54
+ const data = event?.data ?? {};
55
+ const content = data.message?.content ?? data.content;
56
+ const { text, nonTextParts } = textOfParts(content);
57
+ return {
58
+ ...itemBase(event, data),
59
+ kind: 'message',
60
+ role,
61
+ text,
62
+ nonTextParts,
63
+ toolCallId: null,
64
+ toolName: null,
65
+ isError: false,
66
+ messageIndex: null,
67
+ toolIndex: null,
68
+ callIndex: null,
69
+ };
70
+ }
71
+
72
+ function callItem(event) {
73
+ const data = event?.data ?? {};
74
+ const args = typeof data.arguments === 'string'
75
+ ? data.arguments
76
+ : (data.arguments == null ? '' : JSON.stringify(data.arguments));
77
+ return {
78
+ ...itemBase(event, data),
79
+ kind: 'call',
80
+ role: 'tool',
81
+ text: args,
82
+ nonTextParts: 0,
83
+ toolCallId: typeof data.callId === 'string' ? data.callId : null,
84
+ toolName: typeof data.name === 'string' ? data.name : null,
85
+ isError: false,
86
+ messageIndex: null,
87
+ toolIndex: null,
88
+ callIndex: null,
89
+ };
90
+ }
91
+
92
+ function resultItem(event) {
93
+ const data = event?.data ?? {};
94
+ const message = data.message ?? {};
95
+ const { text, nonTextParts } = textOfParts(message.content ?? data.content);
96
+ return {
97
+ ...itemBase(event, data),
98
+ kind: 'tool',
99
+ role: 'tool',
100
+ text,
101
+ nonTextParts,
102
+ toolCallId: typeof message.toolCallId === 'string'
103
+ ? message.toolCallId
104
+ : (typeof data.toolCallId === 'string' ? data.toolCallId : null),
105
+ toolName: typeof data.name === 'string' ? data.name : null,
106
+ isError: message.isError === true,
107
+ messageIndex: null,
108
+ toolIndex: null,
109
+ callIndex: null,
110
+ };
111
+ }
112
+
113
+ /**
114
+ * Group the four addressable event types by turn.
115
+ *
116
+ * A user/message usually has no `data.turn` (the live host omits it); it is
117
+ * attributed to the most recent turn/start. A log whose visible prefix was
118
+ * truncated can begin with a user message before its turn/start: such items
119
+ * wait in `pending` and join the first turn that becomes known.
120
+ *
121
+ * Returns Map<turn, item[]> with items sorted by seq and indexes assigned.
122
+ */
123
+ export function buildTurnItems(events) {
124
+ const turns = new Map();
125
+ const pending = [];
126
+ let current = null;
127
+
128
+ const add = (turn, item) => {
129
+ if (!turns.has(turn)) turns.set(turn, []);
130
+ turns.get(turn).push(item);
131
+ };
132
+ const flushPending = (turn) => {
133
+ while (pending.length > 0) add(turn, pending.shift());
134
+ };
135
+
136
+ for (const event of asArray(events)) {
137
+ const type = event?.type;
138
+ const data = event?.data ?? {};
139
+ if (type === 'turn/start') {
140
+ if (Number.isInteger(data.turn)) {
141
+ current = data.turn;
142
+ flushPending(current);
143
+ }
144
+ continue;
145
+ }
146
+ let item = null;
147
+ if (type === 'user/message') item = messageItem(event, 'user');
148
+ else if (type === 'assistant/message') item = messageItem(event, 'assistant');
149
+ else if (type === 'tool/call') item = callItem(event);
150
+ else if (type === 'tool/result') item = resultItem(event);
151
+ if (!item) continue;
152
+
153
+ const turn = Number.isInteger(data.turn) ? data.turn : current;
154
+ if (turn == null) pending.push(item);
155
+ else add(turn, item);
156
+ }
157
+
158
+ for (const [turn, items] of turns) {
159
+ items.sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
160
+ let messageIndex = 0;
161
+ let toolIndex = 0;
162
+ let callIndex = 0;
163
+ for (const item of items) {
164
+ item.turn = turn;
165
+ item.index = items.indexOf(item);
166
+ if (item.kind === 'message') item.messageIndex = messageIndex++;
167
+ else if (item.kind === 'tool') item.toolIndex = toolIndex++;
168
+ else if (item.kind === 'call') item.callIndex = callIndex++;
169
+ }
170
+ // A result usually has no tool name of its own; borrow the matching call.
171
+ const names = new Map();
172
+ for (const item of items) {
173
+ if (item.kind === 'call' && item.toolCallId && item.toolName) names.set(item.toolCallId, item.toolName);
174
+ }
175
+ for (const item of items) {
176
+ if (item.kind === 'tool' && !item.toolName && item.toolCallId) {
177
+ item.toolName = names.get(item.toolCallId) ?? null;
178
+ }
179
+ }
180
+ }
181
+ return turns;
182
+ }
183
+
184
+ /** Sorted turn numbers present in a buildTurnItems() map. */
185
+ export function availableTurns(turns) {
186
+ return [...turns.keys()].sort((a, b) => a - b);
187
+ }
188
+
189
+ /**
190
+ * Select items of one turn. Explicit selectors win over `kind`:
191
+ * messageIndex -> the one message with that index
192
+ * toolCallId -> the tool result(s) and/or call with that call id
193
+ * A miss is returned as a coded error, never an empty list that hides a typo.
194
+ */
195
+ export function selectTurnItems(items, { kind = 'tool', toolCallId = null, messageIndex = null } = {}) {
196
+ const list = asArray(items);
197
+ if (messageIndex != null) {
198
+ const hits = list.filter((item) => item.kind === 'message' && item.messageIndex === messageIndex);
199
+ if (hits.length === 0) {
200
+ return {
201
+ error: {
202
+ code: 'MESSAGE_INDEX_OUT_OF_RANGE',
203
+ message: `messageIndex ${messageIndex} does not exist in this turn ` +
204
+ `(the turn has ${list.filter((item) => item.kind === 'message').length} message(s))`,
205
+ },
206
+ };
207
+ }
208
+ return { items: hits };
209
+ }
210
+ if (toolCallId) {
211
+ const hits = list.filter((item) => {
212
+ if (item.toolCallId !== toolCallId) return false;
213
+ if (kind === 'all') return item.kind === 'tool' || item.kind === 'call';
214
+ if (kind === 'tool') return item.kind === 'tool';
215
+ if (kind === 'call') return item.kind === 'call';
216
+ return false;
217
+ });
218
+ if (hits.length === 0) {
219
+ return {
220
+ error: {
221
+ code: 'TOOL_CALL_NOT_FOUND',
222
+ message: `no ${kind === 'all' ? 'tool call/result' : kind} with toolCallId ${JSON.stringify(toolCallId)} in this turn`,
223
+ },
224
+ };
225
+ }
226
+ return { items: hits };
227
+ }
228
+ if (kind === 'all') return { items: list };
229
+ return { items: list.filter((item) => item.kind === kind) };
230
+ }
231
+
232
+ /**
233
+ * The logical text of a selection. One item is returned verbatim; several are
234
+ * separated by stable markers so paging offsets are reproducible across calls.
235
+ */
236
+ export function joinTurnItems(items) {
237
+ const list = asArray(items);
238
+ if (list.length === 0) return '';
239
+ if (list.length === 1) return list[0].text;
240
+ return list.map((item) => {
241
+ const id = item.kind === 'message'
242
+ ? `#${item.messageIndex}`
243
+ : (item.toolCallId ? ` ${item.toolCallId}` : ` #${item.index}`);
244
+ return `===== [${item.kind}${id} seq=${item.seq}] =====\n${item.text}`;
245
+ }).join('\n\n');
246
+ }
247
+
248
+ /**
249
+ * Slice a string by UTF-8 bytes without splitting a code point.
250
+ *
251
+ * `offset` is a byte offset. If it lands inside a multi-byte character it is
252
+ * moved back to that character's first byte, so the returned `offset` is the
253
+ * one actually used. `nextOffset` is `end` while more bytes remain.
254
+ */
255
+ export function sliceUtf8(text, offset = 0, maxBytes = 65536) {
256
+ const buf = Buffer.from(String(text ?? ''), 'utf8');
257
+ const totalBytes = buf.length;
258
+ let start = Math.min(Math.max(0, Number.isInteger(offset) ? offset : 0), totalBytes);
259
+ while (start > 0 && start < totalBytes && (buf[start] & 0xc0) === 0x80) start -= 1;
260
+
261
+ let end = Math.min(start + Math.max(1, maxBytes), totalBytes);
262
+ while (end > start && end < totalBytes && (buf[end] & 0xc0) === 0x80) end -= 1;
263
+
264
+ return {
265
+ content: buf.subarray(start, end).toString('utf8'),
266
+ offset: start,
267
+ end,
268
+ totalBytes,
269
+ returnedBytes: end - start,
270
+ nextOffset: end < totalBytes ? end : null,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * D2 archive filename for one selected item. The convention is
276
+ * `<memoryRoot>/.longlive/tool-output/<turn>/<id>.txt`.
277
+ *
278
+ * A tool result uses its toolCallId (D2's natural id); a message uses
279
+ * `msg-<messageIndex>`; a tool call uses `call-<callId>` so it cannot collide
280
+ * with the result of the same call.
281
+ */
282
+ export function archiveFileName(item) {
283
+ let raw;
284
+ if (item.kind === 'tool') raw = item.toolCallId || `result-${item.seq}`;
285
+ else if (item.kind === 'call') raw = item.toolCallId ? `call-${item.toolCallId}` : `call-${item.seq}`;
286
+ else raw = `msg-${item.messageIndex ?? item.seq}`;
287
+ const safe = String(raw)
288
+ .replace(/[^A-Za-z0-9._-]+/g, '_')
289
+ .replace(/^\.+/, '')
290
+ .slice(0, 96);
291
+ return `${safe || `item-${item.seq}`}.txt`;
292
+ }
293
+
294
+ export { MESSAGE_TYPES };
@@ -0,0 +1,224 @@
1
+ // 1.8.3 threshold policy — fixed numbers from THRESHOLD-FINAL-1.8.3.
2
+ //
3
+ // IMPORTANT: these are POLICY budgets, not API-enforced limits. The host does
4
+ // not expose the main model's max_tokens; only router face has a separate 1024
5
+ // cap. Therefore output reserves / hard limits below are used for planning,
6
+ // warning and segmentation; the only enforceable knobs are the existing
7
+ // autoTruncate.tokensThreshold and hotTruncate.autoMinTokens config keys.
8
+ //
9
+ // Evidence labels:
10
+ // official: DeepSeek API docs, fetched 2026-11-09 (1M shared context window;
11
+ // max_tokens 1..393216; finish_reason=length on overflow)
12
+ // measured: local 1,443-turn sample (output P99 91,431 / max 179,567)
13
+ // estimate: safety reserve / tokenizer + system-prompt headroom
14
+ // unverified: whether max_tokens includes reasoning tokens (we assume yes);
15
+ // exact input-overflow error shape.
16
+
17
+ export const CONTEXT_WINDOW_TOKENS = 1_000_000;
18
+ export const MAX_OUTPUT_TOKENS = 393_216;
19
+ export const SAFETY_TOKENS = 50_000;
20
+ export const OUTPUT_HARD_LIMIT_TOKENS = 350_000;
21
+ export const OUTPUT_RESERVE_NORMAL_TOKENS = 192_000;
22
+ export const OUTPUT_RESERVE_LONG_TOKENS = 350_000;
23
+ export const INPUT_COMPACT_AT_TOKENS = 350_000;
24
+ // 1.8.10: auto-truncate is about the *session log file*, not the model-context
25
+ // line above. 12M tokens ≈ 60MB of session log at the empirical ~5 B/token
26
+ // (2026-11-26 c045: 1,846,218 B ↔ 360,026 tokens). Keep the two metrics apart:
27
+ // the old default inherited INPUT_COMPACT_AT_TOKENS (350k) and cut a 1.8MB log
28
+ // every hour under heavy tool use.
29
+ export const AUTO_TRUNCATE_LOG_TOKENS = 12_000_000;
30
+ export const INPUT_HARD_LIMIT_NORMAL_TOKENS = 757_000; // trigger >=; 1M - 192K - 50K - 1K safety
31
+ export const INPUT_HARD_LIMIT_LONG_TOKENS = 599_000; // trigger >=; 1M - 350K - 50K - 1K safety
32
+
33
+ // Fold (host compaction; semantic summary) and truncate (direct cut; no summary)
34
+ // are distinct concepts. Keep the names separated at every layer.
35
+ export const FOLD_TRIGGER_TOKENS = INPUT_COMPACT_AT_TOKENS;
36
+ // Not implemented in 1.8.3: the compaction backend has no targetTokens option.
37
+ // Measured post-fold median is 52K; 84K is the v0.6 cost-neutral target and
38
+ // must not be claimed as achieved until targetTokens exists and is tested.
39
+ export const FOLD_MEASURED_MEDIAN_TOKENS = 52_000;
40
+ export const FOLD_TARGET_TOKENS = 84_000;
41
+ export const FOLD_TARGET_MIN_TOKENS = 52_000;
42
+ export const FOLD_TARGET_MAX_TOKENS = 84_000;
43
+ export const TRUNCATE_INPUT_HARD_CAP_NORMAL_TOKENS = INPUT_HARD_LIMIT_NORMAL_TOKENS;
44
+ export const TRUNCATE_INPUT_HARD_CAP_LONG_TOKENS = INPUT_HARD_LIMIT_LONG_TOKENS;
45
+ export const TRUNCATE_OUTPUT_MAX_TOKENS = OUTPUT_HARD_LIMIT_TOKENS;
46
+ export const TRUNCATE_SAFETY_TOKENS = SAFETY_TOKENS;
47
+ export const TRUNCATE_RESERVE_NORMAL_TOKENS = OUTPUT_RESERVE_NORMAL_TOKENS;
48
+ export const TRUNCATE_RESERVE_LONG_TOKENS = OUTPUT_RESERVE_LONG_TOKENS;
49
+
50
+ export const FOLD_DEFAULTS = Object.freeze({ triggerTokens: FOLD_TRIGGER_TOKENS });
51
+ export const TRUNCATE_DEFAULTS = Object.freeze({
52
+ inputHardCapNormal: TRUNCATE_INPUT_HARD_CAP_NORMAL_TOKENS,
53
+ inputHardCapLongOutput: TRUNCATE_INPUT_HARD_CAP_LONG_TOKENS,
54
+ outputMaxTokens: TRUNCATE_OUTPUT_MAX_TOKENS,
55
+ safetyTokens: TRUNCATE_SAFETY_TOKENS,
56
+ reserveNormal: TRUNCATE_RESERVE_NORMAL_TOKENS,
57
+ reserveLongOutput: TRUNCATE_RESERVE_LONG_TOKENS,
58
+ });
59
+
60
+ export function evaluateFoldTrigger({ inputTokens, triggerTokens = FOLD_TRIGGER_TOKENS } = {}) {
61
+ const input = finiteNonNegative(inputTokens, 'inputTokens');
62
+ return { triggered: input >= triggerTokens, inputTokens: input, triggerTokens };
63
+ }
64
+
65
+ export const THRESHOLD_DEFAULTS = Object.freeze({
66
+ contextWindowTokens: CONTEXT_WINDOW_TOKENS,
67
+ maxOutputTokens: MAX_OUTPUT_TOKENS,
68
+ safetyTokens: SAFETY_TOKENS,
69
+ outputHardLimitTokens: OUTPUT_HARD_LIMIT_TOKENS,
70
+ outputReserveNormalTokens: OUTPUT_RESERVE_NORMAL_TOKENS,
71
+ outputReserveLongTokens: OUTPUT_RESERVE_LONG_TOKENS,
72
+ inputCompactAtTokens: INPUT_COMPACT_AT_TOKENS,
73
+ inputHardLimitNormalTokens: INPUT_HARD_LIMIT_NORMAL_TOKENS,
74
+ inputHardLimitLongTokens: INPUT_HARD_LIMIT_LONG_TOKENS,
75
+ });
76
+
77
+ export const THRESHOLD_EVIDENCE = Object.freeze({
78
+ contextWindowTokens: 'official',
79
+ maxOutputTokens: 'official',
80
+ safetyTokens: 'estimate',
81
+ outputHardLimitTokens: 'user-decision+official',
82
+ outputReserveNormalTokens: 'measured',
83
+ outputReserveLongTokens: 'user-decision',
84
+ inputCompactAtTokens: 'measured+user-decision',
85
+ inputHardLimitNormalTokens: 'formula',
86
+ inputHardLimitLongTokens: 'formula',
87
+ reasoningTokensIncluded: 'unverified-assumed-yes',
88
+ hostMaxTokensEnforceable: false,
89
+ });
90
+
91
+ export const THRESHOLD_POLICY_WARNING = [
92
+ 'threshold policy: main-model max_tokens is not exposed by the host;',
93
+ '350K/192K are planning reserves and segmentation triggers, not enforced API limits;',
94
+ 'fallback = fixed 350K reserve + 600K input hard cap when dynamic mode cannot be observed.',
95
+ ].join(' ');
96
+
97
+ export function outputReserveTokens({ longOutput = false } = {}) {
98
+ return longOutput ? OUTPUT_RESERVE_LONG_TOKENS : OUTPUT_RESERVE_NORMAL_TOKENS;
99
+ }
100
+
101
+ export function inputHardLimitTokens({ longOutput = false } = {}) {
102
+ return longOutput ? INPUT_HARD_LIMIT_LONG_TOKENS : INPUT_HARD_LIMIT_NORMAL_TOKENS;
103
+ }
104
+
105
+ export const FOLD_RETRY_MIN_TURNS = 3;
106
+ export const FOLD_RETRY_MIN_MS = 30 * 60 * 1000; // 30min
107
+ export const FOLD_FAILURE_REASONS = Object.freeze(['failed', 'busy', 'no-backend', 'unavailable']);
108
+ export function classifyFoldFailure(reason) {
109
+ const normalized = typeof reason === 'string' ? reason : 'failed';
110
+ const known = FOLD_FAILURE_REASONS.includes(normalized) ? normalized : 'failed';
111
+ return {
112
+ foldFailed: true, reason: known, retryNextTurn: true, retryLimit: 1,
113
+ retryMinTurns: FOLD_RETRY_MIN_TURNS, retryMinMs: FOLD_RETRY_MIN_MS,
114
+ backoffMs: FOLD_RETRY_MIN_MS, silent: false,
115
+ };
116
+ }
117
+
118
+ export function foldRetrySchedule({ turn = 0, now = Date.now() } = {}) {
119
+ return { retryTurn: Number(turn) + FOLD_RETRY_MIN_TURNS, retryAt: Number(now) + FOLD_RETRY_MIN_MS };
120
+ }
121
+
122
+ export function thresholdEnforceability() {
123
+ return Object.freeze({
124
+ enforced: false,
125
+ hostMaxTokensConfigurable: false,
126
+ reason: 'host main-model max_tokens is not exposed; only router-face 1024 is configurable',
127
+ fallback: Object.freeze({
128
+ outputReserveTokens: OUTPUT_RESERVE_LONG_TOKENS,
129
+ inputHardLimitTokens: INPUT_HARD_LIMIT_LONG_TOKENS,
130
+ }),
131
+ });
132
+ }
133
+
134
+ function finiteNonNegative(value, name) {
135
+ const number = Number(value);
136
+ if (!Number.isFinite(number) || number < 0) {
137
+ throw new TypeError(`${name} must be a finite non-negative number`);
138
+ }
139
+ return number;
140
+ }
141
+
142
+ /**
143
+ * Evaluate the shared-context budget. Pure; no I/O, no session read.
144
+ * Returns an action for the caller to implement elsewhere (compact/handoff).
145
+ */
146
+ export function evaluateThresholds({
147
+ inputTokens,
148
+ actualOutputTokens = null,
149
+ longOutput = null,
150
+ contextWindowTokens = CONTEXT_WINDOW_TOKENS,
151
+ safetyTokens = SAFETY_TOKENS,
152
+ } = {}) {
153
+ const input = finiteNonNegative(inputTokens, 'inputTokens');
154
+ const context = finiteNonNegative(contextWindowTokens, 'contextWindowTokens');
155
+ const safety = finiteNonNegative(safetyTokens, 'safetyTokens');
156
+ // At the 350K strategy line we cannot know the real output, so default to
157
+ // the long-output reserve; 192K is only used when normal output is explicit.
158
+ // Unknown output length defaults to the long-output reserve; 192K requires
159
+ // an explicit normal-output task marker.
160
+ const effectiveLong = longOutput === null ? true : longOutput === true;
161
+ const reserve = outputReserveTokens({ longOutput: effectiveLong });
162
+ const hardLimit = inputHardLimitTokens({ longOutput: effectiveLong });
163
+ const totalWithReserve = input + reserve + safety;
164
+
165
+ if (totalWithReserve >= context || input >= hardLimit) {
166
+ return {
167
+ action: 'handoff',
168
+ reason: totalWithReserve >= context ? 'input+reserve+safety>=context' : 'input>=inputHardLimit',
169
+ inputTokens: input, reserveTokens: reserve, safetyTokens: safety,
170
+ inputHardLimitTokens: hardLimit, outputReserveTokens: reserve,
171
+ reserveMode: effectiveLong ? 'long' : 'normal',
172
+ outputOverReserve: false,
173
+ };
174
+ }
175
+ let outputOverReserve = false;
176
+ if (actualOutputTokens !== null) {
177
+ const output = finiteNonNegative(actualOutputTokens, 'actualOutputTokens');
178
+ outputOverReserve = output >= reserve;
179
+ if (input + output + safety >= context) {
180
+ return {
181
+ action: 'handoff', reason: 'input+actualOutput+safety>=context',
182
+ inputTokens: input, actualOutputTokens: output, reserveTokens: reserve,
183
+ safetyTokens: safety, inputHardLimitTokens: hardLimit,
184
+ outputReserveTokens: reserve, outputOverReserve: true,
185
+ };
186
+ }
187
+ }
188
+ if (outputOverReserve) {
189
+ return {
190
+ action: 'switch-long-output-or-segment', reason: 'actualOutput>=reserve',
191
+ inputTokens: input, actualOutputTokens: Number(actualOutputTokens),
192
+ reserveTokens: reserve, safetyTokens: safety,
193
+ inputHardLimitTokens: hardLimit, outputReserveTokens: reserve,
194
+ reserveMode: effectiveLong ? 'long' : 'normal',
195
+ nextReserveMode: 'long',
196
+ outputOverReserve: true,
197
+ };
198
+ }
199
+ if (input >= INPUT_COMPACT_AT_TOKENS && input >= 0) {
200
+ return {
201
+ action: 'compact', reason: 'input>=inputCompactAt',
202
+ inputTokens: input, reserveTokens: reserve, safetyTokens: safety,
203
+ inputHardLimitTokens: hardLimit, outputReserveTokens: reserve,
204
+ reserveMode: effectiveLong ? 'long' : 'normal',
205
+ outputOverReserve: false,
206
+ };
207
+ }
208
+ return {
209
+ action: 'ok', reason: 'within-budget',
210
+ inputTokens: input, reserveTokens: reserve, safetyTokens: safety,
211
+ inputHardLimitTokens: hardLimit, outputReserveTokens: reserve,
212
+ reserveMode: effectiveLong ? 'long' : 'normal',
213
+ outputOverReserve: false,
214
+ };
215
+ }
216
+
217
+ /** Truncate-side view: direct cuts only; the 350K fold line is not a cut. */
218
+ export function evaluateTruncateBudget(options = {}) {
219
+ const result = evaluateThresholds(options);
220
+ if (result.action === 'compact') {
221
+ return { ...result, action: 'ok', reason: 'within-truncate-budget' };
222
+ }
223
+ return result;
224
+ }