@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
package/src/tools.js
ADDED
|
@@ -0,0 +1,3262 @@
|
|
|
1
|
+
// @local/dsh-longlive - tools
|
|
2
|
+
//
|
|
3
|
+
// Four groups:
|
|
4
|
+
// - session_* read or rewrite one DSH session log and default to dryRun=true:
|
|
5
|
+
// a dry run performs all reads and computations and writes NOTHING (no tmp,
|
|
6
|
+
// no backup, no ledger); writing requires an explicit confirm word.
|
|
7
|
+
// - session_wake is the v0.2 wake-up kit, lease_acquire / lease_release hand
|
|
8
|
+
// out a cross-process write lease over the memory store so two hosts never
|
|
9
|
+
// believe they both own it, and worker_* drive one background child session
|
|
10
|
+
// when the host exposes a subagents service.
|
|
11
|
+
// - memory_* (v0.4) read and write ONLY inside the directory configured as
|
|
12
|
+
// `memoryRoot`. Since 0.7.3 an unset root derives to <DSH home>/longlive-memory
|
|
13
|
+
// (create-on-demand) and $DSH_MEM / $DSH_LONGLIVE_MEMORY_ROOT override it;
|
|
14
|
+
// `strictMemoryRoot` restores the old "unset root is an error" behaviour.
|
|
15
|
+
// Every write is backed up, verified, and rolled back on failure.
|
|
16
|
+
// - session_live_* (v0.5) maintain the "正在" live session registry under
|
|
17
|
+
// <memoryRoot>/.longlive/live: one atomically written JSON row per session.
|
|
18
|
+
// idle/running/waiting/blocked/stale are declared by the writer;
|
|
19
|
+
// dead/corrupt are computed by the reader.
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { dshHome } from './home.js';
|
|
24
|
+
import { parseSession, deriveMessagesDigest } from './codec.js';
|
|
25
|
+
import { sha256File, stamp, readLedger, writeLedger } from './backup.js';
|
|
26
|
+
import { resolveCurrentSessionId } from './identity.js';
|
|
27
|
+
import { truncateSession, formatBytes, CONFIRM_WORD } from './truncate.js';
|
|
28
|
+
import {
|
|
29
|
+
truncateVisibleSession,
|
|
30
|
+
VISIBLE_CONFIRM_WORD,
|
|
31
|
+
DEFAULT_KEEP_TURNS,
|
|
32
|
+
DEFAULT_KEEP_TOKENS,
|
|
33
|
+
} from './truncate-visible.js';
|
|
34
|
+
import { hotTruncateDiagOptions } from './hot-truncate-diag.js';
|
|
35
|
+
import { analyzeCompaction, describeCompaction } from './compaction.js';
|
|
36
|
+
import { memoryIndex } from './memory/index.js';
|
|
37
|
+
import { memoryConsolidate } from './memory/consolidate.js';
|
|
38
|
+
import { memoryReinforce } from './memory/reinforce.js';
|
|
39
|
+
import { memoryForget, forgetStatus } from './memory/forget.js';
|
|
40
|
+
import { forgetV2 } from './memory/forget-v2.js';
|
|
41
|
+
import { memoryRecall } from './memory/recall.js';
|
|
42
|
+
import { recallV2 } from './memory/recall-v2.js';
|
|
43
|
+
import { memoryProcedure, PROCEDURES_DIR, PROCEDURE_ACTIONS } from './memory/procedure.js';
|
|
44
|
+
import { memoryFeedback } from './memory/recall-feedback.mjs';
|
|
45
|
+
import { memoryConflicts } from './memory/conflicts.js';
|
|
46
|
+
import { memoryWake as wakeTool } from './memory/wake-bridge.mjs';
|
|
47
|
+
import { withWriteEvidence as landWithWriteEvidence, UNIMPLEMENTED_CODE as LAND_UNIMPLEMENTED_CODE } from './memory/land.mjs';
|
|
48
|
+
import {
|
|
49
|
+
memoryError,
|
|
50
|
+
memoryRootFromConfig,
|
|
51
|
+
memoryRootSetting,
|
|
52
|
+
defaultMemoryRoot,
|
|
53
|
+
MEMORY_ROOT_ENV,
|
|
54
|
+
LEGACY_MEMORY_ROOT_ENV,
|
|
55
|
+
DEFAULT_MEMORY_DIRNAME,
|
|
56
|
+
} from './memory/paths.js';
|
|
57
|
+
import { normalizeTiering, buildTierHint, DEFAULT_TIERING } from './memory/tiers.js';
|
|
58
|
+
import { liveUpdate, liveList, liveGet, livePrune } from './live.js';
|
|
59
|
+
import { sessionIdOfLogFile } from './live-target.js';
|
|
60
|
+
import { privacyScan } from './recall/privacy.mjs';
|
|
61
|
+
import { searchEventsFts, searchEventsReadOnly } from './memory/event-index.js';
|
|
62
|
+
import {
|
|
63
|
+
buildTurnItems,
|
|
64
|
+
availableTurns,
|
|
65
|
+
selectTurnItems,
|
|
66
|
+
joinTurnItems,
|
|
67
|
+
sliceUtf8,
|
|
68
|
+
archiveFileName,
|
|
69
|
+
ORIGINAL_KINDS,
|
|
70
|
+
} from './original.js';
|
|
71
|
+
|
|
72
|
+
const SESSION_FILE = 'session.v4.jsonl.zstd';
|
|
73
|
+
|
|
74
|
+
export { dshHome };
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Every session log under <home>/sessions/<scope>/<id>/session.v4.jsonl.zstd.
|
|
78
|
+
* Read-only: never creates anything.
|
|
79
|
+
*/
|
|
80
|
+
export function listSessions(home = dshHome()) {
|
|
81
|
+
const root = path.join(home, 'sessions');
|
|
82
|
+
const out = [];
|
|
83
|
+
let scopes = [];
|
|
84
|
+
try {
|
|
85
|
+
scopes = fs.readdirSync(root, { withFileTypes: true });
|
|
86
|
+
} catch {
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
for (const scope of scopes) {
|
|
90
|
+
if (!scope.isDirectory()) continue;
|
|
91
|
+
const scopeDir = path.join(root, scope.name);
|
|
92
|
+
let entries = [];
|
|
93
|
+
try {
|
|
94
|
+
entries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
95
|
+
} catch {
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
for (const entry of entries) {
|
|
99
|
+
if (!entry.isDirectory()) continue;
|
|
100
|
+
const file = path.join(scopeDir, entry.name, SESSION_FILE);
|
|
101
|
+
let stat;
|
|
102
|
+
try {
|
|
103
|
+
stat = fs.statSync(file);
|
|
104
|
+
} catch {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (!stat.isFile()) continue;
|
|
108
|
+
out.push({ id: entry.name, scope: scope.name, file, bytes: stat.size, mtimeMs: stat.mtimeMs });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function candidatesOf(sessions, limit = 3) {
|
|
115
|
+
return [...sessions]
|
|
116
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
117
|
+
.slice(0, limit)
|
|
118
|
+
.map((s) => ({ id: s.id, scope: s.scope, bytes: s.bytes, modified: new Date(s.mtimeMs).toISOString() }));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function lookupError(code, message, sessions) {
|
|
122
|
+
return { ok: false, error: { code, message, candidates: candidatesOf(sessions ?? []) } };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
// Path whitelist (F2) and backup planning (F1/F3/F4)
|
|
127
|
+
//
|
|
128
|
+
// Every session tool resolves a path before it reads or writes anything, and
|
|
129
|
+
// that path must stay inside <DSH_HOME>/sessions: the plugin's whole contract is
|
|
130
|
+
// "one session log, never any other file". A relative path is refused outright
|
|
131
|
+
// (it would silently resolve against whatever cwd the host happened to have),
|
|
132
|
+
// and only the two names a session log can have are accepted.
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
const BACKUP_CONFIRM_WORD = 'BACKUP';
|
|
136
|
+
|
|
137
|
+
/** The sessions root every resolved path must live under. */
|
|
138
|
+
function sessionsRoot(home) {
|
|
139
|
+
return path.join(home, 'sessions');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** True for the log itself — the only name a destructive tool may touch. */
|
|
143
|
+
function isSessionLogName(name) {
|
|
144
|
+
return name === SESSION_FILE;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** True for a `.bak-*` copy of the log. Read tools may inspect these; writers may not. */
|
|
148
|
+
function isBackupFileName(name) {
|
|
149
|
+
return name.startsWith(`${SESSION_FILE}.bak-`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** True for the two names a session tool may touch: the log, and its .bak-* copies. */
|
|
153
|
+
function isSessionFileName(name) {
|
|
154
|
+
return isSessionLogName(name) || isBackupFileName(name);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** `target` is strictly inside `dir` (not the directory itself, not its parent). */
|
|
158
|
+
function isInsideDir(dir, target) {
|
|
159
|
+
const rel = path.relative(path.resolve(dir), path.resolve(target));
|
|
160
|
+
return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** One shape for every refusal: no read, no write, and the offending path named. */
|
|
164
|
+
function pathRefusal(code, abs, message) {
|
|
165
|
+
const error = { code, message, path: abs, candidates: [], ok: false, status: 'unavailable' };
|
|
166
|
+
return { ok: false, code, status: 'unavailable', refused: true, path: abs, message, error };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Enforce the whitelist on an already-resolved absolute path.
|
|
171
|
+
*
|
|
172
|
+
* `destructive: true` narrows it to the log itself: truncating a `.bak-*` copy
|
|
173
|
+
* rewrites a backup, which is the one thing a backup exists to prevent. Reads
|
|
174
|
+
* keep the wider whitelist, because inspecting a backup is a legitimate question.
|
|
175
|
+
*/
|
|
176
|
+
function guardSessionPath(abs, home, { destructive = false } = {}) {
|
|
177
|
+
if (!isInsideDir(sessionsRoot(home), abs)) {
|
|
178
|
+
return pathRefusal('PATH_OUTSIDE_SESSIONS', abs, `unavailable: 路径不在 sessions 目录内 ${abs}`);
|
|
179
|
+
}
|
|
180
|
+
const name = path.basename(abs);
|
|
181
|
+
if (!isSessionFileName(name)) {
|
|
182
|
+
return pathRefusal('PATH_NOT_SESSION_FILE', abs,
|
|
183
|
+
`unavailable: 不是 session 文件名(只能是 ${SESSION_FILE} 或其 .bak-* 备份)${abs}`);
|
|
184
|
+
}
|
|
185
|
+
if (destructive && isBackupFileName(name)) {
|
|
186
|
+
return pathRefusal('IS_BACKUP', abs,
|
|
187
|
+
`unavailable: 这是 ${SESSION_FILE} 的备份文件,破坏性工具只对日志本体操作(备份不可被截断;` +
|
|
188
|
+
`要动日志请指向 ${SESSION_FILE})${abs}`);
|
|
189
|
+
}
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** An already-vetted path (from listSessions or the whitelist) becomes a resolution. */
|
|
194
|
+
function acceptPath(file, home, extra = {}, options = {}) {
|
|
195
|
+
const guarded = guardSessionPath(file, home, options);
|
|
196
|
+
if (guarded) return guarded;
|
|
197
|
+
return { ok: true, sessionPath: file, ...extra, home };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Backup files that really are files; a same-named directory is not a backup. */
|
|
201
|
+
function backupFilesUnder(sessionPath) {
|
|
202
|
+
const dir = path.dirname(sessionPath);
|
|
203
|
+
const base = path.basename(sessionPath);
|
|
204
|
+
let names = [];
|
|
205
|
+
try {
|
|
206
|
+
names = fs.readdirSync(dir);
|
|
207
|
+
} catch {
|
|
208
|
+
return [];
|
|
209
|
+
}
|
|
210
|
+
const out = [];
|
|
211
|
+
for (const name of names) {
|
|
212
|
+
if (!name.startsWith(`${base}.bak-`)) continue;
|
|
213
|
+
const file = path.join(dir, name);
|
|
214
|
+
try {
|
|
215
|
+
const stat = fs.statSync(file);
|
|
216
|
+
if (stat.isFile()) out.push({ file, size: stat.size, mtimeMs: stat.mtimeMs });
|
|
217
|
+
} catch {
|
|
218
|
+
// Unreadable or vanished mid-scan: it cannot be counted as a backup.
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return out.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const FS_REASONS = {
|
|
225
|
+
ENOENT: '文件不存在',
|
|
226
|
+
EACCES: '没有权限',
|
|
227
|
+
EPERM: '没有权限',
|
|
228
|
+
EISDIR: '目标是目录',
|
|
229
|
+
ENOTDIR: '路径不是目录',
|
|
230
|
+
ENOSPC: '磁盘空间不足',
|
|
231
|
+
EEXIST: '目标已存在',
|
|
232
|
+
EBUSY: '文件被占用',
|
|
233
|
+
EMFILE: '文件句柄耗尽',
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/** `中文原因(CODE)` for any filesystem error, so a bare code never escapes. */
|
|
237
|
+
function fsReason(error) {
|
|
238
|
+
const code = error?.code ?? 'UNKNOWN';
|
|
239
|
+
return `${FS_REASONS[code] ?? (typeof error?.message === 'string' ? error.message : String(error))}(${code})`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** `unavailable: …` wrapper shared by the session tools. */
|
|
243
|
+
function fsUnavailable(action, error, extra = {}) {
|
|
244
|
+
return {
|
|
245
|
+
ok: false,
|
|
246
|
+
status: 'unavailable',
|
|
247
|
+
code: error?.code ?? 'UNKNOWN',
|
|
248
|
+
...extra,
|
|
249
|
+
message: `unavailable: ${action}:${fsReason(error)}`,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Pick the backup path for this invocation: today's stamp, then -2, -3, … until
|
|
255
|
+
* a free name is found. Never reuses an older backup and never overwrites one,
|
|
256
|
+
* so a dry run and the real run that follows it name the same file.
|
|
257
|
+
*/
|
|
258
|
+
function planBackupTarget(sessionPath, date = new Date()) {
|
|
259
|
+
const dir = path.dirname(sessionPath);
|
|
260
|
+
const base = path.basename(sessionPath);
|
|
261
|
+
const day = stamp(date);
|
|
262
|
+
for (let n = 1; n <= 1000; n += 1) {
|
|
263
|
+
const name = n === 1 ? `${base}.bak-${day}` : `${base}.bak-${day}-${n}`;
|
|
264
|
+
const file = path.join(dir, name);
|
|
265
|
+
if (!fs.existsSync(file)) return { file, day, suffix: n };
|
|
266
|
+
}
|
|
267
|
+
const error = new Error('backup name space exhausted');
|
|
268
|
+
error.code = 'EEXIST';
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Copy + verify + ledger. COPYFILE_EXCL means an existing file is never clobbered. */
|
|
273
|
+
function createBackupNow(sessionPath, targetFile, expectedSha256, size) {
|
|
274
|
+
fs.copyFileSync(sessionPath, targetFile, fs.constants.COPYFILE_EXCL);
|
|
275
|
+
let copied;
|
|
276
|
+
try {
|
|
277
|
+
copied = sha256File(targetFile);
|
|
278
|
+
} catch (error) {
|
|
279
|
+
try { fs.unlinkSync(targetFile); } catch { /* best effort */ }
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
if (copied !== expectedSha256) {
|
|
283
|
+
try { fs.unlinkSync(targetFile); } catch { /* best effort */ }
|
|
284
|
+
const error = new Error(`backup verification failed: ${copied} != ${expectedSha256}`);
|
|
285
|
+
error.code = 'BACKUP_SHA256_MISMATCH';
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
const result = { created: true, file: targetFile, sha256: copied, size, ledgerWritten: true };
|
|
289
|
+
try {
|
|
290
|
+
const ledger = readLedger(sessionPath);
|
|
291
|
+
ledger.backups.push({
|
|
292
|
+
file: targetFile,
|
|
293
|
+
sha256: copied,
|
|
294
|
+
size,
|
|
295
|
+
createdAt: new Date().toISOString(),
|
|
296
|
+
deletable: ledger.backups.length + 1 > 7,
|
|
297
|
+
});
|
|
298
|
+
writeLedger(sessionPath, ledger);
|
|
299
|
+
} catch (error) {
|
|
300
|
+
// The bytes are on disk and verified; a ledger that could not be written is
|
|
301
|
+
// reported, not turned into a fake failure.
|
|
302
|
+
result.ledgerWritten = false;
|
|
303
|
+
result.ledgerWarning = fsReason(error);
|
|
304
|
+
}
|
|
305
|
+
return result;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The confirm word is case-insensitive but never approximate. */
|
|
309
|
+
function backupConfirmOk(value) {
|
|
310
|
+
return typeof value === 'string' && value.trim().toUpperCase() === BACKUP_CONFIRM_WORD;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Turn any of { sessionPath, sessionId, session } into an absolute log path.
|
|
315
|
+
* Resolution is read-only and happens before any write; failures carry
|
|
316
|
+
* SESSION_NOT_FOUND / SESSION_AMBIGUOUS plus up to three recent candidates.
|
|
317
|
+
*/
|
|
318
|
+
export function resolveSessionPath(args = {}, config = {}, options = {}) {
|
|
319
|
+
const home = config.home ?? dshHome();
|
|
320
|
+
const explicit = typeof args.sessionPath === 'string' ? args.sessionPath.trim() : '';
|
|
321
|
+
|
|
322
|
+
if (explicit) {
|
|
323
|
+
if (!path.isAbsolute(explicit)) {
|
|
324
|
+
return pathRefusal('PATH_NOT_ABSOLUTE', path.resolve(explicit),
|
|
325
|
+
`unavailable: 需要绝对路径或 sessionId(收到 ${JSON.stringify(explicit)})`);
|
|
326
|
+
}
|
|
327
|
+
const abs = path.resolve(explicit);
|
|
328
|
+
const guarded = guardSessionPath(abs, home, options);
|
|
329
|
+
if (guarded) return guarded;
|
|
330
|
+
let stat = null;
|
|
331
|
+
try { stat = fs.statSync(abs); } catch { stat = null; }
|
|
332
|
+
if (!stat || !stat.isFile()) {
|
|
333
|
+
return lookupError('SESSION_NOT_FOUND', `no session log at ${abs}`, listSessions(home));
|
|
334
|
+
}
|
|
335
|
+
return { ok: true, sessionPath: abs, source: 'sessionPath', home };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const sessions = listSessions(home);
|
|
339
|
+
const id = typeof args.sessionId === 'string' ? args.sessionId.trim() : '';
|
|
340
|
+
const want = typeof args.session === 'string' ? args.session.trim() : '';
|
|
341
|
+
|
|
342
|
+
if (id) {
|
|
343
|
+
const matches = sessions.filter((s) => s.id === id);
|
|
344
|
+
if (matches.length === 1) return acceptPath(matches[0].file, home, { source: 'sessionId' });
|
|
345
|
+
if (matches.length > 1) {
|
|
346
|
+
return {
|
|
347
|
+
ok: false,
|
|
348
|
+
error: {
|
|
349
|
+
code: 'SESSION_AMBIGUOUS',
|
|
350
|
+
message: `session id ${id} exists in ${matches.length} scopes; pass sessionPath instead`,
|
|
351
|
+
candidates: matches.map((s) => ({ id: s.id, scope: s.scope, bytes: s.bytes, modified: new Date(s.mtimeMs).toISOString() })),
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
return lookupError('SESSION_NOT_FOUND',
|
|
356
|
+
`no session with id ${id} under ${path.join(home, 'sessions')}`, sessions);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (want === 'current') {
|
|
360
|
+
let current = null;
|
|
361
|
+
try {
|
|
362
|
+
// `exec` is the current tool execution: identity.js reads the explicit
|
|
363
|
+
// caller Agent from it before falling back to anything ambient.
|
|
364
|
+
current = typeof config.currentSessionId === 'function'
|
|
365
|
+
? config.currentSessionId(config.exec)
|
|
366
|
+
: config.currentSessionId;
|
|
367
|
+
} catch { current = null; }
|
|
368
|
+
if (!current) current = process.env.DSH_SESSION_ID ?? null;
|
|
369
|
+
if (!current) {
|
|
370
|
+
return lookupError('SESSION_NOT_FOUND',
|
|
371
|
+
'this host did not expose the current session id; pass sessionId or sessionPath', sessions);
|
|
372
|
+
}
|
|
373
|
+
const match = sessions.find((s) => s.id === current);
|
|
374
|
+
if (!match) {
|
|
375
|
+
return lookupError('SESSION_NOT_FOUND',
|
|
376
|
+
`current session ${current} has no log under ${path.join(home, 'sessions')}`, sessions);
|
|
377
|
+
}
|
|
378
|
+
return acceptPath(match.file, home, { source: 'current' });
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (want === 'latest') {
|
|
382
|
+
if (sessions.length === 0) {
|
|
383
|
+
return lookupError('SESSION_NOT_FOUND', `no session logs under ${path.join(home, 'sessions')}`, sessions);
|
|
384
|
+
}
|
|
385
|
+
const newest = [...sessions].sort((a, b) => b.mtimeMs - a.mtimeMs)[0];
|
|
386
|
+
return acceptPath(newest.file, home, { source: 'latest', sessionId: newest.id });
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
return lookupError('SESSION_NOT_FOUND',
|
|
390
|
+
'no session selected: pass sessionPath, sessionId, or session:"latest" | "current"', sessions);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// --- live-session guard (0.7.2) -------------------------------------------
|
|
394
|
+
//
|
|
395
|
+
// A manual truncation rewrites the file, but the app that has the session
|
|
396
|
+
// loaded still holds the *old* event sequence in memory: the next append then
|
|
397
|
+
// writes a torn/duplicate seq and the log becomes unreadable (measured 0.7.0:
|
|
398
|
+
// 77 -> 3532). Truncating the session this very app has loaded is therefore
|
|
399
|
+
// refused unless the caller proves it is a test/diagnostic run.
|
|
400
|
+
//
|
|
401
|
+
// The caller id comes from the 0.5.1 chain: identity.resolveCurrentSessionId
|
|
402
|
+
// (explicit tool exec -> initiator agent -> env), and is bound into the
|
|
403
|
+
// heartbeat registry so the same id is what live tooling sees.
|
|
404
|
+
|
|
405
|
+
export const LIVE_ESCAPE_CONFIRM_WORD = 'I-KNOW-THIS-CORRUPTS';
|
|
406
|
+
|
|
407
|
+
export const LIVE_GUARD_CODES = Object.freeze({
|
|
408
|
+
TARGET_IS_LIVE_SESSION: 'VISIBLE_TARGET_IS_LIVE_SESSION',
|
|
409
|
+
CURRENT_ID_UNKNOWN: 'VISIBLE_CURRENT_ID_UNKNOWN',
|
|
410
|
+
ESCAPE_CONFIRM_REQUIRED: 'VISIBLE_LIVE_ESCAPE_CONFIRM_REQUIRED',
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
// The id helper lives in live-target.js so the out-of-app CLI can share it
|
|
414
|
+
// without importing the whole tool layer (which depends on the host plugin
|
|
415
|
+
// runtime). Re-exported here for the tool modules and existing callers.
|
|
416
|
+
export { sessionIdOfLogFile };
|
|
417
|
+
|
|
418
|
+
/** Resolve the session this app has loaded; never throws. */
|
|
419
|
+
export function resolveCallerSessionId(config = {}) {
|
|
420
|
+
let ctx = null;
|
|
421
|
+
try { ctx = typeof config.host === 'function' ? config.host() : null; } catch { ctx = null; }
|
|
422
|
+
let resolved = { id: null, source: 'none' };
|
|
423
|
+
try {
|
|
424
|
+
resolved = resolveCurrentSessionId({ ctx, exec: config.exec ?? null });
|
|
425
|
+
} catch { resolved = { id: null, source: 'none' }; }
|
|
426
|
+
let id = typeof resolved?.id === 'string' ? resolved.id.trim() : '';
|
|
427
|
+
let source = resolved?.source ?? 'none';
|
|
428
|
+
if (!id) {
|
|
429
|
+
try {
|
|
430
|
+
const fallback = typeof config.currentSessionId === 'function'
|
|
431
|
+
? config.currentSessionId(config.exec)
|
|
432
|
+
: config.currentSessionId;
|
|
433
|
+
if (typeof fallback === 'string' && fallback.trim() !== '') {
|
|
434
|
+
id = fallback.trim();
|
|
435
|
+
source = 'config.currentSessionId';
|
|
436
|
+
}
|
|
437
|
+
} catch { /* fail closed below */ }
|
|
438
|
+
}
|
|
439
|
+
if (!id) return { id: null, source: 'none' };
|
|
440
|
+
try { config.autoHeartbeat?.bind?.(id); } catch { /* registry must not block the guard */ }
|
|
441
|
+
return { id, source };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Refuse to write the session this app has loaded. Fail-closed: an unknown
|
|
446
|
+
* caller id is a refusal too, because "I cannot tell" must never mean "go".
|
|
447
|
+
*
|
|
448
|
+
* `allowLive:true` is a test/diagnostic escape hatch and additionally requires
|
|
449
|
+
* confirm:"I-KNOW-THIS-CORRUPTS"; the automatic path never sets it.
|
|
450
|
+
*/
|
|
451
|
+
export function assertNotOwnLiveSession(sessionPath, args = {}, config = {}) {
|
|
452
|
+
const allowLive = args.allowLive === true;
|
|
453
|
+
const escaped = allowLive && args.confirm === LIVE_ESCAPE_CONFIRM_WORD;
|
|
454
|
+
if (allowLive && !escaped) {
|
|
455
|
+
return {
|
|
456
|
+
ok: false,
|
|
457
|
+
code: LIVE_GUARD_CODES.ESCAPE_CONFIRM_REQUIRED,
|
|
458
|
+
escaped: false,
|
|
459
|
+
message: `allowLive:true is diagnostics-only and needs confirm:"${LIVE_ESCAPE_CONFIRM_WORD}" ` +
|
|
460
|
+
`(got ${JSON.stringify(args.confirm)}); it is never used by the automatic path`,
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
const target = sessionIdOfLogFile(sessionPath);
|
|
464
|
+
const caller = resolveCallerSessionId(config);
|
|
465
|
+
if (!caller.id && !escaped) {
|
|
466
|
+
return {
|
|
467
|
+
ok: false,
|
|
468
|
+
code: LIVE_GUARD_CODES.CURRENT_ID_UNKNOWN,
|
|
469
|
+
targetId: target.id,
|
|
470
|
+
targetIdSource: target.source,
|
|
471
|
+
currentId: null,
|
|
472
|
+
escaped: false,
|
|
473
|
+
message: 'cannot determine which session this app has loaded (no exec, agent, or DSH_SESSION_ID); ' +
|
|
474
|
+
'refusing to write. Stop the app and use the CLI, or pass allowLive:true with ' +
|
|
475
|
+
`confirm:"${LIVE_ESCAPE_CONFIRM_WORD}" for a test/diagnostic run.`,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
const same = Boolean(caller.id) && caller.id.toLowerCase() === String(target.id).toLowerCase();
|
|
479
|
+
if (same && !escaped) {
|
|
480
|
+
return {
|
|
481
|
+
ok: false,
|
|
482
|
+
code: LIVE_GUARD_CODES.TARGET_IS_LIVE_SESSION,
|
|
483
|
+
targetId: target.id,
|
|
484
|
+
targetIdSource: target.source,
|
|
485
|
+
currentId: caller.id,
|
|
486
|
+
identitySource: caller.source,
|
|
487
|
+
escaped: false,
|
|
488
|
+
message: 'target is the session currently loaded by this app; truncate it only while the app is stopped',
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
return {
|
|
492
|
+
ok: true,
|
|
493
|
+
targetId: target.id,
|
|
494
|
+
targetIdSource: target.source,
|
|
495
|
+
currentId: caller.id,
|
|
496
|
+
identitySource: caller.source,
|
|
497
|
+
escaped,
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
function lastTruncation(sessionPath) {
|
|
503
|
+
const file = path.join(path.dirname(sessionPath), 'truncate.json');
|
|
504
|
+
if (!fs.existsSync(file)) return null;
|
|
505
|
+
try {
|
|
506
|
+
const ledger = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
507
|
+
return Array.isArray(ledger.truncations) && ledger.truncations.length
|
|
508
|
+
? ledger.truncations.at(-1)
|
|
509
|
+
: null;
|
|
510
|
+
} catch {
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export function sessionHealth(args = {}, config = {}) {
|
|
516
|
+
const resolved = resolveSessionPath(args, config);
|
|
517
|
+
if (!resolved.ok) return { status: 'error', ...resolved.error, error: resolved.error };
|
|
518
|
+
const abs = resolved.sessionPath;
|
|
519
|
+
const base = {
|
|
520
|
+
sessionPath: abs,
|
|
521
|
+
exists: fs.existsSync(abs),
|
|
522
|
+
bytes: null,
|
|
523
|
+
events: null,
|
|
524
|
+
firstSeq: null,
|
|
525
|
+
lastType: null,
|
|
526
|
+
visibleMessages: null,
|
|
527
|
+
deriveSha256: null,
|
|
528
|
+
ageSeconds: null,
|
|
529
|
+
backups: 0,
|
|
530
|
+
lastTruncation: lastTruncation(abs),
|
|
531
|
+
status: 'ok',
|
|
532
|
+
message: '',
|
|
533
|
+
};
|
|
534
|
+
if (!base.exists) return { ...base, status: 'missing', message: `no such file: ${abs}` };
|
|
535
|
+
|
|
536
|
+
let stat;
|
|
537
|
+
try {
|
|
538
|
+
stat = fs.statSync(abs);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
return { ...base, status: 'unavailable', message: fsUnavailable('无法读取会话日志', error).message };
|
|
541
|
+
}
|
|
542
|
+
if (!stat.isFile()) {
|
|
543
|
+
return { ...base, status: 'unavailable', message: `unavailable: 会话路径不是普通文件 ${abs}` };
|
|
544
|
+
}
|
|
545
|
+
base.bytes = stat.size;
|
|
546
|
+
base.ageSeconds = Math.round((Date.now() - stat.mtimeMs) / 1000);
|
|
547
|
+
base.backups = backupFilesUnder(abs).length;
|
|
548
|
+
try {
|
|
549
|
+
const parsed = parseSession(fs.readFileSync(abs));
|
|
550
|
+
const digest = deriveMessagesDigest(parsed.header, parsed.events);
|
|
551
|
+
base.events = parsed.events.length;
|
|
552
|
+
base.firstSeq = parsed.events[0]?.seq ?? null;
|
|
553
|
+
base.lastType = parsed.events.at(-1)?.type ?? null;
|
|
554
|
+
base.visibleMessages = digest.count;
|
|
555
|
+
base.deriveSha256 = digest.sha256;
|
|
556
|
+
// Shadowed-vs-reclaimed is the difference between "the model forgot" and
|
|
557
|
+
// "the disk forgot"; a longevity tool that reports only one of them will
|
|
558
|
+
// happily approve a truncation that deletes live history. `filePath` makes
|
|
559
|
+
// the analysis re-read the log from disk, so "reclaimed" is a counted fact
|
|
560
|
+
// instead of an inference from event metadata.
|
|
561
|
+
base.compaction = analyzeCompaction(parsed, { filePath: abs });
|
|
562
|
+
base.compactionMessage = describeCompaction(base.compaction);
|
|
563
|
+
base.message = `${formatBytes(stat.size)} / ${base.events} events / ${digest.count} visible messages`;
|
|
564
|
+
} catch (error) {
|
|
565
|
+
base.status = 'corrupt';
|
|
566
|
+
base.message = fsUnavailable('无法解析会话日志', error).message;
|
|
567
|
+
}
|
|
568
|
+
return base;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export function sessionBackupPlan(args = {}, config = {}) {
|
|
572
|
+
const dryRun = args.dryRun !== false;
|
|
573
|
+
const resolved = resolveSessionPath(args, config);
|
|
574
|
+
if (!resolved.ok) return { dryRun, status: 'error', ...resolved.error, error: resolved.error };
|
|
575
|
+
const abs = resolved.sessionPath;
|
|
576
|
+
// N4: a backup of a backup is not a backup. Refusing here keeps one clear
|
|
577
|
+
// chain (log -> .bak-*) instead of nesting .bak-…bak-… copies nobody can
|
|
578
|
+
// attribute, and it is refused before confirm/stat/read so nothing is written.
|
|
579
|
+
if (isBackupFileName(path.basename(abs))) {
|
|
580
|
+
return {
|
|
581
|
+
ok: false,
|
|
582
|
+
code: 'IS_BACKUP',
|
|
583
|
+
status: 'unavailable',
|
|
584
|
+
dryRun,
|
|
585
|
+
sessionPath: abs,
|
|
586
|
+
message: `unavailable: ${path.basename(abs)} 已经是 ${SESSION_FILE} 的备份;备份不能再被备份,` +
|
|
587
|
+
`请指向日志本体 ${SESSION_FILE}`,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
// F1: a write needs the explicit word. Checked before any read, so a missing
|
|
591
|
+
// or wrong confirm cannot leave a stat, a sha256 or a file behind.
|
|
592
|
+
if (!dryRun && !backupConfirmOk(args.confirm)) {
|
|
593
|
+
return {
|
|
594
|
+
ok: false,
|
|
595
|
+
sessionPath: abs,
|
|
596
|
+
dryRun: false,
|
|
597
|
+
status: 'unavailable',
|
|
598
|
+
confirm: typeof args.confirm === 'string' ? args.confirm : null,
|
|
599
|
+
message: `unavailable: 需 confirm:"${BACKUP_CONFIRM_WORD}" 才能真写盘`,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
let size;
|
|
604
|
+
let sha256;
|
|
605
|
+
let target;
|
|
606
|
+
try {
|
|
607
|
+
if (!fs.existsSync(abs)) {
|
|
608
|
+
return { sessionPath: abs, dryRun, status: 'missing', message: `no such file: ${abs}` };
|
|
609
|
+
}
|
|
610
|
+
const stat = fs.statSync(abs);
|
|
611
|
+
if (!stat.isFile()) {
|
|
612
|
+
return {
|
|
613
|
+
ok: false, sessionPath: abs, dryRun, status: 'unavailable',
|
|
614
|
+
message: `unavailable: 源路径不是普通文件 ${abs}`,
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
// F3: a zero-byte log has nothing to copy; say so instead of letting the
|
|
618
|
+
// comparison path read a directory afterwards.
|
|
619
|
+
if (stat.size === 0) {
|
|
620
|
+
return { ok: false, sessionPath: abs, dryRun, status: 'unavailable', bytes: 0, message: 'unavailable: 源文件为空' };
|
|
621
|
+
}
|
|
622
|
+
size = stat.size;
|
|
623
|
+
sha256 = sha256File(abs);
|
|
624
|
+
// F4: the target is decided once, in this call, by one function. The real
|
|
625
|
+
// run below uses exactly this name — it never rescans the directory.
|
|
626
|
+
target = planBackupTarget(abs, new Date());
|
|
627
|
+
} catch (error) {
|
|
628
|
+
return fsUnavailable('无法读取会话日志', error, { sessionPath: abs, dryRun });
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// The write must land next to the log and nowhere else, under a session name.
|
|
632
|
+
const sameDir = path.resolve(path.dirname(target.file)) === path.resolve(path.dirname(abs));
|
|
633
|
+
if (!sameDir || !isSessionFileName(path.basename(target.file))) {
|
|
634
|
+
return {
|
|
635
|
+
ok: false, sessionPath: abs, dryRun, status: 'unavailable',
|
|
636
|
+
message: `unavailable: 备份目标不合法(必须与源文件同目录、同 session 文件名)${target.file}`,
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const plan = {
|
|
641
|
+
sessionPath: abs,
|
|
642
|
+
dryRun,
|
|
643
|
+
status: 'planned',
|
|
644
|
+
bytes: size,
|
|
645
|
+
sha256,
|
|
646
|
+
targetFile: target.file,
|
|
647
|
+
targetExists: fs.existsSync(target.file),
|
|
648
|
+
message: dryRun
|
|
649
|
+
? `would back up ${formatBytes(size)} to ${path.basename(target.file)} (sha256 ${sha256.slice(0, 12)})`
|
|
650
|
+
: '',
|
|
651
|
+
};
|
|
652
|
+
if (dryRun) return plan;
|
|
653
|
+
|
|
654
|
+
let created;
|
|
655
|
+
try {
|
|
656
|
+
created = createBackupNow(abs, target.file, sha256, size);
|
|
657
|
+
} catch (error) {
|
|
658
|
+
return fsUnavailable('写备份失败', error, { sessionPath: abs, dryRun, targetFile: target.file });
|
|
659
|
+
}
|
|
660
|
+
return {
|
|
661
|
+
...plan,
|
|
662
|
+
dryRun: false,
|
|
663
|
+
status: 'created',
|
|
664
|
+
targetFile: created.file,
|
|
665
|
+
sha256: created.sha256,
|
|
666
|
+
ledgerWritten: created.ledgerWritten,
|
|
667
|
+
ledgerWarning: created.ledgerWarning ?? null,
|
|
668
|
+
message: `created ${created.file}${created.ledgerWritten ? '' : `(账本未写入:${created.ledgerWarning})`}`,
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
export function truncateTool(args = {}, config = {}) {
|
|
673
|
+
const dryRun = args.dryRun !== false;
|
|
674
|
+
// Destructive: only the log itself. A `.bak-*` target is refused with
|
|
675
|
+
// IS_BACKUP before anything is read, let alone written (N4).
|
|
676
|
+
const resolved = resolveSessionPath(args, config, { destructive: true });
|
|
677
|
+
if (!resolved.ok) {
|
|
678
|
+
return { ok: false, dryRun, status: 'error', ...resolved.error, error: resolved.error };
|
|
679
|
+
}
|
|
680
|
+
const keepEvents = args.keepEvents ?? config.keepEvents;
|
|
681
|
+
if (keepEvents !== undefined && keepEvents !== null
|
|
682
|
+
&& !(Number.isInteger(keepEvents) && keepEvents >= 1)) {
|
|
683
|
+
return {
|
|
684
|
+
ok: false, dryRun, status: 'error', code: 'BAD_ARGUMENT',
|
|
685
|
+
message: `keepEvents 必须是 >= 1 的整数(事件数,收到 ${JSON.stringify(keepEvents)})`,
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
const escapeConfirmed = args.allowLive === true && args.confirm === LIVE_ESCAPE_CONFIRM_WORD;
|
|
689
|
+
if (!dryRun && args.confirm !== CONFIRM_WORD && !escapeConfirmed) {
|
|
690
|
+
return {
|
|
691
|
+
ok: false, dryRun, status: 'error', code: 'CONFIRM_REQUIRED',
|
|
692
|
+
message: `refusing to write: pass confirm:"${CONFIRM_WORD}" (got ${JSON.stringify(args.confirm)})`,
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
if (!dryRun) {
|
|
696
|
+
// Writing the session this app is running is the 0.7.0 torn-log bug: the
|
|
697
|
+
// in-memory cursor still points at the old seq. Refuse before any read that
|
|
698
|
+
// could be mistaken for a write attempt.
|
|
699
|
+
const live = assertNotOwnLiveSession(resolved.sessionPath, args, config);
|
|
700
|
+
if (!live.ok) {
|
|
701
|
+
return { ok: false, dryRun, status: 'error', code: live.code, errorCode: live.code, ...live };
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
// The escape word authorizes the tool-level live guard; the core writer still
|
|
705
|
+
// needs its own canonical confirm word. Forwarding the escape word here made
|
|
706
|
+
// the escape path fail closed at the core instead of writing (V12).
|
|
707
|
+
const writeConfirm = escapeConfirmed ? CONFIRM_WORD : args.confirm;
|
|
708
|
+
let summary;
|
|
709
|
+
try {
|
|
710
|
+
summary = truncateSession(resolved.sessionPath, {
|
|
711
|
+
keepEvents,
|
|
712
|
+
dryRun,
|
|
713
|
+
confirm: writeConfirm,
|
|
714
|
+
recentWriteWindowMs: config.recentWriteWindowMs,
|
|
715
|
+
});
|
|
716
|
+
} catch (error) {
|
|
717
|
+
return {
|
|
718
|
+
ok: false, dryRun, status: 'error',
|
|
719
|
+
code: error?.code ?? 'TRUNCATE_FAILED',
|
|
720
|
+
message: error?.message ?? String(error),
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
return {
|
|
724
|
+
...summary,
|
|
725
|
+
ok: true,
|
|
726
|
+
status: summary.needed === false ? 'noop' : (dryRun ? 'planned' : 'truncated'),
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
export function truncateVisibleTool(args = {}, config = {}) {
|
|
731
|
+
const dryRun = args.dryRun !== false;
|
|
732
|
+
const resolved = resolveSessionPath(args, config, { destructive: true });
|
|
733
|
+
if (!resolved.ok) {
|
|
734
|
+
return { ok: false, dryRun, status: 'error', ...resolved.error, error: resolved.error };
|
|
735
|
+
}
|
|
736
|
+
const keepTurns = args.keepTurns ?? DEFAULT_KEEP_TURNS;
|
|
737
|
+
const keepTokens = args.keepTokens ?? DEFAULT_KEEP_TOKENS;
|
|
738
|
+
if (keepTurns !== undefined && keepTurns !== null && !(Number.isInteger(keepTurns) && keepTurns >= 1)) {
|
|
739
|
+
return {
|
|
740
|
+
ok: false, dryRun, status: 'error', code: 'BAD_ARGUMENT',
|
|
741
|
+
message: `keepTurns 必须是 >= 1 的整数(收到 ${JSON.stringify(keepTurns)})`,
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
if (keepTokens !== undefined && keepTokens !== null && !(Number.isInteger(keepTokens) && keepTokens >= 1)) {
|
|
745
|
+
return {
|
|
746
|
+
ok: false, dryRun, status: 'error', code: 'BAD_ARGUMENT',
|
|
747
|
+
message: `keepTokens 必须是 >= 1 的整数(收到 ${JSON.stringify(keepTokens)})`,
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
const escapeConfirmed = args.allowLive === true && args.confirm === LIVE_ESCAPE_CONFIRM_WORD;
|
|
751
|
+
if (!dryRun && args.confirm !== VISIBLE_CONFIRM_WORD && !escapeConfirmed) {
|
|
752
|
+
return {
|
|
753
|
+
ok: false, dryRun, status: 'error', code: 'CONFIRM_REQUIRED',
|
|
754
|
+
message: `refusing to write: pass confirm:"${VISIBLE_CONFIRM_WORD}" (got ${JSON.stringify(args.confirm)})`,
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
if (args.firstUserCapChars !== undefined && args.firstUserCapChars !== null
|
|
758
|
+
&& !(Number.isInteger(args.firstUserCapChars) && args.firstUserCapChars >= 1)) {
|
|
759
|
+
return {
|
|
760
|
+
ok: false, dryRun, status: 'error', code: 'BAD_ARGUMENT',
|
|
761
|
+
message: `firstUserCapChars 必须是 >= 1 的整数(收到 ${JSON.stringify(args.firstUserCapChars)})`,
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
if (!dryRun) {
|
|
765
|
+
const live = assertNotOwnLiveSession(resolved.sessionPath, args, config);
|
|
766
|
+
if (!live.ok) {
|
|
767
|
+
return { ok: false, dryRun, status: 'error', code: live.code, errorCode: live.code, ...live };
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
// Same split of authority as truncateTool: "I-KNOW-THIS-CORRUPTS" clears the
|
|
771
|
+
// live guard only; the writer below still requires "TRUNCATE-VISIBLE".
|
|
772
|
+
const writeConfirm = escapeConfirmed ? VISIBLE_CONFIRM_WORD : args.confirm;
|
|
773
|
+
const diagMemoryRoot = typeof config.memoryRoot === 'string' && config.memoryRoot.trim() !== ''
|
|
774
|
+
? config.memoryRoot.trim()
|
|
775
|
+
: (typeof config.memRoot === 'string' && config.memRoot.trim() !== '' ? config.memRoot.trim() : null);
|
|
776
|
+
let summary;
|
|
777
|
+
try {
|
|
778
|
+
summary = truncateVisibleSession(resolved.sessionPath, {
|
|
779
|
+
dryRun,
|
|
780
|
+
confirm: writeConfirm,
|
|
781
|
+
keepTurns,
|
|
782
|
+
keepTokens,
|
|
783
|
+
firstUserCapChars: args.firstUserCapChars,
|
|
784
|
+
boundaryRetries: args.boundaryRetries,
|
|
785
|
+
carryFirstUserMessage: args.carryFirstUserMessage,
|
|
786
|
+
insertArchiveCard: args.insertArchiveCard,
|
|
787
|
+
recentWriteWindowMs: config.recentWriteWindowMs,
|
|
788
|
+
faultAt: config.faultAt,
|
|
789
|
+
memoryRoot: diagMemoryRoot,
|
|
790
|
+
diagOptions: hotTruncateDiagOptions(config.autoTruncate ?? {}),
|
|
791
|
+
logger: config.logger,
|
|
792
|
+
});
|
|
793
|
+
} catch (error) {
|
|
794
|
+
const detail = error?.result ?? {};
|
|
795
|
+
const rollback = detail.rollback
|
|
796
|
+
? `\n回滚:${detail.rollback}`
|
|
797
|
+
: (detail.backupPath ? `\n回滚:Copy-Item -LiteralPath "${detail.backupPath}" -Destination "${resolved.sessionPath}" -Force` : '');
|
|
798
|
+
return {
|
|
799
|
+
...detail,
|
|
800
|
+
ok: false, dryRun, status: 'error',
|
|
801
|
+
code: error?.code ?? 'VISIBLE_TRUNCATE_FAILED',
|
|
802
|
+
message: `${error?.message ?? String(error)}${rollback}`,
|
|
803
|
+
errorCode: error?.code ?? null,
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
...summary,
|
|
808
|
+
// 0.8.0-rc.11: a dry run that cannot produce a cut is a failed plan, not a
|
|
809
|
+
// successful tool call. `feasible:false` keeps its structured reason and
|
|
810
|
+
// attempts, so the caller never has to guess why nothing was planned.
|
|
811
|
+
ok: summary.feasible === false ? false : true,
|
|
812
|
+
status: summary.feasible === false
|
|
813
|
+
? 'infeasible'
|
|
814
|
+
: (summary.needed === false ? 'noop' : (dryRun ? 'planned' : 'truncated')),
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Trigger one native DSH compaction, whose summary is appended to the session
|
|
820
|
+
* log itself (`compaction/summary` + a `compact-checkpoint` user message).
|
|
821
|
+
*
|
|
822
|
+
* Only the host can append those events: a compaction must cover an exact
|
|
823
|
+
* current surface span and run start -> summary -> end inside one open turn.
|
|
824
|
+
* A session log that already ends in `turn/end` therefore cannot be compacted
|
|
825
|
+
* from the outside, and never by hand — which is exactly why the 2026-10-30
|
|
826
|
+
* 13:48 truncation could not restore a summary it had deleted.
|
|
827
|
+
*
|
|
828
|
+
* `compactNow` requires an idle agent, so inside a running turn the request is
|
|
829
|
+
* queued on `whenIdle()` and reported as `scheduled`.
|
|
830
|
+
*/
|
|
831
|
+
/**
|
|
832
|
+
* Read one Cordis service off the host context without tripping its inject guard.
|
|
833
|
+
*
|
|
834
|
+
* A context object is a Proxy: `ctx.compaction` throws
|
|
835
|
+
* `cannot get property "compaction" without inject` when this plugin never
|
|
836
|
+
* declared that service (Cordis treats an undeclared read as a bug, not as a
|
|
837
|
+
* missing dependency). A profile that simply does not load a compaction service
|
|
838
|
+
* is the normal case here, so the read has to fail soft and report
|
|
839
|
+
* `unavailable` instead of throwing out of the tool.
|
|
840
|
+
*/
|
|
841
|
+
function probeService(host, name) {
|
|
842
|
+
if (!host) return null;
|
|
843
|
+
try {
|
|
844
|
+
const direct = host[name];
|
|
845
|
+
if (direct != null) return direct;
|
|
846
|
+
} catch {
|
|
847
|
+
// Not declared by this plugin's inject list: treat as absent.
|
|
848
|
+
}
|
|
849
|
+
try {
|
|
850
|
+
const viaGet = typeof host.get === 'function' ? host.get(name) : null;
|
|
851
|
+
if (viaGet != null) return viaGet;
|
|
852
|
+
} catch {
|
|
853
|
+
// Same guard on the accessor path.
|
|
854
|
+
}
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
export async function compactTool(args = {}, config = {}) {
|
|
859
|
+
const dryRun = args.dryRun !== false;
|
|
860
|
+
// Compaction rewrites the log it is invoked for, so naming a `.bak-*` copy is
|
|
861
|
+
// refused exactly like truncation (N4). The host service itself only ever
|
|
862
|
+
// targets the live session; this guard makes the tool's own contract match.
|
|
863
|
+
if (args.sessionPath !== undefined || args.sessionId !== undefined || args.session !== undefined) {
|
|
864
|
+
const resolved = resolveSessionPath(args, config, { destructive: true });
|
|
865
|
+
if (!resolved.ok) {
|
|
866
|
+
return { ok: false, dryRun, status: 'error', ...resolved.error, error: resolved.error };
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
const host = config.host?.() ?? null;
|
|
870
|
+
const compaction = probeService(host, 'compaction');
|
|
871
|
+
const agent = probeService(host, 'agent');
|
|
872
|
+
// A queued compaction settles after this call returns; keep its state here
|
|
873
|
+
// and hand out copies, so a caller's snapshot can never mutate underneath it.
|
|
874
|
+
const state = {
|
|
875
|
+
ok: true,
|
|
876
|
+
dryRun,
|
|
877
|
+
status: 'unavailable',
|
|
878
|
+
available: Boolean(compaction && agent),
|
|
879
|
+
agentStatus: agent?.status ?? null,
|
|
880
|
+
message: '',
|
|
881
|
+
};
|
|
882
|
+
const snapshot = () => ({ ...state });
|
|
883
|
+
const fail = (error) => {
|
|
884
|
+
state.ok = false;
|
|
885
|
+
state.status = 'failed';
|
|
886
|
+
state.code = error?.code ?? 'COMPACTION_FAILED';
|
|
887
|
+
state.message = `compaction failed: ${error?.message ?? error?.code ?? error}`;
|
|
888
|
+
return snapshot();
|
|
889
|
+
};
|
|
890
|
+
if (!compaction || !agent) {
|
|
891
|
+
state.ok = false;
|
|
892
|
+
state.status = 'unavailable';
|
|
893
|
+
state.code = compaction ? 'COMPACTION_NO_AGENT' : 'COMPACTION_UNAVAILABLE';
|
|
894
|
+
state.message = compaction
|
|
895
|
+
? 'no agent on this context; run /compact from the composer instead'
|
|
896
|
+
: 'this profile loads no compaction service; run /compact from the composer instead';
|
|
897
|
+
return snapshot();
|
|
898
|
+
}
|
|
899
|
+
if (dryRun) {
|
|
900
|
+
state.status = 'planned';
|
|
901
|
+
state.message = 'native compaction is available; pass dryRun:false to run it now';
|
|
902
|
+
return snapshot();
|
|
903
|
+
}
|
|
904
|
+
const abort = new AbortController();
|
|
905
|
+
const timer = setTimeout(
|
|
906
|
+
() => abort.abort(new Error('compaction did not start within 10 minutes')),
|
|
907
|
+
10 * 60_000,
|
|
908
|
+
);
|
|
909
|
+
// A queued compaction outlives the tool call; never keep a process alive for it.
|
|
910
|
+
timer.unref?.();
|
|
911
|
+
const run = () => compaction.compactNow(agent, abort.signal, args.sourceCommandId);
|
|
912
|
+
const succeed = (result) => {
|
|
913
|
+
state.status = result === null ? 'nothing-to-compact' : 'compacted';
|
|
914
|
+
state.result = result;
|
|
915
|
+
state.message = result === null
|
|
916
|
+
? 'no compactable history yet'
|
|
917
|
+
: `compacted ${result.shadowedSeqs.length} events (~${result.shadowedTokenCount} tokens), summary at seq ${result.summarySeq}`;
|
|
918
|
+
state.message += ' — verify with session_health: compactionFiles must grow and truncation becomes possible.';
|
|
919
|
+
};
|
|
920
|
+
if (agent.status !== 'idle') {
|
|
921
|
+
state.status = 'scheduled';
|
|
922
|
+
state.message = 'queued: compaction starts as soon as this turn ends';
|
|
923
|
+
agent.whenIdle()
|
|
924
|
+
.then(run)
|
|
925
|
+
.then(succeed)
|
|
926
|
+
.catch((error) => {
|
|
927
|
+
fail(error);
|
|
928
|
+
console.error('[longlive] compaction failed:', error?.message ?? error);
|
|
929
|
+
})
|
|
930
|
+
.finally(() => clearTimeout(timer));
|
|
931
|
+
return snapshot();
|
|
932
|
+
}
|
|
933
|
+
try {
|
|
934
|
+
succeed(await run());
|
|
935
|
+
return snapshot();
|
|
936
|
+
} catch (error) {
|
|
937
|
+
clearTimeout(timer);
|
|
938
|
+
return fail(error);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// ---------------------------------------------------------------------------
|
|
943
|
+
// session_wake — one bounded "where was I" slice of the memory store
|
|
944
|
+
//
|
|
945
|
+
// The wake-up problem: a fresh process cannot afford to read the whole store,
|
|
946
|
+
// but it must not start blind either. So it reads four small, high-value
|
|
947
|
+
// sources and nothing else. Everything is failure-tolerant on purpose: a
|
|
948
|
+
// missing file is a note, never a thrown error, because a wake-up that dies
|
|
949
|
+
// because one file is gone is worse than a wake-up that says "that file is
|
|
950
|
+
// gone" and continues.
|
|
951
|
+
// ---------------------------------------------------------------------------
|
|
952
|
+
|
|
953
|
+
const WAKE_LIMIT = 2500;
|
|
954
|
+
const STATE_SECTIONS = ['我在哪', '在等什么', '最近三件'];
|
|
955
|
+
const STATE_SECTION_CHARS = 400;
|
|
956
|
+
const FLOW_CHARS = 800;
|
|
957
|
+
const JOURNAL_HEADINGS = 3;
|
|
958
|
+
const INDEX_LINES = 20;
|
|
959
|
+
const INDEX_LINE_MAX = 60;
|
|
960
|
+
|
|
961
|
+
/**
|
|
962
|
+
* Resolve the memory-store root used by session_wake / lease_acquire /
|
|
963
|
+
* lease_release. This MUST stay the same resolver as `memory_*` uses
|
|
964
|
+
* (`memoryRootSetting` in ./memory/paths.js): in 0.7.2 these two families had
|
|
965
|
+
* different keys and different defaults, so a user who configured
|
|
966
|
+
* `memoryRoot` still had `session_wake` reading a non-existent drive.
|
|
967
|
+
*
|
|
968
|
+
* Order: config.memoryRoot → config.memRoot → $DSH_LONGLIVE_MEMORY_ROOT →
|
|
969
|
+
* $DSH_MEM → <DSH home>/longlive-memory (created on demand). An explicitly
|
|
970
|
+
* configured root is never created here — a typo must surface as
|
|
971
|
+
* `memRootUnavailable`, not as a silent empty store.
|
|
972
|
+
*/
|
|
973
|
+
export function memRoot(config = {}, env = process.env) {
|
|
974
|
+
const setting = memoryRootSetting(config, env);
|
|
975
|
+
if (setting.explicit) {
|
|
976
|
+
try {
|
|
977
|
+
return path.resolve(setting.explicit);
|
|
978
|
+
} catch {
|
|
979
|
+
return setting.explicit;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
const derived = defaultMemoryRoot(config, env);
|
|
983
|
+
try {
|
|
984
|
+
fs.mkdirSync(derived, { recursive: true });
|
|
985
|
+
} catch {
|
|
986
|
+
// Let memRootUnavailable report the concrete path and the next action.
|
|
987
|
+
}
|
|
988
|
+
return derived;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/**
|
|
992
|
+
* One wording for "the memory root is not there", shared by all three
|
|
993
|
+
* memory-store tools. Every caller gets the same shape: 原因 — 怎么办.
|
|
994
|
+
*/
|
|
995
|
+
function memRootUnavailableMessage(root) {
|
|
996
|
+
return `unavailable: 记忆根目录不存在 ${root} — 创建该目录(mkdir -p),或设置环境变量 ` +
|
|
997
|
+
`${MEMORY_ROOT_ENV}(旧名 ${LEGACY_MEMORY_ROOT_ENV})指向一个已有记忆库;` +
|
|
998
|
+
`插件配置 memoryRoot 优先级最高,默认根是 <DSH home>/${DEFAULT_MEMORY_DIRNAME}`;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** Codes that mean "the root is gone or not writable", never "someone else holds the lease". */
|
|
1002
|
+
const LEASE_WRITE_CODES = new Set(['ENOENT', 'EACCES', 'EPERM']);
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* Pre-flight shared by session_wake / lease_acquire / lease_release.
|
|
1006
|
+
*
|
|
1007
|
+
* Returns null when `root` is an existing directory, else a report-shaped
|
|
1008
|
+
* answer. Never throws: a stat failure (ENOENT/EACCES) is reported, and a path
|
|
1009
|
+
* that stats as a *file* counts as missing because these tools need a directory.
|
|
1010
|
+
*/
|
|
1011
|
+
function memRootUnavailable(root) {
|
|
1012
|
+
let stat = null;
|
|
1013
|
+
try {
|
|
1014
|
+
stat = fs.statSync(root);
|
|
1015
|
+
} catch {
|
|
1016
|
+
stat = null;
|
|
1017
|
+
}
|
|
1018
|
+
if (stat && stat.isDirectory()) return null;
|
|
1019
|
+
return {
|
|
1020
|
+
status: 'unavailable',
|
|
1021
|
+
reason: 'mem root unavailable',
|
|
1022
|
+
memRoot: root,
|
|
1023
|
+
message: memRootUnavailableMessage(root),
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/** Read a text file, reporting a reason instead of throwing. */
|
|
1028
|
+
function readText(file) {
|
|
1029
|
+
try {
|
|
1030
|
+
const stat = fs.statSync(file);
|
|
1031
|
+
if (!stat.isFile()) return { ok: false, code: 'NOT_A_FILE' };
|
|
1032
|
+
return { ok: true, text: fs.readFileSync(file, 'utf8') };
|
|
1033
|
+
} catch (error) {
|
|
1034
|
+
return { ok: false, code: error?.code ?? 'READ_FAILED' };
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
/** Trim to at most `limit` characters; the truncation marker is inside the budget. */
|
|
1039
|
+
function clampText(text, limit, note) {
|
|
1040
|
+
const clean = String(text ?? '').trim();
|
|
1041
|
+
if (clean.length <= limit) return { text: clean, truncated: false };
|
|
1042
|
+
const suffix = note ?? '…';
|
|
1043
|
+
const room = Math.max(0, limit - suffix.length);
|
|
1044
|
+
return { text: clean.slice(0, room) + suffix, truncated: true };
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* Pull the bodies of the headings whose title contains one of `keywords`
|
|
1049
|
+
* (first match per keyword). Body = everything up to the next heading of any
|
|
1050
|
+
* level. Sections are looked up, not assumed to be in a fixed order.
|
|
1051
|
+
*/
|
|
1052
|
+
function extractSections(text, keywords) {
|
|
1053
|
+
const found = new Map();
|
|
1054
|
+
let current = null;
|
|
1055
|
+
let buffer = [];
|
|
1056
|
+
const flush = () => {
|
|
1057
|
+
if (current == null) return;
|
|
1058
|
+
if (!found.has(current)) found.set(current, buffer.join('\n').trim());
|
|
1059
|
+
current = null;
|
|
1060
|
+
buffer = [];
|
|
1061
|
+
};
|
|
1062
|
+
for (const line of String(text ?? '').split(/\r?\n/)) {
|
|
1063
|
+
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
|
|
1064
|
+
if (heading) {
|
|
1065
|
+
flush();
|
|
1066
|
+
const title = heading[2].trim();
|
|
1067
|
+
const hit = keywords.find((keyword) => title.includes(keyword));
|
|
1068
|
+
if (hit != null && !found.has(hit)) current = hit;
|
|
1069
|
+
continue;
|
|
1070
|
+
}
|
|
1071
|
+
if (current != null) buffer.push(line);
|
|
1072
|
+
}
|
|
1073
|
+
flush();
|
|
1074
|
+
return found;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* A session label is display-only. It must never be able to start a new line or
|
|
1079
|
+
* a heading: the wake text is assembled from headings, so a label containing
|
|
1080
|
+
* `\n## …` would forge sections that the memory store never contained.
|
|
1081
|
+
*/
|
|
1082
|
+
function wakeSessionLabel(value) {
|
|
1083
|
+
if (typeof value !== 'string') return null;
|
|
1084
|
+
const cleaned = value
|
|
1085
|
+
.replace(/[\r\n\u2028\u2029]+/g, ' ')
|
|
1086
|
+
.replace(/#/g, '')
|
|
1087
|
+
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
1088
|
+
.replace(/\s+/g, ' ')
|
|
1089
|
+
.trim()
|
|
1090
|
+
.slice(0, 64)
|
|
1091
|
+
.trim();
|
|
1092
|
+
return cleaned || null;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
/** Numeric year/month/day key for journal file names; null when not dated. */
|
|
1096
|
+
function journalTimestamp(name) {
|
|
1097
|
+
const match = /^(\d{4})[-_.](\d{1,2})(?:[-_.](\d{1,2}))?/.exec(name);
|
|
1098
|
+
if (!match) return null;
|
|
1099
|
+
const year = Number(match[1]);
|
|
1100
|
+
const month = Number(match[2]);
|
|
1101
|
+
const day = match[3] ? Number(match[3]) : 0;
|
|
1102
|
+
if (month < 1 || month > 12 || day > 31) return null;
|
|
1103
|
+
return [year, month, day];
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* Newest journal by date, not by string. `.sort()` is lexicographic, so
|
|
1108
|
+
* `2026-9.md` would beat `2026-10.md`; a year/month/day key fixes that.
|
|
1109
|
+
*/
|
|
1110
|
+
function compareJournalNames(a, b) {
|
|
1111
|
+
const left = journalTimestamp(a);
|
|
1112
|
+
const right = journalTimestamp(b);
|
|
1113
|
+
if (left && right) {
|
|
1114
|
+
for (let i = 0; i < 3; i += 1) if (left[i] !== right[i]) return left[i] - right[i];
|
|
1115
|
+
return a.localeCompare(b);
|
|
1116
|
+
}
|
|
1117
|
+
if (left) return 1;
|
|
1118
|
+
if (right) return -1;
|
|
1119
|
+
return a.localeCompare(b);
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/**
|
|
1123
|
+
* Read a bounded wake-up slice of the memory store.
|
|
1124
|
+
*
|
|
1125
|
+
* Order matters: STATE.md (where am I / what am I waiting for / last three
|
|
1126
|
+
* unfinished things) first, then the flow snapshot, then the newest journal's
|
|
1127
|
+
* last three headings, then INDEX.md's short lines. Total output is capped at
|
|
1128
|
+
* WAKE_LIMIT characters; the caller gets `missing` and `sources` so a host can
|
|
1129
|
+
* tell "nothing to say" from "could not read".
|
|
1130
|
+
*/
|
|
1131
|
+
export function sessionWake(args = {}, config = {}) {
|
|
1132
|
+
const root = memRoot(config);
|
|
1133
|
+
const sessionTag = wakeSessionLabel(args.session);
|
|
1134
|
+
const rootProblem = memRootUnavailable(root);
|
|
1135
|
+
if (rootProblem) {
|
|
1136
|
+
return {
|
|
1137
|
+
status: 'unavailable',
|
|
1138
|
+
memRoot: root,
|
|
1139
|
+
session: sessionTag,
|
|
1140
|
+
chars: rootProblem.message.length,
|
|
1141
|
+
message: rootProblem.message,
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
const missing = [];
|
|
1146
|
+
const sources = [];
|
|
1147
|
+
const blocks = [];
|
|
1148
|
+
let truncated = false;
|
|
1149
|
+
blocks.push(`# 醒来 · ${root}${sessionTag ? ` · session=${sessionTag}` : ''}`);
|
|
1150
|
+
|
|
1151
|
+
// 1) STATE.md sections, 400 chars each.
|
|
1152
|
+
const statePath = path.join(root, 'STATE.md');
|
|
1153
|
+
const stateRead = readText(statePath);
|
|
1154
|
+
blocks.push('## STATE.md');
|
|
1155
|
+
if (!stateRead.ok) {
|
|
1156
|
+
missing.push(`STATE.md (${stateRead.code})`);
|
|
1157
|
+
blocks.push(`(跳过:读不到 ${statePath},${stateRead.code})`);
|
|
1158
|
+
} else {
|
|
1159
|
+
sources.push('STATE.md');
|
|
1160
|
+
const sections = extractSections(stateRead.text, STATE_SECTIONS);
|
|
1161
|
+
for (const keyword of STATE_SECTIONS) {
|
|
1162
|
+
const body = sections.get(keyword);
|
|
1163
|
+
if (body == null) {
|
|
1164
|
+
missing.push(`STATE.md › ${keyword}`);
|
|
1165
|
+
blocks.push(`### ${keyword}`, '(跳过:没有这一节)');
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
const capped = clampText(body, STATE_SECTION_CHARS, '…(本节已截断)');
|
|
1169
|
+
if (capped.truncated) truncated = true;
|
|
1170
|
+
blocks.push(`### ${keyword}`, capped.text || '(本节为空)');
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// 2) flow/current.md, 800 chars.
|
|
1175
|
+
const flowPath = path.join(root, 'flow', 'current.md');
|
|
1176
|
+
const flowRead = readText(flowPath);
|
|
1177
|
+
blocks.push('## flow/current.md');
|
|
1178
|
+
if (!flowRead.ok) {
|
|
1179
|
+
missing.push(`flow/current.md (${flowRead.code})`);
|
|
1180
|
+
blocks.push(`(跳过:读不到 ${flowPath},${flowRead.code})`);
|
|
1181
|
+
} else {
|
|
1182
|
+
sources.push('flow/current.md');
|
|
1183
|
+
const capped = clampText(flowRead.text, FLOW_CHARS, '…(已截断:flow/current.md 超过 800 字)');
|
|
1184
|
+
if (capped.truncated) truncated = true;
|
|
1185
|
+
blocks.push(capped.text);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// 3) The newest journal file (largest file name) and its last three ## headings.
|
|
1189
|
+
const journalDir = path.join(root, 'journal');
|
|
1190
|
+
blocks.push('## journal 最新文件的最后 3 个标题');
|
|
1191
|
+
let journalName = null;
|
|
1192
|
+
try {
|
|
1193
|
+
const names = fs
|
|
1194
|
+
.readdirSync(journalDir)
|
|
1195
|
+
.filter((entry) => entry.toLowerCase().endsWith('.md'))
|
|
1196
|
+
.sort(compareJournalNames);
|
|
1197
|
+
if (names.length === 0) {
|
|
1198
|
+
missing.push('journal/*.md');
|
|
1199
|
+
blocks.push(`(跳过:${journalDir} 里没有 .md 文件)`);
|
|
1200
|
+
} else {
|
|
1201
|
+
journalName = names.at(-1);
|
|
1202
|
+
}
|
|
1203
|
+
} catch (error) {
|
|
1204
|
+
missing.push(`journal/ (${error?.code ?? 'READ_FAILED'})`);
|
|
1205
|
+
blocks.push(`(跳过:读不到 ${journalDir},${error?.code ?? 'READ_FAILED'})`);
|
|
1206
|
+
}
|
|
1207
|
+
if (journalName) {
|
|
1208
|
+
const journalPath = path.join(journalDir, journalName);
|
|
1209
|
+
const journalRead = readText(journalPath);
|
|
1210
|
+
if (!journalRead.ok) {
|
|
1211
|
+
missing.push(`journal/${journalName} (${journalRead.code})`);
|
|
1212
|
+
blocks.push(`(跳过:读不到 ${journalPath},${journalRead.code})`);
|
|
1213
|
+
} else {
|
|
1214
|
+
const headings = journalRead.text
|
|
1215
|
+
.split(/\r?\n/)
|
|
1216
|
+
.filter((line) => /^##\s+/.test(line))
|
|
1217
|
+
.map((line) => line.trim())
|
|
1218
|
+
.slice(-JOURNAL_HEADINGS);
|
|
1219
|
+
if (headings.length === 0) {
|
|
1220
|
+
blocks.push(`(journal/${journalName} 里没有 ## 标题)`);
|
|
1221
|
+
} else {
|
|
1222
|
+
sources.push(`journal/${journalName}`);
|
|
1223
|
+
blocks.push(`文件:journal/${journalName}`, ...headings.map((line) => `- ${line}`));
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
// 4) INDEX.md short lines (length < 60), at most 20.
|
|
1229
|
+
const indexPath = path.join(root, 'INDEX.md');
|
|
1230
|
+
const indexRead = readText(indexPath);
|
|
1231
|
+
blocks.push('## INDEX.md 短行');
|
|
1232
|
+
if (!indexRead.ok) {
|
|
1233
|
+
missing.push(`INDEX.md (${indexRead.code})`);
|
|
1234
|
+
blocks.push(`(跳过:读不到 ${indexPath},${indexRead.code})`);
|
|
1235
|
+
} else {
|
|
1236
|
+
sources.push('INDEX.md');
|
|
1237
|
+
const short = indexRead.text
|
|
1238
|
+
.split(/\r?\n/)
|
|
1239
|
+
.map((line) => line.trim())
|
|
1240
|
+
.filter((line) => line.length > 0 && line.length < INDEX_LINE_MAX);
|
|
1241
|
+
const picked = short.slice(0, INDEX_LINES);
|
|
1242
|
+
if (picked.length === 0) {
|
|
1243
|
+
blocks.push('(没有长度小于 60 的行)');
|
|
1244
|
+
} else {
|
|
1245
|
+
blocks.push(...picked.map((line) => `- ${line}`));
|
|
1246
|
+
if (short.length > picked.length) blocks.push(`(另有 ${short.length - picked.length} 行短行未列出)`);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
if (missing.length > 0) blocks.push(`(缺失:${missing.join(';')})`);
|
|
1251
|
+
|
|
1252
|
+
let text = blocks.join('\n').trim();
|
|
1253
|
+
if (text.length > WAKE_LIMIT) {
|
|
1254
|
+
const note = '\n…(整体已截断到 2500 字上限)';
|
|
1255
|
+
const room = WAKE_LIMIT - note.length;
|
|
1256
|
+
// Cut on a line boundary so a half-written INDEX row never ends the wake
|
|
1257
|
+
// text; fall back to a hard cut only if one single line eats the budget.
|
|
1258
|
+
const boundary = text.lastIndexOf('\n', room);
|
|
1259
|
+
text = text.slice(0, boundary > Math.floor(room / 2) ? boundary : room) + note;
|
|
1260
|
+
truncated = true;
|
|
1261
|
+
}
|
|
1262
|
+
return {
|
|
1263
|
+
status: 'ok',
|
|
1264
|
+
memRoot: root,
|
|
1265
|
+
session: sessionTag,
|
|
1266
|
+
chars: text.length,
|
|
1267
|
+
truncated,
|
|
1268
|
+
sources,
|
|
1269
|
+
missing,
|
|
1270
|
+
message: text,
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
// ---------------------------------------------------------------------------
|
|
1275
|
+
// lease_acquire / lease_release — one writer at a time across processes
|
|
1276
|
+
//
|
|
1277
|
+
// The lease is a single file created with O_EXCL ('wx'): the kernel guarantees
|
|
1278
|
+
// exactly one creator, so no read-check-then-write race. Content is a small
|
|
1279
|
+
// JSON record; a record that is dead by TTL (or unparseable) can be replaced,
|
|
1280
|
+
// and replacement is attempted exactly once so two contenders cannot livelock.
|
|
1281
|
+
// ---------------------------------------------------------------------------
|
|
1282
|
+
|
|
1283
|
+
/** A lease longer than a day is a typo, not a plan: it also overflows Date. */
|
|
1284
|
+
const MAX_LEASE_TTL_SEC = 86_400;
|
|
1285
|
+
const MIN_LEASE_TTL_SEC = 1;
|
|
1286
|
+
/** Date can only render milliseconds in this span; outside it toISOString throws. */
|
|
1287
|
+
const MIN_ISO_MS = -8.64e15;
|
|
1288
|
+
const MAX_ISO_MS = 8.64e15;
|
|
1289
|
+
|
|
1290
|
+
/** True when `ms` is a timestamp Date can format without throwing RangeError. */
|
|
1291
|
+
function isSafeDateMs(ms) {
|
|
1292
|
+
return Number.isFinite(ms) && ms >= MIN_ISO_MS && ms <= MAX_ISO_MS;
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
/** ISO string, or null when the timestamp is not representable. Never throws. */
|
|
1296
|
+
function isoOrNull(ms) {
|
|
1297
|
+
return isSafeDateMs(ms) ? new Date(ms).toISOString() : null;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
function leasePayloadOf(holder, ttlSec, now = Date.now()) {
|
|
1301
|
+
// expiresAt is built and validated before the record is written: a lease that
|
|
1302
|
+
// cannot state when it ends must never reach the disk (it used to be written
|
|
1303
|
+
// first and throw afterwards, leaving every later caller stuck).
|
|
1304
|
+
const expiresAt = isoOrNull(now + ttlSec * 1000);
|
|
1305
|
+
if (!expiresAt) {
|
|
1306
|
+
const error = new Error('lease expiry is out of the representable date range');
|
|
1307
|
+
error.code = 'BAD_ARGUMENT';
|
|
1308
|
+
throw error;
|
|
1309
|
+
}
|
|
1310
|
+
return { holder, pid: process.pid, acquiredAt: new Date(now).toISOString(), expiresAt, ttlSec };
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
/**
|
|
1314
|
+
* "The root passed the pre-flight but the .lease file still could not be
|
|
1315
|
+
* created" — the directory vanished between the check and the open, or it is
|
|
1316
|
+
* not writable. Same shape as the missing-root answer, with the OS code kept in
|
|
1317
|
+
* parentheses so the cause is diagnosable without dumping a bare ENOENT.
|
|
1318
|
+
*/
|
|
1319
|
+
function leaseCreateUnavailable(leasePath, holder, code) {
|
|
1320
|
+
return {
|
|
1321
|
+
ok: false,
|
|
1322
|
+
status: 'unavailable',
|
|
1323
|
+
reason: 'mem root not writable',
|
|
1324
|
+
code,
|
|
1325
|
+
leasePath,
|
|
1326
|
+
holder: null,
|
|
1327
|
+
requestedHolder: holder,
|
|
1328
|
+
message: `unavailable: 无法在 ${leasePath} 创建租约文件(${code})— 检查记忆根目录是否存在且可写`,
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/** Read and parse the lease file without throwing. */
|
|
1333
|
+
function readLease(file) {
|
|
1334
|
+
let text;
|
|
1335
|
+
try {
|
|
1336
|
+
text = fs.readFileSync(file, 'utf8');
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
return { ok: false, code: error?.code ?? 'READ_FAILED', lease: null };
|
|
1339
|
+
}
|
|
1340
|
+
try {
|
|
1341
|
+
const lease = JSON.parse(text);
|
|
1342
|
+
if (!lease || typeof lease !== 'object' || Array.isArray(lease)) {
|
|
1343
|
+
return { ok: false, code: 'INVALID', lease: null };
|
|
1344
|
+
}
|
|
1345
|
+
return { ok: true, lease };
|
|
1346
|
+
} catch {
|
|
1347
|
+
return { ok: false, code: 'INVALID', lease: null };
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
/** TTL judgement: no usable acquiredAt/ttlSec counts as expired. */
|
|
1352
|
+
/**
|
|
1353
|
+
* Decide whether a lease record is still valid, and when it ends.
|
|
1354
|
+
*
|
|
1355
|
+
* A corrupt expiry must never be able to wedge the memory root: a record whose
|
|
1356
|
+
* `expiresAt` is unparseable, NaN or outside the representable date range is
|
|
1357
|
+
* treated as expired, so the next writer takes it over instead of crashing on
|
|
1358
|
+
* every read (the old code called new Date(expiresAt).toISOString() and threw
|
|
1359
|
+
* RangeError here, locking every later caller out of the lease).
|
|
1360
|
+
*/
|
|
1361
|
+
function leaseExpiry(lease) {
|
|
1362
|
+
const acquiredMs = typeof lease?.acquiredAt === 'string' ? Date.parse(lease.acquiredAt) : NaN;
|
|
1363
|
+
const ttlSec = Number(lease?.ttlSec);
|
|
1364
|
+
const declared = lease && lease.expiresAt !== undefined && lease.expiresAt !== null
|
|
1365
|
+
? (typeof lease.expiresAt === 'string' ? Date.parse(lease.expiresAt) : NaN)
|
|
1366
|
+
: null;
|
|
1367
|
+
|
|
1368
|
+
// An explicit expiresAt is authoritative when it is usable. When it is not,
|
|
1369
|
+
// the record cannot be trusted to still hold the lease — treat it as expired.
|
|
1370
|
+
if (declared !== null) {
|
|
1371
|
+
if (!isSafeDateMs(declared)) return { valid: false, expired: true, expiresAt: null, reason: 'bad-expiresAt' };
|
|
1372
|
+
return { valid: true, expired: Date.now() >= declared, expiresAt: declared };
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
if (!Number.isFinite(acquiredMs) || !isSafeDateMs(acquiredMs)) {
|
|
1376
|
+
return { valid: false, expired: true, expiresAt: null, reason: 'bad-acquiredAt' };
|
|
1377
|
+
}
|
|
1378
|
+
if (!Number.isFinite(ttlSec) || ttlSec < MIN_LEASE_TTL_SEC || ttlSec > MAX_LEASE_TTL_SEC) {
|
|
1379
|
+
return { valid: false, expired: true, expiresAt: null, reason: 'bad-ttl' };
|
|
1380
|
+
}
|
|
1381
|
+
const expiresAt = acquiredMs + ttlSec * 1000;
|
|
1382
|
+
if (!isSafeDateMs(expiresAt)) {
|
|
1383
|
+
return { valid: false, expired: true, expiresAt: null, reason: 'expiry-out-of-range' };
|
|
1384
|
+
}
|
|
1385
|
+
return { valid: true, expired: Date.now() >= expiresAt, expiresAt };
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
/**
|
|
1389
|
+
* Atomic create: openSync(path, 'wx') fails with EEXIST when the lease exists,
|
|
1390
|
+
* and succeeds for exactly one writer when it does not.
|
|
1391
|
+
*
|
|
1392
|
+
* After writing we re-read the file. A contender that observes our still-empty
|
|
1393
|
+
* file treats it as expired, unlinks it and creates its own — the re-read makes
|
|
1394
|
+
* sure the lease that survives is ours, so two writers never both report ok.
|
|
1395
|
+
*/
|
|
1396
|
+
function createLease(file, payload) {
|
|
1397
|
+
const text = JSON.stringify(payload);
|
|
1398
|
+
let fd;
|
|
1399
|
+
try {
|
|
1400
|
+
fd = fs.openSync(file, 'wx');
|
|
1401
|
+
} catch (error) {
|
|
1402
|
+
return { created: false, error };
|
|
1403
|
+
}
|
|
1404
|
+
try {
|
|
1405
|
+
fs.writeFileSync(fd, text, 'utf8');
|
|
1406
|
+
try { fs.fsyncSync(fd); } catch { /* best effort: durability is not the contract */ }
|
|
1407
|
+
} finally {
|
|
1408
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
1409
|
+
}
|
|
1410
|
+
let seen = null;
|
|
1411
|
+
try { seen = fs.readFileSync(file, 'utf8'); } catch { seen = null; }
|
|
1412
|
+
if (seen !== text) {
|
|
1413
|
+
const error = new Error('lease changed while it was being created');
|
|
1414
|
+
error.code = 'LEASE_RACE';
|
|
1415
|
+
return { created: false, raceLost: true, error };
|
|
1416
|
+
}
|
|
1417
|
+
return { created: true };
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
function acquireOk(leasePath, payload, extra = {}) {
|
|
1421
|
+
const expiry = leaseExpiry(payload);
|
|
1422
|
+
return {
|
|
1423
|
+
ok: true,
|
|
1424
|
+
leasePath,
|
|
1425
|
+
holder: payload.holder,
|
|
1426
|
+
pid: payload.pid,
|
|
1427
|
+
acquiredAt: payload.acquiredAt,
|
|
1428
|
+
ttlSec: payload.ttlSec,
|
|
1429
|
+
expiresAt: isoOrNull(expiry.expiresAt),
|
|
1430
|
+
...extra,
|
|
1431
|
+
message: `${extra.tookOver ? 'lease taken over' : 'lease acquired'} by ${payload.holder} (pid ${payload.pid}) for ${payload.ttlSec}s`,
|
|
1432
|
+
};
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
function heldBy(leasePath, lease, requestedHolder, message) {
|
|
1436
|
+
const expiry = leaseExpiry(lease);
|
|
1437
|
+
return {
|
|
1438
|
+
ok: false,
|
|
1439
|
+
reason: 'held by another writer',
|
|
1440
|
+
leasePath,
|
|
1441
|
+
holder: typeof lease?.holder === 'string' ? lease.holder : null,
|
|
1442
|
+
acquiredAt: typeof lease?.acquiredAt === 'string' ? lease.acquiredAt : null,
|
|
1443
|
+
pid: Number.isInteger(lease?.pid) ? lease.pid : null,
|
|
1444
|
+
ttlSec: Number.isFinite(Number(lease?.ttlSec)) ? Number(lease.ttlSec) : null,
|
|
1445
|
+
expiresAt: isoOrNull(expiry.expiresAt),
|
|
1446
|
+
requestedHolder,
|
|
1447
|
+
message: message ?? `lease is held by ${lease?.holder ?? '(unknown holder)'} since ${lease?.acquiredAt ?? '(unknown time)'} — reason: held by another writer`,
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
/** Take the lease for `holder`; TTL default 300s. Exactly one caller wins per lease. */
|
|
1452
|
+
export function leaseAcquire(args = {}, config = {}) {
|
|
1453
|
+
const root = memRoot(config);
|
|
1454
|
+
const holder = typeof args.holder === 'string' ? args.holder.trim() : '';
|
|
1455
|
+
const leasePath = path.join(root, '.lease');
|
|
1456
|
+
// Checked before anything opens a path under the root: on a host with no
|
|
1457
|
+
// memory store, openSync('wx') used to surface a bare ENOENT that said
|
|
1458
|
+
// nothing about what to do. Must be a directory, not just an existing path.
|
|
1459
|
+
const rootProblem = memRootUnavailable(root);
|
|
1460
|
+
if (rootProblem) {
|
|
1461
|
+
return { ok: false, ...rootProblem, leasePath, holder: null, requestedHolder: holder || null };
|
|
1462
|
+
}
|
|
1463
|
+
if (!holder) {
|
|
1464
|
+
return {
|
|
1465
|
+
ok: false,
|
|
1466
|
+
reason: 'holder required',
|
|
1467
|
+
leasePath,
|
|
1468
|
+
holder: null,
|
|
1469
|
+
requestedHolder: null,
|
|
1470
|
+
message: 'lease_acquire needs holder (a non-empty string)',
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
if (args.ttlSec !== undefined && args.ttlSec !== null
|
|
1474
|
+
&& !(Number.isInteger(args.ttlSec)
|
|
1475
|
+
&& args.ttlSec >= MIN_LEASE_TTL_SEC && args.ttlSec <= MAX_LEASE_TTL_SEC)) {
|
|
1476
|
+
return {
|
|
1477
|
+
ok: false,
|
|
1478
|
+
status: 'error',
|
|
1479
|
+
reason: 'invalid ttlSec',
|
|
1480
|
+
code: 'BAD_ARGUMENT',
|
|
1481
|
+
leasePath,
|
|
1482
|
+
holder: null,
|
|
1483
|
+
requestedHolder: holder,
|
|
1484
|
+
message: `ttlSec 必须是 ${MIN_LEASE_TTL_SEC}..${MAX_LEASE_TTL_SEC} 之间的整数(秒)`,
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
const ttlSec = Number.isInteger(args.ttlSec)
|
|
1488
|
+
&& args.ttlSec >= MIN_LEASE_TTL_SEC && args.ttlSec <= MAX_LEASE_TTL_SEC
|
|
1489
|
+
? args.ttlSec : 300;
|
|
1490
|
+
|
|
1491
|
+
// memRoot creates only the derived default; an explicitly configured root
|
|
1492
|
+
// that is missing was reported above and must not be created here — that
|
|
1493
|
+
// would hide the exact misconfiguration the message explains.
|
|
1494
|
+
const payload = leasePayloadOf(holder, ttlSec);
|
|
1495
|
+
const first = createLease(leasePath, payload);
|
|
1496
|
+
if (first.created) return acquireOk(leasePath, payload);
|
|
1497
|
+
if (!first.raceLost && LEASE_WRITE_CODES.has(first.error?.code)) {
|
|
1498
|
+
return leaseCreateUnavailable(leasePath, holder, first.error.code);
|
|
1499
|
+
}
|
|
1500
|
+
if (first.error?.code !== 'EEXIST' && !first.raceLost) {
|
|
1501
|
+
return {
|
|
1502
|
+
ok: false,
|
|
1503
|
+
reason: 'lease io error',
|
|
1504
|
+
code: first.error?.code ?? 'UNKNOWN',
|
|
1505
|
+
leasePath,
|
|
1506
|
+
requestedHolder: holder,
|
|
1507
|
+
message: `cannot create ${leasePath}: ${first.error?.code ?? first.error?.message}`,
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
const seen = readLease(leasePath);
|
|
1512
|
+
if (seen.ok) {
|
|
1513
|
+
const expiry = leaseExpiry(seen.lease);
|
|
1514
|
+
if (expiry.valid && !expiry.expired) return heldBy(leasePath, seen.lease, holder);
|
|
1515
|
+
}
|
|
1516
|
+
const previous = seen.ok
|
|
1517
|
+
? { holder: seen.lease.holder ?? null, acquiredAt: seen.lease.acquiredAt ?? null, expired: true }
|
|
1518
|
+
: null;
|
|
1519
|
+
|
|
1520
|
+
// Expired (or unreadable, or vanished) — clear it and retry exactly once.
|
|
1521
|
+
try {
|
|
1522
|
+
fs.unlinkSync(leasePath);
|
|
1523
|
+
} catch (error) {
|
|
1524
|
+
if (error?.code !== 'ENOENT') {
|
|
1525
|
+
return {
|
|
1526
|
+
ok: false,
|
|
1527
|
+
reason: 'lease io error',
|
|
1528
|
+
code: error?.code ?? 'UNKNOWN',
|
|
1529
|
+
leasePath,
|
|
1530
|
+
requestedHolder: holder,
|
|
1531
|
+
message: `cannot clear expired lease ${leasePath}: ${error?.code ?? error?.message}`,
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
const second = createLease(leasePath, payload);
|
|
1536
|
+
if (second.created) return acquireOk(leasePath, payload, { tookOver: true, previous });
|
|
1537
|
+
if (!second.raceLost && LEASE_WRITE_CODES.has(second.error?.code)) {
|
|
1538
|
+
return leaseCreateUnavailable(leasePath, holder, second.error.code);
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
const now = readLease(leasePath);
|
|
1542
|
+
if (now.ok) return heldBy(leasePath, now.lease, holder, 'lost the takeover race — reason: held by another writer');
|
|
1543
|
+
return {
|
|
1544
|
+
ok: false,
|
|
1545
|
+
reason: 'held by another writer',
|
|
1546
|
+
leasePath,
|
|
1547
|
+
holder: null,
|
|
1548
|
+
acquiredAt: null,
|
|
1549
|
+
requestedHolder: holder,
|
|
1550
|
+
message: 'lost the takeover race and the lease vanished — retry lease_acquire',
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/** Release the lease, but only for the holder recorded inside it. */
|
|
1555
|
+
export function leaseRelease(args = {}, config = {}) {
|
|
1556
|
+
const root = memRoot(config);
|
|
1557
|
+
const holder = typeof args.holder === 'string' ? args.holder.trim() : '';
|
|
1558
|
+
const leasePath = path.join(root, '.lease');
|
|
1559
|
+
// Same pre-flight as lease_acquire: "no lease at <root>/.lease" is a wrong
|
|
1560
|
+
// answer when the root itself does not exist.
|
|
1561
|
+
const rootProblem = memRootUnavailable(root);
|
|
1562
|
+
if (rootProblem) {
|
|
1563
|
+
return { ok: false, ...rootProblem, leasePath, holder: null, requestedHolder: holder || null };
|
|
1564
|
+
}
|
|
1565
|
+
if (!holder) {
|
|
1566
|
+
return {
|
|
1567
|
+
ok: false,
|
|
1568
|
+
reason: 'holder required',
|
|
1569
|
+
leasePath,
|
|
1570
|
+
holder: null,
|
|
1571
|
+
requestedHolder: null,
|
|
1572
|
+
message: 'lease_release needs holder (a non-empty string)',
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
const seen = readLease(leasePath);
|
|
1576
|
+
if (!seen.ok) {
|
|
1577
|
+
if (seen.code === 'ENOENT') {
|
|
1578
|
+
return {
|
|
1579
|
+
ok: false,
|
|
1580
|
+
reason: 'no lease',
|
|
1581
|
+
leasePath,
|
|
1582
|
+
holder: null,
|
|
1583
|
+
requestedHolder: holder,
|
|
1584
|
+
message: `no lease at ${leasePath}`,
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
return {
|
|
1588
|
+
ok: false,
|
|
1589
|
+
reason: 'lease unreadable',
|
|
1590
|
+
code: seen.code,
|
|
1591
|
+
leasePath,
|
|
1592
|
+
holder: null,
|
|
1593
|
+
requestedHolder: holder,
|
|
1594
|
+
message: `lease at ${leasePath} is unreadable (${seen.code}); refusing to delete it`,
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
const current = typeof seen.lease?.holder === 'string' ? seen.lease.holder : null;
|
|
1598
|
+
if (current !== holder) {
|
|
1599
|
+
return {
|
|
1600
|
+
ok: false,
|
|
1601
|
+
reason: 'not the holder',
|
|
1602
|
+
leasePath,
|
|
1603
|
+
holder: current,
|
|
1604
|
+
requestedHolder: holder,
|
|
1605
|
+
message: `lease is held by ${current ?? '(unknown holder)'}; ${holder} may not release it`,
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
1608
|
+
try {
|
|
1609
|
+
fs.unlinkSync(leasePath);
|
|
1610
|
+
} catch (error) {
|
|
1611
|
+
if (error?.code === 'ENOENT') {
|
|
1612
|
+
// Someone removed it between our read and our unlink: the lease is gone,
|
|
1613
|
+
// which is the outcome the holder asked for.
|
|
1614
|
+
return { ok: true, released: true, alreadyGone: true, leasePath, holder, message: `lease released by ${holder} (already removed)` };
|
|
1615
|
+
}
|
|
1616
|
+
return {
|
|
1617
|
+
ok: false,
|
|
1618
|
+
reason: 'lease io error',
|
|
1619
|
+
code: error?.code ?? 'UNKNOWN',
|
|
1620
|
+
leasePath,
|
|
1621
|
+
holder,
|
|
1622
|
+
requestedHolder: holder,
|
|
1623
|
+
message: `cannot delete ${leasePath}: ${error?.code ?? error?.message}`,
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
return { ok: true, released: true, leasePath, holder, message: `lease released by ${holder}` };
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
// ---------------------------------------------------------------------------
|
|
1630
|
+
// worker_* — background child sessions through the host `subagents` service
|
|
1631
|
+
//
|
|
1632
|
+
// The Cordis service key is the string "subagents", and it must be read with
|
|
1633
|
+
// ctx.get('subagents'): a bare ctx.subagents read is blocked by the inject guard
|
|
1634
|
+
// because this plugin only injects ['tools'].
|
|
1635
|
+
//
|
|
1636
|
+
// Confirmed against @deepseek-ai/dsh-subagent/lib/index.js:
|
|
1637
|
+
// async startActivation(spec) (index.js:3036)
|
|
1638
|
+
// spec = { provider, label?, request: { prompt, parent, ... }, signal, delivery }
|
|
1639
|
+
// request.prompt is an ARRAY of content parts — [{ type: 'text', text }]
|
|
1640
|
+
// request.parent must be the exact live Agent object from the registry (:3045)
|
|
1641
|
+
// returns { childId, messageId, result, dispose } (manager.js:400 -> receipt at :2072)
|
|
1642
|
+
// interrupt(targetSessionId, authority) (index.js:3105)
|
|
1643
|
+
// authority = { kind: 'ancestor', agent } | { kind: 'user', parentSessionId }
|
|
1644
|
+
// an absent target is an accepted no-op, so existence is proven first
|
|
1645
|
+
//
|
|
1646
|
+
// Every failure is reported as "unavailable: …" and never thrown: a tool that
|
|
1647
|
+
// throws takes the whole turn down, while a tool that degrades tells the model
|
|
1648
|
+
// what to do next. Same wording discipline as session_wake / lease_*.
|
|
1649
|
+
// ---------------------------------------------------------------------------
|
|
1650
|
+
|
|
1651
|
+
const DEFAULT_WORKER_TIMEOUT_SEC = 600;
|
|
1652
|
+
const WORKER_NO_SERVICE = 'unavailable: 本宿主未提供 subagents 服务';
|
|
1653
|
+
|
|
1654
|
+
/**
|
|
1655
|
+
* 1.6.0 safety default (abuse assessment §3.1 / §4.1): the three fan-out tools
|
|
1656
|
+
* stay in the documented 22-tool table so the surface stays stable, but every
|
|
1657
|
+
* host invocation returns `status:'unavailable'` until the profile explicitly
|
|
1658
|
+
* sets `workers.enabled: true`. A switch, not a removal, keeps the tool list
|
|
1659
|
+
* byte-identical to 1.5.0 while taking the capability away by default.
|
|
1660
|
+
*/
|
|
1661
|
+
export const WORKER_TOOL_NAMES = Object.freeze(['worker_spawn', 'worker_status', 'worker_kill']);
|
|
1662
|
+
export const WORKERS_DEFAULTS = Object.freeze({ enabled: true });
|
|
1663
|
+
export const WORKERS_DISABLED_MESSAGE =
|
|
1664
|
+
'unavailable: worker_* 已关闭(workers.enabled=false);需要派子会话时显式设置 workers.enabled: true';
|
|
1665
|
+
|
|
1666
|
+
function workerUnavailable(message) {
|
|
1667
|
+
return { ok: false, status: 'unavailable', available: false, message };
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
/** `code: message` when there is one, else `String(error)`; never empty. */
|
|
1671
|
+
function errorDetail(error) {
|
|
1672
|
+
if (!error) return '未知原因';
|
|
1673
|
+
const code = error.code ? `${error.code}: ` : '';
|
|
1674
|
+
return `${code}${error.message ?? String(error)}`;
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
/** Reach the plugin's Cordis context without letting a host() throw escape. */
|
|
1678
|
+
function safeHost(config = {}) {
|
|
1679
|
+
try {
|
|
1680
|
+
return typeof config.host === 'function' ? config.host() ?? null : null;
|
|
1681
|
+
} catch {
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
/**
|
|
1687
|
+
* The exact live Agent that authorizes a child. `exec.agent` is the calling
|
|
1688
|
+
* agent handed to every tool execution (dsh-tool-subagent uses the same field);
|
|
1689
|
+
* probed only as a fallback so plain-node tests and older hosts still resolve.
|
|
1690
|
+
*/
|
|
1691
|
+
function workerParent(config = {}) {
|
|
1692
|
+
const exec = config.exec;
|
|
1693
|
+
const fromExec = exec && typeof exec === 'object' ? exec.agent : null;
|
|
1694
|
+
if (fromExec) return fromExec;
|
|
1695
|
+
return probeService(safeHost(config), 'agent');
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
function workerIdArg(args = {}) {
|
|
1699
|
+
return typeof args.workerId === 'string' ? args.workerId.trim() : '';
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
/**
|
|
1703
|
+
* Pick a provider without hard-coding one: ask the service what it has.
|
|
1704
|
+
* Continuable providers (correct `prepareContinuable`, i.e. the in-process
|
|
1705
|
+
* spawn/fork backends) are preferred, because only they can honor a reserved
|
|
1706
|
+
* child id and report progress by session id.
|
|
1707
|
+
*/
|
|
1708
|
+
function chooseWorkerProvider(subagents) {
|
|
1709
|
+
let names = [];
|
|
1710
|
+
try {
|
|
1711
|
+
names = typeof subagents.list === 'function' ? subagents.list() : [];
|
|
1712
|
+
} catch {
|
|
1713
|
+
names = [];
|
|
1714
|
+
}
|
|
1715
|
+
if (!Array.isArray(names) || names.length === 0) return null;
|
|
1716
|
+
const continuable = [];
|
|
1717
|
+
for (const name of names) {
|
|
1718
|
+
try {
|
|
1719
|
+
const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(name) : null;
|
|
1720
|
+
if (provider && typeof provider.prepareContinuable === 'function') continuable.push(name);
|
|
1721
|
+
} catch {
|
|
1722
|
+
// A lookup failure is not fatal; fall back to registration order below.
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
const pool = continuable.length > 0 ? continuable : names;
|
|
1726
|
+
for (const preferred of ['spawn', 'fork']) {
|
|
1727
|
+
if (pool.includes(preferred)) return preferred;
|
|
1728
|
+
}
|
|
1729
|
+
return pool[0];
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
/** One dispatched worker: return its id, never its promise, never throw. */
|
|
1733
|
+
export async function workerSpawn(args = {}, config = {}) {
|
|
1734
|
+
const prompt = typeof args.prompt === 'string' ? args.prompt.trim() : '';
|
|
1735
|
+
if (!prompt) return workerUnavailable('unavailable: 缺少必填参数 prompt(要派给子会话的任务文本)');
|
|
1736
|
+
if (args.timeoutSec !== undefined && args.timeoutSec !== null
|
|
1737
|
+
&& !(Number.isInteger(args.timeoutSec) && args.timeoutSec >= 1)) {
|
|
1738
|
+
return {
|
|
1739
|
+
ok: false,
|
|
1740
|
+
status: 'error',
|
|
1741
|
+
reason: 'invalid timeoutSec',
|
|
1742
|
+
code: 'BAD_ARGUMENT',
|
|
1743
|
+
message: 'timeoutSec 必须是 >= 1 的整数(秒)',
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
const labelArg = typeof args.label === 'string' ? args.label.trim() : '';
|
|
1747
|
+
const timeoutSec = Number.isInteger(args.timeoutSec) && args.timeoutSec >= 1
|
|
1748
|
+
? Math.min(args.timeoutSec, 24 * 60 * 60)
|
|
1749
|
+
: DEFAULT_WORKER_TIMEOUT_SEC;
|
|
1750
|
+
const host = safeHost(config);
|
|
1751
|
+
const subagents = probeService(host, 'subagents');
|
|
1752
|
+
if (!subagents || typeof subagents.startActivation !== 'function') {
|
|
1753
|
+
return workerUnavailable(WORKER_NO_SERVICE);
|
|
1754
|
+
}
|
|
1755
|
+
const parent = workerParent(config);
|
|
1756
|
+
if (!parent || typeof parent.id !== 'string' || parent.id.length === 0) {
|
|
1757
|
+
return workerUnavailable('unavailable: 开子会话失败(当前上下文没有活着的 Agent,spec.request.parent 必须是注册表里的活 Agent)');
|
|
1758
|
+
}
|
|
1759
|
+
const provider = chooseWorkerProvider(subagents);
|
|
1760
|
+
if (!provider) {
|
|
1761
|
+
return workerUnavailable('unavailable: 开子会话失败(subagents 服务没有注册任何 provider)');
|
|
1762
|
+
}
|
|
1763
|
+
const label = (labelArg || prompt).slice(0, 120);
|
|
1764
|
+
const controller = new AbortController();
|
|
1765
|
+
const timer = setTimeout(
|
|
1766
|
+
() => controller.abort(new Error(`worker_spawn 超过 ${timeoutSec} 秒仍未派发完成`)),
|
|
1767
|
+
timeoutSec * 1000,
|
|
1768
|
+
);
|
|
1769
|
+
// A dispatched child outlives this tool call; never keep the process alive.
|
|
1770
|
+
timer.unref?.();
|
|
1771
|
+
let signal = controller.signal;
|
|
1772
|
+
try {
|
|
1773
|
+
const callerSignal = config.exec?.signal;
|
|
1774
|
+
if (callerSignal && typeof AbortSignal !== 'undefined' && typeof AbortSignal.any === 'function') {
|
|
1775
|
+
signal = AbortSignal.any([callerSignal, controller.signal]);
|
|
1776
|
+
}
|
|
1777
|
+
} catch {
|
|
1778
|
+
signal = controller.signal;
|
|
1779
|
+
}
|
|
1780
|
+
try {
|
|
1781
|
+
const started = await subagents.startActivation({
|
|
1782
|
+
provider,
|
|
1783
|
+
label,
|
|
1784
|
+
request: {
|
|
1785
|
+
// Confirmed shape (dsh-tool-subagent/lib/index.js:464): content parts,
|
|
1786
|
+
// not a bare string.
|
|
1787
|
+
prompt: [{ type: 'text', text: prompt }],
|
|
1788
|
+
parent,
|
|
1789
|
+
},
|
|
1790
|
+
signal,
|
|
1791
|
+
delivery: 'parent',
|
|
1792
|
+
});
|
|
1793
|
+
const workerId = typeof started?.childId === 'string' && started.childId.length > 0 ? started.childId : null;
|
|
1794
|
+
if (!workerId) {
|
|
1795
|
+
return workerUnavailable('unavailable: 开子会话失败(startActivation 没有返回 childId)');
|
|
1796
|
+
}
|
|
1797
|
+
return {
|
|
1798
|
+
ok: true,
|
|
1799
|
+
status: 'dispatched',
|
|
1800
|
+
available: true,
|
|
1801
|
+
workerId,
|
|
1802
|
+
provider,
|
|
1803
|
+
label,
|
|
1804
|
+
messageId: typeof started?.messageId === 'string' ? started.messageId : null,
|
|
1805
|
+
timeoutSec,
|
|
1806
|
+
parentSessionId: parent.id,
|
|
1807
|
+
message: `已派发 ${workerId}(provider ${provider},label "${label}",超时 ${timeoutSec} 秒)`,
|
|
1808
|
+
};
|
|
1809
|
+
} catch (error) {
|
|
1810
|
+
return workerUnavailable(`unavailable: 开子会话失败(${errorDetail(error)})`);
|
|
1811
|
+
} finally {
|
|
1812
|
+
clearTimeout(timer);
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
/**
|
|
1817
|
+
* Where a worker stands. Three layers, cheapest first: the live Agent registry,
|
|
1818
|
+
* the parent-owned child catalog, then the persisted session log. A worker that
|
|
1819
|
+
* is none of the three does not exist.
|
|
1820
|
+
*/
|
|
1821
|
+
export async function workerStatus(args = {}, config = {}) {
|
|
1822
|
+
const workerId = workerIdArg(args);
|
|
1823
|
+
if (!workerId) return workerUnavailable('unavailable: 缺少必填参数 workerId(worker_spawn 返回的 id)');
|
|
1824
|
+
const host = safeHost(config);
|
|
1825
|
+
const home = config.home ?? dshHome();
|
|
1826
|
+
|
|
1827
|
+
// 1) Live: local children stay in the Agent registry while they run.
|
|
1828
|
+
const agents = probeService(host, 'agents');
|
|
1829
|
+
let live = null;
|
|
1830
|
+
try {
|
|
1831
|
+
live = agents && typeof agents.get === 'function' ? agents.get(workerId) : null;
|
|
1832
|
+
} catch {
|
|
1833
|
+
live = null;
|
|
1834
|
+
}
|
|
1835
|
+
const persisted = listSessions(home).find((session) => session.id === workerId) ?? null;
|
|
1836
|
+
if (live) {
|
|
1837
|
+
const status = typeof live.status === 'string' && live.status.length > 0 ? live.status : 'unknown';
|
|
1838
|
+
let events = null;
|
|
1839
|
+
let lastEventType = null;
|
|
1840
|
+
try {
|
|
1841
|
+
const snapshot = typeof live.session?.snapshotEvents === 'function' ? live.session.snapshotEvents() : null;
|
|
1842
|
+
if (Array.isArray(snapshot)) {
|
|
1843
|
+
events = snapshot.length;
|
|
1844
|
+
lastEventType = snapshot.length > 0 ? snapshot.at(-1)?.type ?? null : null;
|
|
1845
|
+
}
|
|
1846
|
+
} catch {
|
|
1847
|
+
events = null;
|
|
1848
|
+
}
|
|
1849
|
+
return {
|
|
1850
|
+
ok: true,
|
|
1851
|
+
status,
|
|
1852
|
+
available: true,
|
|
1853
|
+
live: true,
|
|
1854
|
+
workerId,
|
|
1855
|
+
events,
|
|
1856
|
+
lastEventType,
|
|
1857
|
+
lastMessageAt: persisted ? new Date(persisted.mtimeMs).toISOString() : null,
|
|
1858
|
+
sessionPath: persisted?.file ?? null,
|
|
1859
|
+
message: `worker ${workerId} 活着,状态 ${status}${events === null ? '' : `,已记 ${events} 个事件`}`,
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
// 2) Catalog: durable direct-child rows owned by this parent (needs the
|
|
1864
|
+
// sessionQuery service; degrade to the log when it is absent).
|
|
1865
|
+
const subagents = probeService(host, 'subagents');
|
|
1866
|
+
const parent = workerParent(config);
|
|
1867
|
+
let catalogRow = null;
|
|
1868
|
+
if (subagents && typeof subagents.listChildren === 'function' && parent && typeof parent.id === 'string') {
|
|
1869
|
+
try {
|
|
1870
|
+
const rows = await subagents.listChildren(parent.id, undefined);
|
|
1871
|
+
catalogRow = Array.isArray(rows) ? rows.find((row) => row && row.id === workerId) ?? null : null;
|
|
1872
|
+
} catch {
|
|
1873
|
+
catalogRow = null;
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
// 3) Persisted session log: events count, last message time, and a status word.
|
|
1878
|
+
if (persisted) {
|
|
1879
|
+
let events = null;
|
|
1880
|
+
let lastEventType = null;
|
|
1881
|
+
try {
|
|
1882
|
+
const parsed = parseSession(fs.readFileSync(persisted.file));
|
|
1883
|
+
events = parsed.events.length;
|
|
1884
|
+
lastEventType = parsed.events.at(-1)?.type ?? null;
|
|
1885
|
+
} catch {
|
|
1886
|
+
events = null;
|
|
1887
|
+
}
|
|
1888
|
+
const state = catalogRow ? 'inactive-child' : 'persisted';
|
|
1889
|
+
const lastMessageAt = new Date(persisted.mtimeMs).toISOString();
|
|
1890
|
+
return {
|
|
1891
|
+
ok: true,
|
|
1892
|
+
status: state,
|
|
1893
|
+
available: true,
|
|
1894
|
+
live: false,
|
|
1895
|
+
workerId,
|
|
1896
|
+
events,
|
|
1897
|
+
lastEventType,
|
|
1898
|
+
lastMessageAt,
|
|
1899
|
+
sessionPath: persisted.file,
|
|
1900
|
+
catalog: catalogRow,
|
|
1901
|
+
message: `worker ${workerId} 不在运行:状态 ${state},${events === null ? '事件数未知' : `${events} 个事件`},最后写入 ${lastMessageAt}`,
|
|
1902
|
+
};
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
if (catalogRow) {
|
|
1906
|
+
return {
|
|
1907
|
+
ok: true,
|
|
1908
|
+
status: 'inactive',
|
|
1909
|
+
available: true,
|
|
1910
|
+
live: false,
|
|
1911
|
+
workerId,
|
|
1912
|
+
events: null,
|
|
1913
|
+
lastEventType: null,
|
|
1914
|
+
lastMessageAt: null,
|
|
1915
|
+
sessionPath: null,
|
|
1916
|
+
catalog: catalogRow,
|
|
1917
|
+
message: `worker ${workerId} 在子会话目录里,但既不在运行也没有会话文件可读`,
|
|
1918
|
+
};
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
return workerUnavailable('unavailable: 找不到这个 worker');
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
/**
|
|
1925
|
+
* Stop a running worker. `interrupt` is fire-and-return and treats an absent
|
|
1926
|
+
* target as an accepted no-op, so the target is proven live first — otherwise a
|
|
1927
|
+
* typo would be reported as a successful kill.
|
|
1928
|
+
*/
|
|
1929
|
+
export async function workerKill(args = {}, config = {}) {
|
|
1930
|
+
const workerId = workerIdArg(args);
|
|
1931
|
+
if (!workerId) return workerUnavailable('unavailable: 缺少必填参数 workerId(worker_spawn 返回的 id)');
|
|
1932
|
+
const reason = typeof args.reason === 'string' && args.reason.trim().length > 0 ? args.reason.trim() : null;
|
|
1933
|
+
const host = safeHost(config);
|
|
1934
|
+
const subagents = probeService(host, 'subagents');
|
|
1935
|
+
if (!subagents || typeof subagents.interrupt !== 'function') {
|
|
1936
|
+
return workerUnavailable('unavailable: 终止失败(本宿主未提供 subagents 服务)');
|
|
1937
|
+
}
|
|
1938
|
+
const parent = workerParent(config);
|
|
1939
|
+
if (!parent || typeof parent.id !== 'string' || parent.id.length === 0) {
|
|
1940
|
+
return workerUnavailable('unavailable: 终止失败(当前上下文没有活着的 Agent,拿不到终止授权)');
|
|
1941
|
+
}
|
|
1942
|
+
// F5: interrupt() accepts an absent target as a no-op, so "killed" may only be
|
|
1943
|
+
// reported after the same probe worker_status uses says the worker is live.
|
|
1944
|
+
// Sharing that probe is what keeps kill and status from contradicting each
|
|
1945
|
+
// other on the same id (no `agents` service ⇒ status unavailable ⇒ kill too).
|
|
1946
|
+
let statusReport;
|
|
1947
|
+
try {
|
|
1948
|
+
statusReport = await workerStatus({ workerId }, config);
|
|
1949
|
+
} catch (error) {
|
|
1950
|
+
return workerUnavailable(`unavailable: 终止失败(查不到 worker 状态:${errorDetail(error)})`);
|
|
1951
|
+
}
|
|
1952
|
+
if (!statusReport || statusReport.ok !== true || statusReport.live !== true) {
|
|
1953
|
+
const detail = statusReport?.ok === true
|
|
1954
|
+
? `worker ${workerId} 不在运行(状态 ${statusReport.status})`
|
|
1955
|
+
: '找不到这个 worker';
|
|
1956
|
+
return workerUnavailable(`unavailable: 终止失败(${detail};未调用 interrupt,不返回假成功)`);
|
|
1957
|
+
}
|
|
1958
|
+
try {
|
|
1959
|
+
await subagents.interrupt(workerId, { kind: 'ancestor', agent: parent });
|
|
1960
|
+
return {
|
|
1961
|
+
ok: true,
|
|
1962
|
+
status: 'killed',
|
|
1963
|
+
available: true,
|
|
1964
|
+
live: true,
|
|
1965
|
+
workerId,
|
|
1966
|
+
reason,
|
|
1967
|
+
message: `worker killed: ${workerId}${reason ? `(${reason})` : ''}`,
|
|
1968
|
+
};
|
|
1969
|
+
} catch (error) {
|
|
1970
|
+
return workerUnavailable(`unavailable: 终止失败(${errorDetail(error)})`);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
|
|
1974
|
+
const SESSION_ARGS = {
|
|
1975
|
+
sessionPath: {
|
|
1976
|
+
type: 'string',
|
|
1977
|
+
description: 'Absolute path to a session.v4.jsonl.zstd file (highest priority).',
|
|
1978
|
+
},
|
|
1979
|
+
sessionId: {
|
|
1980
|
+
type: 'string',
|
|
1981
|
+
description: 'Session id (the folder name under <DSH_HOME>/sessions/<scope>/).',
|
|
1982
|
+
},
|
|
1983
|
+
session: {
|
|
1984
|
+
type: 'string',
|
|
1985
|
+
description: 'Shortcut instead of an id: "latest" (most recently modified log) or "current".',
|
|
1986
|
+
},
|
|
1987
|
+
};
|
|
1988
|
+
|
|
1989
|
+
const OUTPUT_TEXT = (value) => [{ type: 'text', text: typeof value === 'string' ? value : value.message ?? JSON.stringify(value) }];
|
|
1990
|
+
|
|
1991
|
+
function isPlainObject(value) {
|
|
1992
|
+
if (value == null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
1993
|
+
const proto = Object.getPrototypeOf(value);
|
|
1994
|
+
return proto === Object.prototype || proto === null;
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
function argumentType(value) {
|
|
1998
|
+
if (value === null) return 'null';
|
|
1999
|
+
if (Array.isArray(value)) return 'array';
|
|
2000
|
+
return typeof value;
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
/**
|
|
2004
|
+
* Tool-entry gate for the memory_* family. args and config must be plain
|
|
2005
|
+
* objects: without this, `null` dies with a bare TypeError on the first
|
|
2006
|
+
* property read, and a string/array is silently treated as an empty object.
|
|
2007
|
+
* The check is explicit rather than optional chaining so a wrong type is
|
|
2008
|
+
* reported as such instead of being masked.
|
|
2009
|
+
*/
|
|
2010
|
+
function memoryTool(name, fn) {
|
|
2011
|
+
return (args, config) => {
|
|
2012
|
+
if (!isPlainObject(args)) {
|
|
2013
|
+
throw memoryError('E_BAD_ARGUMENT', `${name} 的 args 必须是普通对象,收到 ${argumentType(args)}`);
|
|
2014
|
+
}
|
|
2015
|
+
if (!isPlainObject(config)) {
|
|
2016
|
+
throw memoryError('E_BAD_ARGUMENT', `${name} 的 config 必须是普通对象,收到 ${argumentType(config)}`);
|
|
2017
|
+
}
|
|
2018
|
+
return fn(args, config);
|
|
2019
|
+
};
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
/**
|
|
2023
|
+
* M10 双路由:写类 memory 工具的落盘门委托。
|
|
2024
|
+
* 新路径 = memory/land.mjs(批次 B,当前 fail-closed 骨架);land 未实现时如实回退到旧路径,
|
|
2025
|
+
* 不双写、不静默吞错。land 一旦实现,同一入口自动切到新路径(旧路径保留,直到新路径全绿)。
|
|
2026
|
+
* 只读工具(memory_recall / memory_recall_v2)不经过落盘门。
|
|
2027
|
+
*/
|
|
2028
|
+
function withLandDoubleRoute(name, invoke) {
|
|
2029
|
+
return (args, config) => {
|
|
2030
|
+
try {
|
|
2031
|
+
return landWithWriteEvidence(name, () => invoke(args, config));
|
|
2032
|
+
} catch (error) {
|
|
2033
|
+
if (error?.code === LAND_UNIMPLEMENTED_CODE) return invoke(args, config);
|
|
2034
|
+
throw error;
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
/** Product path must use forgetV2 so hostkey gate + tombstone enrichment cannot be bypassed. */
|
|
2040
|
+
function memoryForgetTool(args, config) {
|
|
2041
|
+
if (args.status === true) return forgetStatus(args, config);
|
|
2042
|
+
// Preserve the legacy invalid-confirm error (throws before any execution).
|
|
2043
|
+
if (args.confirm !== undefined && args.confirm !== 'FORGET') return memoryForget(args, config);
|
|
2044
|
+
return forgetV2({ ...args, mode: args.confirm === 'FORGET' ? 'execute' : 'propose' }, config);
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
// --- D3: fetch the original text of one turn ------------------------------
|
|
2048
|
+
//
|
|
2049
|
+
// session_original is the deliberate escape hatch from the compressed view:
|
|
2050
|
+
// the agent has a sessionId + turn (usually from session_search or
|
|
2051
|
+
// memory_recall) and needs the bytes that were folded away. It is read-only,
|
|
2052
|
+
// scans the WHOLE selection before slicing anything, and never writes the D2
|
|
2053
|
+
// archive — it only reports the path D2 would use.
|
|
2054
|
+
|
|
2055
|
+
const ORIGINAL_DEFAULT_MAX_BYTES = 64 * 1024;
|
|
2056
|
+
const ORIGINAL_MIN_MAX_BYTES = 1024;
|
|
2057
|
+
const ORIGINAL_MAX_MAX_BYTES = 4 * 1024 * 1024;
|
|
2058
|
+
const ORIGINAL_ARCHIVE_LIMIT = 20;
|
|
2059
|
+
const ORIGINAL_TURN_LIMIT = 50;
|
|
2060
|
+
const ORIGINAL_CALL_ID_LIMIT = 50;
|
|
2061
|
+
|
|
2062
|
+
function originalError(code, message, extra = {}) {
|
|
2063
|
+
return {
|
|
2064
|
+
ok: false,
|
|
2065
|
+
status: code === 'PRIVACY_BLOCKED' ? 'blocked' : 'error',
|
|
2066
|
+
code,
|
|
2067
|
+
error: { code, message },
|
|
2068
|
+
message: `unavailable: ${message}`,
|
|
2069
|
+
...extra,
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
function originalClampInteger(value, min, max) {
|
|
2074
|
+
if (!Number.isInteger(value)) return min;
|
|
2075
|
+
return Math.min(Math.max(value, min), max);
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
function originalMaxBytes(config) {
|
|
2079
|
+
const configured = config?.originalFetchMaxBytes;
|
|
2080
|
+
return originalClampInteger(
|
|
2081
|
+
Number.isInteger(configured) ? configured : ORIGINAL_DEFAULT_MAX_BYTES,
|
|
2082
|
+
ORIGINAL_MIN_MAX_BYTES,
|
|
2083
|
+
ORIGINAL_MAX_MAX_BYTES,
|
|
2084
|
+
);
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2087
|
+
/** Where D2 would archive a turn, without creating anything. */
|
|
2088
|
+
function originalArchiveRoot(config) {
|
|
2089
|
+
const env = config?.env ?? process.env;
|
|
2090
|
+
const setting = memoryRootSetting(config ?? {}, env);
|
|
2091
|
+
return setting.explicit
|
|
2092
|
+
? path.resolve(setting.explicit)
|
|
2093
|
+
: defaultMemoryRoot(config ?? {}, env);
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
function originalSessionCoordinates(sessionPath, home) {
|
|
2097
|
+
try {
|
|
2098
|
+
const rel = path.relative(path.join(home, 'sessions'), sessionPath);
|
|
2099
|
+
const parts = rel.split(path.sep);
|
|
2100
|
+
if (parts.length >= 3 && parts[0] !== '..' && !path.isAbsolute(rel)) {
|
|
2101
|
+
return { scope: parts[0], sessionId: parts[1] };
|
|
2102
|
+
}
|
|
2103
|
+
} catch {
|
|
2104
|
+
// fall through
|
|
2105
|
+
}
|
|
2106
|
+
return { scope: null, sessionId: null };
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
function originalItemSummary(item, archive) {
|
|
2110
|
+
return {
|
|
2111
|
+
kind: item.kind,
|
|
2112
|
+
role: item.role,
|
|
2113
|
+
step: item.step,
|
|
2114
|
+
seq: item.seq,
|
|
2115
|
+
time: item.time,
|
|
2116
|
+
messageIndex: item.messageIndex,
|
|
2117
|
+
toolIndex: item.toolIndex,
|
|
2118
|
+
callIndex: item.callIndex,
|
|
2119
|
+
toolCallId: item.toolCallId,
|
|
2120
|
+
toolName: item.toolName,
|
|
2121
|
+
isError: item.isError,
|
|
2122
|
+
nonTextParts: item.nonTextParts,
|
|
2123
|
+
bytes: Buffer.byteLength(item.text, 'utf8'),
|
|
2124
|
+
archive,
|
|
2125
|
+
};
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
function originalArchivePlan(items, turn, config) {
|
|
2129
|
+
const dir = path.join(originalArchiveRoot(config), '.longlive', 'tool-output', String(turn));
|
|
2130
|
+
const used = new Set();
|
|
2131
|
+
return items.slice(0, ORIGINAL_ARCHIVE_LIMIT).map((item) => {
|
|
2132
|
+
let name = archiveFileName(item);
|
|
2133
|
+
if (used.has(name)) name = name.replace(/\.txt$/, `-${item.seq}.txt`);
|
|
2134
|
+
used.add(name);
|
|
2135
|
+
const file = path.join(dir, name);
|
|
2136
|
+
let exists = false;
|
|
2137
|
+
let size = null;
|
|
2138
|
+
try {
|
|
2139
|
+
const stat = fs.statSync(file);
|
|
2140
|
+
if (stat.isFile()) {
|
|
2141
|
+
exists = true;
|
|
2142
|
+
size = stat.size;
|
|
2143
|
+
}
|
|
2144
|
+
} catch {
|
|
2145
|
+
// A missing archive is the normal case: this tool never writes it.
|
|
2146
|
+
}
|
|
2147
|
+
return {
|
|
2148
|
+
convention: '<memoryRoot>/.longlive/tool-output/<turn>/<id>.txt',
|
|
2149
|
+
path: file,
|
|
2150
|
+
exists,
|
|
2151
|
+
...(size == null ? {} : { size }),
|
|
2152
|
+
};
|
|
2153
|
+
});
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
function originalRender(_args, value) {
|
|
2157
|
+
if (!isPlainObject(value)) return OUTPUT_TEXT(value);
|
|
2158
|
+
const lines = [];
|
|
2159
|
+
if (value.ok) {
|
|
2160
|
+
const size = `${value.returnedBytes ?? 0}/${value.totalBytes ?? 0} B`;
|
|
2161
|
+
lines.push(`session_original: turn ${value.turn} — ${value.selectedCount ?? 0} selected item(s), ${size}` +
|
|
2162
|
+
`${value.truncated ? ' (truncated)' : ''}`);
|
|
2163
|
+
if (value.message) lines.push(value.message);
|
|
2164
|
+
if (typeof value.content === 'string' && value.content !== '') {
|
|
2165
|
+
lines.push('', value.content);
|
|
2166
|
+
}
|
|
2167
|
+
if (value.truncated) {
|
|
2168
|
+
lines.push('', `... [truncated; continue with offset=${value.nextOffset}]`);
|
|
2169
|
+
}
|
|
2170
|
+
if (Array.isArray(value.archives) && value.archives.length > 0) {
|
|
2171
|
+
lines.push('', 'D2 archive path (written by D2 only when d2.enabled; this tool just plans it):');
|
|
2172
|
+
for (const archive of value.archives) {
|
|
2173
|
+
lines.push(` ${archive.path}${archive.exists ? ` (exists, ${archive.size} B)` : ' (not present)'}`);
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
} else {
|
|
2177
|
+
lines.push(`session_original: ${value.code ?? 'error'} — ${value.error?.message ?? value.message ?? ''}`);
|
|
2178
|
+
if (Array.isArray(value.availableTurns) && value.availableTurns.length > 0) {
|
|
2179
|
+
lines.push(` recent turns: ${value.availableTurns.join(', ')}`);
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
return [{ type: 'text', text: lines.join('\n') }];
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
function sessionOriginalImpl(args = {}, config = {}) {
|
|
2186
|
+
if (!isPlainObject(args)) {
|
|
2187
|
+
return originalError('E_BAD_ARGUMENT', `args must be an object, received ${argumentType(args)}`);
|
|
2188
|
+
}
|
|
2189
|
+
if (!isPlainObject(config)) {
|
|
2190
|
+
return originalError('E_BAD_ARGUMENT', `config must be an object, received ${argumentType(config)}`);
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
const turn = args.turn;
|
|
2194
|
+
if (!Number.isInteger(turn) || turn < 1) {
|
|
2195
|
+
return originalError('E_BAD_ARGUMENT', 'turn is required and must be an integer >= 1');
|
|
2196
|
+
}
|
|
2197
|
+
const kind = args.kind === undefined ? 'tool' : args.kind;
|
|
2198
|
+
if (!ORIGINAL_KINDS.includes(kind)) {
|
|
2199
|
+
return originalError('E_BAD_ARGUMENT', `kind must be one of ${ORIGINAL_KINDS.join(', ')}`);
|
|
2200
|
+
}
|
|
2201
|
+
const toolCallId = typeof args.toolCallId === 'string' ? args.toolCallId.trim() : '';
|
|
2202
|
+
if (args.toolCallId !== undefined && toolCallId === '') {
|
|
2203
|
+
return originalError('E_BAD_ARGUMENT', 'toolCallId must be a non-empty string when given');
|
|
2204
|
+
}
|
|
2205
|
+
if (toolCallId && kind === 'message') {
|
|
2206
|
+
return originalError('E_BAD_ARGUMENT', 'toolCallId selects a tool call/result; kind "message" cannot match it');
|
|
2207
|
+
}
|
|
2208
|
+
if (args.messageIndex !== undefined && (!Number.isInteger(args.messageIndex) || args.messageIndex < 0)) {
|
|
2209
|
+
return originalError('E_BAD_ARGUMENT', 'messageIndex must be an integer >= 0');
|
|
2210
|
+
}
|
|
2211
|
+
if (toolCallId && args.messageIndex !== undefined) {
|
|
2212
|
+
return originalError('E_BAD_ARGUMENT', 'pass either toolCallId or messageIndex, not both');
|
|
2213
|
+
}
|
|
2214
|
+
if (args.offset !== undefined && (!Number.isInteger(args.offset) || args.offset < 0)) {
|
|
2215
|
+
return originalError('E_BAD_ARGUMENT', 'offset must be an integer >= 0');
|
|
2216
|
+
}
|
|
2217
|
+
if (args.maxBytes !== undefined && (!Number.isInteger(args.maxBytes) || args.maxBytes < 1)) {
|
|
2218
|
+
return originalError('E_BAD_ARGUMENT', 'maxBytes must be an integer >= 1');
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
let resolved = null;
|
|
2222
|
+
try {
|
|
2223
|
+
resolved = resolveSessionPath(args, config);
|
|
2224
|
+
} catch (error) {
|
|
2225
|
+
return originalError('SESSION_READ_FAILED', `cannot resolve session: ${errorDetail(error)}`);
|
|
2226
|
+
}
|
|
2227
|
+
if (!resolved.ok) {
|
|
2228
|
+
const error = resolved.error ?? {
|
|
2229
|
+
code: resolved.code ?? 'SESSION_NOT_FOUND',
|
|
2230
|
+
message: resolved.message ?? 'session is unavailable',
|
|
2231
|
+
};
|
|
2232
|
+
return {
|
|
2233
|
+
ok: false,
|
|
2234
|
+
status: resolved.status ?? 'error',
|
|
2235
|
+
code: error.code,
|
|
2236
|
+
error,
|
|
2237
|
+
...(resolved.path ? { path: resolved.path } : {}),
|
|
2238
|
+
...(resolved.candidates ? { candidates: resolved.candidates } : {}),
|
|
2239
|
+
message: error.message,
|
|
2240
|
+
};
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
const sessionPath = resolved.sessionPath;
|
|
2244
|
+
const coordinates = originalSessionCoordinates(sessionPath, resolved.home);
|
|
2245
|
+
const context = {
|
|
2246
|
+
sessionPath,
|
|
2247
|
+
sessionId: coordinates.sessionId,
|
|
2248
|
+
scope: coordinates.scope,
|
|
2249
|
+
turn,
|
|
2250
|
+
};
|
|
2251
|
+
|
|
2252
|
+
let parsed = null;
|
|
2253
|
+
try {
|
|
2254
|
+
parsed = parseSession(fs.readFileSync(sessionPath));
|
|
2255
|
+
} catch (error) {
|
|
2256
|
+
return originalError('SESSION_CORRUPT', `cannot parse session log: ${errorDetail(error)}`, context);
|
|
2257
|
+
}
|
|
2258
|
+
|
|
2259
|
+
const turns = buildTurnItems(parsed.events);
|
|
2260
|
+
const turnNumbers = availableTurns(turns);
|
|
2261
|
+
if (!turns.has(turn)) {
|
|
2262
|
+
const recent = turnNumbers.slice(-ORIGINAL_TURN_LIMIT);
|
|
2263
|
+
const range = turnNumbers.length > 0
|
|
2264
|
+
? `turn ${turn} is not in this log; available turns ${turnNumbers[0]}..${turnNumbers[turnNumbers.length - 1]}`
|
|
2265
|
+
: `turn ${turn} is not in this log; the log has no turns`;
|
|
2266
|
+
return originalError('TURN_NOT_FOUND', range, {
|
|
2267
|
+
...context,
|
|
2268
|
+
availableTurns: recent,
|
|
2269
|
+
turnCount: turnNumbers.length,
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
|
|
2273
|
+
const items = turns.get(turn);
|
|
2274
|
+
const selection = selectTurnItems(items, {
|
|
2275
|
+
kind,
|
|
2276
|
+
toolCallId: toolCallId || null,
|
|
2277
|
+
messageIndex: args.messageIndex ?? null,
|
|
2278
|
+
});
|
|
2279
|
+
|
|
2280
|
+
if (selection.error) {
|
|
2281
|
+
const extra = { ...context, itemCount: items.length };
|
|
2282
|
+
if (selection.error.code === 'MESSAGE_INDEX_OUT_OF_RANGE') {
|
|
2283
|
+
extra.messages = items
|
|
2284
|
+
.filter((item) => item.kind === 'message')
|
|
2285
|
+
.map((item) => ({ messageIndex: item.messageIndex, role: item.role, bytes: Buffer.byteLength(item.text, 'utf8') }));
|
|
2286
|
+
}
|
|
2287
|
+
if (selection.error.code === 'TOOL_CALL_NOT_FOUND') {
|
|
2288
|
+
extra.toolCalls = items
|
|
2289
|
+
.filter((item) => item.kind === 'tool' || item.kind === 'call')
|
|
2290
|
+
.slice(0, ORIGINAL_CALL_ID_LIMIT)
|
|
2291
|
+
.map((item) => ({ kind: item.kind, toolCallId: item.toolCallId, toolName: item.toolName }));
|
|
2292
|
+
}
|
|
2293
|
+
return originalError(selection.error.code, selection.error.message, extra);
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
const selected = selection.items;
|
|
2297
|
+
const archives = originalArchivePlan(selected, turn, config);
|
|
2298
|
+
const summaries = selected.map((item, index) => originalItemSummary(item, archives[index] ?? null));
|
|
2299
|
+
|
|
2300
|
+
const base = {
|
|
2301
|
+
...context,
|
|
2302
|
+
itemCount: items.length,
|
|
2303
|
+
selectedCount: selected.length,
|
|
2304
|
+
items: items.length,
|
|
2305
|
+
selected: summaries,
|
|
2306
|
+
archives,
|
|
2307
|
+
};
|
|
2308
|
+
|
|
2309
|
+
if (selected.length === 0) {
|
|
2310
|
+
return {
|
|
2311
|
+
ok: true,
|
|
2312
|
+
status: 'empty',
|
|
2313
|
+
...base,
|
|
2314
|
+
content: '',
|
|
2315
|
+
offset: 0,
|
|
2316
|
+
totalBytes: 0,
|
|
2317
|
+
returnedBytes: 0,
|
|
2318
|
+
truncated: false,
|
|
2319
|
+
nextOffset: null,
|
|
2320
|
+
privacy: { verdict: 'none', reasons: [], spans: 0, source: 'not-scanned' },
|
|
2321
|
+
message: `turn ${turn} has no ${kind === 'all' ? 'items' : kind} to fetch; ` +
|
|
2322
|
+
'try kind:"message" / "call" / "all" (and toolCallId / messageIndex when the turn has several)',
|
|
2323
|
+
};
|
|
2324
|
+
}
|
|
2325
|
+
|
|
2326
|
+
const joined = joinTurnItems(selected);
|
|
2327
|
+
const privacy = privacyScan(joined);
|
|
2328
|
+
if (privacy.verdict !== 'none') {
|
|
2329
|
+
return {
|
|
2330
|
+
ok: false,
|
|
2331
|
+
status: 'blocked',
|
|
2332
|
+
code: 'PRIVACY_BLOCKED',
|
|
2333
|
+
error: {
|
|
2334
|
+
code: 'PRIVACY_BLOCKED',
|
|
2335
|
+
message: `original text hit the privacy gate (${privacy.reasons.join(', ') || privacy.verdict}); no content is returned`,
|
|
2336
|
+
},
|
|
2337
|
+
message: `blocked: privacy gate matched ${privacy.reasons.join(', ') || 'local-only content'} — ` +
|
|
2338
|
+
'the original text is not returned, and maxBytes/offset cannot bypass the gate',
|
|
2339
|
+
...base,
|
|
2340
|
+
privacy: {
|
|
2341
|
+
verdict: privacy.verdict,
|
|
2342
|
+
reasons: privacy.reasons,
|
|
2343
|
+
spans: Array.isArray(privacy.spans) ? privacy.spans.length : 0,
|
|
2344
|
+
source: privacy.source,
|
|
2345
|
+
},
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
const maxBytes = originalClampInteger(
|
|
2350
|
+
Number.isInteger(args.maxBytes) ? args.maxBytes : originalMaxBytes(config),
|
|
2351
|
+
ORIGINAL_MIN_MAX_BYTES,
|
|
2352
|
+
ORIGINAL_MAX_MAX_BYTES,
|
|
2353
|
+
);
|
|
2354
|
+
const slice = sliceUtf8(joined, Number.isInteger(args.offset) ? args.offset : 0, maxBytes);
|
|
2355
|
+
|
|
2356
|
+
return {
|
|
2357
|
+
ok: true,
|
|
2358
|
+
status: 'ok',
|
|
2359
|
+
...base,
|
|
2360
|
+
content: slice.content,
|
|
2361
|
+
offset: slice.offset,
|
|
2362
|
+
nextOffset: slice.nextOffset,
|
|
2363
|
+
totalBytes: slice.totalBytes,
|
|
2364
|
+
returnedBytes: slice.returnedBytes,
|
|
2365
|
+
truncated: slice.nextOffset != null,
|
|
2366
|
+
maxBytes,
|
|
2367
|
+
privacy: {
|
|
2368
|
+
verdict: privacy.verdict,
|
|
2369
|
+
reasons: privacy.reasons,
|
|
2370
|
+
spans: Array.isArray(privacy.spans) ? privacy.spans.length : 0,
|
|
2371
|
+
source: privacy.source,
|
|
2372
|
+
},
|
|
2373
|
+
message: `turn ${turn}: ${selected.length} item(s), ${slice.totalBytes} B total, ` +
|
|
2374
|
+
`${slice.returnedBytes} B returned from byte ${slice.offset}` +
|
|
2375
|
+
`${slice.nextOffset == null ? '' : `; continue with offset=${slice.nextOffset}`}` +
|
|
2376
|
+
`${archives.some((archive) => archive.exists) ? '; one or more D2 archives already exist' : ''}`,
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
/**
|
|
2381
|
+
* D3: read one turn back out of a session log.
|
|
2382
|
+
*
|
|
2383
|
+
* This is the only tool that returns bytes that were deliberately compressed
|
|
2384
|
+
* away. It is read-only, keeps the selection out of the context unless asked
|
|
2385
|
+
* for, and refuses to return anything when the privacy gate matches the FULL
|
|
2386
|
+
* selection (scanning before slicing, so paging cannot smuggle a match).
|
|
2387
|
+
*/
|
|
2388
|
+
export function sessionOriginal(args, config) {
|
|
2389
|
+
try {
|
|
2390
|
+
return sessionOriginalImpl(args, config);
|
|
2391
|
+
} catch (error) {
|
|
2392
|
+
return originalError('SESSION_ORIGINAL_FAILED', `session_original failed: ${errorDetail(error)}`);
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
// --- 1.8.4-dev: fast keyword search over the FTS5 event index --------------
|
|
2397
|
+
//
|
|
2398
|
+
// session_search rescans session logs and can run past its 30 s budget on this
|
|
2399
|
+
// store (727 sessions / ~9.5k events / 120 MB index). The plugin already keeps
|
|
2400
|
+
// a rebuildable SQLite FTS5 index of every turn (.longlive/index/events.db), so
|
|
2401
|
+
// grepping costs ~0.2-0.8 s here. This is the fast path; a hit points at
|
|
2402
|
+
// session_original(turn=..., sessionId=...) for the actual bytes.
|
|
2403
|
+
export function sessionGrep(args, config) {
|
|
2404
|
+
if (!isPlainObject(args)) {
|
|
2405
|
+
throw memoryError('E_BAD_ARGUMENT', 'session_grep 的 args 必须是普通对象');
|
|
2406
|
+
}
|
|
2407
|
+
const query = String(args.query ?? '').trim();
|
|
2408
|
+
if (!query) {
|
|
2409
|
+
return { ok: false, code: 'E_EMPTY_QUERY', message: 'query 不能为空:给一个词或短语(2 个汉字 / 3 个字母以上更容易命中)' };
|
|
2410
|
+
}
|
|
2411
|
+
const requested = Number(args.limit);
|
|
2412
|
+
const limit = Math.max(1, Math.min(30, Number.isFinite(requested) ? Math.trunc(requested) : 8));
|
|
2413
|
+
const sessionFilter = String(args.sessionId ?? '').trim();
|
|
2414
|
+
const kindFilter = String(args.kind ?? '').trim();
|
|
2415
|
+
// MINOR-1:null/undefined = "没传" = auto;其余非白名单 = E_TIER_ARG
|
|
2416
|
+
const TIER_ARG_WHITELIST = ['auto', 'hot', 'warm', 'cold', 'all'];
|
|
2417
|
+
const explicitTierArg = args.tier !== undefined && args.tier !== null;
|
|
2418
|
+
const tierArg = explicitTierArg ? String(args.tier) : 'auto';
|
|
2419
|
+
if (!TIER_ARG_WHITELIST.includes(tierArg)) {
|
|
2420
|
+
return {
|
|
2421
|
+
ok: false,
|
|
2422
|
+
code: 'E_TIER_ARG',
|
|
2423
|
+
message: `tier 必须是 ${TIER_ARG_WHITELIST.join(' / ')} 之一(收到 ${JSON.stringify(args.tier)})`,
|
|
2424
|
+
hint: "默认 tier=auto;查旧事传 tier:'all'。",
|
|
2425
|
+
};
|
|
2426
|
+
}
|
|
2427
|
+
const tiering = normalizeTiering((config && typeof config === 'object' && config.tiering) ? config.tiering : {});
|
|
2428
|
+
// 1.8.3 默认等价(收尾问题 2):只有 filter 生效,或调用方显式传 tier:'hot'|'warm'|'cold'|'all'
|
|
2429
|
+
// 时才在响应里回填 03 新增字段;默认 shadow/off 且未传 tier ⇒ 响应与 1.8.3 逐字节一致。
|
|
2430
|
+
const explicitTier = explicitTierArg && ['hot', 'warm', 'cold', 'all'].includes(tierArg);
|
|
2431
|
+
const showTierFields = explicitTier || tiering.mode === 'filter';
|
|
2432
|
+
// MINOR-7(round1):reader 身份改用 canonical resolver(identity 链:exec.agent →
|
|
2433
|
+
// agents.currentInitiator → ctx.agent → env.DSH_SESSION_ID);不再手写属性链。
|
|
2434
|
+
// MINOR-8(round1):同时删除模型可伪造的 currentSessionId 入参 seam——reader
|
|
2435
|
+
// 身份只来自宿主传入的 exec / config,session_grep 的 parameters 里没有这个键。
|
|
2436
|
+
let readerSessionId = '';
|
|
2437
|
+
try { readerSessionId = String(resolveCallerSessionId(config ?? {}).id ?? '').trim(); } catch { readerSessionId = ''; }
|
|
2438
|
+
let memoryRoot;
|
|
2439
|
+
try {
|
|
2440
|
+
memoryRoot = memoryRootFromConfig(config ?? {}, process.env);
|
|
2441
|
+
} catch (error) {
|
|
2442
|
+
return { ok: false, code: error?.code ?? 'E_MEMORY_ROOT', message: error?.message ?? String(error) };
|
|
2443
|
+
}
|
|
2444
|
+
const startedAt = Date.now();
|
|
2445
|
+
const searchArgs = { memoryRoot, query, limit, sessionId: sessionFilter, kind: kindFilter, tier: tierArg, currentSessionId: readerSessionId, tiering };
|
|
2446
|
+
let result;
|
|
2447
|
+
try {
|
|
2448
|
+
result = searchEventsFts(searchArgs);
|
|
2449
|
+
} catch (error) {
|
|
2450
|
+
return {
|
|
2451
|
+
ok: false,
|
|
2452
|
+
code: 'E_INDEX_UNAVAILABLE',
|
|
2453
|
+
message: `FTS 索引不可用:${error?.message ?? error}`,
|
|
2454
|
+
hint: '先跑 scripts/recall-index-build.mjs(或 scripts/index-maintain.mjs)重建 .longlive/index/events.db',
|
|
2455
|
+
};
|
|
2456
|
+
}
|
|
2457
|
+
if (!result || result.ok === false) {
|
|
2458
|
+
// 默认关等价:未显式传 tier 且 tiering.mode 非 filter ⇒ 与 1.8.3 相同的错误面
|
|
2459
|
+
//(一律 E_INDEX_UNAVAILABLE、同 message/hint;不新增 retryable/detail/tierFilter/queryDegraded)。
|
|
2460
|
+
if (!showTierFields) {
|
|
2461
|
+
return {
|
|
2462
|
+
ok: false,
|
|
2463
|
+
code: 'E_INDEX_UNAVAILABLE',
|
|
2464
|
+
message: `FTS 索引查询失败:${result?.error?.message ?? result?.message ?? 'unknown'}`,
|
|
2465
|
+
hint: '先跑 scripts/recall-index-build.mjs 重建索引',
|
|
2466
|
+
};
|
|
2467
|
+
}
|
|
2468
|
+
const PASS_THROUGH = new Set(['E_TIER_ARG', 'E_TIER_SCHEMA_MISSING', 'E_INDEX_QUERY_BUSY', 'E_INDEX_QUERY_FAILED']);
|
|
2469
|
+
const code = PASS_THROUGH.has(result?.code) ? result.code : 'E_INDEX_UNAVAILABLE';
|
|
2470
|
+
const hint = code === 'E_INDEX_QUERY_BUSY'
|
|
2471
|
+
? '索引正被写入(E_INDEX_QUERY_BUSY),请重试。'
|
|
2472
|
+
: code === 'E_TIER_SCHEMA_MISSING'
|
|
2473
|
+
? "这个库还没有 tier 列:显式 tier 不可用;tier:'auto' 仍可按时间回退查询。"
|
|
2474
|
+
: '先跑 scripts/recall-index-build.mjs 重建索引';
|
|
2475
|
+
return {
|
|
2476
|
+
ok: false,
|
|
2477
|
+
code,
|
|
2478
|
+
retryable: Boolean(result?.retryable),
|
|
2479
|
+
message: `FTS 索引查询失败:${result?.message ?? 'unknown'}`,
|
|
2480
|
+
detail: result?.detail,
|
|
2481
|
+
tierFilter: result?.tierFilter ?? null,
|
|
2482
|
+
queryDegraded: result?.queryDegraded ?? false,
|
|
2483
|
+
hint,
|
|
2484
|
+
};
|
|
2485
|
+
}
|
|
2486
|
+
let rows = Array.isArray(result.rows) ? result.rows : [];
|
|
2487
|
+
let strategy = result.strategy;
|
|
2488
|
+
let coldSuppressed = result.coldSuppressed;
|
|
2489
|
+
let coldSuppressedCapped = result.coldSuppressedCapped;
|
|
2490
|
+
let suppressedBasis = result.suppressedBasis;
|
|
2491
|
+
let queryDegraded = result.queryDegraded;
|
|
2492
|
+
let queryDegradedCode = result.queryDegradedCode;
|
|
2493
|
+
let suppressedCountStrategy = result.suppressedCountStrategy ?? null;
|
|
2494
|
+
let fallback = 'none';
|
|
2495
|
+
// ★ B1-②:1–2 字兜底路径——计数与 FTS 合并(max),采用兜底行的条件仍是"可见行 > 0"。
|
|
2496
|
+
if (rows.length === 0 && [...query].length <= 2) {
|
|
2497
|
+
try {
|
|
2498
|
+
const scan = searchEventsReadOnly({ memoryRoot, query, limit: 20, tier: tierArg, currentSessionId: readerSessionId, sessionId: sessionFilter, kind: kindFilter, tiering });
|
|
2499
|
+
if (scan && scan.ok) {
|
|
2500
|
+
const nums = [coldSuppressed, scan.coldSuppressed].filter((v) => typeof v === 'number' && Number.isFinite(v));
|
|
2501
|
+
if (nums.length > 0) {
|
|
2502
|
+
const ftsNum = typeof coldSuppressed === 'number' && Number.isFinite(coldSuppressed) ? coldSuppressed : -1;
|
|
2503
|
+
const scanNum = typeof scan.coldSuppressed === 'number' && Number.isFinite(scan.coldSuppressed) ? scan.coldSuppressed : -1;
|
|
2504
|
+
if (scanNum > ftsNum) { // 并列取 fts
|
|
2505
|
+
coldSuppressed = scan.coldSuppressed;
|
|
2506
|
+
coldSuppressedCapped = scan.coldSuppressedCapped;
|
|
2507
|
+
suppressedBasis = scan.suppressedBasis;
|
|
2508
|
+
suppressedCountStrategy = scan.suppressedCountStrategy ?? 'scan';
|
|
2509
|
+
}
|
|
2510
|
+
} else {
|
|
2511
|
+
coldSuppressed = null; // 两条路径都降级
|
|
2512
|
+
}
|
|
2513
|
+
if (Array.isArray(scan.rows) && scan.rows.length > 0) {
|
|
2514
|
+
rows = scan.rows;
|
|
2515
|
+
strategy = 'readonly-scan';
|
|
2516
|
+
fallback = 'scan-used';
|
|
2517
|
+
} else {
|
|
2518
|
+
fallback = 'scan-no-row';
|
|
2519
|
+
}
|
|
2520
|
+
} else {
|
|
2521
|
+
fallback = 'none';
|
|
2522
|
+
}
|
|
2523
|
+
} catch {
|
|
2524
|
+
fallback = 'none';
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
const hits = rows.slice(0, limit).map((row) => {
|
|
2528
|
+
const summary = String(row.summary ?? '').replace(/\s+/g, ' ').trim();
|
|
2529
|
+
return {
|
|
2530
|
+
sessionId: row.sessionId,
|
|
2531
|
+
turn: row.turn,
|
|
2532
|
+
kind: row.kind,
|
|
2533
|
+
...(showTierFields ? { tier: row.tier ?? null } : {}),
|
|
2534
|
+
snippet: summary.length > 240 ? `${summary.slice(0, 240)}…` : summary,
|
|
2535
|
+
next: `session_original({ turn: ${row.turn}, sessionId: ${JSON.stringify(row.sessionId)} })`,
|
|
2536
|
+
};
|
|
2537
|
+
});
|
|
2538
|
+
const baseHint = hits.length
|
|
2539
|
+
? (query.length === 1
|
|
2540
|
+
? '单字命中面很宽:换 2 个汉字以上的词会更准。要原文用 hits[].next。'
|
|
2541
|
+
: '要原文用 hits[].next;turn 号直接喂给 session_original。')
|
|
2542
|
+
: '没命中:换更短的词(2 个汉字),或确认索引是最新的(scripts/index-maintain.mjs)。';
|
|
2543
|
+
const hint = showTierFields ? buildTierHint({
|
|
2544
|
+
tierFilter: result.tierFilter,
|
|
2545
|
+
coldSuppressed,
|
|
2546
|
+
coldSuppressedCapped,
|
|
2547
|
+
suppressedBasis,
|
|
2548
|
+
hits: hits.length,
|
|
2549
|
+
warmDays: result.warmDays ?? tiering.warmDays ?? DEFAULT_TIERING.warmDays,
|
|
2550
|
+
queryDegraded,
|
|
2551
|
+
queryDegradedCode,
|
|
2552
|
+
suppressedCap: tiering.suppressedCap,
|
|
2553
|
+
baseHint,
|
|
2554
|
+
}) : baseHint;
|
|
2555
|
+
return {
|
|
2556
|
+
ok: true,
|
|
2557
|
+
query,
|
|
2558
|
+
strategy,
|
|
2559
|
+
elapsedMs: Date.now() - startedAt,
|
|
2560
|
+
matched: rows.length,
|
|
2561
|
+
returned: hits.length,
|
|
2562
|
+
hits,
|
|
2563
|
+
hint,
|
|
2564
|
+
// 收尾问题 2:默认关(shadow/off 且未显式传 tier)不输出 03 新字段,响应=1.8.3。
|
|
2565
|
+
...(showTierFields ? {
|
|
2566
|
+
tierFilter: result.tierFilter,
|
|
2567
|
+
tierApplied: result.tierApplied,
|
|
2568
|
+
suppressedBasis,
|
|
2569
|
+
coldSuppressed,
|
|
2570
|
+
coldSuppressedCapped,
|
|
2571
|
+
suppressedCountStrategy,
|
|
2572
|
+
fallback,
|
|
2573
|
+
// ★ M-A6:off 模式不读 meta ⇒ 这组键在响应里缺席(JSON 里不出现),不伪造 stale:true。
|
|
2574
|
+
...(result.tierPassAt === undefined ? {} : {
|
|
2575
|
+
tierPassAt: result.tierPassAt,
|
|
2576
|
+
tierStale: result.tierStale,
|
|
2577
|
+
tierLabelsUsable: result.tierLabelsUsable,
|
|
2578
|
+
tierLabelsSource: result.tierLabelsSource,
|
|
2579
|
+
}),
|
|
2580
|
+
queryDegraded,
|
|
2581
|
+
queryDegradedCode,
|
|
2582
|
+
} : {}),
|
|
2583
|
+
};
|
|
2584
|
+
}
|
|
2585
|
+
export const TOOLS = [
|
|
2586
|
+
{
|
|
2587
|
+
name: 'session_health',
|
|
2588
|
+
description:
|
|
2589
|
+
'Inspect a DSH session log (session.v4.jsonl.zstd): size, event count, last event type, ' +
|
|
2590
|
+
'visible-message count and sha256, age, backups, last truncation. Read-only. ' +
|
|
2591
|
+
'Pass sessionPath, sessionId, or session:"latest"/"current".',
|
|
2592
|
+
parameters: { ...SESSION_ARGS },
|
|
2593
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2594
|
+
invoke: (args, config) => sessionHealth(args, config),
|
|
2595
|
+
},
|
|
2596
|
+
{
|
|
2597
|
+
name: 'session_grep',
|
|
2598
|
+
description:
|
|
2599
|
+
'Fast keyword search over the rebuildable FTS5 event index of every session turn ' +
|
|
2600
|
+
'(<memoryRoot>/.longlive/index/events.db): typically 0.2-0.8 s on this store, while ' +
|
|
2601
|
+
'session_search can run past its 30 s budget. Read-only, bounded output. Returns ' +
|
|
2602
|
+
'sessionId + turn + kind + snippet and a ready-made session_original call for the ' +
|
|
2603
|
+
'original bytes. Use it to find "that turn where we talked about X", then ' +
|
|
2604
|
+
'session_original(turn=..., sessionId=...) for the text. In tier-filter mode old turns ' +
|
|
2605
|
+
"may be in the cold layer: pass tier:'all' when searching for older work. In shadow mode " +
|
|
2606
|
+
'(default) nothing is filtered.',
|
|
2607
|
+
parameters: {
|
|
2608
|
+
query: { type: 'string', description: 'Required. Keywords or a phrase; 2+ CJK chars or 3+ letters hit best.' },
|
|
2609
|
+
limit: { type: 'integer', description: 'Max hits (default 8, clamped 1..30).' },
|
|
2610
|
+
sessionId: { type: 'string', description: 'Optional: keep only events whose session id contains this substring.' },
|
|
2611
|
+
kind: { type: 'string', description: 'Optional: keep only one event kind (chat / conclusion / incident / ...).' },
|
|
2612
|
+
tier: {
|
|
2613
|
+
type: 'string',
|
|
2614
|
+
enum: ['auto', 'hot', 'warm', 'cold', 'all'],
|
|
2615
|
+
description: "Recall layer filter: auto (default; cold hidden only in tier-filter mode), hot/warm/cold (explicit layer), all (never filtered). Old turns may be in the cold layer.",
|
|
2616
|
+
},
|
|
2617
|
+
},
|
|
2618
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2619
|
+
invoke: (args, config) => sessionGrep(args, config),
|
|
2620
|
+
},
|
|
2621
|
+
{
|
|
2622
|
+
name: 'session_original',
|
|
2623
|
+
description:
|
|
2624
|
+
'D3 "fetch the original": return the text of ONE turn from a session log, including tool ' +
|
|
2625
|
+
'output that was compressed out of the context. Read-only and privacy-gated: the FULL ' +
|
|
2626
|
+
'selection is scanned before slicing, so maxBytes/offset cannot page around a match. ' +
|
|
2627
|
+
'turn is required and 1-based (a user message belongs to its preceding turn/start). ' +
|
|
2628
|
+
'kind defaults to "tool" (tool results); use "message" for user/assistant text, "call" for ' +
|
|
2629
|
+
'tool arguments, or "all". Narrow a turn with toolCallId, or with messageIndex (0-based ' +
|
|
2630
|
+
'among the turn\'s user/assistant messages). The response is capped at maxBytes UTF-8 bytes ' +
|
|
2631
|
+
'(default 65536, config originalFetchMaxBytes): when truncated, content stops on a code-point ' +
|
|
2632
|
+
'boundary and nextOffset is the byte offset for the next call. Find a turn first with ' +
|
|
2633
|
+
'session_search or memory_recall. The result also reports the D2 archive path ' +
|
|
2634
|
+
'<memoryRoot>/.longlive/tool-output/<turn>/<id>.txt but NEVER writes it. ' +
|
|
2635
|
+
'Pass sessionPath, sessionId, or session:"latest"/"current".',
|
|
2636
|
+
parameters: {
|
|
2637
|
+
...SESSION_ARGS,
|
|
2638
|
+
turn: {
|
|
2639
|
+
type: 'integer',
|
|
2640
|
+
description: 'Required. 1-based turn number (the value in turn/start events).',
|
|
2641
|
+
},
|
|
2642
|
+
kind: {
|
|
2643
|
+
type: 'string',
|
|
2644
|
+
enum: [...ORIGINAL_KINDS],
|
|
2645
|
+
description: 'Default "tool" (tool results). "message" = user/assistant text, "call" = tool arguments, "all" = every item in the turn.',
|
|
2646
|
+
},
|
|
2647
|
+
toolCallId: {
|
|
2648
|
+
type: 'string',
|
|
2649
|
+
description: 'Select one tool call/result by call id (the toolCallId on the result event).',
|
|
2650
|
+
},
|
|
2651
|
+
messageIndex: {
|
|
2652
|
+
type: 'integer',
|
|
2653
|
+
description: 'Select one message by its 0-based index among the turn\'s user/assistant messages.',
|
|
2654
|
+
},
|
|
2655
|
+
offset: {
|
|
2656
|
+
type: 'integer',
|
|
2657
|
+
description: 'Byte offset into the full selection for paging (default 0). Use nextOffset from a truncated response.',
|
|
2658
|
+
},
|
|
2659
|
+
maxBytes: {
|
|
2660
|
+
type: 'integer',
|
|
2661
|
+
description: 'Byte cap for this call (default config originalFetchMaxBytes = 65536; clamped to 1024..4194304).',
|
|
2662
|
+
},
|
|
2663
|
+
},
|
|
2664
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: originalRender },
|
|
2665
|
+
invoke: (args, config) => sessionOriginal(args, config),
|
|
2666
|
+
},
|
|
2667
|
+
{
|
|
2668
|
+
name: 'session_backup',
|
|
2669
|
+
description:
|
|
2670
|
+
'Plan or create a byte-identical backup of a session log next to it ' +
|
|
2671
|
+
'(session.v4.jsonl.zstd.bak-YYYYMMDD, sha256 verified). dryRun=true writes nothing. ' +
|
|
2672
|
+
'Pass sessionPath, sessionId, or session:"latest"/"current".',
|
|
2673
|
+
parameters: {
|
|
2674
|
+
...SESSION_ARGS,
|
|
2675
|
+
dryRun: { type: 'boolean', description: 'Default true: only report the planned backup.' },
|
|
2676
|
+
confirm: { type: 'string', description: 'Pass "BACKUP" to actually create the backup.' },
|
|
2677
|
+
},
|
|
2678
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2679
|
+
invoke: (args, config) => sessionBackupPlan(args, config),
|
|
2680
|
+
},
|
|
2681
|
+
{
|
|
2682
|
+
name: 'session_truncate',
|
|
2683
|
+
description:
|
|
2684
|
+
'Safely drop the oldest events of a session log while keeping the visible conversation ' +
|
|
2685
|
+
'byte-identical (verified by a deriveMessages digest), with backup, tmp verify and rollback. ' +
|
|
2686
|
+
'dryRun=true writes nothing; writing requires confirm:"TRUNCATE". Refuses the session this app ' +
|
|
2687
|
+
'has loaded (VISIBLE_TARGET_IS_LIVE_SESSION; unknown caller id: VISIBLE_CURRENT_ID_UNKNOWN): ' +
|
|
2688
|
+
'stop the app first. ' +
|
|
2689
|
+
'Pass sessionPath, sessionId, or session:"latest"/"current".',
|
|
2690
|
+
parameters: {
|
|
2691
|
+
...SESSION_ARGS,
|
|
2692
|
+
keepEvents: { type: 'integer', description: 'How many trailing events to keep (integer >= 1, default 20000).' },
|
|
2693
|
+
dryRun: { type: 'boolean', description: 'Default true: plan and verify without writing.' },
|
|
2694
|
+
confirm: { type: 'string', description: 'Pass "TRUNCATE" to actually rewrite the log.' },
|
|
2695
|
+
allowLive: { type: 'boolean', description: 'Diagnostics only. Bypass the live-session refusal; also requires confirm:"I-KNOW-THIS-CORRUPTS". Never use it on the session this app has loaded.' },
|
|
2696
|
+
},
|
|
2697
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2698
|
+
invoke: (args, config) => truncateTool(args, config),
|
|
2699
|
+
},
|
|
2700
|
+
{
|
|
2701
|
+
name: 'session_truncate_visible',
|
|
2702
|
+
description:
|
|
2703
|
+
'Drop whole turns from the FRONT of the visible conversation so the model actually receives ' +
|
|
2704
|
+
'less context. The cut is always on a turn boundary; the first user-authored message survives ' +
|
|
2705
|
+
'(copied into the retained head when its turn is dropped); a protected system/message is kept; ' +
|
|
2706
|
+
'a synthetic user/message archive card records what was removed. The removed prefix is archived ' +
|
|
2707
|
+
'under <session>.archive/<ts>.jsonl.zstd; seq is renumbered 0..n-1; the write is tmp + fsync + ' +
|
|
2708
|
+
'atomic rename with read-back verification and an inflight rollback record. dryRun=true writes ' +
|
|
2709
|
+
'nothing; writing requires confirm:"TRUNCATE-VISIBLE". Refuses the session this app has loaded ' +
|
|
2710
|
+
'(VISIBLE_TARGET_IS_LIVE_SESSION; unknown caller id: VISIBLE_CURRENT_ID_UNKNOWN): truncate it only ' +
|
|
2711
|
+
'while the app is stopped. Defaults: keepTurns=12, keepTokens=80000 ' +
|
|
2712
|
+
'(the later boundary wins). When the first user message is dropped it is carried as a bounded ' +
|
|
2713
|
+
'prefix (firstUserCapChars, default 4000) that names the archive instead of copying megabytes; ' +
|
|
2714
|
+
'the post-cut token budget counts that card, the archive card and the protected head. An unstable ' +
|
|
2715
|
+
'boundary is retried by dropping one more turn (boundaryRetries, default 3); if no cut fits, the ' +
|
|
2716
|
+
'result is feasible=false with the attempted cuts, never a silent success. ' +
|
|
2717
|
+
'Pass sessionPath, sessionId, or session:"latest"/"current".',
|
|
2718
|
+
parameters: {
|
|
2719
|
+
...SESSION_ARGS,
|
|
2720
|
+
keepTurns: { type: 'integer', description: 'Keep at least this many trailing turns (integer >= 1, default 12).' },
|
|
2721
|
+
keepTokens: { type: 'integer', description: 'Keep at least this many estimated trailing message tokens (integer >= 1, default 80000).' },
|
|
2722
|
+
firstUserCapChars: { type: 'integer', description: 'Cap the carried first user message at this many characters (integer >= 1, default 4000); the full text stays in the archive.' },
|
|
2723
|
+
boundaryRetries: { type: 'integer', description: 'When the cut boundary cannot be stabilized, retry with one more dropped turn this many times (integer >= 0, default 3).' },
|
|
2724
|
+
dryRun: { type: 'boolean', description: 'Default true: plan and report without writing.' },
|
|
2725
|
+
confirm: { type: 'string', description: 'Pass "TRUNCATE-VISIBLE" to actually rewrite the log.' },
|
|
2726
|
+
carryFirstUserMessage: { type: 'boolean', description: 'Copy the first user-authored message into the retained head when its turn is dropped (default true).' },
|
|
2727
|
+
insertArchiveCard: { type: 'boolean', description: 'Insert the synthetic [已归档 ...] user/message card (default true). Set false if the host rejects it.' },
|
|
2728
|
+
allowLive: { type: 'boolean', description: 'Diagnostics only. Bypass the live-session refusal; also requires confirm:"I-KNOW-THIS-CORRUPTS". Never use it on the session this app has loaded.' },
|
|
2729
|
+
},
|
|
2730
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2731
|
+
invoke: (args, config) => truncateVisibleTool(args, config),
|
|
2732
|
+
},
|
|
2733
|
+
{
|
|
2734
|
+
name: 'session_compact',
|
|
2735
|
+
description:
|
|
2736
|
+
'Trigger one native harness compaction so the summary is written into the session log ' +
|
|
2737
|
+
'(compaction/summary + compact-checkpoint) instead of living in process memory. ' +
|
|
2738
|
+
'This is the only way to make a long session shorter without losing what it knows; ' +
|
|
2739
|
+
'run it BEFORE session_truncate, because truncation can only delete history a ' +
|
|
2740
|
+
'compaction already shadowed. dryRun=true only reports availability. When called ' +
|
|
2741
|
+
'inside a running turn the request is queued until the agent goes idle.',
|
|
2742
|
+
parameters: {
|
|
2743
|
+
dryRun: { type: 'boolean', description: 'Default true: only report whether compaction is available.' },
|
|
2744
|
+
sourceCommandId: { type: 'string', description: 'Optional command identity recorded on the compaction.' },
|
|
2745
|
+
},
|
|
2746
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2747
|
+
invoke: (args, config) => compactTool(args, config),
|
|
2748
|
+
},
|
|
2749
|
+
{
|
|
2750
|
+
name: 'session_wake',
|
|
2751
|
+
description:
|
|
2752
|
+
'Read a bounded wake-up slice of the memory store (default <DSH home>/longlive-memory; ' +
|
|
2753
|
+
'override with plugin config memoryRoot / memRoot or $DSH_LONGLIVE_MEMORY_ROOT, legacy $DSH_MEM): ' +
|
|
2754
|
+
'the STATE.md sections 我在哪 / 在等什么 / 最近三件 (400 chars each), flow/current.md (800 chars max), ' +
|
|
2755
|
+
'the last three "##" headings of the newest journal/*.md (newest by year/month, not by string sort), and up to 20 INDEX.md lines shorter than 60 chars. ' +
|
|
2756
|
+
'Read-only. Missing files are skipped with a note instead of failing; an absent memory root reports ' +
|
|
2757
|
+
'unavailable. The text is capped at 2500 characters; truncated is true whenever a section or the whole text was cut.',
|
|
2758
|
+
parameters: {
|
|
2759
|
+
session: { type: 'string', description: 'Optional session label for the caller. It never selects or replaces memory content; newlines and "#" are stripped before it can appear in the text.' },
|
|
2760
|
+
},
|
|
2761
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2762
|
+
invoke: (args, config) => sessionWake(args, config),
|
|
2763
|
+
},
|
|
2764
|
+
{
|
|
2765
|
+
name: 'lease_acquire',
|
|
2766
|
+
description:
|
|
2767
|
+
'Atomically take the memory-store write lease (<memoryRoot>/.lease, default ' +
|
|
2768
|
+
'<DSH home>/longlive-memory/.lease; override with memoryRoot / memRoot, $DSH_LONGLIVE_MEMORY_ROOT, or legacy $DSH_MEM). ' +
|
|
2769
|
+
'Concurrency-safe across processes (O_EXCL create): exactly one caller gets ok:true. An existing, ' +
|
|
2770
|
+
'unexpired lease returns ok:false with its holder and acquiredAt (reason "held by another writer"); ' +
|
|
2771
|
+
'an expired or unparseable lease is replaced, retried exactly once.',
|
|
2772
|
+
parameters: {
|
|
2773
|
+
holder: { type: 'string', description: 'Who wants the lease (a process/session name). Required.' },
|
|
2774
|
+
ttlSec: {
|
|
2775
|
+
type: 'integer',
|
|
2776
|
+
description: 'Lease lifetime in whole seconds (integer 1..86400, default 300). A day is the ceiling: a longer lease is a typo, not a plan.',
|
|
2777
|
+
},
|
|
2778
|
+
},
|
|
2779
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2780
|
+
invoke: (args, config) => leaseAcquire(args, config),
|
|
2781
|
+
},
|
|
2782
|
+
{
|
|
2783
|
+
name: 'lease_release',
|
|
2784
|
+
description:
|
|
2785
|
+
'Release the memory-store write lease, but only for the holder recorded inside it. ' +
|
|
2786
|
+
'No file reports ok:false reason "no lease"; a different holder reports ok:false reason ' +
|
|
2787
|
+
'"not the holder" and the lease is left in place.',
|
|
2788
|
+
parameters: {
|
|
2789
|
+
holder: { type: 'string', description: 'Who is releasing; must match the recorded holder. Required.' },
|
|
2790
|
+
},
|
|
2791
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2792
|
+
invoke: (args, config) => leaseRelease(args, config),
|
|
2793
|
+
},
|
|
2794
|
+
{
|
|
2795
|
+
name: 'worker_spawn',
|
|
2796
|
+
description:
|
|
2797
|
+
'Dispatch one background child session (worker) through the host subagents service and return ' +
|
|
2798
|
+
'immediately with its workerId. The child runs in its own context and reports back through the ' +
|
|
2799
|
+
'host; read its state with worker_status and stop it with worker_kill. ' +
|
|
2800
|
+
'Pass prompt (required: the task text), an optional label, and timeoutSec (default 600).',
|
|
2801
|
+
parameters: {
|
|
2802
|
+
prompt: { type: 'string', description: 'The task to hand to the child session. Required.' },
|
|
2803
|
+
label: { type: 'string', description: 'Optional short label for the child (defaults to the prompt head).' },
|
|
2804
|
+
timeoutSec: { type: 'integer', description: 'How long the dispatch itself may take, in whole seconds (integer >= 1, default 600).' },
|
|
2805
|
+
},
|
|
2806
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2807
|
+
invoke: (args, config) => workerSpawn(args, config),
|
|
2808
|
+
},
|
|
2809
|
+
{
|
|
2810
|
+
name: 'worker_status',
|
|
2811
|
+
description:
|
|
2812
|
+
'Report where a worker stands: live status from the Agent registry, else the parent child catalog, ' +
|
|
2813
|
+
'else its persisted session log (events count, last message time, status). ' +
|
|
2814
|
+
'Pass workerId (required), the id worker_spawn returned.',
|
|
2815
|
+
parameters: {
|
|
2816
|
+
workerId: { type: 'string', description: 'The worker id returned by worker_spawn. Required.' },
|
|
2817
|
+
},
|
|
2818
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2819
|
+
invoke: (args, config) => workerStatus(args, config),
|
|
2820
|
+
},
|
|
2821
|
+
{
|
|
2822
|
+
name: 'worker_kill',
|
|
2823
|
+
description:
|
|
2824
|
+
'Stop one running worker through the host subagents service (interrupt, fire-and-return). ' +
|
|
2825
|
+
'A worker that is not running reports unavailable instead of a fake success. ' +
|
|
2826
|
+
'Pass workerId (required) and an optional reason.',
|
|
2827
|
+
parameters: {
|
|
2828
|
+
workerId: { type: 'string', description: 'The worker id returned by worker_spawn. Required.' },
|
|
2829
|
+
reason: { type: 'string', description: 'Optional short reason recorded in the report.' },
|
|
2830
|
+
},
|
|
2831
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2832
|
+
invoke: (args, config) => workerKill(args, config),
|
|
2833
|
+
},
|
|
2834
|
+
{
|
|
2835
|
+
name: 'memory_index',
|
|
2836
|
+
description:
|
|
2837
|
+
'Rebuild the generated section of <memoryRoot>/INDEX.md from every card under topics/, journal/ and ' +
|
|
2838
|
+
'procedures/. Only the region between <!-- BEGIN GENERATED --> and <!-- END GENERATED --> is replaced; hand-written ' +
|
|
2839
|
+
'content outside is preserved byte-for-byte. Cards without frontmatter are legacy cards and still get a row. ' +
|
|
2840
|
+
'Procedures get their own 「程序性」 table (name / trigger / path / strength / version) so they are counted without ' +
|
|
2841
|
+
'appearing twice; a broken procedure card is listed as an invalid row instead of failing the run. ' +
|
|
2842
|
+
'Default is dry-run (returns the section and the resulting file, writes nothing); pass apply:true to write. ' +
|
|
2843
|
+
'Memory root: plugin config memoryRoot (alias memRoot), else $DSH_LONGLIVE_MEMORY_ROOT, ' +
|
|
2844
|
+
'else legacy $DSH_MEM, else <DSH home>/longlive-memory (created on demand).',
|
|
2845
|
+
parameters: {
|
|
2846
|
+
apply: { type: 'boolean', description: 'Default false (dry-run). true rewrites only the generated section, after backing INDEX.md up.' },
|
|
2847
|
+
},
|
|
2848
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2849
|
+
invoke: withLandDoubleRoute('memory_index', memoryTool('memory_index', memoryIndex)),
|
|
2850
|
+
},
|
|
2851
|
+
{
|
|
2852
|
+
name: 'memory_consolidate',
|
|
2853
|
+
description:
|
|
2854
|
+
'Daily consolidation proposals plus resolution. Default action=report reads journal paragraphs after the ' +
|
|
2855
|
+
'last consolidation (or an explicit since) and writes one proposal report; it never edits a card. ' +
|
|
2856
|
+
'action:"accept" (with proposalId) writes a NEW card through the normal writeCard path and records the ' +
|
|
2857
|
+
'resolution in memory-state.json; action:"reject" records the reason instead. Both advance lastConsolidated ' +
|
|
2858
|
+
'over fully resolved days. action:"status" returns the pending backlog. Every proposal id is stable ' +
|
|
2859
|
+
'(sha1(source paragraph)[:12]); ids already seen are never proposed twice. There is no apply flag.',
|
|
2860
|
+
parameters: {
|
|
2861
|
+
since: { type: 'string', description: 'Optional YYYY-MM-DD override for the incremental start; defaults to memory-state.json lastConsolidated.' },
|
|
2862
|
+
action: { type: 'string', enum: ['report', 'accept', 'reject', 'status'], description: 'report (default) | accept | reject | status.' },
|
|
2863
|
+
proposalId: { type: 'string', description: '12-char proposal id (required for accept/reject).' },
|
|
2864
|
+
reason: { type: 'string', description: 'Operator reason (required for reject; recorded in state + audit).' },
|
|
2865
|
+
},
|
|
2866
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2867
|
+
invoke: withLandDoubleRoute('memory_consolidate', memoryTool('memory_consolidate', memoryConsolidate)),
|
|
2868
|
+
},
|
|
2869
|
+
{
|
|
2870
|
+
name: 'memory_reinforce',
|
|
2871
|
+
description:
|
|
2872
|
+
'Record one real use of a card: strength = min(9, strength+1), last_used = today, revisions += 1, plus one ' +
|
|
2873
|
+
'<!-- rev: ... --> line with the reason. The prose body must stay byte-identical; the original is backed up ' +
|
|
2874
|
+
'to <memoryRoot>/.longlive/backups/ before writing, and any post-write mismatch rolls the card back. ' +
|
|
2875
|
+
'Pass path (required, relative to memoryRoot or absolute inside it).',
|
|
2876
|
+
parameters: {
|
|
2877
|
+
path: { type: 'string', description: 'The card to reinforce, relative to memoryRoot or an absolute path inside it. Required.' },
|
|
2878
|
+
reason: { type: 'string', description: 'Optional short reason stored in the rev comment (default "被真实使用").' },
|
|
2879
|
+
},
|
|
2880
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2881
|
+
invoke: withLandDoubleRoute('memory_reinforce', memoryTool('memory_reinforce', memoryReinforce)),
|
|
2882
|
+
},
|
|
2883
|
+
{
|
|
2884
|
+
name: 'memory_forget',
|
|
2885
|
+
description:
|
|
2886
|
+
'Propose forgetting by decay rules: last_used > 90 days and strength <= 2 demotes to epochs/, last_used > ' +
|
|
2887
|
+
'365 days tombstones. Cards with salience >= 5 are never proposed. Default is dry-run and writes nothing: it ' +
|
|
2888
|
+
'only reports proposals and whether epochs/, archive/tombstones/ and .longlive/backups exist. Execution ' +
|
|
2889
|
+
'requires confirm:"FORGET": it creates those paths, backs up each card into .longlive/backups/ first, rewrites ' +
|
|
2890
|
+
'tombstones.md atomically with a three-question epitaph per card (reason / affects / stillUseful) BEFORE moving ' +
|
|
2891
|
+
'the card to archive/tombstones/ (or epochs/), appends exactly one line to .longlive/audit.log, and never ' +
|
|
2892
|
+
'deletes a file.',
|
|
2893
|
+
parameters: {
|
|
2894
|
+
confirm: { type: 'string', description: 'Default absent = dry-run. Pass "FORGET" to execute the proposals.' },
|
|
2895
|
+
status: { type: 'boolean', description: 'true = read-only forget visibility: recorded dry/real runs, scaffold dirs, execution gate.' },
|
|
2896
|
+
},
|
|
2897
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2898
|
+
invoke: withLandDoubleRoute('memory_forget', memoryTool('memory_forget', memoryForgetTool)),
|
|
2899
|
+
},
|
|
2900
|
+
{
|
|
2901
|
+
name: 'memory_procedure',
|
|
2902
|
+
description:
|
|
2903
|
+
'Procedural memory: how a task is done, not what happened. One card per procedure at ' +
|
|
2904
|
+
'<memoryRoot>/procedures/<slug>.md. Frontmatter is required: name / trigger / salience / ' +
|
|
2905
|
+
'strength / last_used (plus revisions). Body sections: 何时用 / 怎么做 (a numbered list) / ' +
|
|
2906
|
+
'失败模式 / 例子. action:"save" creates or merges by slug (same slug -> revisions+1, the old ' +
|
|
2907
|
+
'version is backed up under .longlive/backups/, and fields you omit keep their old value); a NEW ' +
|
|
2908
|
+
'card needs name plus when and at least one step. action:"list" filters by trigger keyword ' +
|
|
2909
|
+
'(space or comma separated, case-insensitive, OR over keywords); action:"get" returns one card ' +
|
|
2910
|
+
'including its raw text; action:"report" records one real use: success -> strength+1, failure -> ' +
|
|
2911
|
+
'strength-1 (clamped to 0..9), last_used = today, plus one <!-- rev: ... --> line. report leaves ' +
|
|
2912
|
+
'revisions alone: revisions counts content versions, strength counts how often it worked. A card ' +
|
|
2913
|
+
'whose frontmatter is broken or misses a required field is reported with E_PROCEDURE_INVALID and ' +
|
|
2914
|
+
'is never silently overwritten.',
|
|
2915
|
+
parameters: {
|
|
2916
|
+
action: {
|
|
2917
|
+
type: 'string',
|
|
2918
|
+
enum: [...PROCEDURE_ACTIONS],
|
|
2919
|
+
description: 'Required. save | list | get | report.',
|
|
2920
|
+
},
|
|
2921
|
+
name: { type: 'string', description: 'Card title (frontmatter name). save derives the slug from it when slug is absent; get/report accept it instead of slug.' },
|
|
2922
|
+
slug: { type: 'string', description: `File stem under ${PROCEDURES_DIR}/. save/get/report may pass it explicitly (no path separators, no ..).` },
|
|
2923
|
+
trigger: { type: 'array', items: { type: 'string' }, description: 'When this procedure applies (frontmatter trigger). save replaces the whole list; list uses the keywords as an OR filter.' },
|
|
2924
|
+
salience: { type: 'integer', description: 'Importance 1..5 (default 3 on a new card, kept on merge unless given).' },
|
|
2925
|
+
strength: { type: 'integer', description: 'How often it worked 0..9 (default 3 on a new card; report changes it, save sets it explicitly).' },
|
|
2926
|
+
when: { type: 'string', description: 'Body section 「何时用」: the situation that calls for this procedure. Required for a new card.' },
|
|
2927
|
+
steps: { type: 'array', items: { type: 'string' }, description: 'Body section 「怎么做」: ordered steps, written as a numbered list. Required (at least one) for a new card. A single string with newlines is accepted too.' },
|
|
2928
|
+
failureModes: { type: 'string', description: 'Optional body section 「失败模式」: how this procedure goes wrong.' },
|
|
2929
|
+
example: { type: 'string', description: 'Optional body section 「例子」: one concrete run.' },
|
|
2930
|
+
outcome: { type: 'string', enum: ['success', 'failure'], description: 'report only, required: success raises strength by 1, failure lowers it by 1.' },
|
|
2931
|
+
reason: { type: 'string', description: 'report only: short reason stored in the rev comment.' },
|
|
2932
|
+
limit: { type: 'integer', description: 'list only: page size (default 50, max 500). total/count/truncated are always reported.' },
|
|
2933
|
+
},
|
|
2934
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2935
|
+
invoke: withLandDoubleRoute('memory_procedure', memoryTool('memory_procedure', memoryProcedure)),
|
|
2936
|
+
},
|
|
2937
|
+
{
|
|
2938
|
+
name: 'memory_recall',
|
|
2939
|
+
description:
|
|
2940
|
+
'Search memory cards by meaning-ish keywords and get the best few back. Mixed, reproducible score: title ' +
|
|
2941
|
+
'hits *5 + tags *3 + body frequency (capped 3) + whole-query phrase bonus + character-bigram Dice similarity. ' +
|
|
2942
|
+
'Returns {path, title, score, excerpt} sorted by score desc then path asc; the same tree and query always ' +
|
|
2943
|
+
'produce byte-identical results. Defaults: topK 3 (1..20), room any, status active+locked — already-locked ' +
|
|
2944
|
+
'cards are searchable. Pass status:"archived" or "any" to widen, room:"topics" to narrow. READ-ONLY: it never ' +
|
|
2945
|
+
'writes a card, never builds INDEX.md and never creates .longlive/. An empty query throws ' +
|
|
2946
|
+
'E_RECALL_EMPTY_QUERY; no hit is not an error — it returns an empty results list with code ' +
|
|
2947
|
+
'E_RECALL_NO_MATCH and a hint.',
|
|
2948
|
+
parameters: {
|
|
2949
|
+
query: { type: 'string', description: 'Required. Natural language or keywords, e.g. "听觉 训练".' },
|
|
2950
|
+
topK: { type: 'integer', description: 'How many cards to return (default 3, clamped to 1..20).' },
|
|
2951
|
+
room: { type: 'string', description: 'Optional relative directory filter: topics, journal, or a subdirectory of either.' },
|
|
2952
|
+
status: { type: 'string', enum: ['active', 'locked', 'archived', 'any'], description: 'Card status filter. Default active+locked; "any" includes archived.' },
|
|
2953
|
+
archive: { type: 'boolean', description: 'archive:true 走冷档 fail-closed 检索(2.0.0 W3b):返回 {ok, archived:true, items, manifestSha, stats};冷档离线/坏 state 抛 E_HG_ARCHIVE_OFFLINE,manifest schema/index 不符抛 E_HG_ARCHIVE_MIGRATE_MISMATCH;未配置冷档则静默空。默认 false(本地卡召回)。' },
|
|
2954
|
+
},
|
|
2955
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2956
|
+
invoke: memoryTool('memory_recall', memoryRecall),
|
|
2957
|
+
},
|
|
2958
|
+
{
|
|
2959
|
+
name: 'memory_recall_v2',
|
|
2960
|
+
description:
|
|
2961
|
+
'Multi-route recall with an evidence gate and a deterministic fast-answer channel (read-only). Returns ' +
|
|
2962
|
+
'{query,confidence,hits:[{card,anchor,quote,score}],didYouMean,slowPath,fastAnswer,evidenceGate}. ' +
|
|
2963
|
+
'Fail-safe: no hit => confidence "none" with E_NO_EVIDENCE and NO guess; multiple/ambiguous/non-live ' +
|
|
2964
|
+
'anchors => slowPath true and fallback "model"; only a unique high-confidence hit whose quote matches the ' +
|
|
2965
|
+
'asked value type (version/path/time/number) produces fastAnswer (quote + coordinate, no generation). ' +
|
|
2966
|
+
'Params: query (required), topK 1..10, project?, since?, until?, includeForgotten (default false).',
|
|
2967
|
+
parameters: {
|
|
2968
|
+
query: { type: 'string', description: 'Required. Natural-language question or keywords.' },
|
|
2969
|
+
topK: { type: 'integer', description: 'How many hits to return (default 3, clamped 1..10).' },
|
|
2970
|
+
project: { type: 'string', description: 'Optional project filter (card frontmatter project when present).' },
|
|
2971
|
+
since: { type: 'string', description: 'Optional ISO date lower bound on card date.' },
|
|
2972
|
+
until: { type: 'string', description: 'Optional ISO date upper bound on card date.' },
|
|
2973
|
+
includeForgotten: { type: 'boolean', description: 'Default false; true also returns archived/forgotten cards (marked stale anchors).' },
|
|
2974
|
+
},
|
|
2975
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
2976
|
+
invoke: withLandDoubleRoute('memory_recall_v2', memoryTool('memory_recall_v2', recallV2)),
|
|
2977
|
+
},
|
|
2978
|
+
{
|
|
2979
|
+
name: 'session_live_update',
|
|
2980
|
+
description:
|
|
2981
|
+
'Write or patch this session\'s row in the live registry (<memoryRoot>/.longlive/live/<sessionId>.json). ' +
|
|
2982
|
+
'state is required: idle | running | waiting | blocked | stale. Omitted optional fields keep their previous ' +
|
|
2983
|
+
'value, except blocked_on, which is cleared whenever state is not "blocked". pid and host are always the ' +
|
|
2984
|
+
'calling process and machine; startedAt is preserved. goal is cut to 80 characters, queued to 200 items of ' +
|
|
2985
|
+
'300 characters each, and last_action.detail to 500 characters; the result reports every cut ' +
|
|
2986
|
+
'(goalTruncated / queuedTruncated / lastActionDetailTruncated). The file is written tmp -> rename with a ' +
|
|
2987
|
+
'read-back, so a crash never leaves half a JSON. If a directory or symlink occupies the row path, the write ' +
|
|
2988
|
+
'is refused up front with E_LIVE_ROW_BLOCKED instead of failing late in rename. Pass sessionId only to write ' +
|
|
2989
|
+
'another session\'s row; by default the host\'s current session is used.',
|
|
2990
|
+
parameters: {
|
|
2991
|
+
sessionId: { type: 'string', description: 'Optional session id; defaults to the host\'s current session id.' },
|
|
2992
|
+
state: {
|
|
2993
|
+
type: 'string',
|
|
2994
|
+
enum: ['idle', 'running', 'waiting', 'blocked', 'stale'],
|
|
2995
|
+
description: 'Required writer-declared state. dead/corrupt are computed by readers and cannot be written.',
|
|
2996
|
+
},
|
|
2997
|
+
turn: { type: 'integer', description: 'Current turn number (integer >= 0, default keeps the previous value or 0).' },
|
|
2998
|
+
goal: { type: 'string', description: 'What this session is doing; stored at most 80 characters (longer input is truncated and flagged).' },
|
|
2999
|
+
blocked_on: { type: 'string', description: 'What the session is waiting on. Only kept while state is "blocked".' },
|
|
3000
|
+
queued: { type: 'array', items: { type: 'string' }, description: 'Queued work items (strings); replaces the previous queue.' },
|
|
3001
|
+
ttlMs: {
|
|
3002
|
+
type: 'integer',
|
|
3003
|
+
description: 'Heartbeat lifetime in ms (integer 1000..86400000, default 60000). Older than 2x this is stale.',
|
|
3004
|
+
},
|
|
3005
|
+
last_action: {
|
|
3006
|
+
type: 'object',
|
|
3007
|
+
additionalProperties: false,
|
|
3008
|
+
properties: {
|
|
3009
|
+
at: { type: 'string', description: 'ISO timestamp; defaults to now.' },
|
|
3010
|
+
kind: { type: 'string', description: 'Short action kind, e.g. "edit" or "tool".' },
|
|
3011
|
+
detail: { type: 'string', description: 'Short human-readable detail.' },
|
|
3012
|
+
},
|
|
3013
|
+
description: 'Last action {at, kind, detail}; defaults to now/create or now/update.',
|
|
3014
|
+
},
|
|
3015
|
+
},
|
|
3016
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
3017
|
+
invoke: (args, config) => liveUpdate(args, config),
|
|
3018
|
+
},
|
|
3019
|
+
{
|
|
3020
|
+
name: 'session_live_list',
|
|
3021
|
+
description:
|
|
3022
|
+
'List the live registry (<memoryRoot>/.longlive/live) with a computed effectiveState for every row. ' +
|
|
3023
|
+
'Liveness is heartbeat-first: a heartbeat within one ttlMs is running regardless of pid (pid is the ' +
|
|
3024
|
+
'writer\'s, not the session\'s); older than 2x ttlMs is stale; older than 4x ttlMs, or same-host with a pid ' +
|
|
3025
|
+
'that definitively no longer exists, is dead; a file that cannot be parsed or has the wrong shape is corrupt ' +
|
|
3026
|
+
'(listed, never thrown). Other hosts\' pids are never probed, so remote rows age purely by heartbeat and can ' +
|
|
3027
|
+
'be stale or dead but are never treated as dead by pid. dead rows are hidden unless includeDead:true; the ' +
|
|
3028
|
+
'result always reports hiddenDead and per-state counts. Orphan tmp files are ignored by the list.',
|
|
3029
|
+
parameters: {
|
|
3030
|
+
includeDead: { type: 'boolean', description: 'Default false: hide rows whose same-host pid no longer exists.' },
|
|
3031
|
+
},
|
|
3032
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
3033
|
+
invoke: (args, config) => liveList(args, config),
|
|
3034
|
+
},
|
|
3035
|
+
{
|
|
3036
|
+
name: 'session_live_get',
|
|
3037
|
+
description:
|
|
3038
|
+
'Read one row of the live registry by sessionId, with the same computed effectiveState as session_live_list ' +
|
|
3039
|
+
'(dead / stale / corrupt included). sessionId must already be canonical (lowercase): a case or whitespace ' +
|
|
3040
|
+
'alias throws E_SESSION_ID_NOT_CANONICAL with the canonical id in error.canonical, because NTFS maps aliases ' +
|
|
3041
|
+
'to one file and a silent lookup cannot say which session was read. A symlinked row is refused rather than ' +
|
|
3042
|
+
'followed. A missing row returns ok:false status:"absent" instead of failing; a row that cannot be parsed ' +
|
|
3043
|
+
'throws E_LIVE_CORRUPT.',
|
|
3044
|
+
parameters: {
|
|
3045
|
+
sessionId: { type: 'string', description: 'Session id whose row to read. Required.' },
|
|
3046
|
+
},
|
|
3047
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
3048
|
+
invoke: (args, config) => liveGet(args, config),
|
|
3049
|
+
},
|
|
3050
|
+
{
|
|
3051
|
+
name: 'session_live_prune',
|
|
3052
|
+
description:
|
|
3053
|
+
'Clean the live registry. Row candidates are dead rows from this host (heartbeat older than 4x ttlMs, or ' +
|
|
3054
|
+
'same-host pid definitively gone), or corrupt rows without another host\'s stamp. Before unlinking, each ' +
|
|
3055
|
+
'candidate is re-read and re-judged: it is deleted only if it is STILL dead/corrupt AND its bytes did not ' +
|
|
3056
|
+
'change; otherwise it is returned under skipped. A row carrying blocked_on is never auto-deleted (skipped), ' +
|
|
3057
|
+
'and every deleted/skipped row keeps blocked_on, queued and startedAt in the result. Remote rows are never ' +
|
|
3058
|
+
'deleted: a merely dead remote row is left alone, and a corrupt row whose bytes still name a remote host is ' +
|
|
3059
|
+
'skipped too (host unknown is the only corrupt case prune may remove). Also reports (and with confirm ' +
|
|
3060
|
+
'removes) orphan *.tmp-* files older than one hour and empty directory placeholders; non-empty directories ' +
|
|
3061
|
+
'and symlinks are reported only. Default is dry-run (candidates, wouldDelete, skipped; deletes nothing); a ' +
|
|
3062
|
+
'real delete requires confirm:"PRUNE". dryRun:false without the confirm word throws E_CONFIRM_REQUIRED.',
|
|
3063
|
+
parameters: {
|
|
3064
|
+
dryRun: { type: 'boolean', description: 'Default true (preview only). false with confirm:"PRUNE" really deletes.' },
|
|
3065
|
+
confirm: { type: 'string', description: 'Pass "PRUNE" to actually delete the previewed candidates.' },
|
|
3066
|
+
},
|
|
3067
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
3068
|
+
invoke: (args, config) => livePrune(args, config),
|
|
3069
|
+
},
|
|
3070
|
+
{
|
|
3071
|
+
name: 'memory_feedback',
|
|
3072
|
+
description:
|
|
3073
|
+
'Recall feedback (D20): record one real use of a card (up/down ±0.5 salience, down never lowers ' +
|
|
3074
|
+
'salience), with a bounded feedback.jsonl (<=2000 rows / 180d, <=2 per round, rollbackable). ' +
|
|
3075
|
+
'STATUS ONLY TODAY: action "status" returns a structured UNSET (implemented:false) because the ' +
|
|
3076
|
+
'feedback store belongs to a later batch; write actions throw E_HG_RECALL_FEEDBACK_UNIMPLEMENTED. ' +
|
|
3077
|
+
'Fail-closed: no write, no row, no silent success before the store exists.',
|
|
3078
|
+
parameters: {
|
|
3079
|
+
action: { type: 'string', enum: ['status', 'up', 'down', 'rollback'], description: 'status = read-only UNSET report; up/down/rollback require the D20 store (not implemented yet).' },
|
|
3080
|
+
card: { type: 'string', description: 'Card path (relative to memoryRoot) the feedback is about.' },
|
|
3081
|
+
reason: { type: 'string', description: 'Short reason stored with the feedback row.' },
|
|
3082
|
+
},
|
|
3083
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
3084
|
+
invoke: memoryTool('memory_feedback', (args) => {
|
|
3085
|
+
if (args.action === undefined || args.action === 'status') {
|
|
3086
|
+
return {
|
|
3087
|
+
ok: true,
|
|
3088
|
+
status: 'UNSET',
|
|
3089
|
+
implemented: false,
|
|
3090
|
+
code: 'E_HG_RECALL_FEEDBACK_UNIMPLEMENTED',
|
|
3091
|
+
batch: 'D',
|
|
3092
|
+
message: 'memory_feedback 的落盘存储属于后续批次;本批只登记工具入口,不写 feedback.jsonl。',
|
|
3093
|
+
};
|
|
3094
|
+
}
|
|
3095
|
+
return memoryFeedback(args);
|
|
3096
|
+
}),
|
|
3097
|
+
},
|
|
3098
|
+
{
|
|
3099
|
+
name: 'memory_conflicts',
|
|
3100
|
+
description:
|
|
3101
|
+
'Conflict view and the human approval surface for conflict candidates (D14). action "list" ' +
|
|
3102
|
+
'(default) returns the unified conflict view (claims preferred, legacy records only when no claims ' +
|
|
3103
|
+
'exist) plus the scanned candidate pairs/edges and pending ledger counts; includeLifecycle=true adds ' +
|
|
3104
|
+
'the read-only lifecycle view. action "accept" appends exactly one conflicts_with edge to ' +
|
|
3105
|
+
'.longlive/recall/edges.jsonl and exactly one auto-authz audit row (kind=conflict-accept), after ' +
|
|
3106
|
+
'validating both cards exist and the edge is not a duplicate; action "reject" only marks the ' +
|
|
3107
|
+
'candidate rejected and writes no edge and no audit row. It never merges cards and never resolves ' +
|
|
3108
|
+
'a content conflict; resolution stays with memory_consolidate.',
|
|
3109
|
+
parameters: {
|
|
3110
|
+
memoryRoot: { type: 'string', description: 'Memory root to inspect. Required (no implicit default).' },
|
|
3111
|
+
action: { type: 'string', enum: ['list', 'accept', 'reject'], description: 'list = read-only view (default); accept = write one conflicts_with edge + one audit row; reject = mark candidate rejected only.' },
|
|
3112
|
+
includeLifecycle: { type: 'boolean', description: 'list only: also return lifecycle conflicts (default false).' },
|
|
3113
|
+
id: { type: 'string', description: 'accept/reject: candidate id from a previous list.' },
|
|
3114
|
+
from: { type: 'string', description: 'accept/reject without id: first card path (topics/…).' },
|
|
3115
|
+
to: { type: 'string', description: 'accept/reject without id: second card path (topics/…).' },
|
|
3116
|
+
evidence: {
|
|
3117
|
+
type: 'object',
|
|
3118
|
+
description: 'accept: optional evidence {path, lines:[start,end], quote}; lines must be exactly two integers.',
|
|
3119
|
+
properties: {
|
|
3120
|
+
path: { type: 'string', required: true, description: 'Card path (topics/…).' },
|
|
3121
|
+
lines: { type: 'array', items: { type: 'integer' }, description: '[start, end], 1-based, start >= 1.' },
|
|
3122
|
+
quote: { type: 'string', description: 'Exact quoted text.' },
|
|
3123
|
+
sha256: { type: 'string', description: 'Optional sha256 of the evidence source.' },
|
|
3124
|
+
},
|
|
3125
|
+
additionalProperties: false,
|
|
3126
|
+
},
|
|
3127
|
+
confidence: { type: 'number', description: 'accept: optional confidence for the written edge (default 1).' },
|
|
3128
|
+
source: { type: 'string', description: 'accept: optional source label for the written edge.' },
|
|
3129
|
+
actor: { type: 'string', description: 'accept/reject: actor label recorded in the edge/ledger/audit.' },
|
|
3130
|
+
reason: { type: 'string', description: 'reject: reason recorded in the candidate ledger.' },
|
|
3131
|
+
now: { type: 'string', description: 'Optional ISO timestamp override (deterministic fixtures).' },
|
|
3132
|
+
},
|
|
3133
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
3134
|
+
invoke: memoryTool('memory_conflicts', (args, config) => {
|
|
3135
|
+
const memoryRoot = args.memoryRoot ?? config.memoryRoot;
|
|
3136
|
+
if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
|
|
3137
|
+
throw memoryError('E_MEMORY_ROOT_UNSET', 'memory_conflicts 需要显式 memoryRoot。');
|
|
3138
|
+
}
|
|
3139
|
+
return memoryConflicts({ ...args, memoryRoot });
|
|
3140
|
+
}),
|
|
3141
|
+
},
|
|
3142
|
+
{
|
|
3143
|
+
name: 'memory_wake',
|
|
3144
|
+
description:
|
|
3145
|
+
'Wake bridge (D23): hand a queued todo to a fresh isolated subagent under a bounded budget ' +
|
|
3146
|
+
'(<=3 rounds / 2K tokens / 180s soft budget, <=20/day, 10min cooldown, <=200 queued tickets, ' +
|
|
3147
|
+
'2 retries). action "status" returns a read-only report (capability probe, queue/pending counts, ' +
|
|
3148
|
+
'last run, bounds); "drain" runs at most one cycle now (fail-closed: 0 sessions when the bridge ' +
|
|
3149
|
+
'is disabled, the capability (auto preset + auto-review 0.2.3-alpha.2) is missing, the daily ' +
|
|
3150
|
+
'quota/cooldown is hit, or the queue is empty); "enqueue" adds one ticket {kind,target,params?' +
|
|
3151
|
+
',evidence?,expectedEffect?,risk?} with dedupe (busy ticket with the same dedupeKey is returned ' +
|
|
3152
|
+
'instead of duplicated). Never creates a session from status.',
|
|
3153
|
+
parameters: {
|
|
3154
|
+
action: { type: 'string', enum: ['status', 'drain', 'enqueue'], description: 'status = read-only report; drain = run one cycle; enqueue = add a ticket.' },
|
|
3155
|
+
ticket: { type: 'object', additionalProperties: true, description: 'enqueue payload: {kind: forget_historical|conflict_resolved|procedure_candidate|promise_done|migration_confirm, target, params?, evidence?, expectedEffect?, risk?}.' },
|
|
3156
|
+
},
|
|
3157
|
+
output: { schema: { type: 'object', additionalProperties: true }, render: (_a, value) => OUTPUT_TEXT(value) },
|
|
3158
|
+
invoke: memoryTool('memory_wake', (args, config) => {
|
|
3159
|
+
const root = config?.memoryRoot ?? config?.memRoot ?? memRoot(config);
|
|
3160
|
+
return wakeTool(args, { ...(config ?? {}), memoryRoot: root });
|
|
3161
|
+
}),
|
|
3162
|
+
},
|
|
3163
|
+
];
|
|
3164
|
+
|
|
3165
|
+
|
|
3166
|
+
/**
|
|
3167
|
+
* Register the tools on a Cordis context. `@deepseek-ai/dsh-tools` is imported
|
|
3168
|
+
* lazily so plain-node tests can exercise `TOOLS` without the host present.
|
|
3169
|
+
*/
|
|
3170
|
+
export async function registerTools(ctx, config = {}) {
|
|
3171
|
+
// `@deepseek-ai/dsh-tools` is imported lazily so plain-node tests can exercise
|
|
3172
|
+
// `TOOLS` without the host present; `config.defineTool` is the same seam for a
|
|
3173
|
+
// suite that wants to drive the real registration path (test/router-runtime).
|
|
3174
|
+
const defineTool =
|
|
3175
|
+
typeof config.defineTool === 'function'
|
|
3176
|
+
? config.defineTool
|
|
3177
|
+
: (await import('@deepseek-ai/dsh-tools')).defineTool;
|
|
3178
|
+
// `host` keeps the live Cordis context reachable from a tool body: compaction
|
|
3179
|
+
// is a host service (ctx.compaction) acting on the host agent (ctx.agent), and
|
|
3180
|
+
// neither can be reconstructed from arguments.
|
|
3181
|
+
const bound = { ...config, host: () => ctx };
|
|
3182
|
+
// Fan-out tools are opt-in from 1.6.0 on; `undefined` means the safe default.
|
|
3183
|
+
const workersEnabled = bound.workers?.enabled !== false;
|
|
3184
|
+
// R1 runtime adapter. Absent (or `routerRuntime: 'off'`, which creates no
|
|
3185
|
+
// adapter) means the execute closure below is byte-identical to before.
|
|
3186
|
+
const routerRuntime = bound.routerRuntime && typeof bound.routerRuntime.intercept === 'function' ? bound.routerRuntime : null;
|
|
3187
|
+
// RouterService tools exist only when the service is enabled and was passed in
|
|
3188
|
+
// by apply(). With routerEnabled=false this array is empty, so registration is
|
|
3189
|
+
// byte-for-byte the 0.9.0 path (22 tools, no extra hooks).
|
|
3190
|
+
// RouterService tools exist only when the service is enabled and apply()
|
|
3191
|
+
// injected them. With routerEnabled=false this array is empty, so registration
|
|
3192
|
+
// is byte-for-byte the 0.9.0 path (22 tools, no extra hooks).
|
|
3193
|
+
const routerTools = Array.isArray(bound.routerTools) ? bound.routerTools : [];
|
|
3194
|
+
// D6 (default off): the fallback tool_search is registered only when the
|
|
3195
|
+
// feature is enabled; appending it after the normal set keeps the baseline
|
|
3196
|
+
// order byte-identical when D6 is off.
|
|
3197
|
+
const d6Tools = Array.isArray(bound.d6Tools) ? bound.d6Tools : [];
|
|
3198
|
+
// 1.8.0 answer-guard: read-only answer_audit tool appended when enabled.
|
|
3199
|
+
const answerTools = Array.isArray(bound.answerTools) ? bound.answerTools : [];
|
|
3200
|
+
const extraTools = [...routerTools, ...d6Tools, ...answerTools];
|
|
3201
|
+
const allTools = extraTools.length > 0
|
|
3202
|
+
? [...TOOLS, ...extraTools]
|
|
3203
|
+
: TOOLS;
|
|
3204
|
+
const ownNames = new Set(allTools.map((tool) => tool.name));
|
|
3205
|
+
for (const tool of allTools) {
|
|
3206
|
+
ctx.tools.register(defineTool({
|
|
3207
|
+
name: tool.name,
|
|
3208
|
+
description: tool.description,
|
|
3209
|
+
parameters: tool.parameters,
|
|
3210
|
+
output: tool.output,
|
|
3211
|
+
// `exec` carries the exact live calling Agent (exec.agent) and its signal
|
|
3212
|
+
// (exec.signal); the worker tools need both to authorize a child.
|
|
3213
|
+
execute: (args, exec) => {
|
|
3214
|
+
// 1.6.0 safety gate: no child session can be spawned, listed or killed
|
|
3215
|
+
// until the profile opts in. This is the only path the Host uses.
|
|
3216
|
+
if (!workersEnabled && WORKER_TOOL_NAMES.includes(tool.name)) {
|
|
3217
|
+
return workerUnavailable(WORKERS_DISABLED_MESSAGE);
|
|
3218
|
+
}
|
|
3219
|
+
// Auto-heartbeat: every longlive call is also a liveness signal for the
|
|
3220
|
+
// caller's own row (never for an explicit `sessionId` argument). This is
|
|
3221
|
+
// best effort and must never change what the tool itself returns.
|
|
3222
|
+
try {
|
|
3223
|
+
bound.autoHeartbeat?.autoTouch?.(exec, tool.name);
|
|
3224
|
+
} catch {
|
|
3225
|
+
/* heartbeat is decoration; the tool call wins */
|
|
3226
|
+
}
|
|
3227
|
+
const invoke = () => tool.invoke(args, { ...bound, exec });
|
|
3228
|
+
// Shadow records and returns the tool's own value; on may refuse a
|
|
3229
|
+
// high-risk write before invoke ever runs. Without an adapter this is a
|
|
3230
|
+
// direct call, so the synchronous contract of every tool is preserved.
|
|
3231
|
+
return routerRuntime ? routerRuntime.intercept(tool.name, args, invoke) : invoke();
|
|
3232
|
+
},
|
|
3233
|
+
}));
|
|
3234
|
+
}
|
|
3235
|
+
// The external memory tool belongs to its plugin, not to this plugin, so wrapping
|
|
3236
|
+
// cannot see it. The host's pre-execute guard is the only non-invasive hook
|
|
3237
|
+
// that can: in shadow it returns undefined (allow) and only records; in `on`
|
|
3238
|
+
// it may return a denial reason for a high-risk write. `ownNames` keeps the
|
|
3239
|
+
// guard away from tools already wrapped above (no double records).
|
|
3240
|
+
if (routerRuntime && routerRuntime.enabled) {
|
|
3241
|
+
if (typeof ctx.tools.guard === 'function') {
|
|
3242
|
+
try {
|
|
3243
|
+
ctx.tools.guard((execution) =>
|
|
3244
|
+
ownNames.has(execution.name) ? undefined : routerRuntime.guard(execution.name, execution.arguments),
|
|
3245
|
+
);
|
|
3246
|
+
} catch (error) {
|
|
3247
|
+
try {
|
|
3248
|
+
console.warn?.(`[longlive] router guard unavailable, shadow records only wrapped tools: ${error && error.message}`);
|
|
3249
|
+
} catch {
|
|
3250
|
+
/* a missing warning must not fail registration */
|
|
3251
|
+
}
|
|
3252
|
+
}
|
|
3253
|
+
} else {
|
|
3254
|
+
try {
|
|
3255
|
+
console.warn?.(`[longlive] host tools.guard() absent; routerRuntime=${routerRuntime.mode} covers wrapped tools only`);
|
|
3256
|
+
} catch {
|
|
3257
|
+
/* ignore */
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
return allTools.length;
|
|
3262
|
+
}
|