@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,119 @@
1
+ // routerFace v1 · 后台面自己的 journal(JSONL)。
2
+ //
3
+ // 这是「最近 5 条 router 自己的 journal」的唯一来源:仓库里原先没有
4
+ // router 服务自写的 journal 文件,v1 就把它定义成 face 自己的连续记忆。
5
+ //
6
+ // 幂等:每条记录带 tickKey(face-<day>-<tick 序号>)。同一个 tick 重复
7
+ // 追加时只保留第一条,崩溃重放或定时器抖动都不会写重。
8
+ //
9
+ // 永不抛错:读失败返回 [],写失败返回 {ok:false},由调用方决定是否记失败。
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ export const JOURNAL_VERSION = 1;
15
+ export const JOURNAL_MAX_ROWS = 500;
16
+
17
+ function clean(value, maxChars = 0) {
18
+ let text = String(value ?? '')
19
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]+/g, ' ')
20
+ .replace(/\s+/g, ' ')
21
+ .trim();
22
+ if (maxChars > 0) {
23
+ const chars = Array.from(text);
24
+ if (chars.length > maxChars) text = `${chars.slice(0, Math.max(1, maxChars - 1)).join('')}…`;
25
+ }
26
+ return text;
27
+ }
28
+
29
+ function parseLines(text) {
30
+ const out = [];
31
+ for (const line of String(text ?? '').split(/\r?\n/u)) {
32
+ if (line.trim() === '') continue;
33
+ try {
34
+ const value = JSON.parse(line);
35
+ if (value && typeof value === 'object' && typeof value.tickKey === 'string') out.push(value);
36
+ } catch {
37
+ // 坏行跳过;journal 不是审计账本,容忍单行损坏。
38
+ }
39
+ }
40
+ return out;
41
+ }
42
+
43
+ function readAll(file) {
44
+ try {
45
+ return parseLines(fs.readFileSync(file, 'utf8'));
46
+ } catch {
47
+ return [];
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 读最近 N 条(文件顺序的尾部,不按时间排序)。
53
+ * @returns {Array<object>}
54
+ */
55
+ export function readJournal(file, options = {}) {
56
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 5;
57
+ if (!file) return [];
58
+ const rows = readAll(file);
59
+ return rows.slice(-limit);
60
+ }
61
+
62
+ /** 该 tickKey 是否已经写过(幂等判据)。 */
63
+ export function hasJournalTick(file, tickKey) {
64
+ if (!file || typeof tickKey !== 'string' || tickKey === '') return false;
65
+ return readAll(file).some((row) => row.tickKey === tickKey);
66
+ }
67
+
68
+ function trimInPlace(file, maxRows) {
69
+ try {
70
+ const rows = readAll(file);
71
+ if (rows.length <= maxRows) return;
72
+ const kept = rows.slice(-maxRows);
73
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
74
+ fs.writeFileSync(tmp, `${kept.map((row) => JSON.stringify(row)).join('\n')}\n`, 'utf8');
75
+ fs.renameSync(tmp, file);
76
+ } catch {
77
+ // 裁剪失败不影响主路径;下一次追加再试。
78
+ }
79
+ }
80
+
81
+ /**
82
+ * 追加一条 journal;同 tickKey 已存在时返回 {ok:true, appended:false, duplicate:true}。
83
+ *
84
+ * @param {string} file
85
+ * @param {object} entry 至少含 tickKey / at / text
86
+ * @param {{maxRows?:number}} [options]
87
+ */
88
+ export function appendJournalOnce(file, entry, options = {}) {
89
+ if (!file) return { ok: false, error: 'E_NO_JOURNAL_FILE' };
90
+ const tickKey = clean(entry?.tickKey, 120);
91
+ if (tickKey === '') return { ok: false, error: 'E_NO_TICK_KEY' };
92
+ try {
93
+ fs.mkdirSync(path.dirname(file), { recursive: true });
94
+ const rows = readAll(file);
95
+ if (rows.some((row) => row.tickKey === tickKey)) {
96
+ return { ok: true, appended: false, duplicate: true };
97
+ }
98
+ const record = {
99
+ v: JOURNAL_VERSION,
100
+ tickKey,
101
+ at: typeof entry.at === 'string' ? entry.at : new Date().toISOString(),
102
+ day: clean(entry.day, 20),
103
+ text: clean(entry.text, 1200),
104
+ kind: clean(entry.kind, 40) || 'tick',
105
+ ...(Array.isArray(entry.suggestions) ? { suggestions: entry.suggestions.slice(0, 10) } : {}),
106
+ ...(entry.usage && typeof entry.usage === 'object' ? { usage: entry.usage } : {}),
107
+ ...(entry.provider ? { provider: clean(entry.provider, 80) } : {}),
108
+ ...(entry.model ? { model: clean(entry.model, 120) } : {}),
109
+ ...(entry.dryRun === true ? { dryRun: true } : {}),
110
+ };
111
+ fs.appendFileSync(file, `${JSON.stringify(record)}\n`, 'utf8');
112
+ trimInPlace(file, Number.isInteger(options.maxRows) && options.maxRows > 0 ? options.maxRows : JOURNAL_MAX_ROWS);
113
+ return { ok: true, appended: true, record };
114
+ } catch (error) {
115
+ return { ok: false, error: error?.code ?? 'E_JOURNAL_WRITE', message: String(error?.message ?? error) };
116
+ }
117
+ }
118
+
119
+ export { clean };
@@ -0,0 +1,252 @@
1
+ // routerFace v1 · 调用宿主的 LLM。
2
+ //
3
+ // 宿主 API 假设(2026-11-05,依据本仓 src/router/service/service.mjs 的既有
4
+ // 用法,不是猜的):
5
+ // const llm = ctx.get('llm'); // 不能读 ctx.llm
6
+ // llm.stream({ messages, task, signal, maxTokens,
7
+ // provider, model, reasoningEffort? }) // 返回 AsyncIterable
8
+ // chunk 协议 block-start / text-delta / usage / finish,由
9
+ // src/router/background/stream.mjs 的 consumeStream 消费。
10
+ // provider/model 由 src/router/service/model-resolve.mjs 的
11
+ // resolveModelTarget 解析(显式配置 → 宿主当前选择 → 列表首个)。
12
+ //
13
+ // 没有 HTTP 兜底:宿主 llm 服务缺失时进入 waiting-provider(写 status,
14
+ // 不调用、不重试、不读凭据)。HTTP 直连会绕开宿主 provider 配置和审计,
15
+ // v1 明确不做。
16
+ //
17
+ // 测试注入:deps.client 支持
18
+ // - { complete: async ({messages,...}) => "文本" | { text } }
19
+ // - { stream: async function* ({messages,...}) { ... } } (走 consumeStream)
20
+ // - 直接一个 async 函数(等价于 complete)
21
+ // 注入 client 时完全不碰 ctx.get('llm')。
22
+
23
+ import { buildMessages, consumeStream } from '../background/stream.mjs';
24
+ import { resolveModelTarget } from '../service/model-resolve.mjs';
25
+ import { estimateTokens } from '../service/tokens.mjs';
26
+ import { FACE_TICK_TASK } from './config.mjs';
27
+
28
+ export const FACE_SYSTEM_PROMPT = [
29
+ '你是 longlive 的后台面(不是前台会话,也没有任何工具)。',
30
+ '你只能读下面给出的只读材料,写一条 journal 和最多 3 条建议。',
31
+ '硬约束:',
32
+ '1) 你没有工具、不能读文件、不能执行命令、不能修改任何记忆或状态、不能给前台派活;',
33
+ '2) 建议只会写进跨会话 outbox,前台自己决定要不要看,不要把它写成命令或承诺;',
34
+ '3) 不确定的事就说不确定,不要编数字,不要复述自己看不到的东西;',
35
+ '4) journal ≤400 字,建议每条 ≤200 字,最多 3 条;',
36
+ '5) 只输出一个 JSON 对象:{"journal":"...","suggestions":["..."]},不要输出 JSON 之外的文字。',
37
+ ].join('\n');
38
+
39
+ function oneLine(value) {
40
+ return String(value ?? '').replace(/\s+/g, ' ').trim();
41
+ }
42
+
43
+ /** 把组装好的上下文包成 user prompt。 */
44
+ export function buildFacePrompt(contextText, options = {}) {
45
+ const at = typeof options.at === 'string' ? options.at : new Date().toISOString();
46
+ return [
47
+ `现在:${at}`,
48
+ '',
49
+ contextText && String(contextText).trim() !== ''
50
+ ? String(contextText).trim()
51
+ : '(这个 tick 没有可读材料;请如实写一条 journal,不要编造状态。)',
52
+ '',
53
+ '请按要求输出 JSON:{"journal":"…","suggestions":["…"]}。',
54
+ ].join('\n');
55
+ }
56
+
57
+ /**
58
+ * 解析模型输出。模型不听话(输出纯文本、代码块、多个 JSON)时退回
59
+ * 「整段当 journal、没有建议」,而不是让 tick 失败。
60
+ */
61
+ export function parseFaceOutput(text, options = {}) {
62
+ const maxJournalChars = Number.isInteger(options.maxJournalChars) ? options.maxJournalChars : 400;
63
+ const maxSuggestions = Number.isInteger(options.maxSuggestions) ? options.maxSuggestions : 3;
64
+ const maxSuggestionChars = Number.isInteger(options.maxSuggestionChars) ? options.maxSuggestionChars : 200;
65
+ const raw = String(text ?? '').trim();
66
+ const cap = (value, max) => {
67
+ const chars = Array.from(oneLine(value));
68
+ return chars.length > max ? `${chars.slice(0, Math.max(1, max - 1)).join('')}…` : chars.join('');
69
+ };
70
+ if (raw === '') return { journal: '', suggestions: [], mode: 'empty' };
71
+
72
+ let parsed = null;
73
+ let mode = 'text';
74
+ const unfenced = raw.replace(/^```(?:json)?\s*/iu, '').replace(/\s*```$/u, '');
75
+ const candidates = [unfenced];
76
+ const first = unfenced.indexOf('{');
77
+ const last = unfenced.lastIndexOf('}');
78
+ if (first >= 0 && last > first) candidates.push(unfenced.slice(first, last + 1));
79
+ for (const candidate of candidates) {
80
+ try {
81
+ const value = JSON.parse(candidate);
82
+ if (value && typeof value === 'object') {
83
+ parsed = value;
84
+ mode = 'json';
85
+ break;
86
+ }
87
+ } catch {
88
+ // 继续尝试下一个候选。
89
+ }
90
+ }
91
+
92
+ if (!parsed) {
93
+ return { journal: cap(raw, maxJournalChars), suggestions: [], mode };
94
+ }
95
+ const journal = cap(parsed.journal ?? parsed.text ?? parsed.summary ?? '', maxJournalChars);
96
+ const suggestions = [];
97
+ const list = Array.isArray(parsed.suggestions) ? parsed.suggestions : [];
98
+ for (const item of list) {
99
+ const value = typeof item === 'string' ? item : item && typeof item.text === 'string' ? item.text : '';
100
+ const text = cap(value, maxSuggestionChars);
101
+ if (text !== '') suggestions.push(text);
102
+ if (suggestions.length >= maxSuggestions) break;
103
+ }
104
+ return { journal, suggestions, mode };
105
+ }
106
+
107
+ function readClient(ctx) {
108
+ try {
109
+ const llm = typeof ctx?.get === 'function' ? ctx.get('llm') : null;
110
+ return llm && typeof llm.stream === 'function' ? llm : null;
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
115
+
116
+ function normalizeUsage(usage, promptText, outputText) {
117
+ if (usage && typeof usage === 'object') {
118
+ const inputTokens = Number.isInteger(usage.inputTokens) ? usage.inputTokens : 0;
119
+ const outputTokens = Number.isInteger(usage.outputTokens) ? usage.outputTokens : 0;
120
+ if (inputTokens > 0 || outputTokens > 0) {
121
+ return {
122
+ inputTokens,
123
+ outputTokens,
124
+ cacheReadTokens: Number.isInteger(usage.cacheReadTokens) ? usage.cacheReadTokens : 0,
125
+ cacheWriteTokens: Number.isInteger(usage.cacheWriteTokens) ? usage.cacheWriteTokens : 0,
126
+ estimated: false,
127
+ };
128
+ }
129
+ }
130
+ return {
131
+ inputTokens: estimateTokens(promptText),
132
+ outputTokens: estimateTokens(outputText),
133
+ cacheReadTokens: 0,
134
+ cacheWriteTokens: 0,
135
+ estimated: true,
136
+ };
137
+ }
138
+
139
+ async function callInjectedClient(client, request) {
140
+ const complete = typeof client === 'function' ? client : client?.complete;
141
+ if (typeof complete === 'function') {
142
+ const value = await complete.call(client, request);
143
+ const text = typeof value === 'string' ? value : value?.text ?? value?.content ?? '';
144
+ return {
145
+ ok: true,
146
+ text: String(text ?? ''),
147
+ usage: normalizeUsage(value?.usage, request.prompt, String(text ?? '')),
148
+ provider: 'injected',
149
+ model: 'injected',
150
+ };
151
+ }
152
+ if (typeof client?.stream === 'function') {
153
+ const stream = await client.stream(request);
154
+ const result = await consumeStream(stream, { signal: request.signal });
155
+ if (!result.ok) {
156
+ return {
157
+ ok: false,
158
+ error: result.failure?.code ?? result.code ?? 'E_FACE_STREAM',
159
+ fatal: true,
160
+ failure: result.failure ?? null,
161
+ text: result.text ?? '',
162
+ };
163
+ }
164
+ return {
165
+ ok: true,
166
+ text: result.text ?? '',
167
+ usage: normalizeUsage(result.usage, request.prompt, result.text ?? ''),
168
+ provider: 'injected',
169
+ model: 'injected',
170
+ };
171
+ }
172
+ return { ok: false, error: 'E_FACE_CLIENT_INVALID', fatal: true };
173
+ }
174
+
175
+ /**
176
+ * 调一次模型。
177
+ *
178
+ * @returns {Promise<{ok:boolean,text:string,usage?:object,provider?:string,model?:string,error?:string,reason?:string,fatal?:boolean}>}
179
+ */
180
+ export async function callFaceModel(options = {}) {
181
+ const { ctx, config = {}, client = null, system, prompt, signal = null, maxTokens = 1024 } = options;
182
+ const messages = buildMessages({ system: system ?? FACE_SYSTEM_PROMPT, prompt });
183
+
184
+ if (client) {
185
+ try {
186
+ return await callInjectedClient(client, { messages, system, prompt, maxTokens, signal, task: FACE_TICK_TASK });
187
+ } catch (error) {
188
+ return {
189
+ ok: false,
190
+ error: error?.code ?? 'E_FACE_CLIENT',
191
+ reason: String(error?.message ?? error),
192
+ fatal: false,
193
+ text: '',
194
+ };
195
+ }
196
+ }
197
+
198
+ const llm = readClient(ctx);
199
+ if (!llm) {
200
+ return { ok: false, error: 'E_NO_LLM', reason: 'waiting-provider', fatal: true, text: '' };
201
+ }
202
+ const resolved = resolveModelTarget({
203
+ config: {
204
+ provider: config.provider ?? '',
205
+ model: config.model ?? 'auto',
206
+ providerExplicit: config.providerExplicit === true,
207
+ },
208
+ ctx,
209
+ llm,
210
+ });
211
+ if (!resolved.ok) {
212
+ return { ok: false, error: resolved.code ?? 'E_NO_PROVIDER', reason: resolved.reason ?? 'unresolved', fatal: true, text: '' };
213
+ }
214
+
215
+ try {
216
+ const stream = llm.stream({
217
+ messages,
218
+ task: FACE_TICK_TASK,
219
+ signal,
220
+ maxTokens,
221
+ provider: resolved.provider,
222
+ model: resolved.model,
223
+ ...(resolved.reasoningEffort ? { reasoningEffort: resolved.reasoningEffort } : {}),
224
+ });
225
+ const result = await consumeStream(stream, { signal });
226
+ if (!result.ok) {
227
+ return {
228
+ ok: false,
229
+ error: result.failure?.code ?? result.code ?? 'E_FACE_STREAM',
230
+ reason: result.failure?.message ?? null,
231
+ fatal: true,
232
+ failure: result.failure ?? null,
233
+ text: result.text ?? '',
234
+ };
235
+ }
236
+ return {
237
+ ok: true,
238
+ text: result.text ?? '',
239
+ usage: normalizeUsage(result.usage, prompt, result.text ?? ''),
240
+ provider: resolved.provider,
241
+ model: resolved.model,
242
+ };
243
+ } catch (error) {
244
+ return {
245
+ ok: false,
246
+ error: error?.code ?? 'E_FACE_MODEL',
247
+ reason: String(error?.message ?? error),
248
+ fatal: false,
249
+ text: '',
250
+ };
251
+ }
252
+ }
@@ -0,0 +1,153 @@
1
+ // routerFace v1 · 跨会话通道(bridge)。
2
+ //
3
+ // 后台面只能把话写进 `<root>/.longlive/bridge/router-outbox.jsonl`;
4
+ // 前台 hint 读到「最近 1 条未读」,渲染后写回该行的 readAt。
5
+ // 通道只是文件,不注入会话历史、不触发任何工具、不调度任何执行。
6
+ //
7
+ // 行格式(应答任务书的字段,额外带 v/id/readAt 以便标记已读):
8
+ // { "v":1, "id":"<sha1 前 12>", "at":"ISO", "sessionHint":"root",
9
+ // "text":"≤300 字", "kind":"suggestion", "readAt":null }
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import crypto from 'node:crypto';
14
+ import { FACE_MAX_HINT_CHARS } from './config.mjs';
15
+
16
+ export const OUTBOX_VERSION = 1;
17
+ export const OUTBOX_MAX_ROWS = 200;
18
+ export const BRIDGE_TEXT_MAX_CHARS = FACE_MAX_HINT_CHARS;
19
+
20
+ function clean(value, maxChars) {
21
+ let text = String(value ?? '')
22
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]+/g, ' ')
23
+ .replace(/\s+/g, ' ')
24
+ .trim();
25
+ if (typeof maxChars === 'number' && maxChars > 0) {
26
+ const chars = Array.from(text);
27
+ if (chars.length > maxChars) text = `${chars.slice(0, Math.max(1, maxChars - 1)).join('')}…`;
28
+ }
29
+ return text;
30
+ }
31
+
32
+ function hashId(seed) {
33
+ return crypto.createHash('sha1').update(String(seed)).digest('hex').slice(0, 12);
34
+ }
35
+
36
+ function readRows(file) {
37
+ let text = '';
38
+ try {
39
+ text = fs.readFileSync(file, 'utf8');
40
+ } catch {
41
+ return [];
42
+ }
43
+ const rows = [];
44
+ for (const line of text.split(/\r?\n/u)) {
45
+ if (line.trim() === '') continue;
46
+ try {
47
+ const value = JSON.parse(line);
48
+ if (value && typeof value === 'object' && typeof value.text === 'string') rows.push(value);
49
+ } catch {
50
+ // 坏行忽略:bridge 是通知通道,不做校验器。
51
+ }
52
+ }
53
+ return rows;
54
+ }
55
+
56
+ function writeRows(file, rows) {
57
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
58
+ fs.writeFileSync(tmp, `${rows.map((row) => JSON.stringify(row)).join('\n')}\n`, 'utf8');
59
+ fs.renameSync(tmp, file);
60
+ }
61
+
62
+ /**
63
+ * 写一条后台留话。返回 {ok, id, duplicate}。
64
+ * 同一个 (kind,text,at 分钟) 不重复写:防止定时器抖动刷屏。
65
+ */
66
+ export function appendOutbox(file, entry, options = {}) {
67
+ if (!file) return { ok: false, error: 'E_NO_OUTBOX_FILE' };
68
+ const text = clean(entry?.text, Number.isInteger(options.maxChars) ? options.maxChars : BRIDGE_TEXT_MAX_CHARS);
69
+ if (text === '') return { ok: false, error: 'E_EMPTY_TEXT' };
70
+ const at = typeof entry?.at === 'string' && entry.at !== '' ? entry.at : new Date().toISOString();
71
+ const kind = clean(entry?.kind, 40) || 'suggestion';
72
+ const sessionHint = clean(entry?.sessionHint, 80) || 'root';
73
+ const id = clean(entry?.id, 64) || hashId(`${kind}\n${sessionHint}\n${text}\n${at.slice(0, 16)}`);
74
+ try {
75
+ fs.mkdirSync(path.dirname(file), { recursive: true });
76
+ const rows = readRows(file);
77
+ if (rows.some((row) => row.id === id)) return { ok: true, added: false, duplicate: true, id };
78
+ const record = { v: OUTBOX_VERSION, id, at, sessionHint, text, kind, readAt: null };
79
+ fs.appendFileSync(file, `${JSON.stringify(record)}\n`, 'utf8');
80
+ if (rows.length + 1 > OUTBOX_MAX_ROWS) {
81
+ writeRows(file, readRows(file).slice(-OUTBOX_MAX_ROWS));
82
+ }
83
+ return { ok: true, added: true, id, record };
84
+ } catch (error) {
85
+ return { ok: false, error: error?.code ?? 'E_OUTBOX_WRITE', message: String(error?.message ?? error) };
86
+ }
87
+ }
88
+
89
+ /** 读全部(或尾部 limit 条),永不抛。 */
90
+ export function readOutbox(file, options = {}) {
91
+ if (!file) return [];
92
+ const rows = readRows(file);
93
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 0;
94
+ return limit > 0 ? rows.slice(-limit) : rows;
95
+ }
96
+
97
+ /** 最近一条未读;读不到返回 null。 */
98
+ export function readLatestUnread(file) {
99
+ const rows = readRows(file);
100
+ for (let i = rows.length - 1; i >= 0; i -= 1) {
101
+ if (rows[i].readAt === null || rows[i].readAt === undefined) return rows[i];
102
+ }
103
+ return null;
104
+ }
105
+
106
+ /**
107
+ * 标记已读:整文件读-改-写(bridge 很小,v1 接受这个代价)。
108
+ * 找不到 id / 写失败都返回 ok:false,由前台忽略。
109
+ */
110
+ export function markRead(file, id, options = {}) {
111
+ if (!file || typeof id !== 'string' || id === '') return { ok: false, error: 'E_NO_ID' };
112
+ const at = typeof options.at === 'string' && options.at !== '' ? options.at : new Date().toISOString();
113
+ try {
114
+ const rows = readRows(file);
115
+ let found = false;
116
+ for (const row of rows) {
117
+ if (row.id === id && (row.readAt === null || row.readAt === undefined)) {
118
+ row.readAt = at;
119
+ found = true;
120
+ }
121
+ }
122
+ if (!found) return { ok: false, error: 'E_NOT_FOUND' };
123
+ fs.mkdirSync(path.dirname(file), { recursive: true });
124
+ writeRows(file, rows);
125
+ return { ok: true, id, readAt: at };
126
+ } catch (error) {
127
+ return { ok: false, error: error?.code ?? 'E_OUTBOX_WRITE', message: String(error?.message ?? error) };
128
+ }
129
+ }
130
+
131
+ /**
132
+ * 渲染给前台 hint 的一行。≤300 字,且中和提示信封标记,防止后台文本
133
+ * 伪造「【提示结束】」。
134
+ */
135
+ export function renderBridgeHint(entry, options = {}) {
136
+ if (!entry || typeof entry.text !== 'string') return '';
137
+ const maxChars = Number.isInteger(options.maxChars) && options.maxChars > 0
138
+ ? Math.min(options.maxChars, BRIDGE_TEXT_MAX_CHARS)
139
+ : BRIDGE_TEXT_MAX_CHARS;
140
+ const text = clean(entry.text, maxChars)
141
+ .replace(/【/gu, '[')
142
+ .replace(/】/gu, ']');
143
+ if (text === '') return '';
144
+ const when = localClock(entry.at);
145
+ return `后台留话${when ? `(${when})` : ''}:${text}`;
146
+ }
147
+
148
+ function localClock(value) {
149
+ if (typeof value !== 'string' || value === '') return '';
150
+ const date = new Date(value);
151
+ if (!Number.isFinite(date.getTime())) return '';
152
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
153
+ }
@@ -0,0 +1,54 @@
1
+ // routerFace v1 · 所有落盘位置。
2
+ //
3
+ // 固定布局(<root> = memoryRoot):
4
+ // <root>/IDENTITY.md 前后台共用身份(只读)
5
+ // <root>/STATE.md 状态卡(只读)
6
+ // <root>/flow/current.md 心流快照(只读)
7
+ // <root>/.longlive/router/board.json 共享板(只读;主路径)
8
+ // <root>/.longlive/board.json 共享板(只读;兼容回退)
9
+ // <root>/.longlive/live/*.json 会话心跳/队列(只读)
10
+ // <root>/.longlive/face/journal.jsonl 后台面自己的 journal(写)
11
+ // <root>/.longlive/face/state.json 预算/失败/刹车状态(写)
12
+ // <root>/.longlive/face/status.json 对外的状态快照(写)
13
+ // <root>/.longlive/face/face.lock tick 单飞锁(写,短命)
14
+ // <root>/.longlive/bridge/router-outbox.jsonl 跨会话通道(写)
15
+
16
+ import path from 'node:path';
17
+
18
+ export const FACE_DIR_NAME = 'face';
19
+ export const BRIDGE_DIR_NAME = 'bridge';
20
+ export const OUTBOX_FILE_NAME = 'router-outbox.jsonl';
21
+ export const FACE_JOURNAL_FILE_NAME = 'journal.jsonl';
22
+ export const FACE_STATE_FILE_NAME = 'state.json';
23
+ export const FACE_STATUS_FILE_NAME = 'status.json';
24
+ export const FACE_LOCK_FILE_NAME = 'face.lock';
25
+
26
+ /**
27
+ * @param {string} memoryRoot
28
+ * @returns {object|null} null when memoryRoot is not a usable path
29
+ */
30
+ export function facePaths(memoryRoot) {
31
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') return null;
32
+ const root = path.resolve(memoryRoot);
33
+ const longlive = path.join(root, '.longlive');
34
+ const dir = path.join(longlive, FACE_DIR_NAME);
35
+ const bridgeDir = path.join(longlive, BRIDGE_DIR_NAME);
36
+ return {
37
+ root,
38
+ dir,
39
+ journalFile: path.join(dir, FACE_JOURNAL_FILE_NAME),
40
+ stateFile: path.join(dir, FACE_STATE_FILE_NAME),
41
+ statusFile: path.join(dir, FACE_STATUS_FILE_NAME),
42
+ lockFile: path.join(dir, FACE_LOCK_FILE_NAME),
43
+ identityFile: path.join(root, 'IDENTITY.md'),
44
+ stateMdFile: path.join(root, 'STATE.md'),
45
+ flowFile: path.join(root, 'flow', 'current.md'),
46
+ liveDir: path.join(longlive, 'live'),
47
+ bridgeDir,
48
+ outboxFile: path.join(bridgeDir, OUTBOX_FILE_NAME),
49
+ boardFile: path.join(longlive, 'router', 'board.json'),
50
+ boardFallbackFile: path.join(longlive, 'board.json'),
51
+ routerQueueFile: path.join(longlive, 'router', 'queue.jsonl'),
52
+ memoryJournalDir: path.join(root, 'journal'),
53
+ };
54
+ }