@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/ui/flags.js
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
// Pure model for the longlive settings panel: the seven feature switches the
|
|
2
|
+
// row's `plugins.row.config` page edits, plus the read-only memory root.
|
|
3
|
+
//
|
|
4
|
+
// The model has no Host service imports on purpose. The route layer supplies
|
|
5
|
+
// readConfig/writeConfig, and the tests can drive the same functions with a
|
|
6
|
+
// plain object. Keep every string here in sync with src/config.js ZH copy —
|
|
7
|
+
// the client panel receives these labels from the Host so the browser half
|
|
8
|
+
// never carries a second copy.
|
|
9
|
+
|
|
10
|
+
/** Package name the row key is derived from (see `rowConfigKey` in the Host). */
|
|
11
|
+
export const FLAGS_PACKAGE = '@jjh32456/longlive';
|
|
12
|
+
/** Row id the shipped cordis.patch.yml declares. */
|
|
13
|
+
export const FLAGS_ROW_ID = 'session-longlive';
|
|
14
|
+
/** Key for `plugins.row.config`: `<package name>#<row id>`. */
|
|
15
|
+
export const FLAGS_SLOT_KEY = `${FLAGS_PACKAGE}#${FLAGS_ROW_ID}`;
|
|
16
|
+
/** Panel heading shown above the switches. */
|
|
17
|
+
export const FLAGS_TITLE = '久视 · 功能开关';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One editable switch. `path` is the config path written through the profile
|
|
21
|
+
* editor; the displayed value falls back to `fallback` when the raw row does
|
|
22
|
+
* not carry the key yet (the schema's own default).
|
|
23
|
+
*/
|
|
24
|
+
export const FLAGS = Object.freeze([
|
|
25
|
+
Object.freeze({
|
|
26
|
+
key: 'd2.enabled',
|
|
27
|
+
path: Object.freeze(['d2', 'enabled']),
|
|
28
|
+
group: 'tools',
|
|
29
|
+
label: '工具输出裁剪',
|
|
30
|
+
description: '超过上限的工具输出全文归档,只保留头尾内联。',
|
|
31
|
+
fallback: false,
|
|
32
|
+
}),
|
|
33
|
+
Object.freeze({
|
|
34
|
+
key: 'd6.enabled',
|
|
35
|
+
path: Object.freeze(['d6', 'enabled']),
|
|
36
|
+
group: 'tools',
|
|
37
|
+
label: '工具面裁剪',
|
|
38
|
+
description: '第一轮冻结按任务挑选的工具清单,其余工具用 tool_search 申请。',
|
|
39
|
+
fallback: false,
|
|
40
|
+
}),
|
|
41
|
+
Object.freeze({
|
|
42
|
+
key: 'autoRecall.enabled',
|
|
43
|
+
path: Object.freeze(['autoRecall', 'enabled']),
|
|
44
|
+
group: 'memory',
|
|
45
|
+
label: '自动想起',
|
|
46
|
+
description: '按轮次从记忆库召回卡片并注入上下文。',
|
|
47
|
+
fallback: false,
|
|
48
|
+
}),
|
|
49
|
+
Object.freeze({
|
|
50
|
+
key: 'presenceBus.enabled',
|
|
51
|
+
path: Object.freeze(['presenceBus', 'enabled']),
|
|
52
|
+
group: 'memory',
|
|
53
|
+
label: '共享大脑',
|
|
54
|
+
description: '消费其他会话写入总线的消息。',
|
|
55
|
+
fallback: false,
|
|
56
|
+
}),
|
|
57
|
+
Object.freeze({
|
|
58
|
+
key: 'routerFace.enabled',
|
|
59
|
+
path: Object.freeze(['routerFace', 'enabled']),
|
|
60
|
+
group: 'memory',
|
|
61
|
+
label: '后台面',
|
|
62
|
+
description: '定时读取共享记忆,写 journal 与建议 outbox。',
|
|
63
|
+
fallback: false,
|
|
64
|
+
}),
|
|
65
|
+
Object.freeze({
|
|
66
|
+
key: 'autoMaintenance.enabled',
|
|
67
|
+
path: Object.freeze(['autoMaintenance', 'enabled']),
|
|
68
|
+
group: 'memory',
|
|
69
|
+
label: '每日维护',
|
|
70
|
+
description: '本地午夜调度合并报告与遗忘候选清单。',
|
|
71
|
+
fallback: false,
|
|
72
|
+
}),
|
|
73
|
+
Object.freeze({
|
|
74
|
+
key: 'routerEnabled',
|
|
75
|
+
path: Object.freeze(['routerEnabled']),
|
|
76
|
+
group: 'router',
|
|
77
|
+
label: 'Router',
|
|
78
|
+
description: '判定工具调用并按策略记录/拦截。',
|
|
79
|
+
fallback: false,
|
|
80
|
+
}),
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
/** Display order and headings of the switch groups. */
|
|
84
|
+
export const FLAGS_GROUPS = Object.freeze([
|
|
85
|
+
Object.freeze({ id: 'tools', label: '工具与会话' }),
|
|
86
|
+
Object.freeze({ id: 'memory', label: '记忆与后台' }),
|
|
87
|
+
Object.freeze({ id: 'router', label: '路由' }),
|
|
88
|
+
]);
|
|
89
|
+
|
|
90
|
+
/** Error codes the Host route maps to a 4xx and the client shows verbatim. */
|
|
91
|
+
export class FlagsError extends Error {
|
|
92
|
+
constructor(code, message) {
|
|
93
|
+
super(message);
|
|
94
|
+
this.name = 'FlagsError';
|
|
95
|
+
this.code = code;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function isRecord(value) {
|
|
100
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Read one descriptor's value from a raw config object.
|
|
105
|
+
* @param raw - the row's raw config, possibly missing the key.
|
|
106
|
+
* @param flag - a descriptor from {@link FLAGS}.
|
|
107
|
+
* @returns the boolean effective value (`true` only for literal true).
|
|
108
|
+
*/
|
|
109
|
+
export function readFlagValue(raw, flag) {
|
|
110
|
+
let current = isRecord(raw) ? raw : {};
|
|
111
|
+
for (const key of flag.path) {
|
|
112
|
+
if (!isRecord(current) || !Object.hasOwn(current, key)) return flag.fallback === true;
|
|
113
|
+
current = current[key];
|
|
114
|
+
}
|
|
115
|
+
return current === true;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Project every switch value out of a raw config.
|
|
120
|
+
* @param raw - the row's raw config.
|
|
121
|
+
* @returns a `{ [flag.key]: boolean }` object.
|
|
122
|
+
*/
|
|
123
|
+
export function readFlagValues(raw) {
|
|
124
|
+
const values = {};
|
|
125
|
+
for (const flag of FLAGS) values[flag.key] = readFlagValue(raw, flag);
|
|
126
|
+
return values;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Find a switch descriptor by its public key.
|
|
131
|
+
* @param key - e.g. `d2.enabled`.
|
|
132
|
+
* @returns the descriptor, or undefined.
|
|
133
|
+
*/
|
|
134
|
+
export function flagByKey(key) {
|
|
135
|
+
return FLAGS.find((flag) => flag.key === key);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Validate a write and return the next raw config. Only whitelisted switch
|
|
140
|
+
* paths are touched; unknown top-level keys and sibling fields are preserved
|
|
141
|
+
* byte-for-byte at the value level.
|
|
142
|
+
* @param raw - the current raw config.
|
|
143
|
+
* @param key - the switch key.
|
|
144
|
+
* @param value - the next boolean.
|
|
145
|
+
* @returns a new raw config object; the input is never mutated.
|
|
146
|
+
* @throws {FlagsError} for an unknown key, a read-only field, or a non-boolean.
|
|
147
|
+
*/
|
|
148
|
+
export function setFlagInConfig(raw, key, value) {
|
|
149
|
+
const flag = flagByKey(key);
|
|
150
|
+
if (flag === undefined) {
|
|
151
|
+
if (key === 'memoryRoot' || key === 'memRoot') {
|
|
152
|
+
throw new FlagsError('E_FLAG_READONLY', 'memoryRoot 是只读展示字段,不能在面板里修改。');
|
|
153
|
+
}
|
|
154
|
+
throw new FlagsError('E_FLAG_UNKNOWN', `未知的功能开关:${String(key)}`);
|
|
155
|
+
}
|
|
156
|
+
if (typeof value !== 'boolean') {
|
|
157
|
+
throw new FlagsError('E_FLAG_TYPE', `开关 ${key} 只接受布尔值(收到 ${typeof value})。`);
|
|
158
|
+
}
|
|
159
|
+
const before = isRecord(raw) ? raw : {};
|
|
160
|
+
const next = { ...before };
|
|
161
|
+
if (flag.path.length === 1) {
|
|
162
|
+
next[flag.path[0]] = value;
|
|
163
|
+
return next;
|
|
164
|
+
}
|
|
165
|
+
const [block, field] = flag.path;
|
|
166
|
+
const existing = isRecord(before[block]) ? before[block] : {};
|
|
167
|
+
next[block] = { ...existing, [field]: value };
|
|
168
|
+
return next;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Build the payload the browser panel renders: groups in display order, each
|
|
173
|
+
* switch carrying its current value, and the read-only memory root.
|
|
174
|
+
* @param raw - the row's raw config.
|
|
175
|
+
* @param options - `{ memoryRoot, writable }`.
|
|
176
|
+
* @returns a JSON-safe snapshot.
|
|
177
|
+
*/
|
|
178
|
+
export function describeFlags(raw, options = {}) {
|
|
179
|
+
const values = readFlagValues(raw);
|
|
180
|
+
const writable = options.writable === true;
|
|
181
|
+
return {
|
|
182
|
+
ok: true,
|
|
183
|
+
title: FLAGS_TITLE,
|
|
184
|
+
packageName: FLAGS_PACKAGE,
|
|
185
|
+
rowId: FLAGS_ROW_ID,
|
|
186
|
+
slotKey: FLAGS_SLOT_KEY,
|
|
187
|
+
writable,
|
|
188
|
+
memoryRoot: typeof options.memoryRoot === 'string' && options.memoryRoot !== '' ? options.memoryRoot : null,
|
|
189
|
+
groups: FLAGS_GROUPS.map((group) => ({
|
|
190
|
+
id: group.id,
|
|
191
|
+
label: group.label,
|
|
192
|
+
switches: FLAGS.filter((flag) => flag.group === group.id).map((flag) => ({
|
|
193
|
+
key: flag.key,
|
|
194
|
+
label: flag.label,
|
|
195
|
+
description: flag.description,
|
|
196
|
+
value: values[flag.key],
|
|
197
|
+
readOnly: false,
|
|
198
|
+
writable,
|
|
199
|
+
})),
|
|
200
|
+
})),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Host-side service the route calls. The write path is injected so tests can
|
|
206
|
+
* model the profile editor without a Host.
|
|
207
|
+
* @param options - `{ readConfig, writeConfig, memoryRoot, canWrite }`.
|
|
208
|
+
* @returns `{ snapshot, setFlag }`.
|
|
209
|
+
*/
|
|
210
|
+
export function createFlagsService(options) {
|
|
211
|
+
const readConfig = typeof options?.readConfig === 'function' ? options.readConfig : () => ({});
|
|
212
|
+
const writeConfig = typeof options?.writeConfig === 'function' ? options.writeConfig : undefined;
|
|
213
|
+
const canWrite = typeof options?.canWrite === 'function' ? options.canWrite : () => writeConfig !== undefined;
|
|
214
|
+
|
|
215
|
+
function readRaw() {
|
|
216
|
+
try {
|
|
217
|
+
const raw = readConfig();
|
|
218
|
+
return isRecord(raw) ? raw : {};
|
|
219
|
+
} catch {
|
|
220
|
+
return {};
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
/** Current panel state, never throws. */
|
|
226
|
+
snapshot() {
|
|
227
|
+
let writable = false;
|
|
228
|
+
try {
|
|
229
|
+
writable = canWrite() === true && writeConfig !== undefined;
|
|
230
|
+
} catch {
|
|
231
|
+
writable = false;
|
|
232
|
+
}
|
|
233
|
+
return describeFlags(readRaw(), { memoryRoot: options?.memoryRoot, writable });
|
|
234
|
+
},
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Persist one whitelisted switch.
|
|
238
|
+
* @param key - the switch key.
|
|
239
|
+
* @param value - the next boolean.
|
|
240
|
+
* @returns the new snapshot, read after the write settles.
|
|
241
|
+
* @throws {FlagsError} when the write cannot be performed or the editor rejects it.
|
|
242
|
+
*/
|
|
243
|
+
async setFlag(key, value) {
|
|
244
|
+
// Validate before touching the editor so a bad key never learns whether
|
|
245
|
+
// the profile is writable.
|
|
246
|
+
setFlagInConfig({}, key, value);
|
|
247
|
+
if (writeConfig === undefined || canWrite() !== true) {
|
|
248
|
+
throw new FlagsError('E_FLAG_WRITE', '当前宿主不允许写入插件配置(configEditor 或配置行不可用)。');
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
await writeConfig(key, value);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (error instanceof FlagsError) throw error;
|
|
254
|
+
throw new FlagsError('E_FLAG_WRITE', `保存 ${key} 失败:${error?.message ?? String(error)}`);
|
|
255
|
+
}
|
|
256
|
+
return describeFlags(readRaw(), { memoryRoot: options?.memoryRoot, writable: true });
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// src/ui/panel-api.js — M2-F/M2-G 装配层(宿主接线 + HTTP 分派)
|
|
2
|
+
//
|
|
3
|
+
// 把权限门(panel-auth)、完整性(panel-integrity)、审计链(actions/audit)、
|
|
4
|
+
// evidence 写路径(actions/evidence)、动作面(ui/actions)与 22 条只读路由
|
|
5
|
+
// (ui/routes-readonly)装配成一个可测试的门面:
|
|
6
|
+
// - createPanelApi(options) 纯内存/文件装配,契约测试直接驱动;
|
|
7
|
+
// - registerPanelApiRoutes(ctx, options) 通过 ctx.inject(['webServer']) 注册
|
|
8
|
+
// 22 条只读路由 + 5 条动作路由 = 27 路由(POST preview/apply/undo、GET actions/audit 等)
|
|
9
|
+
// + G3 distill 详情前缀路由。宿主没有 Web server 时注册失败只 warn,不阻塞加载。
|
|
10
|
+
//
|
|
11
|
+
// 开关:由 src/index.js 读 `memoryV2.enabled`(默认 false)决定是否调用本模块;
|
|
12
|
+
// 未开启时本模块不注册任何路由、不创建任何文件。
|
|
13
|
+
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
|
|
17
|
+
import { AuditError } from '../actions/audit.js';
|
|
18
|
+
import { createAuditLog } from '../actions/audit.js';
|
|
19
|
+
import { EvidenceError } from '../actions/evidence.js';
|
|
20
|
+
import { createEvidenceWriter } from '../actions/evidence.js';
|
|
21
|
+
import { createEventsIndexReader } from '../memory/event-index.js';
|
|
22
|
+
import { createActionService, PanelActionError } from './actions.js';
|
|
23
|
+
import { createPanelAuth } from './panel-auth.js';
|
|
24
|
+
import { createIntegrityGuard } from './panel-integrity.js';
|
|
25
|
+
import {
|
|
26
|
+
DISTILL_DETAIL_PREFIX,
|
|
27
|
+
READONLY_ROUTES,
|
|
28
|
+
createReadonlyRouter,
|
|
29
|
+
registerReadonlyRoutes,
|
|
30
|
+
} from './routes-readonly.js';
|
|
31
|
+
|
|
32
|
+
export const ACTIONS_BODY_LIMIT = 64 * 1024;
|
|
33
|
+
export const ACTION_ROUTE_PATHS = Object.freeze([
|
|
34
|
+
'/api/longlive/actions/preview',
|
|
35
|
+
'/api/longlive/actions/apply',
|
|
36
|
+
'/api/longlive/actions/undo',
|
|
37
|
+
'/api/longlive/actions',
|
|
38
|
+
'/api/longlive/audit',
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
/** Host DSH home (never a machine path literal in this published file). */
|
|
42
|
+
export function dshHomeDir() {
|
|
43
|
+
const raw = process.env.DSH_HOME;
|
|
44
|
+
if (typeof raw === 'string' && raw.trim() !== '') return path.resolve(raw.trim());
|
|
45
|
+
return path.join(os.homedir(), '.dsh');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Resolve the installed panel package root.
|
|
50
|
+
*
|
|
51
|
+
* P1-1(2): the default lives **outside** the memory root (`<DSH_HOME>/longlive-panel`)
|
|
52
|
+
* so a model/agent that can write memoryRoot cannot also own the signed manifest
|
|
53
|
+
* directory. Host installers may override via option/config; Gate-2 wires the
|
|
54
|
+
* real installed path.
|
|
55
|
+
*/
|
|
56
|
+
function defaultPanelRoot(memoryRoot, options) {
|
|
57
|
+
if (typeof options.panelRoot === 'string' && options.panelRoot.trim() !== '') return path.resolve(options.panelRoot);
|
|
58
|
+
if (typeof options.config?.memoryV2?.panelRoot === 'string' && options.config.memoryV2.panelRoot.trim() !== '') {
|
|
59
|
+
return path.resolve(options.config.memoryV2.panelRoot);
|
|
60
|
+
}
|
|
61
|
+
const candidate = path.join(dshHomeDir(), 'longlive-panel');
|
|
62
|
+
const resolvedMemory = memoryRoot !== '' ? path.resolve(memoryRoot) : null;
|
|
63
|
+
if (resolvedMemory !== null
|
|
64
|
+
&& (candidate === resolvedMemory || candidate.startsWith(`${resolvedMemory}${path.sep}`))) {
|
|
65
|
+
// Never fall back inside memoryRoot; use the OS-local app data dir instead.
|
|
66
|
+
const localAppData = process.env.LOCALAPPDATA;
|
|
67
|
+
if (typeof localAppData === 'string' && localAppData.trim() !== '') {
|
|
68
|
+
return path.join(localAppData.trim(), 'dsh-longlive', 'panel');
|
|
69
|
+
}
|
|
70
|
+
return path.join(os.tmpdir(), 'dsh-longlive-panel');
|
|
71
|
+
}
|
|
72
|
+
return candidate;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Assemble the whole panel API (no host wiring).
|
|
77
|
+
* @param {object} options
|
|
78
|
+
* @param {string} options.memoryRoot
|
|
79
|
+
* @param {string} [options.panelRoot] installed panel package root (integrity manifest base)
|
|
80
|
+
* @param {() => Date} [options.now]
|
|
81
|
+
* @param {(size:number)=>Buffer} [options.randomBytes] CSPRNG seam
|
|
82
|
+
* @param {boolean} [options.panelPresent] false simulates uninstalled panel
|
|
83
|
+
* @param {() => object} [options.flagsSnapshot]
|
|
84
|
+
* @param {(query:object)=>object} [options.eventsReader]
|
|
85
|
+
* @param {(anchorId:string)=>object|null} [options.anchorResolver]
|
|
86
|
+
*/
|
|
87
|
+
export function createPanelApi(options = {}) {
|
|
88
|
+
const memoryRoot = String(options.memoryRoot ?? '');
|
|
89
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
90
|
+
const monoNow = typeof options.monoNow === 'function' ? options.monoNow : undefined;
|
|
91
|
+
const auth = createPanelAuth({
|
|
92
|
+
now,
|
|
93
|
+
// P0-1: host-injected capability secret (profile-private env/file); absent => fail closed.
|
|
94
|
+
hostSecret: options.hostSecret,
|
|
95
|
+
monoNow,
|
|
96
|
+
randomBytes: options.randomBytes,
|
|
97
|
+
panelPresent: options.panelPresent,
|
|
98
|
+
panelIntegrityKey: options.panelIntegrityKey,
|
|
99
|
+
});
|
|
100
|
+
const panelRoot = defaultPanelRoot(memoryRoot, options);
|
|
101
|
+
const integrity = createIntegrityGuard({
|
|
102
|
+
panelRoot,
|
|
103
|
+
now,
|
|
104
|
+
signKey: auth.panelIntegrityKeyBytes(),
|
|
105
|
+
});
|
|
106
|
+
const auditKey = auth.auditKeyBytes();
|
|
107
|
+
const audit = createAuditLog({ memoryRoot, auditKey, now });
|
|
108
|
+
const evidence = createEvidenceWriter({ memoryRoot, auditKey, now });
|
|
109
|
+
const actions = createActionService({
|
|
110
|
+
memoryRoot,
|
|
111
|
+
auth,
|
|
112
|
+
auditKey,
|
|
113
|
+
integrity,
|
|
114
|
+
audit,
|
|
115
|
+
evidence,
|
|
116
|
+
now,
|
|
117
|
+
monoNow,
|
|
118
|
+
clockToleranceMs: options.clockToleranceMs,
|
|
119
|
+
});
|
|
120
|
+
const readonly = createReadonlyRouter({
|
|
121
|
+
memoryRoot,
|
|
122
|
+
auth,
|
|
123
|
+
auditKey,
|
|
124
|
+
integrity,
|
|
125
|
+
now,
|
|
126
|
+
flagsSnapshot: options.flagsSnapshot,
|
|
127
|
+
// 1.8.8 M3: the board route reports the activity live window; hand it the
|
|
128
|
+
// configured retainHours so the panel matches what the writer keeps instead
|
|
129
|
+
// of always showing the 24h default. Undefined keeps the default.
|
|
130
|
+
retainHours: options.config?.sharedBrain?.activity?.retainHours,
|
|
131
|
+
// M2-A: #11 events route reads the FTS5 event index when it has been built
|
|
132
|
+
// (`.longlive/index/events.db`); without an index the honest empty state
|
|
133
|
+
// (`present:false` + E_EVENTS_INDEX_NOT_BUILT) is returned unchanged.
|
|
134
|
+
eventsReader: options.eventsReader ?? createEventsIndexReader({ memoryRoot, now }),
|
|
135
|
+
anchorResolver: options.anchorResolver,
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
function handleReadonly(request = {}) {
|
|
139
|
+
return readonly.handle(request);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function actionResponse(status, body) {
|
|
143
|
+
return { status, body, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function actionErrorResponse(error) {
|
|
147
|
+
if (error instanceof PanelActionError) {
|
|
148
|
+
return actionResponse(error.status, {
|
|
149
|
+
ok: false,
|
|
150
|
+
error: { code: error.code, message: error.message, ...(error.details !== undefined ? { details: error.details } : {}) },
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
if (error instanceof AuditError) {
|
|
154
|
+
return actionResponse(500, { ok: false, error: { code: error.code, message: error.message, ...(error.details !== undefined ? { details: error.details } : {}) } });
|
|
155
|
+
}
|
|
156
|
+
if (error instanceof EvidenceError) {
|
|
157
|
+
return actionResponse(error.status ?? 403, { ok: false, error: { code: error.code, message: error.message } });
|
|
158
|
+
}
|
|
159
|
+
return actionResponse(500, { ok: false, error: { code: 'E_ACTION_FAILED', message: error?.message ?? String(error) } });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Handle one in-process action request.
|
|
164
|
+
* @param {{method?:string, path:string, headers?:object, body?:object, source?:string, actorKind?:string, rawBodySize?:number}} request
|
|
165
|
+
*/
|
|
166
|
+
function handleAction(request = {}) {
|
|
167
|
+
const method = String(request.method ?? 'POST').toUpperCase();
|
|
168
|
+
let url;
|
|
169
|
+
try {
|
|
170
|
+
url = new URL(String(request.path ?? ''), 'http://longlive.local');
|
|
171
|
+
} catch {
|
|
172
|
+
return actionResponse(400, { ok: false, error: { code: 'E_PATH', message: '非法请求路径。' } });
|
|
173
|
+
}
|
|
174
|
+
const query = {};
|
|
175
|
+
for (const [key, value] of url.searchParams.entries()) {
|
|
176
|
+
query[key] = /^\d+$/.test(value) ? Number.parseInt(value, 10) : value;
|
|
177
|
+
}
|
|
178
|
+
const gateRequest = { source: request.source ?? 'http', headers: request.headers ?? {}, actorKind: request.actorKind ?? 'host' };
|
|
179
|
+
const body = request.body !== null && typeof request.body === 'object' && !Array.isArray(request.body) ? request.body : {};
|
|
180
|
+
try {
|
|
181
|
+
if (url.pathname === '/api/longlive/actions/preview') {
|
|
182
|
+
if (method !== 'POST') return actionResponse(405, { ok: false, error: { code: 'E_METHOD', message: 'preview 只支持 POST。' } });
|
|
183
|
+
const size = Number.isInteger(request.rawBodySize) ? request.rawBodySize : Buffer.byteLength(JSON.stringify(body));
|
|
184
|
+
if (size > ACTIONS_BODY_LIMIT) return actionResponse(413, { ok: false, error: { code: 'E_BODY_TOO_LARGE', message: `请求体超过 ${ACTIONS_BODY_LIMIT} 字节。` } });
|
|
185
|
+
return actionResponse(200, actions.preview(gateRequest, body));
|
|
186
|
+
}
|
|
187
|
+
if (url.pathname === '/api/longlive/actions/apply') {
|
|
188
|
+
if (method !== 'POST') return actionResponse(405, { ok: false, error: { code: 'E_METHOD', message: 'apply 只支持 POST。' } });
|
|
189
|
+
const size = Number.isInteger(request.rawBodySize) ? request.rawBodySize : Buffer.byteLength(JSON.stringify(body));
|
|
190
|
+
if (size > ACTIONS_BODY_LIMIT) return actionResponse(413, { ok: false, error: { code: 'E_BODY_TOO_LARGE', message: `请求体超过 ${ACTIONS_BODY_LIMIT} 字节。` } });
|
|
191
|
+
return actionResponse(200, actions.apply(gateRequest, body));
|
|
192
|
+
}
|
|
193
|
+
if (url.pathname === '/api/longlive/actions/undo') {
|
|
194
|
+
if (method !== 'POST') return actionResponse(405, { ok: false, error: { code: 'E_METHOD', message: 'undo 只支持 POST。' } });
|
|
195
|
+
const size = Number.isInteger(request.rawBodySize) ? request.rawBodySize : Buffer.byteLength(JSON.stringify(body));
|
|
196
|
+
if (size > ACTIONS_BODY_LIMIT) return actionResponse(413, { ok: false, error: { code: 'E_BODY_TOO_LARGE', message: `请求体超过 ${ACTIONS_BODY_LIMIT} 字节。` } });
|
|
197
|
+
return actionResponse(200, actions.undo(gateRequest, body));
|
|
198
|
+
}
|
|
199
|
+
if (url.pathname === '/api/longlive/actions') {
|
|
200
|
+
if (method !== 'GET') return actionResponse(405, { ok: false, error: { code: 'E_METHOD', message: 'actions 列表只支持 GET。' } });
|
|
201
|
+
return actionResponse(200, actions.listActions(gateRequest, query));
|
|
202
|
+
}
|
|
203
|
+
if (url.pathname === '/api/longlive/audit') {
|
|
204
|
+
if (method !== 'GET') return actionResponse(405, { ok: false, error: { code: 'E_METHOD', message: 'audit 只支持 GET。' } });
|
|
205
|
+
return actionResponse(200, actions.readAudit(gateRequest, query));
|
|
206
|
+
}
|
|
207
|
+
return actionResponse(404, { ok: false, error: { code: 'E_ROUTE_UNKNOWN', message: `未知动作路由:${url.pathname}` } });
|
|
208
|
+
} catch (error) {
|
|
209
|
+
return actionErrorResponse(error);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
memoryRoot,
|
|
215
|
+
panelRoot,
|
|
216
|
+
auth,
|
|
217
|
+
integrity,
|
|
218
|
+
audit,
|
|
219
|
+
evidence,
|
|
220
|
+
actions,
|
|
221
|
+
readonly,
|
|
222
|
+
handleReadonly,
|
|
223
|
+
handleAction,
|
|
224
|
+
/** Host-internal channel: mint a one-shot capability token for the panel. */
|
|
225
|
+
issueCapability: (opts = {}) => auth.issue(opts),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const warned = new Set();
|
|
230
|
+
function warnOnce(key, error) {
|
|
231
|
+
if (warned.has(key)) return;
|
|
232
|
+
warned.add(key);
|
|
233
|
+
try {
|
|
234
|
+
console.warn(`[longlive] ${key}: ${error?.stack ?? error?.message ?? String(error)}`);
|
|
235
|
+
} catch {
|
|
236
|
+
/* logging must never break activation */
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function makeResponder(handler) {
|
|
241
|
+
return (req, res) => {
|
|
242
|
+
let body = {};
|
|
243
|
+
(async () => {
|
|
244
|
+
if (req?.method === 'POST') {
|
|
245
|
+
const chunks = [];
|
|
246
|
+
let size = 0;
|
|
247
|
+
let tooLarge = false;
|
|
248
|
+
await new Promise((resolve) => {
|
|
249
|
+
req.on('data', (chunk) => {
|
|
250
|
+
if (tooLarge) return;
|
|
251
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
252
|
+
size += buffer.length;
|
|
253
|
+
if (size > ACTIONS_BODY_LIMIT) {
|
|
254
|
+
tooLarge = true;
|
|
255
|
+
resolve();
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
chunks.push(buffer);
|
|
259
|
+
});
|
|
260
|
+
req.on('end', resolve);
|
|
261
|
+
req.on('error', resolve);
|
|
262
|
+
});
|
|
263
|
+
if (tooLarge) {
|
|
264
|
+
const payload = JSON.stringify({ ok: false, error: { code: 'E_BODY_TOO_LARGE', message: `请求体超过 ${ACTIONS_BODY_LIMIT} 字节。` } });
|
|
265
|
+
try {
|
|
266
|
+
res.writeHead(413, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(payload) });
|
|
267
|
+
res.end(payload);
|
|
268
|
+
} catch {
|
|
269
|
+
/* peer gone */
|
|
270
|
+
}
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
body = chunks.length === 0 ? {} : JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
275
|
+
} catch {
|
|
276
|
+
body = {};
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const host = String(req?.headers?.host ?? 'longlive.local');
|
|
280
|
+
const verdict = handler({
|
|
281
|
+
method: req?.method ?? 'GET',
|
|
282
|
+
path: `http://${host}${String(req?.url ?? '/')}`,
|
|
283
|
+
headers: req?.headers ?? {},
|
|
284
|
+
body,
|
|
285
|
+
source: 'http',
|
|
286
|
+
});
|
|
287
|
+
const payload = JSON.stringify(verdict.body ?? {});
|
|
288
|
+
try {
|
|
289
|
+
res.writeHead(verdict.status, {
|
|
290
|
+
'content-type': 'application/json; charset=utf-8',
|
|
291
|
+
'cache-control': 'no-store',
|
|
292
|
+
...(verdict.headers ?? {}),
|
|
293
|
+
'content-length': Buffer.byteLength(payload),
|
|
294
|
+
});
|
|
295
|
+
res.end(payload);
|
|
296
|
+
} catch {
|
|
297
|
+
try {
|
|
298
|
+
res.destroy?.();
|
|
299
|
+
} catch {
|
|
300
|
+
/* peer gone */
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
})().catch((error) => warnOnce('panel api responder failed', error));
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Register the panel API routes on the host Web server (memoryV2.enabled only).
|
|
309
|
+
* @returns {Promise<{api:object|null, registered:number}>} resolved after inject callback
|
|
310
|
+
* is set up (the actual registration happens when the web server is available).
|
|
311
|
+
*/
|
|
312
|
+
export function registerPanelApiRoutes(ctx, options = {}) {
|
|
313
|
+
if (typeof ctx?.inject !== 'function') return false;
|
|
314
|
+
try {
|
|
315
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
316
|
+
const webServer = webCtx?.webServer;
|
|
317
|
+
if (webServer === undefined || typeof webServer.register !== 'function') return;
|
|
318
|
+
let api;
|
|
319
|
+
try {
|
|
320
|
+
api = createPanelApi(options);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
warnOnce('panel api create failed', error);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const readonlyResponder = makeResponder(api.handleReadonly);
|
|
326
|
+
const actionResponder = makeResponder(api.handleAction);
|
|
327
|
+
let registered = 0;
|
|
328
|
+
const register = (registration, label) => {
|
|
329
|
+
try {
|
|
330
|
+
const dispose = webServer.register(registration);
|
|
331
|
+
registered += 1;
|
|
332
|
+
if (typeof dispose === 'function' && typeof webCtx.effect === 'function') {
|
|
333
|
+
try {
|
|
334
|
+
webCtx.effect(() => () => dispose(), `longlive: panel api ${label}`);
|
|
335
|
+
} catch {
|
|
336
|
+
/* fake context without an effect scope */
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
} catch (error) {
|
|
340
|
+
warnOnce(`panel api route ${label} registration failed`, error);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
for (const route of READONLY_ROUTES) {
|
|
344
|
+
register(
|
|
345
|
+
route.dynamic
|
|
346
|
+
? { kind: 'prefix', path: route.path.replace(/\/:anchorId$/, '/'), handler: readonlyResponder }
|
|
347
|
+
: { kind: 'exact', path: route.path, handler: readonlyResponder },
|
|
348
|
+
`readonly ${route.id}`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
register({ kind: 'prefix', path: DISTILL_DETAIL_PREFIX, handler: readonlyResponder }, 'distill detail');
|
|
352
|
+
for (const routePath of ACTION_ROUTE_PATHS) {
|
|
353
|
+
register({ kind: 'exact', path: routePath, handler: actionResponder }, `action ${routePath}`);
|
|
354
|
+
}
|
|
355
|
+
if (typeof webCtx.effect === 'function') {
|
|
356
|
+
try {
|
|
357
|
+
webCtx.effect(() => () => { api = null; }, 'longlive: panel api scope');
|
|
358
|
+
} catch {
|
|
359
|
+
/* fake context */
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
warnOnce('panel api registration summary', { registered });
|
|
363
|
+
});
|
|
364
|
+
return true;
|
|
365
|
+
} catch (error) {
|
|
366
|
+
warnOnce('panel api inject failed', error);
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export { registerReadonlyRoutes };
|