@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.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
// identity-router v0 — 交接卡草稿生成
|
|
2
|
+
//
|
|
3
|
+
// 默认只写 <repo>/outbox/,绝不写 memoryRoot。
|
|
4
|
+
// 这里没有语义总结能力:所谓「当前进度/下一步/风险」要么由调用方显式给,
|
|
5
|
+
// 要么从 STATE.md 的三节原样搬运。缺就写占位,不编。
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
DEFAULT_MEMORY_ROOT,
|
|
13
|
+
STATE_SECTIONS,
|
|
14
|
+
charLength,
|
|
15
|
+
compactSection,
|
|
16
|
+
normalizeText,
|
|
17
|
+
parseState,
|
|
18
|
+
readTextFile,
|
|
19
|
+
truncateChars,
|
|
20
|
+
} from './handover.js';
|
|
21
|
+
|
|
22
|
+
/** 草稿默认上限(码点)。交接卡是给人看的,1600 字足够,超出说明该拆卡。 */
|
|
23
|
+
export const DRAFT_MAX_CHARS = 1600;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* v0 默认 outbox:本仓库根目录下的 outbox。
|
|
27
|
+
* 插件被安装到别处时,用 config.outboxDir 或 DSH_IDENTITY_OUTBOX 覆盖。
|
|
28
|
+
* @returns {string}
|
|
29
|
+
*/
|
|
30
|
+
export function defaultOutboxDir() {
|
|
31
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
32
|
+
return path.resolve(here, '..', '..', 'outbox');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 解析 outbox:显式参数 > 环境变量 > 仓库默认。
|
|
37
|
+
* @param {{outboxDir?: string}} [config]
|
|
38
|
+
* @param {Record<string,string|undefined>} [env]
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
export function resolveOutboxDir(config = {}, env = process.env) {
|
|
42
|
+
const explicit = config?.outboxDir;
|
|
43
|
+
if (typeof explicit === 'string' && explicit.trim() !== '') return path.resolve(explicit.trim());
|
|
44
|
+
const fromEnv = env?.DSH_IDENTITY_OUTBOX;
|
|
45
|
+
if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return path.resolve(fromEnv.trim());
|
|
46
|
+
return defaultOutboxDir();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 把字符串/数组统一成干净的条目数组。
|
|
51
|
+
* @param {unknown} input
|
|
52
|
+
* @returns {string[]}
|
|
53
|
+
*/
|
|
54
|
+
export function normalizeItems(input) {
|
|
55
|
+
if (Array.isArray(input)) {
|
|
56
|
+
return input
|
|
57
|
+
.flatMap((item) => normalizeItems(item))
|
|
58
|
+
.filter((item) => item !== '');
|
|
59
|
+
}
|
|
60
|
+
if (typeof input !== 'string') return [];
|
|
61
|
+
return normalizeText(input)
|
|
62
|
+
.split('\n')
|
|
63
|
+
.map((line) => line.replace(/^\s*(?:[-*+]|\d+[.)])\s*/u, '').trim())
|
|
64
|
+
.filter((line) => line !== '');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 中文主题也能生成稳定文件名:只保留 ASCII 安全字符,其余丢弃。
|
|
69
|
+
* 全部丢光时回退到 fallback,不会产出空 slug。
|
|
70
|
+
* @param {unknown} topic
|
|
71
|
+
* @param {string} [fallback]
|
|
72
|
+
* @returns {string}
|
|
73
|
+
*/
|
|
74
|
+
export function slugifyTopic(topic, fallback = 'session') {
|
|
75
|
+
const ascii = String(topic ?? '')
|
|
76
|
+
.normalize('NFKD')
|
|
77
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
78
|
+
.toLowerCase()
|
|
79
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
80
|
+
.replace(/^-+|-+$/g, '')
|
|
81
|
+
.slice(0, 40);
|
|
82
|
+
return ascii === '' ? fallback : ascii;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 本地日期 `YYYY-MM-DD`。
|
|
87
|
+
* @param {Date} date
|
|
88
|
+
* @returns {string}
|
|
89
|
+
*/
|
|
90
|
+
export function formatDate(date) {
|
|
91
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
92
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 本地时间 `YYYY-MM-DD HH:mm`。
|
|
97
|
+
* @param {Date} date
|
|
98
|
+
* @returns {string}
|
|
99
|
+
*/
|
|
100
|
+
export function formatDateTime(date) {
|
|
101
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
102
|
+
return `${formatDate(date)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 把一节里的多行压成一行:去掉 bullet 前缀,条目之间用「;」,不留 `。;`。
|
|
107
|
+
* @param {string} text
|
|
108
|
+
* @returns {string}
|
|
109
|
+
*/
|
|
110
|
+
function inlineSection(text) {
|
|
111
|
+
return String(text ?? '')
|
|
112
|
+
.split('\n')
|
|
113
|
+
.map((line) => line.trim())
|
|
114
|
+
.filter((line) => line !== '')
|
|
115
|
+
.map((line) => line.replace(/^[-*+]\s+/u, '').replace(/[;;]\s*$/u, ''))
|
|
116
|
+
.join(';')
|
|
117
|
+
.replace(/。;/gu, ';')
|
|
118
|
+
.replace(/;{2,}/gu, ';')
|
|
119
|
+
.replace(/;$/u, '');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 从 STATE.md 提「当前进度 / 下一步」,只搬运不总结。
|
|
124
|
+
* @param {unknown} stateText
|
|
125
|
+
* @param {{maxChars?: number}} [options]
|
|
126
|
+
* @returns {{progress:string[], next:string[], warnings:string[]}}
|
|
127
|
+
*/
|
|
128
|
+
export function deriveFromState(stateText, options = {}) {
|
|
129
|
+
const warnings = [];
|
|
130
|
+
const text = normalizeText(stateText);
|
|
131
|
+
if (text.trim() === '') {
|
|
132
|
+
return {
|
|
133
|
+
progress: ['(未提供 STATE.md,当前进度需人工补充)'],
|
|
134
|
+
next: ['(未提供 STATE.md,下一步需人工补充)'],
|
|
135
|
+
warnings: ['STATE_MISSING'],
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const parsed = parseState(text);
|
|
140
|
+
const budget = Number.isFinite(options.maxChars) ? Math.max(80, options.maxChars) : 500;
|
|
141
|
+
const where = compactSection(parsed.sections, STATE_SECTIONS.where, budget);
|
|
142
|
+
const recent = compactSection(parsed.sections, STATE_SECTIONS.recent, budget);
|
|
143
|
+
const waiting = compactSection(parsed.sections, STATE_SECTIONS.waiting, budget);
|
|
144
|
+
|
|
145
|
+
if (!where.found) warnings.push(`SECTION_MISSING:${STATE_SECTIONS.where}`);
|
|
146
|
+
if (!recent.found) warnings.push(`SECTION_MISSING:${STATE_SECTIONS.recent}`);
|
|
147
|
+
if (!waiting.found) warnings.push(`SECTION_MISSING:${STATE_SECTIONS.waiting}`);
|
|
148
|
+
|
|
149
|
+
const progress = [
|
|
150
|
+
where.found ? `【我在哪】${inlineSection(where.text)}` : '',
|
|
151
|
+
recent.found ? `【最近三件】${inlineSection(recent.text)}` : '',
|
|
152
|
+
].filter(Boolean);
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
progress: progress.length > 0 ? progress : ['(STATE.md 的三节都缺失,请人工补充)'],
|
|
156
|
+
next: waiting.found ? [inlineSection(waiting.text)] : ['(STATE.md 没有「在等什么」,请人工补充)'],
|
|
157
|
+
warnings,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 生成交接卡草稿。纯函数,不写盘。
|
|
163
|
+
* @param {{
|
|
164
|
+
* topic?: string,
|
|
165
|
+
* stateText?: string|null,
|
|
166
|
+
* progress?: string[]|string,
|
|
167
|
+
* next?: string[]|string,
|
|
168
|
+
* risks?: string[]|string,
|
|
169
|
+
* now?: Date|number|string,
|
|
170
|
+
* maxChars?: number,
|
|
171
|
+
* source?: string,
|
|
172
|
+
* }} [input]
|
|
173
|
+
* @returns {{text:string, filename:string, slug:string, chars:number,
|
|
174
|
+
* truncated:boolean, warnings:string[], usedFallbackState:boolean}}
|
|
175
|
+
*/
|
|
176
|
+
export function buildHandoverDraft(input = {}) {
|
|
177
|
+
const maxChars = Number.isFinite(input.maxChars) && input.maxChars > 0
|
|
178
|
+
? Math.floor(input.maxChars)
|
|
179
|
+
: DRAFT_MAX_CHARS;
|
|
180
|
+
const now = input.now instanceof Date ? input.now : new Date(input.now ?? Date.now());
|
|
181
|
+
const safeNow = Number.isFinite(now.getTime()) ? now : new Date();
|
|
182
|
+
|
|
183
|
+
const stateText = typeof input.stateText === 'string' ? input.stateText : '';
|
|
184
|
+
const warnings = [];
|
|
185
|
+
const fromState = deriveFromState(stateText);
|
|
186
|
+
warnings.push(...fromState.warnings);
|
|
187
|
+
|
|
188
|
+
const progress = normalizeItems(input.progress);
|
|
189
|
+
const next = normalizeItems(input.next);
|
|
190
|
+
const risks = normalizeItems(input.risks);
|
|
191
|
+
// 只有「STATE 根本读不到」且调用方也没给进度/下一步时,才算真的退化。
|
|
192
|
+
// 正常情况下从 STATE 搬运是设计路径,不该报警。
|
|
193
|
+
const stateMissing = stateText.trim() === '';
|
|
194
|
+
const usedFallbackState = stateMissing && (progress.length === 0 || next.length === 0);
|
|
195
|
+
|
|
196
|
+
const finalProgress = progress.length > 0 ? progress : fromState.progress;
|
|
197
|
+
const finalNext = next.length > 0 ? next : fromState.next;
|
|
198
|
+
const finalRisks = risks.length > 0
|
|
199
|
+
? risks
|
|
200
|
+
: ['(本次未自动识别到新风险;请人工补充「可能坑到下一轮的地方」)'];
|
|
201
|
+
|
|
202
|
+
const topic = typeof input.topic === 'string' && input.topic.trim() !== ''
|
|
203
|
+
? input.topic.trim()
|
|
204
|
+
: '未命名会话';
|
|
205
|
+
const slug = slugifyTopic(topic);
|
|
206
|
+
const filename = `${formatDate(safeNow)}-${slug}.md`;
|
|
207
|
+
const source = typeof input.source === 'string' && input.source.trim() !== ''
|
|
208
|
+
? input.source.trim()
|
|
209
|
+
: 'STATE.md / 会话上下文';
|
|
210
|
+
|
|
211
|
+
const bulletize = (items) => items.map((item) => `- ${item.replace(/\s*\n\s*/gu, ' ').trim()}`);
|
|
212
|
+
|
|
213
|
+
const lines = [
|
|
214
|
+
`# 交接卡草稿:${topic}`,
|
|
215
|
+
'',
|
|
216
|
+
`> identity-router v0 自动生成 · ${formatDateTime(safeNow)} · 来源:${source}`,
|
|
217
|
+
'> 这是草稿,尚未写入 memoryRoot;由人或后续版本合并。',
|
|
218
|
+
'',
|
|
219
|
+
'## 当前进度',
|
|
220
|
+
...bulletize(finalProgress),
|
|
221
|
+
'',
|
|
222
|
+
'## 下一步',
|
|
223
|
+
...bulletize(finalNext),
|
|
224
|
+
'',
|
|
225
|
+
'## 风险',
|
|
226
|
+
...bulletize(finalRisks),
|
|
227
|
+
'',
|
|
228
|
+
];
|
|
229
|
+
|
|
230
|
+
let text = lines.join('\n');
|
|
231
|
+
if (usedFallbackState) {
|
|
232
|
+
warnings.push('DRAFT_USED_STATE_FALLBACK');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const cut = truncateChars(text, maxChars);
|
|
236
|
+
if (cut.truncated) {
|
|
237
|
+
warnings.push('DRAFT_TRUNCATED');
|
|
238
|
+
text = `${cut.text}\n`;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
text,
|
|
243
|
+
filename,
|
|
244
|
+
slug,
|
|
245
|
+
chars: charLength(text),
|
|
246
|
+
truncated: cut.truncated,
|
|
247
|
+
warnings,
|
|
248
|
+
usedFallbackState,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* 原子写入草稿:先写同目录临时文件,再 rename 成目标名。
|
|
254
|
+
* 目标重名时自动加 `-2`、`-3`(最多 50 次),绝不覆盖已有草稿。
|
|
255
|
+
* @param {{text:string,filename:string}} draft
|
|
256
|
+
* @param {{outboxDir?:string}} [options]
|
|
257
|
+
* @returns {{ok:boolean,path:string|null,filename:string|null,bytes:number,error?:string}}
|
|
258
|
+
*/
|
|
259
|
+
export function writeHandoverDraft(draft, options = {}) {
|
|
260
|
+
if (!draft || typeof draft.text !== 'string' || draft.text.trim() === '') {
|
|
261
|
+
return { ok: false, path: null, filename: null, bytes: 0, error: 'EMPTY_DRAFT' };
|
|
262
|
+
}
|
|
263
|
+
const outboxDir = resolveOutboxDir(options);
|
|
264
|
+
const base = String(draft.filename ?? '').trim() === ''
|
|
265
|
+
? `${formatDate(new Date())}-session.md`
|
|
266
|
+
: path.basename(String(draft.filename));
|
|
267
|
+
const stem = base.replace(/\.md$/iu, '');
|
|
268
|
+
|
|
269
|
+
try {
|
|
270
|
+
fs.mkdirSync(outboxDir, { recursive: true });
|
|
271
|
+
} catch (error) {
|
|
272
|
+
return { ok: false, path: null, filename: null, bytes: 0, error: error?.code ?? 'EMKDIR' };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
276
|
+
const candidate = attempt === 0 ? `${stem}.md` : `${stem}-${attempt + 1}.md`;
|
|
277
|
+
const target = path.join(outboxDir, candidate);
|
|
278
|
+
if (fs.existsSync(target)) continue;
|
|
279
|
+
const tmp = path.join(
|
|
280
|
+
outboxDir,
|
|
281
|
+
`.${candidate}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`,
|
|
282
|
+
);
|
|
283
|
+
try {
|
|
284
|
+
fs.writeFileSync(tmp, draft.text, 'utf8');
|
|
285
|
+
fs.renameSync(tmp, target);
|
|
286
|
+
const bytes = fs.statSync(target).size;
|
|
287
|
+
return { ok: true, path: target, filename: candidate, bytes };
|
|
288
|
+
} catch (error) {
|
|
289
|
+
try {
|
|
290
|
+
if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
|
|
291
|
+
} catch {
|
|
292
|
+
// 临时文件清不掉也不遮住真正的错误
|
|
293
|
+
}
|
|
294
|
+
return { ok: false, path: null, filename: null, bytes: 0, error: error?.code ?? 'EWRITE' };
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return { ok: false, path: null, filename: null, bytes: 0, error: 'ENAME_COLLISION' };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 一步到位:读 STATE → 生成草稿 → 写 outbox。只读 STATE,写只落 outbox。
|
|
303
|
+
* @param {{
|
|
304
|
+
* statePath?:string, memoryRoot?:string, outboxDir?:string,
|
|
305
|
+
* topic?:string, progress?:string[]|string, next?:string[]|string,
|
|
306
|
+
* risks?:string[]|string, now?:Date|number|string, maxChars?:number,
|
|
307
|
+
* source?:string, env?:Record<string,string|undefined>,
|
|
308
|
+
* }} [options]
|
|
309
|
+
* @returns {ReturnType<typeof buildHandoverDraft> & {
|
|
310
|
+
* ok:boolean, path:string|null, statePath:string, error?:string,
|
|
311
|
+
* }}
|
|
312
|
+
*/
|
|
313
|
+
export function writeHandoverFromState(options = {}) {
|
|
314
|
+
const env = options.env ?? process.env;
|
|
315
|
+
const memoryRoot = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() !== ''
|
|
316
|
+
? path.resolve(options.memoryRoot)
|
|
317
|
+
: path.resolve(env.DSH_IDENTITY_MEMORY_ROOT || DEFAULT_MEMORY_ROOT);
|
|
318
|
+
const statePath = typeof options.statePath === 'string' && options.statePath.trim() !== ''
|
|
319
|
+
? path.resolve(options.statePath)
|
|
320
|
+
: path.join(memoryRoot, 'STATE.md');
|
|
321
|
+
|
|
322
|
+
const read = readTextFile(statePath);
|
|
323
|
+
const draft = buildHandoverDraft({
|
|
324
|
+
topic: options.topic,
|
|
325
|
+
stateText: read.ok ? read.text : '',
|
|
326
|
+
progress: options.progress,
|
|
327
|
+
next: options.next,
|
|
328
|
+
risks: options.risks,
|
|
329
|
+
now: options.now,
|
|
330
|
+
maxChars: options.maxChars,
|
|
331
|
+
source: options.source ?? statePath,
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
if (!read.ok) draft.warnings.push(`STATE_READ_FAILED:${read.error}`);
|
|
335
|
+
|
|
336
|
+
const written = writeHandoverDraft(draft, { outboxDir: options.outboxDir });
|
|
337
|
+
return {
|
|
338
|
+
...draft,
|
|
339
|
+
ok: written.ok,
|
|
340
|
+
path: written.path,
|
|
341
|
+
statePath,
|
|
342
|
+
...(written.ok ? {} : { error: written.error }),
|
|
343
|
+
};
|
|
344
|
+
}
|
package/src/identity.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Session identity for the longlive plugin.
|
|
2
|
+
//
|
|
3
|
+
// The plugin runs at the profile root, so it has no `ctx.session` / `ctx.agent`
|
|
4
|
+
// of its own. The host still gives every tool call an explicit caller: the
|
|
5
|
+
// second `execute(args, exec)` argument carries the live Agent
|
|
6
|
+
// (`exec.agent.session.header.id`), built by dsh-agent-loop from
|
|
7
|
+
// `ctx.agents.requireInitiator()`. That is route 1 below and the only route
|
|
8
|
+
// this plugin treats as authoritative.
|
|
9
|
+
//
|
|
10
|
+
// Outside a tool call there is no caller: `currentInitiator()` returns
|
|
11
|
+
// `undefined` in timers and event callbacks by design (dsh-agent README:
|
|
12
|
+
// "the boundary is process-local attribution only"). Auto-heartbeat therefore
|
|
13
|
+
// binds the id at tool-call time and only *refreshes* already-bound rows later.
|
|
14
|
+
//
|
|
15
|
+
// Every route is read inside `try/catch`: identity must never turn a tool call
|
|
16
|
+
// into a crash, and a missing id must stay `null` so the existing explicit
|
|
17
|
+
// errors (`无法确定当前会话 id ...`) are preserved.
|
|
18
|
+
|
|
19
|
+
/** Resolution sources, most reliable first. */
|
|
20
|
+
export const IDENTITY_SOURCES = Object.freeze([
|
|
21
|
+
'exec.agent',
|
|
22
|
+
'agents.currentInitiator',
|
|
23
|
+
'ctx.agent',
|
|
24
|
+
'env.DSH_SESSION_ID',
|
|
25
|
+
'none',
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
function cleanId(value) {
|
|
29
|
+
if (typeof value !== 'string') return null;
|
|
30
|
+
const trimmed = value.trim();
|
|
31
|
+
return trimmed === '' ? null : trimmed;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The SessionId carried by one live Agent.
|
|
36
|
+
*
|
|
37
|
+
* `session.header.id` is the persisted header id, `session.id` the live one and
|
|
38
|
+
* `agent.id` the agent's own SessionId; they are expected to agree, and any one
|
|
39
|
+
* of them is a real id rather than a guess.
|
|
40
|
+
*/
|
|
41
|
+
export function sessionIdOfAgent(agent) {
|
|
42
|
+
if (agent == null || typeof agent !== 'object') return null;
|
|
43
|
+
try {
|
|
44
|
+
return cleanId(agent.session?.header?.id)
|
|
45
|
+
?? cleanId(agent.session?.id)
|
|
46
|
+
?? cleanId(agent.id);
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The SessionId carried by a tool-execution context (`exec`). */
|
|
53
|
+
export function sessionIdOfExec(exec) {
|
|
54
|
+
if (exec == null || typeof exec !== 'object') return null;
|
|
55
|
+
const fromAgent = sessionIdOfAgent(exec.agent);
|
|
56
|
+
if (fromAgent) return fromAgent;
|
|
57
|
+
try {
|
|
58
|
+
return cleanId(exec.session?.id) ?? cleanId(exec.sessionId);
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function initiatorOf(ctx) {
|
|
65
|
+
if (ctx == null || typeof ctx !== 'object') return null;
|
|
66
|
+
try {
|
|
67
|
+
const agents = typeof ctx.get === 'function' ? ctx.get('agents') : null;
|
|
68
|
+
return agents != null && typeof agents.currentInitiator === 'function'
|
|
69
|
+
? agents.currentInitiator()
|
|
70
|
+
: null;
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Resolve the session that is calling right now.
|
|
78
|
+
*
|
|
79
|
+
* @param {object} [options]
|
|
80
|
+
* @param {object|null} [options.ctx] live Cordis context (optional; used for
|
|
81
|
+
* the agents service and the legacy ctx-guess routes)
|
|
82
|
+
* @param {object|null} [options.exec] tool-execution context (route 1)
|
|
83
|
+
* @param {object} [options.env] environment to read the last-resort id from
|
|
84
|
+
* @returns {{id: string|null, source: string}}
|
|
85
|
+
*/
|
|
86
|
+
export function resolveCurrentSessionId({ ctx = null, exec = null, env = process.env } = {}) {
|
|
87
|
+
const fromExec = sessionIdOfExec(exec);
|
|
88
|
+
if (fromExec) return { id: fromExec, source: 'exec.agent' };
|
|
89
|
+
|
|
90
|
+
const fromInitiator = sessionIdOfAgent(initiatorOf(ctx));
|
|
91
|
+
if (fromInitiator) return { id: fromInitiator, source: 'agents.currentInitiator' };
|
|
92
|
+
|
|
93
|
+
// Legacy guesses: kept for preset-scoped contexts that really do carry an
|
|
94
|
+
// agent; at the profile root all of these are undefined.
|
|
95
|
+
try {
|
|
96
|
+
const fromCtx = sessionIdOfAgent(ctx?.agent)
|
|
97
|
+
?? cleanId(ctx?.session?.id)
|
|
98
|
+
?? cleanId(ctx?.agent?.sessionId)
|
|
99
|
+
?? cleanId(ctx?.sessionId);
|
|
100
|
+
if (fromCtx) return { id: fromCtx, source: 'ctx.agent' };
|
|
101
|
+
} catch {
|
|
102
|
+
/* fall through */
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Last resort only: dsh-shell-env injects DSH_SESSION_ID per shell call, so a
|
|
106
|
+
// host process may not have it, and a value inherited from a launching shell
|
|
107
|
+
// may be stale. It is still better than refusing to name a session when no
|
|
108
|
+
// host contract is available.
|
|
109
|
+
let fromEnv = null;
|
|
110
|
+
try {
|
|
111
|
+
fromEnv = cleanId(env?.DSH_SESSION_ID);
|
|
112
|
+
} catch {
|
|
113
|
+
fromEnv = null;
|
|
114
|
+
}
|
|
115
|
+
if (fromEnv) return { id: fromEnv, source: 'env.DSH_SESSION_ID' };
|
|
116
|
+
|
|
117
|
+
return { id: null, source: 'none' };
|
|
118
|
+
}
|