@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/heartbeat.js
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// Auto-heartbeat for the "正在" live registry.
|
|
2
|
+
//
|
|
3
|
+
// Two clocks keep a row fresh without the caller passing sessionId:
|
|
4
|
+
// 1. turn lifecycle — `session/event` with `turn/start` / `turn/end`. The
|
|
5
|
+
// event itself carries the session id, so turn boundaries maintain EVERY
|
|
6
|
+
// non-subagent session's row (R4.5), bound or not; a missing row is
|
|
7
|
+
// created on the first boundary (128-row cap respected, R4.3);
|
|
8
|
+
// 2. a fallback interval (`heartbeatMs`, default 15 s, `0` disables), which
|
|
9
|
+
// keeps rows of sessions bound by a longlive tool call fresh through long
|
|
10
|
+
// tool calls and idle stretches. It never fabricates rows.
|
|
11
|
+
//
|
|
12
|
+
// Turn boundaries are a state machine, not a heartbeat: `turn/start` writes
|
|
13
|
+
// `state='running'` plus the turn number, `turn/end` writes
|
|
14
|
+
// `idle`/`waiting`/`blocked` plus the turn number (R4.3). It is event driven,
|
|
15
|
+
// so it still runs when the fallback timer is off (`heartbeatMs: 0`); a timer
|
|
16
|
+
// tick, by contrast, only renews `heartbeatAt` and never touches state or
|
|
17
|
+
// `last_action`.
|
|
18
|
+
//
|
|
19
|
+
// Every write is best effort: a missing/corrupt row, an unset memoryRoot, a
|
|
20
|
+
// full registry or a racing writer must never fail a tool call or crash the
|
|
21
|
+
// host.
|
|
22
|
+
|
|
23
|
+
import { liveGet, liveList, liveTouch, liveUpdate } from './live.js';
|
|
24
|
+
import { resolveCurrentSessionId } from './identity.js';
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_HEARTBEAT_MS = 15_000;
|
|
27
|
+
export const MAX_BOUND_SESSIONS = 64;
|
|
28
|
+
/** DESIGN §2.1 live-row cap; mirrored here so turn boundaries cannot blow it up. */
|
|
29
|
+
export const MAX_LIVE_ROWS = 128;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* R4.3 pure state machine: state a live row must carry when a turn starts.
|
|
33
|
+
* @returns {'running'}
|
|
34
|
+
*/
|
|
35
|
+
export function stateForTurnStart() {
|
|
36
|
+
return 'running';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* R4.3 pure state machine: state a live row must carry when a turn ends.
|
|
41
|
+
* `waiting`/`blocked` are user-facing promises and survive the turn boundary;
|
|
42
|
+
* anything else falls back to `idle`.
|
|
43
|
+
* @param {unknown} priorState declared state read before the turn/end write
|
|
44
|
+
* @returns {'idle'|'waiting'|'blocked'}
|
|
45
|
+
*/
|
|
46
|
+
export function stateForTurnEnd(priorState) {
|
|
47
|
+
return priorState === 'waiting' || priorState === 'blocked' ? priorState : 'idle';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Pure description of the live-row patch caused by one turn boundary. Kept
|
|
52
|
+
* separate from I/O so the state machine can be pinned without a registry.
|
|
53
|
+
* @param {'turn/start'|'turn/end'} type
|
|
54
|
+
* @param {{turn?:unknown, priorState?:unknown}} [options]
|
|
55
|
+
* @returns {{state:string, turn:number|null, kind:'turn', detail:string}}
|
|
56
|
+
*/
|
|
57
|
+
export function turnBoundaryPlan(type, options = {}) {
|
|
58
|
+
const kind = type === 'turn/end' ? 'turn/end' : 'turn/start';
|
|
59
|
+
const state = kind === 'turn/start' ? stateForTurnStart() : stateForTurnEnd(options.priorState);
|
|
60
|
+
const turn = Number.isInteger(options.turn) && options.turn >= 0 ? options.turn : null;
|
|
61
|
+
return { state, turn, kind: 'turn', detail: turn == null ? kind : `${kind} #${turn}` };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function cleanId(value) {
|
|
65
|
+
if (typeof value !== 'string') return null;
|
|
66
|
+
const trimmed = value.trim();
|
|
67
|
+
if (trimmed === '') return null;
|
|
68
|
+
// The live registry's own id rule, applied non-throwing here: a bad id from
|
|
69
|
+
// an environment variable is simply not a session we can bind.
|
|
70
|
+
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(trimmed) ? trimmed.toLowerCase() : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @param {object} [options]
|
|
75
|
+
* @param {object|null} [options.ctx] host context (used for `session/event`)
|
|
76
|
+
* @param {string} [options.memoryRoot] live-registry root; absent disables writes
|
|
77
|
+
* @param {number} [options.heartbeatMs] fallback interval; `0` disables the
|
|
78
|
+
* timer and tool-call touches (binding still happens through the tool
|
|
79
|
+
* resolver). Turn-boundary state writes (`turn/start` → running + turn,
|
|
80
|
+
* `turn/end` → idle/waiting/blocked + turn) are event driven and keep
|
|
81
|
+
* working, because "no timer" is not "no state machine" (R4.3).
|
|
82
|
+
* @param {() => (Date|number)} [options.now] clock injection for tests
|
|
83
|
+
* @param {Function} [options.touch] `liveTouch` injection for tests
|
|
84
|
+
* @param {Function} [options.update] `liveUpdate` injection for tests (first
|
|
85
|
+
* registration of a session that has no row yet)
|
|
86
|
+
* @param {Function} [options.get] `liveGet` injection for tests (turn/end reads
|
|
87
|
+
* the prior declared state so waiting/blocked survive)
|
|
88
|
+
* @param {number} [options.maxRows] live-row cap for rows created by turn
|
|
89
|
+
* boundaries (default 128, DESIGN §2.1)
|
|
90
|
+
* @param {Function} [options.setInterval] timer injection for tests
|
|
91
|
+
* @param {Function} [options.clearInterval]
|
|
92
|
+
* @param {Function} [options.resolve] `(exec) => {id, source}` injection
|
|
93
|
+
*/
|
|
94
|
+
export function createAutoHeartbeat(options = {}) {
|
|
95
|
+
const {
|
|
96
|
+
ctx = null,
|
|
97
|
+
memoryRoot,
|
|
98
|
+
heartbeatMs = DEFAULT_HEARTBEAT_MS,
|
|
99
|
+
now,
|
|
100
|
+
touch = liveTouch,
|
|
101
|
+
update = liveUpdate,
|
|
102
|
+
// Read side, used only to preserve waiting/blocked across turn/end.
|
|
103
|
+
get = liveGet,
|
|
104
|
+
maxRows = MAX_LIVE_ROWS,
|
|
105
|
+
setInterval: setIntervalFn = globalThis.setInterval,
|
|
106
|
+
clearInterval: clearIntervalFn = globalThis.clearInterval,
|
|
107
|
+
resolve = (exec) => resolveCurrentSessionId({ ctx, exec }),
|
|
108
|
+
onTurnEnd = null,
|
|
109
|
+
} = options;
|
|
110
|
+
|
|
111
|
+
const root = typeof memoryRoot === 'string' && memoryRoot.trim() !== ''
|
|
112
|
+
? memoryRoot.trim()
|
|
113
|
+
: null;
|
|
114
|
+
const interval = typeof heartbeatMs === 'number' ? heartbeatMs : Number(heartbeatMs);
|
|
115
|
+
// Only a finite positive interval enables the fallback timer and the
|
|
116
|
+
// tool-call touches; 0/invalid = those two off. Turn-boundary state writes
|
|
117
|
+
// (R4.3) are event driven and deliberately independent of this flag.
|
|
118
|
+
const enabled = Number.isFinite(interval) && interval > 0;
|
|
119
|
+
|
|
120
|
+
const bound = new Set();
|
|
121
|
+
let timer = null;
|
|
122
|
+
let disposeListener = null;
|
|
123
|
+
let started = false;
|
|
124
|
+
let stopped = false;
|
|
125
|
+
|
|
126
|
+
function bind(sessionId) {
|
|
127
|
+
const id = cleanId(sessionId);
|
|
128
|
+
if (!id) return false;
|
|
129
|
+
bound.add(id);
|
|
130
|
+
// Bound set is small in practice (one per session that called us); the cap
|
|
131
|
+
// only stops a pathological host from pinning memory forever.
|
|
132
|
+
while (bound.size > MAX_BOUND_SESSIONS) {
|
|
133
|
+
const oldest = bound.values().next().value;
|
|
134
|
+
bound.delete(oldest);
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function stamp() {
|
|
140
|
+
return typeof now === 'function' ? now() : now;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function touchOne(id, { kind, detail, lastAction = true } = {}) {
|
|
144
|
+
if (!enabled || root == null || typeof touch !== 'function') {
|
|
145
|
+
return { ok: false, status: 'disabled' };
|
|
146
|
+
}
|
|
147
|
+
const config = { memoryRoot: root, lastAction };
|
|
148
|
+
const at = stamp();
|
|
149
|
+
if (at !== undefined) config.now = at;
|
|
150
|
+
if (typeof kind === 'string') config.kind = kind;
|
|
151
|
+
if (typeof detail === 'string') config.detail = detail;
|
|
152
|
+
try {
|
|
153
|
+
return touch(id, config);
|
|
154
|
+
} catch {
|
|
155
|
+
// Heartbeat is liveness decoration, never the task: swallow and move on.
|
|
156
|
+
return { ok: false, status: 'error' };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* First sight of a session: create its row. This is the one deliberate
|
|
162
|
+
* write-on-read in the plugin — the live table learns "I am this session"
|
|
163
|
+
* the moment the session uses a longlive tool, instead of waiting for a
|
|
164
|
+
* caller to pass sessionId (which nobody can know from inside a tool).
|
|
165
|
+
* `liveUpdate` supplies the schema defaults; the row starts `running`
|
|
166
|
+
* because a tool call is, by definition, an active turn.
|
|
167
|
+
*/
|
|
168
|
+
function registerOne(id, { kind, detail } = {}) {
|
|
169
|
+
if (!enabled || root == null || typeof update !== 'function') {
|
|
170
|
+
return { ok: false, status: 'disabled' };
|
|
171
|
+
}
|
|
172
|
+
const args = { sessionId: id, state: 'running' };
|
|
173
|
+
if (typeof kind === 'string' || typeof detail === 'string') {
|
|
174
|
+
args.last_action = { kind, detail };
|
|
175
|
+
}
|
|
176
|
+
const config = { memoryRoot: root };
|
|
177
|
+
const at = stamp();
|
|
178
|
+
if (at !== undefined) config.now = at;
|
|
179
|
+
try {
|
|
180
|
+
return update(args, config);
|
|
181
|
+
} catch {
|
|
182
|
+
return { ok: false, status: 'error' };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Called by the tool wrapper on every longlive tool invocation: resolve the
|
|
188
|
+
* explicit caller, bind it, and refresh its row (creating it on first use).
|
|
189
|
+
*/
|
|
190
|
+
function autoTouch(exec, toolName) {
|
|
191
|
+
if (!enabled) return null;
|
|
192
|
+
let resolved = null;
|
|
193
|
+
try {
|
|
194
|
+
resolved = resolve(exec);
|
|
195
|
+
} catch {
|
|
196
|
+
resolved = null;
|
|
197
|
+
}
|
|
198
|
+
const id = cleanId(resolved?.id);
|
|
199
|
+
if (!id) return null;
|
|
200
|
+
bind(id);
|
|
201
|
+
const lastAction = {
|
|
202
|
+
kind: 'tool',
|
|
203
|
+
detail: `longlive 工具调用:${typeof toolName === 'string' ? toolName : 'unknown'}`,
|
|
204
|
+
};
|
|
205
|
+
const touched = touchOne(id, lastAction);
|
|
206
|
+
// No row yet -> this tool call is the session's self-registration. Keep
|
|
207
|
+
// the same last_action so the row does not look like a bare "create".
|
|
208
|
+
if (touched?.status === 'absent') return registerOne(id, lastAction);
|
|
209
|
+
return touched;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Prior row snapshot for a turn boundary: does it exist, and what state does
|
|
214
|
+
* it declare? Read-only; never throws. `known:false` means the read itself
|
|
215
|
+
* failed, in which case we still attempt the write (liveUpdate is atomic and
|
|
216
|
+
* the row keeps its prior values for omitted fields).
|
|
217
|
+
*/
|
|
218
|
+
function readPriorRow(id) {
|
|
219
|
+
if (root == null || typeof get !== 'function') return { known: false, found: false, state: null };
|
|
220
|
+
const config = { memoryRoot: root };
|
|
221
|
+
const at = stamp();
|
|
222
|
+
if (at !== undefined) config.now = at;
|
|
223
|
+
try {
|
|
224
|
+
const got = get({ sessionId: id }, config);
|
|
225
|
+
if (got?.ok === true) {
|
|
226
|
+
return { known: true, found: true, state: typeof got.live?.state === 'string' ? got.live.state : null };
|
|
227
|
+
}
|
|
228
|
+
if (got?.status === 'absent') return { known: true, found: false, state: null };
|
|
229
|
+
// corrupt/unreadable-but-present: it occupies a slot; a write repairs it.
|
|
230
|
+
return { known: true, found: true, state: null };
|
|
231
|
+
} catch {
|
|
232
|
+
return { known: false, found: false, state: null };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** True when a NEW row may still be created without exceeding the 128 cap. */
|
|
237
|
+
function hasRowCapacity() {
|
|
238
|
+
if (root == null || typeof liveList !== 'function') return true;
|
|
239
|
+
const config = { memoryRoot: root };
|
|
240
|
+
const at = stamp();
|
|
241
|
+
if (at !== undefined) config.now = at;
|
|
242
|
+
try {
|
|
243
|
+
const listed = liveList({ includeDead: true }, config);
|
|
244
|
+
const scanned = Number.isInteger(listed?.scanned)
|
|
245
|
+
? listed.scanned
|
|
246
|
+
: (Array.isArray(listed?.entries) ? listed.entries.length : 0);
|
|
247
|
+
return scanned < maxRows;
|
|
248
|
+
} catch {
|
|
249
|
+
// Cannot tell -> do not create rows, but an existing row may be updated.
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** One best-effort live-row patch at a turn boundary (state + turn + action). */
|
|
255
|
+
function writeTurnBoundary(id, { state, turn, kind, detail }) {
|
|
256
|
+
if (root == null || typeof update !== 'function') return { ok: false, status: 'disabled' };
|
|
257
|
+
const args = { sessionId: id, state, last_action: { kind, detail } };
|
|
258
|
+
if (Number.isInteger(turn) && turn >= 0) args.turn = turn;
|
|
259
|
+
const config = { memoryRoot: root };
|
|
260
|
+
const at = stamp();
|
|
261
|
+
if (at !== undefined) config.now = at;
|
|
262
|
+
try {
|
|
263
|
+
return update(args, config);
|
|
264
|
+
} catch {
|
|
265
|
+
// A state-machine write is decoration for other sessions, never the
|
|
266
|
+
// turn itself: swallow and let the turn proceed.
|
|
267
|
+
return { ok: false, status: 'error' };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function onSessionEvent(session, event) {
|
|
272
|
+
let id = null;
|
|
273
|
+
let origin = null;
|
|
274
|
+
try {
|
|
275
|
+
id = cleanId(session?.id)
|
|
276
|
+
?? cleanId(session?.header?.id)
|
|
277
|
+
?? cleanId(event?.session?.id)
|
|
278
|
+
?? cleanId(event?.session?.header?.id);
|
|
279
|
+
const header = session?.header ?? session?.session?.header ?? event?.session?.header ?? {};
|
|
280
|
+
origin = typeof header.origin === 'string' ? header.origin : null;
|
|
281
|
+
} catch {
|
|
282
|
+
id = null;
|
|
283
|
+
}
|
|
284
|
+
// Auto-truncation watches every session in this agent's scope, not only
|
|
285
|
+
// the ones bound to the live registry: a session that never called a
|
|
286
|
+
// longlive tool can still grow past the threshold. It runs before the
|
|
287
|
+
// live-state gate so `heartbeatMs:0` does not also turn maintenance off.
|
|
288
|
+
if (typeof onTurnEnd === 'function' && event?.type === 'turn/end' && id) {
|
|
289
|
+
try {
|
|
290
|
+
onTurnEnd({ session, event, sessionId: id, turn: event?.data?.turn });
|
|
291
|
+
} catch {
|
|
292
|
+
/* automation is best effort; never fail the host feed */
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const type = event?.type;
|
|
296
|
+
if (!id) return;
|
|
297
|
+
if (type !== 'turn/start' && type !== 'turn/end') return;
|
|
298
|
+
// R4.6: subagents are counted separately on the board; they never get a
|
|
299
|
+
// live row from the heartbeat (same rule as the Router's L1 writer).
|
|
300
|
+
if (origin === 'subagent') return;
|
|
301
|
+
if (root == null || typeof update !== 'function') return;
|
|
302
|
+
const turn = event?.data?.turn;
|
|
303
|
+
// R4.5: the event carries the session id, so turn boundaries maintain
|
|
304
|
+
// EVERY non-subagent session's row — a session that only runs native tools
|
|
305
|
+
// (never calls a longlive tool, so it is never `bind`ed) must still switch
|
|
306
|
+
// state/turn. Create the row on its first boundary, within the 128 cap.
|
|
307
|
+
const prior = readPriorRow(id);
|
|
308
|
+
if (!prior.found && !hasRowCapacity()) return;
|
|
309
|
+
if (type === 'turn/start') {
|
|
310
|
+
// R4.3 状态机:turn/start 立刻让 live 行 state: 'running' 并写入 turn 号
|
|
311
|
+
// (liveUpdate 一次完成;与心跳 tick 无关,tick 只续 heartbeatAt)。
|
|
312
|
+
const plan = turnBoundaryPlan('turn/start', { turn });
|
|
313
|
+
writeTurnBoundary(id, plan);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
// turn/end: idle/blocked/waiting 都落 turn 号;waiting/blocked 是给用户
|
|
317
|
+
// 看的承诺,turn 结束不能把它抹成 idle。
|
|
318
|
+
const endPlan = turnBoundaryPlan('turn/end', { turn, priorState: prior.state });
|
|
319
|
+
writeTurnBoundary(id, endPlan);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function tick() {
|
|
323
|
+
if (!enabled) return;
|
|
324
|
+
for (const id of [...bound]) {
|
|
325
|
+
// A timer tick is pure liveness: it must not rewrite last_action or make
|
|
326
|
+
// an idle session look like it just did something.
|
|
327
|
+
touchOne(id, { lastAction: false });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function start() {
|
|
332
|
+
if (started || stopped) return false;
|
|
333
|
+
started = true;
|
|
334
|
+
if (ctx != null && typeof ctx.on === 'function') {
|
|
335
|
+
try {
|
|
336
|
+
const disposer = ctx.on('session/event', onSessionEvent);
|
|
337
|
+
if (typeof disposer === 'function') disposeListener = disposer;
|
|
338
|
+
} catch {
|
|
339
|
+
disposeListener = null;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (enabled && root != null && typeof setIntervalFn === 'function') {
|
|
343
|
+
timer = setIntervalFn(tick, interval);
|
|
344
|
+
if (timer != null && typeof timer.unref === 'function') {
|
|
345
|
+
// Never hold the process open just to heartbeat.
|
|
346
|
+
timer.unref();
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function stop() {
|
|
353
|
+
if (stopped) return false;
|
|
354
|
+
stopped = true;
|
|
355
|
+
if (timer != null && typeof clearIntervalFn === 'function') {
|
|
356
|
+
try {
|
|
357
|
+
clearIntervalFn(timer);
|
|
358
|
+
} catch {
|
|
359
|
+
/* already gone */
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
timer = null;
|
|
363
|
+
if (typeof disposeListener === 'function') {
|
|
364
|
+
try {
|
|
365
|
+
disposeListener();
|
|
366
|
+
} catch {
|
|
367
|
+
/* already disposed with the plugin fiber */
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
disposeListener = null;
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
return {
|
|
375
|
+
bind,
|
|
376
|
+
autoTouch,
|
|
377
|
+
onSessionEvent,
|
|
378
|
+
start,
|
|
379
|
+
stop,
|
|
380
|
+
touchOne,
|
|
381
|
+
boundIds: () => [...bound],
|
|
382
|
+
isEnabled: () => enabled,
|
|
383
|
+
intervalMs: () => (enabled ? interval : 0),
|
|
384
|
+
};
|
|
385
|
+
}
|
package/src/home.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Where DSH keeps its state on this machine.
|
|
2
|
+
//
|
|
3
|
+
// One definition, two consumers: `src/tools.js` (session logs, default memory
|
|
4
|
+
// store) and `src/memory/paths.js` (memory root). Keeping it here avoids a
|
|
5
|
+
// tools.js <-> memory/paths.js import cycle and, more importantly, keeps the
|
|
6
|
+
// package from ever hard-coding a drive letter: `$DSH_HOME` wins, else
|
|
7
|
+
// `~/.dsh`, which is what the host itself uses on every platform.
|
|
8
|
+
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
/** Resolve the DSH home: $DSH_HOME, else ~/.dsh. Never a hard-coded drive letter. */
|
|
13
|
+
export function dshHome(env = process.env) {
|
|
14
|
+
const configured = typeof env?.DSH_HOME === 'string' ? env.DSH_HOME.trim() : '';
|
|
15
|
+
return path.resolve(configured || path.join(os.homedir(), '.dsh'));
|
|
16
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// Best-effort host compatibility check.
|
|
2
|
+
//
|
|
3
|
+
// `engines.dsh` in package.json is the declared contract; this module is the
|
|
4
|
+
// runtime half of it. A package that only declares a range but never reads the
|
|
5
|
+
// host version leaves the user with tools that silently answer
|
|
6
|
+
// `status:"unavailable"` and no sentence explaining why (that is exactly what
|
|
7
|
+
// 0.7.2 did: probeService turned a missing service into null).
|
|
8
|
+
//
|
|
9
|
+
// Two rules keep this from becoming a new failure mode:
|
|
10
|
+
// - an undetectable host version is NOT an error (the host may not expose
|
|
11
|
+
// one in a given embedding); we say nothing and keep working;
|
|
12
|
+
// - a detected mismatch warns once and continues. The plugin degrades, it
|
|
13
|
+
// does not crash and does not refuse to load.
|
|
14
|
+
//
|
|
15
|
+
// The comparison is intentionally small and dependency-free (the package has
|
|
16
|
+
// no runtime dependencies and should not grow one for this): >=, <=, >, <, =,
|
|
17
|
+
// ^, ~, space-separated AND, || OR, and `*`. Pre-release tags are compared by
|
|
18
|
+
// their core version so a host reporting `0.2.1-rc.5` satisfies `>=0.2.0`.
|
|
19
|
+
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { readPackageManifest, PACKAGE_ROOT } from './version.js';
|
|
23
|
+
|
|
24
|
+
export const HOST_VERSION_ENV = 'DSH_HOST_VERSION';
|
|
25
|
+
/** Explicit override for the host manifest path (tests, unusual embeddings). */
|
|
26
|
+
export const HOST_PACKAGE_ENV = 'DSH_HOST_PACKAGE';
|
|
27
|
+
export const DEFAULT_HOST_RANGE = '>=0.2.0 <1.0.0';
|
|
28
|
+
|
|
29
|
+
/** The desktop host keeps this beside its package.json. */
|
|
30
|
+
const HOST_RUNTIME_FILE = 'desktop-runtime.json';
|
|
31
|
+
|
|
32
|
+
const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
33
|
+
const COMPARATOR_RE = /^(>=|<=|>|<|=|\^|~)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?|\*|x)$/i;
|
|
34
|
+
|
|
35
|
+
export function parseVersion(value) {
|
|
36
|
+
if (typeof value !== 'string') return null;
|
|
37
|
+
const match = VERSION_RE.exec(value.trim());
|
|
38
|
+
if (!match) return null;
|
|
39
|
+
return {
|
|
40
|
+
major: Number(match[1]),
|
|
41
|
+
minor: Number(match[2]),
|
|
42
|
+
patch: Number(match[3]),
|
|
43
|
+
prerelease: match[4] ?? '',
|
|
44
|
+
raw: value.trim(),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function compareCore(a, b) {
|
|
49
|
+
if (a.major !== b.major) return a.major < b.major ? -1 : 1;
|
|
50
|
+
if (a.minor !== b.minor) return a.minor < b.minor ? -1 : 1;
|
|
51
|
+
if (a.patch !== b.patch) return a.patch < b.patch ? -1 : 1;
|
|
52
|
+
return 0;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function upperForCaret(version) {
|
|
56
|
+
if (version.major > 0) return { major: version.major + 1, minor: 0, patch: 0 };
|
|
57
|
+
if (version.minor > 0) return { major: 0, minor: version.minor + 1, patch: 0 };
|
|
58
|
+
return { major: 0, minor: 0, patch: version.patch + 1 };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function matchComparator(version, comparator) {
|
|
62
|
+
const match = COMPARATOR_RE.exec(comparator.trim());
|
|
63
|
+
if (!match) return false;
|
|
64
|
+
const op = match[1] ?? '=';
|
|
65
|
+
const text = match[2];
|
|
66
|
+
if (text === '*' || /^x$/i.test(text)) return true;
|
|
67
|
+
const target = parseVersion(text);
|
|
68
|
+
if (!target) return false;
|
|
69
|
+
const order = compareCore(version, target);
|
|
70
|
+
switch (op) {
|
|
71
|
+
case '>=': return order >= 0;
|
|
72
|
+
case '<=': return order <= 0;
|
|
73
|
+
case '>': return order > 0;
|
|
74
|
+
case '<': return order < 0;
|
|
75
|
+
case '=': return order === 0;
|
|
76
|
+
case '^': {
|
|
77
|
+
if (order < 0) return false;
|
|
78
|
+
const cap = upperForCaret(target);
|
|
79
|
+
return compareCore(version, cap) < 0;
|
|
80
|
+
}
|
|
81
|
+
case '~': {
|
|
82
|
+
if (order < 0) return false;
|
|
83
|
+
return compareCore(version, { major: target.major, minor: target.minor + 1, patch: 0 }) < 0;
|
|
84
|
+
}
|
|
85
|
+
default: return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** True when `version` (string) satisfies `range` (npm-ish, dependency-free). */
|
|
90
|
+
export function satisfies(version, range) {
|
|
91
|
+
const parsed = parseVersion(version);
|
|
92
|
+
if (!parsed) return false;
|
|
93
|
+
const text = typeof range === 'string' ? range.trim() : '';
|
|
94
|
+
if (!text) return true;
|
|
95
|
+
return text.split('||').some((clause) => {
|
|
96
|
+
const parts = clause.trim().split(/\s+/).filter(Boolean);
|
|
97
|
+
return parts.length > 0 && parts.every((part) => matchComparator(parsed, part));
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The range declared in package.json, or the built-in fallback. */
|
|
102
|
+
export function declaredHostRange(root = PACKAGE_ROOT) {
|
|
103
|
+
try {
|
|
104
|
+
const manifest = readPackageManifest(root);
|
|
105
|
+
const range = manifest?.engines?.dsh;
|
|
106
|
+
return typeof range === 'string' && range.trim() ? range.trim() : DEFAULT_HOST_RANGE;
|
|
107
|
+
} catch {
|
|
108
|
+
return DEFAULT_HOST_RANGE;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function pickVersion(value) {
|
|
113
|
+
if (typeof value === 'string') return value;
|
|
114
|
+
if (value && typeof value.version === 'string') return value.version;
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Candidate host manifests, in priority order. The desktop host runs the DSH
|
|
120
|
+
* core inside Electron, so `process.resourcesPath` names the install root and
|
|
121
|
+
* the core package.json lives inside the asar archive (Electron patches fs to
|
|
122
|
+
* read it transparently). A plain Node process has no resourcesPath; there the
|
|
123
|
+
* candidates below simply do not exist and detection falls through to
|
|
124
|
+
* `unknown`, which is a normal result, not an error.
|
|
125
|
+
*/
|
|
126
|
+
export function hostPackageCandidates(options = {}) {
|
|
127
|
+
const env = options.env ?? process.env;
|
|
128
|
+
const resourcesPath = typeof options.resourcesPath === 'string'
|
|
129
|
+
? options.resourcesPath : process.resourcesPath;
|
|
130
|
+
const execPath = typeof options.execPath === 'string' ? options.execPath : process.execPath;
|
|
131
|
+
const found = [];
|
|
132
|
+
const add = (file, origin) => {
|
|
133
|
+
if (typeof file !== 'string' || !file.trim()) return;
|
|
134
|
+
const absolute = path.resolve(file.trim());
|
|
135
|
+
if (found.some((entry) => entry.path === absolute)) return;
|
|
136
|
+
found.push({ path: absolute, origin });
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
add(options.configPath, 'config.hostPackagePath');
|
|
140
|
+
add(env?.[HOST_PACKAGE_ENV], `env.${HOST_PACKAGE_ENV}`);
|
|
141
|
+
|
|
142
|
+
if (typeof resourcesPath === 'string' && resourcesPath.trim()) {
|
|
143
|
+
add(path.join(resourcesPath.trim(), 'app.asar', 'dsh', 'package.json'), 'process.resourcesPath');
|
|
144
|
+
add(path.join(resourcesPath.trim(), 'app.asar', 'dsh', HOST_RUNTIME_FILE), 'process.resourcesPath');
|
|
145
|
+
}
|
|
146
|
+
if (typeof execPath === 'string' && execPath.trim()) {
|
|
147
|
+
const resources = path.join(path.dirname(execPath.trim()), 'resources');
|
|
148
|
+
add(path.join(resources, 'app.asar', 'dsh', 'package.json'), 'process.execPath');
|
|
149
|
+
add(path.join(resources, 'app.asar', 'dsh', HOST_RUNTIME_FILE), 'process.execPath');
|
|
150
|
+
}
|
|
151
|
+
return found;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function manifestVersion(manifest) {
|
|
155
|
+
const direct = pickVersion(manifest);
|
|
156
|
+
if (direct) return direct;
|
|
157
|
+
const release = manifest && typeof manifest === 'object' ? manifest.release : null;
|
|
158
|
+
return pickVersion(release);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Read the first candidate that yields a parseable version.
|
|
163
|
+
* Returns { version, source: 'hostPackage', path, origin } or null.
|
|
164
|
+
* Unreadable/corrupt candidates are skipped silently: this is advisory.
|
|
165
|
+
*/
|
|
166
|
+
export function detectHostPackageVersion(options = {}) {
|
|
167
|
+
const readFile = typeof options.readFile === 'function'
|
|
168
|
+
? options.readFile
|
|
169
|
+
: (file) => fs.readFileSync(file, 'utf8');
|
|
170
|
+
for (const candidate of hostPackageCandidates(options)) {
|
|
171
|
+
try {
|
|
172
|
+
const manifest = JSON.parse(readFile(candidate.path));
|
|
173
|
+
const version = manifestVersion(manifest);
|
|
174
|
+
if (version && parseVersion(version)) {
|
|
175
|
+
return {
|
|
176
|
+
version: version.trim(),
|
|
177
|
+
source: 'hostPackage',
|
|
178
|
+
path: candidate.path,
|
|
179
|
+
origin: candidate.origin,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
/* missing, unreadable or corrupt manifest: try the next candidate */
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Find the host version from the surfaces a Cordis plugin can see.
|
|
191
|
+
* Returns { version, source, path? }. `version` is null when nothing usable
|
|
192
|
+
* exists. `options.resourcesPath` / `options.execPath` / `options.readFile`
|
|
193
|
+
* exist so tests can fake a host install without touching the real one.
|
|
194
|
+
*/
|
|
195
|
+
export function detectHostVersion(ctx, config = {}, env = process.env, options = {}) {
|
|
196
|
+
// A Cordis context is a Proxy: reading a property that is not declared in
|
|
197
|
+
// `inject` throws `cannot get property "..." without inject`. This check is
|
|
198
|
+
// advisory, so every host-surface read must be best-effort. 0.7.3 read
|
|
199
|
+
// ctx.version eagerly and took the whole plugin entry down in the web host.
|
|
200
|
+
const read = (fn) => {
|
|
201
|
+
try { return fn(); } catch { return undefined; }
|
|
202
|
+
};
|
|
203
|
+
const candidates = [
|
|
204
|
+
['ctx.version', read(() => ctx?.version)],
|
|
205
|
+
['ctx.get("version")', read(() => (typeof ctx?.get === 'function' ? ctx.get('version') : undefined))],
|
|
206
|
+
['ctx.app.version', read(() => ctx?.app?.version)],
|
|
207
|
+
['ctx.get("app").version', read(() => (typeof ctx?.get === 'function' ? ctx.get('app')?.version : undefined))],
|
|
208
|
+
['ctx.root.version', read(() => ctx?.root?.version)],
|
|
209
|
+
['config.hostVersion', config?.hostVersion],
|
|
210
|
+
[`env.${HOST_VERSION_ENV}`, env?.[HOST_VERSION_ENV]],
|
|
211
|
+
];
|
|
212
|
+
for (const [source, value] of candidates) {
|
|
213
|
+
const version = pickVersion(value);
|
|
214
|
+
if (version && parseVersion(version)) return { version: version.trim(), source };
|
|
215
|
+
}
|
|
216
|
+
// Last resort: the host's own manifest. This is the primary path on the
|
|
217
|
+
// desktop host (0.2.1), whose Cordis context exposes no version property.
|
|
218
|
+
const fromPackage = detectHostPackageVersion({
|
|
219
|
+
configPath: config?.hostPackagePath,
|
|
220
|
+
env,
|
|
221
|
+
resourcesPath: options.resourcesPath,
|
|
222
|
+
execPath: options.execPath,
|
|
223
|
+
readFile: options.readFile,
|
|
224
|
+
});
|
|
225
|
+
if (fromPackage) return fromPackage;
|
|
226
|
+
return { version: null, source: null };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Compare a detected host version against the declared range.
|
|
231
|
+
* Returns { ok, status: 'ok'|'unknown'|'mismatch', version, range, warning }.
|
|
232
|
+
* `warning` is a complete user-facing sentence, or null.
|
|
233
|
+
*/
|
|
234
|
+
export function checkHostCompatibility(options = {}) {
|
|
235
|
+
const range = typeof options.range === 'string' && options.range.trim()
|
|
236
|
+
? options.range.trim() : declaredHostRange(options.root);
|
|
237
|
+
const version = pickVersion(options.version);
|
|
238
|
+
if (!version || !parseVersion(version)) {
|
|
239
|
+
return { ok: true, status: 'unknown', version: version ?? null, range, warning: null };
|
|
240
|
+
}
|
|
241
|
+
if (satisfies(version, range)) {
|
|
242
|
+
return { ok: true, status: 'ok', version, range, warning: null };
|
|
243
|
+
}
|
|
244
|
+
const plugin = options.pluginVersion ? `dsh-longlive ${options.pluginVersion}` : 'dsh-longlive';
|
|
245
|
+
return {
|
|
246
|
+
ok: false,
|
|
247
|
+
status: 'mismatch',
|
|
248
|
+
version,
|
|
249
|
+
range,
|
|
250
|
+
warning: `宿主版本 ${version} 不在 ${plugin} 声明的 engines.dsh 区间 "${range}" 内 — ` +
|
|
251
|
+
'插件会以降级模式继续加载(缺失的宿主服务对应的工具会返回 status:"unavailable",不会崩溃)。' +
|
|
252
|
+
`请升级/降级宿主到 ${range},或安装与该宿主匹配的插件版本。`,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const warned = new Set();
|
|
257
|
+
|
|
258
|
+
/** Emit `text` at most once per process through ctx.logger, else console.warn. */
|
|
259
|
+
export function warnOnce(ctx, text) {
|
|
260
|
+
if (!text || warned.has(text)) return false;
|
|
261
|
+
warned.add(text);
|
|
262
|
+
let emitted = false;
|
|
263
|
+
try {
|
|
264
|
+
const logger = typeof ctx?.logger === 'function' ? ctx.logger('longlive') : null;
|
|
265
|
+
if (logger && typeof logger.warn === 'function') {
|
|
266
|
+
logger.warn(text);
|
|
267
|
+
emitted = true;
|
|
268
|
+
}
|
|
269
|
+
} catch {
|
|
270
|
+
emitted = false;
|
|
271
|
+
}
|
|
272
|
+
if (!emitted) {
|
|
273
|
+
try {
|
|
274
|
+
console.warn(`[dsh-longlive] ${text}`);
|
|
275
|
+
} catch {
|
|
276
|
+
/* a host without console must not break the plugin */
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return true;
|
|
280
|
+
}
|