@senpi-ai/runtime 3.0.178 → 3.0.188
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/dist/actions/close-position/close-position.action.d.ts.map +1 -1
- package/dist/actions/close-position/close-position.action.js +6 -1
- package/dist/actions/close-position/close-position.action.js.map +1 -1
- package/dist/actions/llm-decision/openclaw-llm-decision.d.ts +8 -0
- package/dist/actions/llm-decision/openclaw-llm-decision.d.ts.map +1 -1
- package/dist/actions/llm-decision/openclaw-llm-decision.js +56 -1
- package/dist/actions/llm-decision/openclaw-llm-decision.js.map +1 -1
- package/dist/actions/position-tracker/position-tracker.action.d.ts.map +1 -1
- package/dist/actions/position-tracker/position-tracker.action.js +1 -0
- package/dist/actions/position-tracker/position-tracker.action.js.map +1 -1
- package/dist/approvals/approval-store.d.ts +37 -7
- package/dist/approvals/approval-store.d.ts.map +1 -1
- package/dist/approvals/approval-store.js +127 -23
- package/dist/approvals/approval-store.js.map +1 -1
- package/dist/approvals/telemetry.d.ts +28 -3
- package/dist/approvals/telemetry.d.ts.map +1 -1
- package/dist/approvals/telemetry.js +8 -4
- package/dist/approvals/telemetry.js.map +1 -1
- package/dist/approvals/tool-approval-gate.d.ts +85 -0
- package/dist/approvals/tool-approval-gate.d.ts.map +1 -1
- package/dist/approvals/tool-approval-gate.js +197 -15
- package/dist/approvals/tool-approval-gate.js.map +1 -1
- package/dist/approvals/turn-context.d.ts +296 -0
- package/dist/approvals/turn-context.d.ts.map +1 -0
- package/dist/approvals/turn-context.js +594 -0
- package/dist/approvals/turn-context.js.map +1 -0
- package/dist/cli/guide-commands.d.ts.map +1 -1
- package/dist/cli/guide-commands.js +18 -3
- package/dist/cli/guide-commands.js.map +1 -1
- package/dist/cli/senpi-commands.d.ts.map +1 -1
- package/dist/cli/senpi-commands.js +80 -5
- package/dist/cli/senpi-commands.js.map +1 -1
- package/dist/deploy/job.d.ts +32 -0
- package/dist/deploy/job.d.ts.map +1 -1
- package/dist/deploy/job.js +72 -7
- package/dist/deploy/job.js.map +1 -1
- package/dist/deploy/register.d.ts +12 -0
- package/dist/deploy/register.d.ts.map +1 -1
- package/dist/deploy/register.js +85 -2
- package/dist/deploy/register.js.map +1 -1
- package/dist/dsl/events/build-closed-event.d.ts +11 -0
- package/dist/dsl/events/build-closed-event.d.ts.map +1 -1
- package/dist/dsl/events/build-closed-event.js +13 -0
- package/dist/dsl/events/build-closed-event.js.map +1 -1
- package/dist/dsl/events/handlers.d.ts.map +1 -1
- package/dist/dsl/events/handlers.js +9 -5
- package/dist/dsl/events/handlers.js.map +1 -1
- package/dist/dsl/monitor/dsl-failure-events.d.ts +38 -2
- package/dist/dsl/monitor/dsl-failure-events.d.ts.map +1 -1
- package/dist/dsl/monitor/dsl-failure-events.js +67 -4
- package/dist/dsl/monitor/dsl-failure-events.js.map +1 -1
- package/dist/dsl/monitor/process-one-position.d.ts.map +1 -1
- package/dist/dsl/monitor/process-one-position.js +37 -9
- package/dist/dsl/monitor/process-one-position.js.map +1 -1
- package/dist/host/openclaw-host.d.ts +138 -0
- package/dist/host/openclaw-host.d.ts.map +1 -0
- package/dist/host/openclaw-host.js +177 -0
- package/dist/host/openclaw-host.js.map +1 -0
- package/dist/host/plugin-logger.d.ts +99 -0
- package/dist/host/plugin-logger.d.ts.map +1 -0
- package/dist/host/plugin-logger.js +142 -0
- package/dist/host/plugin-logger.js.map +1 -0
- package/dist/index.d.ts +57 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +719 -162
- package/dist/index.js.map +1 -1
- package/dist/prompt/session-context-seed-hook.d.ts +7 -0
- package/dist/prompt/session-context-seed-hook.d.ts.map +1 -1
- package/dist/prompt/session-context-seed-hook.js +1 -1
- package/dist/prompt/session-context-seed-hook.js.map +1 -1
- package/dist/prompt/skill-router-hook.d.ts +24 -0
- package/dist/prompt/skill-router-hook.d.ts.map +1 -0
- package/dist/prompt/skill-router-hook.js +381 -0
- package/dist/prompt/skill-router-hook.js.map +1 -0
- package/dist/runtime/auto-update/coordinator.d.ts +220 -0
- package/dist/runtime/auto-update/coordinator.d.ts.map +1 -1
- package/dist/runtime/auto-update/coordinator.js +715 -22
- package/dist/runtime/auto-update/coordinator.js.map +1 -1
- package/dist/runtime/auto-update/gateway-restart.d.ts +60 -1
- package/dist/runtime/auto-update/gateway-restart.d.ts.map +1 -1
- package/dist/runtime/auto-update/gateway-restart.js +95 -21
- package/dist/runtime/auto-update/gateway-restart.js.map +1 -1
- package/dist/runtime/auto-update/idle-gate.d.ts +175 -0
- package/dist/runtime/auto-update/idle-gate.d.ts.map +1 -0
- package/dist/runtime/auto-update/idle-gate.js +229 -0
- package/dist/runtime/auto-update/idle-gate.js.map +1 -0
- package/dist/runtime/auto-update/install-results.d.ts +130 -0
- package/dist/runtime/auto-update/install-results.d.ts.map +1 -0
- package/dist/runtime/auto-update/install-results.js +264 -0
- package/dist/runtime/auto-update/install-results.js.map +1 -0
- package/dist/runtime/auto-update/money-call-tracker.d.ts +36 -0
- package/dist/runtime/auto-update/money-call-tracker.d.ts.map +1 -0
- package/dist/runtime/auto-update/money-call-tracker.js +129 -0
- package/dist/runtime/auto-update/money-call-tracker.js.map +1 -0
- package/dist/runtime/auto-update/register-idle-gate.d.ts +70 -0
- package/dist/runtime/auto-update/register-idle-gate.d.ts.map +1 -0
- package/dist/runtime/auto-update/register-idle-gate.js +127 -0
- package/dist/runtime/auto-update/register-idle-gate.js.map +1 -0
- package/dist/runtime/auto-update/run-update-command.d.ts +13 -0
- package/dist/runtime/auto-update/run-update-command.d.ts.map +1 -1
- package/dist/runtime/auto-update/run-update-command.js +18 -0
- package/dist/runtime/auto-update/run-update-command.js.map +1 -1
- package/dist/runtime/auto-update/state-store.d.ts +14 -1
- package/dist/runtime/auto-update/state-store.d.ts.map +1 -1
- package/dist/runtime/auto-update/state-store.js +37 -3
- package/dist/runtime/auto-update/state-store.js.map +1 -1
- package/dist/runtime/auto-update/types.d.ts +52 -0
- package/dist/runtime/auto-update/types.d.ts.map +1 -1
- package/dist/runtime/auto-update/types.js.map +1 -1
- package/dist/runtime/auto-update/update-marker.d.ts +95 -0
- package/dist/runtime/auto-update/update-marker.d.ts.map +1 -0
- package/dist/runtime/auto-update/update-marker.js +185 -0
- package/dist/runtime/auto-update/update-marker.js.map +1 -0
- package/dist/runtime/auto-update/update-schedule.d.ts +67 -0
- package/dist/runtime/auto-update/update-schedule.d.ts.map +1 -0
- package/dist/runtime/auto-update/update-schedule.js +91 -0
- package/dist/runtime/auto-update/update-schedule.js.map +1 -0
- package/dist/runtime/decision-errors.d.ts +7 -0
- package/dist/runtime/decision-errors.d.ts.map +1 -1
- package/dist/runtime/decision-errors.js +15 -0
- package/dist/runtime/decision-errors.js.map +1 -1
- package/dist/runtime/process-state.d.ts +168 -0
- package/dist/runtime/process-state.d.ts.map +1 -0
- package/dist/runtime/process-state.js +81 -0
- package/dist/runtime/process-state.js.map +1 -0
- package/dist/runtime/reconcile-state.d.ts.map +1 -1
- package/dist/runtime/reconcile-state.js +21 -4
- package/dist/runtime/reconcile-state.js.map +1 -1
- package/dist/runtime/strategy-registry.d.ts +16 -0
- package/dist/runtime/strategy-registry.d.ts.map +1 -1
- package/dist/runtime/strategy-registry.js +7 -3
- package/dist/runtime/strategy-registry.js.map +1 -1
- package/dist/runtime/update-apply-deps.d.ts +5 -3
- package/dist/runtime/update-apply-deps.d.ts.map +1 -1
- package/dist/runtime/update-apply-deps.js +15 -3
- package/dist/runtime/update-apply-deps.js.map +1 -1
- package/dist/senpi/client.d.ts +29 -0
- package/dist/senpi/client.d.ts.map +1 -1
- package/dist/senpi/client.js +71 -2
- package/dist/senpi/client.js.map +1 -1
- package/dist/skill-router/catalog.d.ts +30 -0
- package/dist/skill-router/catalog.d.ts.map +1 -0
- package/dist/skill-router/catalog.js +131 -0
- package/dist/skill-router/catalog.js.map +1 -0
- package/dist/skill-router/classify-client.d.ts +80 -0
- package/dist/skill-router/classify-client.d.ts.map +1 -0
- package/dist/skill-router/classify-client.js +283 -0
- package/dist/skill-router/classify-client.js.map +1 -0
- package/dist/skill-router/prompt.d.ts +36 -0
- package/dist/skill-router/prompt.d.ts.map +1 -0
- package/dist/skill-router/prompt.js +318 -0
- package/dist/skill-router/prompt.js.map +1 -0
- package/dist/skill-router/resolve.d.ts +41 -0
- package/dist/skill-router/resolve.d.ts.map +1 -0
- package/dist/skill-router/resolve.js +43 -0
- package/dist/skill-router/resolve.js.map +1 -0
- package/dist/skills-manager/version-manager.d.ts +14 -0
- package/dist/skills-manager/version-manager.d.ts.map +1 -1
- package/dist/skills-manager/version-manager.js +31 -3
- package/dist/skills-manager/version-manager.js.map +1 -1
- package/dist/strategy/strategy-state.d.ts +11 -3
- package/dist/strategy/strategy-state.d.ts.map +1 -1
- package/dist/strategy/strategy-state.js +18 -8
- package/dist/strategy/strategy-state.js.map +1 -1
- package/dist/telemetry/event-builders.d.ts +4 -2
- package/dist/telemetry/event-builders.d.ts.map +1 -1
- package/dist/telemetry/event-builders.js +4 -2
- package/dist/telemetry/event-builders.js.map +1 -1
- package/dist/telemetry/metrics.d.ts +15 -1
- package/dist/telemetry/metrics.d.ts.map +1 -1
- package/dist/telemetry/metrics.js +25 -1
- package/dist/telemetry/metrics.js.map +1 -1
- package/dist/telemetry/otel-sdk.d.ts +12 -0
- package/dist/telemetry/otel-sdk.d.ts.map +1 -1
- package/dist/telemetry/otel-sdk.js +47 -1
- package/dist/telemetry/otel-sdk.js.map +1 -1
- package/dist/telemetry/spans/span-hooks.d.ts +18 -1
- package/dist/telemetry/spans/span-hooks.d.ts.map +1 -1
- package/dist/telemetry/spans/span-hooks.js +315 -96
- package/dist/telemetry/spans/span-hooks.js.map +1 -1
- package/dist/telemetry/tool-plane.d.ts +2 -0
- package/dist/telemetry/tool-plane.d.ts.map +1 -1
- package/dist/telemetry/tool-plane.js +1 -0
- package/dist/telemetry/tool-plane.js.map +1 -1
- package/dist/test-setup.js +7 -1
- package/dist/test-setup.js.map +1 -1
- package/dist/tool-surface/crib-cache.d.ts +21 -0
- package/dist/tool-surface/crib-cache.d.ts.map +1 -0
- package/dist/tool-surface/crib-cache.js +54 -0
- package/dist/tool-surface/crib-cache.js.map +1 -0
- package/dist/tool-surface/crib-hook.d.ts +78 -0
- package/dist/tool-surface/crib-hook.d.ts.map +1 -0
- package/dist/tool-surface/crib-hook.js +225 -0
- package/dist/tool-surface/crib-hook.js.map +1 -0
- package/dist/tool-surface/crib-sheet.d.ts +56 -0
- package/dist/tool-surface/crib-sheet.d.ts.map +1 -0
- package/dist/tool-surface/crib-sheet.js +129 -0
- package/dist/tool-surface/crib-sheet.js.map +1 -0
- package/dist/tool-surface/mcp-tool-source.d.ts +64 -0
- package/dist/tool-surface/mcp-tool-source.d.ts.map +1 -0
- package/dist/tool-surface/mcp-tool-source.js +189 -0
- package/dist/tool-surface/mcp-tool-source.js.map +1 -0
- package/dist/utils/event-catalog.d.ts +228 -6
- package/dist/utils/event-catalog.d.ts.map +1 -1
- package/dist/utils/event-catalog.js +32 -0
- package/dist/utils/event-catalog.js.map +1 -1
- package/dist/widgets/tool.d.ts +9 -0
- package/dist/widgets/tool.d.ts.map +1 -1
- package/dist/widgets/tool.js +1 -0
- package/dist/widgets/tool.js.map +1 -1
- package/openclaw.plugin.json +11 -1
- package/package.json +5 -2
package/dist/index.js
CHANGED
|
@@ -14,15 +14,17 @@
|
|
|
14
14
|
import { readFileSync } from "node:fs";
|
|
15
15
|
import { parse as parseYaml } from "yaml";
|
|
16
16
|
import { join, dirname } from "node:path";
|
|
17
|
-
import { SenpiClient } from "./senpi/client.js";
|
|
17
|
+
import { isMoneyCallTool, SenpiClient, senpiOrderCallsInFlight } from "./senpi/client.js";
|
|
18
|
+
import { MoneyCallTracker, registerMoneyCallHooks } from "./runtime/auto-update/money-call-tracker.js";
|
|
18
19
|
import { buildWalletStatusHint } from "./senpi/strategy-status.js";
|
|
19
20
|
import { bootSkippedStatusLabel, partitionByWalletStatus, readBootWalletStatuses, trackableWalletKeys, } from "./runtime/boot-skip.js";
|
|
20
21
|
import { DeployJobController } from "./deploy/job.js";
|
|
21
|
-
import { registerDeployGatewayMethods } from "./deploy/register.js";
|
|
22
|
+
import { DEPLOY_CAPABILITIES, registerDeployGatewayMethods } from "./deploy/register.js";
|
|
22
23
|
import { registerUpdateGatewayMethod } from "./runtime/update-register.js";
|
|
23
24
|
import { createStrategiesPublisher } from "./runtime/strategies-telemetry.js";
|
|
24
25
|
import { buildEventsReplay, createEventsPublisher, } from "./runtime/events-telemetry.js";
|
|
25
26
|
import { strategiesStore, strategyRecordFromConfig } from "./runtime/strategies-store.js";
|
|
27
|
+
import { bindProcessLogger, processLog, runtimeProcessState, } from "./runtime/process-state.js";
|
|
26
28
|
import { checkProofCoversRecipe, makeApplyToRuntime, makeWriteRegistry, runtimeChangeLock, } from "./runtime/update-apply-deps.js";
|
|
27
29
|
import { INSTALL_DEADLINE_MS, WALLET_INSTALL_IN_FLIGHT_CODE } from "./deploy/deadlines.js";
|
|
28
30
|
import { AuditQueryError } from "./runtime/audit-query.types.js";
|
|
@@ -47,14 +49,21 @@ import { readEvents } from "./telemetry/event-store.js";
|
|
|
47
49
|
import { VERSION } from "./version.js";
|
|
48
50
|
import { resolvePackageName } from "./runtime/auto-update/resolve-package-name.js";
|
|
49
51
|
import { runOpenClawPluginsUpdate } from "./runtime/auto-update/run-update-command.js";
|
|
52
|
+
import { UpdateIdleGate, createIdleGateActivity } from "./runtime/auto-update/idle-gate.js";
|
|
53
|
+
import { registerIdleGateHooks, resolveUpdateMid } from "./runtime/auto-update/register-idle-gate.js";
|
|
54
|
+
import { resolveUpdateMarkerPath } from "./runtime/auto-update/update-marker.js";
|
|
55
|
+
import { INSTALL_RESULTS_OTEL_FLUSH_MS, INSTALL_RESULTS_OTEL_READY_MS, resolveInstallResultsPath, } from "./runtime/auto-update/install-results.js";
|
|
50
56
|
import { registerSpanHooks } from "./telemetry/spans/index.js";
|
|
51
57
|
import { registerSessionContextSeedHook } from "./prompt/session-context-seed-hook.js";
|
|
58
|
+
import { registerCribSheet } from "./tool-surface/crib-hook.js";
|
|
59
|
+
import { registerSkillRouterHook } from "./prompt/skill-router-hook.js";
|
|
52
60
|
import { getDefaultPiiRedactor, initDefaultPiiRedactor } from "./telemetry/spans/redact-pii.js";
|
|
53
|
-
import { initOtelSdk, shutdownOtelSdk } from "./telemetry/otel-sdk.js";
|
|
61
|
+
import { flushOtelLogs, initOtelSdk, shutdownOtelSdk, waitForOtelInit } from "./telemetry/otel-sdk.js";
|
|
54
62
|
import { getLogLevel, getLogLevelSource, parseLogLevel, setLogLevel, } from "./utils/logger.js";
|
|
55
63
|
import { ExternalScannerIngestError, } from "./scanners/external-scanner-receiver.js";
|
|
56
64
|
import { createLogger } from "./utils/logger.js";
|
|
57
|
-
import { registerToolApprovalGate, resolveToolApprovalsMode, } from "./approvals/tool-approval-gate.js";
|
|
65
|
+
import { PendingApprovalTracker, registerToolApprovalGate, resolveToolApprovalsMode, } from "./approvals/tool-approval-gate.js";
|
|
66
|
+
import { registerTurnContextHooks, turnClassificationAvailable, TurnContextTracker, } from "./approvals/turn-context.js";
|
|
58
67
|
import { registerShowWidgetTool } from "./widgets/index.js";
|
|
59
68
|
import { EVENT_NAME, SENPI_ERROR_CODE, eventAttrs, scannerUnwiredErrorCode } from "./utils/event-catalog.js";
|
|
60
69
|
import { emitEvent } from "./actions/event-derivation.js";
|
|
@@ -71,6 +80,9 @@ import { ingestDispatchMutex, ingestDispatchKey } from "./runtime-api/intake/ing
|
|
|
71
80
|
import { buildScaffoldErrorRouter } from "./runtime-api/intake/scaffold-error-router.js";
|
|
72
81
|
import { loadRuntimeConfig } from "./runtime/load-runtime-config.js";
|
|
73
82
|
import { errorText } from "./deploy/error-text.js";
|
|
83
|
+
import { getOpenClawHost, initOpenClawHost } from "./host/openclaw-host.js";
|
|
84
|
+
import { createRegisterPluginLogger, withEventLogger } from "./host/plugin-logger.js";
|
|
85
|
+
import { hostname } from "node:os";
|
|
74
86
|
import { BOOT_FACTS_CALL_TIMEOUT_MS, planBootFacts, syncBootFacts, } from "./strategy/facts-sync.js";
|
|
75
87
|
/** Initialize all core features (DSL, risk, health) on the given event bus. */
|
|
76
88
|
export function initCore(bus) {
|
|
@@ -101,21 +113,6 @@ export { createScannerRuntimeModule, createSenpiScannerProviders, emergingMovers
|
|
|
101
113
|
export { run } from "./runtime/run.js";
|
|
102
114
|
export { loadRuntimeConfig } from "./runtime/load-runtime-config.js";
|
|
103
115
|
export { Runtime } from "./runtime/runtime.js";
|
|
104
|
-
/**
|
|
105
|
-
* A coordinator logger: info/warn/error route through `pluginLogger` unchanged (the gateway's own
|
|
106
|
-
* sink), and `event()` goes to a dedicated OTel-backed logger tagged `tag`. `PluginLogger`
|
|
107
|
-
* (api.logger) predates the event catalog and has no `event()`, so coordinators that emit
|
|
108
|
-
* first-class events (auto-update, skills-manager) get this split.
|
|
109
|
-
*/
|
|
110
|
-
function withEventLogger(pluginLogger, tag) {
|
|
111
|
-
const eventLogger = createLogger(tag);
|
|
112
|
-
return {
|
|
113
|
-
info: (...args) => pluginLogger.info(...args),
|
|
114
|
-
warn: (...args) => pluginLogger.warn(...args),
|
|
115
|
-
error: (message, meta) => pluginLogger.error(message, meta),
|
|
116
|
-
event: eventLogger.event,
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
116
|
/**
|
|
120
117
|
* Read the plugin version from the sibling `openclaw.plugin.json` manifest.
|
|
121
118
|
* Performed once at module load — the manifest is shipped alongside the
|
|
@@ -184,11 +181,50 @@ const WALLET_INSTALL_IN_FLIGHT = `[${WALLET_INSTALL_IN_FLIGHT_CODE}]`;
|
|
|
184
181
|
*/
|
|
185
182
|
const RUNTIME_ID_TAKEN = "[E_RUNTIME_ID_TAKEN]";
|
|
186
183
|
/**
|
|
187
|
-
* One StrategyFacts send per runtime at a time, keyed on runtime id, across the whole process
|
|
188
|
-
*
|
|
189
|
-
*
|
|
184
|
+
* One StrategyFacts send per runtime at a time, keyed on runtime id, across the whole process.
|
|
185
|
+
* Held in the process state (`runtime/process-state.ts`), not this module: a 10.x plugin reload
|
|
186
|
+
* evaluates a new copy of this module, and the previous registration's send may still be running.
|
|
187
|
+
* Separate from `runtimeChangeLock`. Delete does not take it; an apply queues its send here and
|
|
188
|
+
* does not wait.
|
|
190
189
|
*/
|
|
191
|
-
|
|
190
|
+
function factsSendLock() {
|
|
191
|
+
const state = runtimeProcessState();
|
|
192
|
+
state.factsSendLock ??= new KeyedMutex();
|
|
193
|
+
return state.factsSendLock;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Clears the process-state latch for the 5.x "cannot classify runs" notice
|
|
197
|
+
* (`legacyTurnClassificationNoticeLogged`). Tests only.
|
|
198
|
+
*
|
|
199
|
+
* The latch lives in the process state so a plugin reload (which re-registers the plugin and
|
|
200
|
+
* restarts its service in the same process, from a new copy of this module) does not repeat the
|
|
201
|
+
* notice. The 5.x case is a host-version limit with no config fix, so one info line per process is
|
|
202
|
+
* the whole message; the fixable 10.x case stays an ERROR at every registration and does not read
|
|
203
|
+
* this latch.
|
|
204
|
+
*/
|
|
205
|
+
export function resetLegacyTurnClassificationNoticeForTests() {
|
|
206
|
+
runtimeProcessState().legacyTurnClassificationNoticeLogged = false;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The whole of `register()` in the `"cli-metadata"` pass: the `senpi` CLI root, under the same
|
|
210
|
+
* preconditions and with the same metadata as the full pass, and nothing else.
|
|
211
|
+
*
|
|
212
|
+
* Reads no `api.runtime`: on 10.x that pass's runtime throws on any read, and the host prints the
|
|
213
|
+
* throw as `runtime failed during register` on every `openclaw senpi …` call (RT566-04). Logs
|
|
214
|
+
* nothing: a skipped precondition is reported by the full pass, which follows in the same process.
|
|
215
|
+
*/
|
|
216
|
+
function registerSenpiCliMetadata(api) {
|
|
217
|
+
const config = api.pluginConfig;
|
|
218
|
+
if (!config)
|
|
219
|
+
return;
|
|
220
|
+
const mcpTransport = api.mcpTransport;
|
|
221
|
+
const apiKey = resolveSenpiApiKeyFromStore(readSenpiCliStore(), typeof config.apiKey === "string" && config.apiKey.length > 0 ? config.apiKey : undefined);
|
|
222
|
+
if (!mcpTransport && !apiKey)
|
|
223
|
+
return;
|
|
224
|
+
api.registerCli((ctx) => {
|
|
225
|
+
registerSenpiCli(ctx.program);
|
|
226
|
+
}, { commands: ["senpi"] });
|
|
227
|
+
}
|
|
192
228
|
/**
|
|
193
229
|
* OpenClaw plugin entry.
|
|
194
230
|
* Boots from internal registry (installed_runtimes.json) in stateDir; does not read runtime list from config.
|
|
@@ -219,16 +255,34 @@ const senpiRuntimePlugin = {
|
|
|
219
255
|
// The diagnostics are not dropped, only moved to stderr where diagnostics belong. Warnings and
|
|
220
256
|
// errors are left on the logger untouched: those are not routine chatter, and a caller piping
|
|
221
257
|
// stdout to a parser still wants them visible.
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
258
|
+
//
|
|
259
|
+
// OpenClaw 2026.5.20+ (every modern host) moves plugin logs to stderr itself under `--json` and
|
|
260
|
+
// files them at their real level, so the reroute is kept for 5.x only: on 10.x it made the
|
|
261
|
+
// console capture file every registration line at ERROR (F5). See host/plugin-logger.ts.
|
|
262
|
+
//
|
|
263
|
+
// The cli-metadata pass only collects CLI command roots. 10.x hands it a runtime that throws on
|
|
264
|
+
// any read (RT566-04), so register the `senpi` root and nothing else — and read no api.runtime.
|
|
265
|
+
if (api.registrationMode === "cli-metadata") {
|
|
266
|
+
registerSenpiCliMetadata(api);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
// Host facts first: the logger and every version-gated registration below read them. 10.x also
|
|
270
|
+
// registers plugins in non-full modes inside the gateway (`tool-discovery` for tools.catalog);
|
|
271
|
+
// that pass must keep registering tools, but its throwaway api must not replace the record the
|
|
272
|
+
// live registration made.
|
|
273
|
+
const fullRegistration = api.registrationMode === undefined || api.registrationMode === "full";
|
|
274
|
+
const openClawHost = (!fullRegistration && getOpenClawHost()) || initOpenClawHost(api);
|
|
275
|
+
// State kept across a reload (the deploy controller, the gate trackers) logs through the latest
|
|
276
|
+
// full registration's logger, never through an `api` a reload has replaced.
|
|
277
|
+
const processState = runtimeProcessState();
|
|
278
|
+
if (fullRegistration)
|
|
279
|
+
bindProcessLogger(api.logger);
|
|
280
|
+
const pluginLogger = createRegisterPluginLogger(api.logger, {
|
|
281
|
+
jsonMode: process.argv.includes("--json"),
|
|
282
|
+
hostRoutesJsonLogsToStderr: openClawHost.modern,
|
|
283
|
+
});
|
|
231
284
|
pluginLogger.info("[senpi-runtime] register(api) invoked");
|
|
285
|
+
pluginLogger.info(`[senpi-runtime] host OpenClaw ${openClawHost.version ?? "unknown"} (${openClawHost.modern ? "modern" : "legacy"})`);
|
|
232
286
|
const config = api.pluginConfig;
|
|
233
287
|
if (!config) {
|
|
234
288
|
pluginLogger.warn("[senpi-runtime] No plugin config found — skipping registration");
|
|
@@ -278,8 +332,10 @@ const senpiRuntimePlugin = {
|
|
|
278
332
|
// loader doesn't await it; awaiting init would defer the registrations below), so it's
|
|
279
333
|
// fire-and-forget — the hooks resolve their tracer lazily at fire time, by which point
|
|
280
334
|
// init has run. Self-guarding; see src/telemetry/otel-sdk.ts.
|
|
335
|
+
// The box's per-user Senpi token: the OTel user token and the skill router's bearer.
|
|
336
|
+
const userToken = apiKey ?? process.env.SENPI_AUTH_TOKEN ?? process.env.SENPI_API_KEY;
|
|
281
337
|
void initOtelSdk({
|
|
282
|
-
userToken
|
|
338
|
+
userToken,
|
|
283
339
|
serviceVersion: VERSION,
|
|
284
340
|
}).catch((err) => {
|
|
285
341
|
pluginLogger.warn("[senpi-runtime] OTel SDK init failed", {
|
|
@@ -289,8 +345,8 @@ const senpiRuntimePlugin = {
|
|
|
289
345
|
// Agent telemetry — gateway hooks emit gen_ai spans (llm/tool/subagent) through
|
|
290
346
|
// the shared tracer; on-site MCP calls emit their own spans from SenpiClient.
|
|
291
347
|
try {
|
|
292
|
-
registerSpanHooks({ api });
|
|
293
|
-
pluginLogger.info(
|
|
348
|
+
const spanHookCount = registerSpanHooks({ api, modernHost: openClawHost.modern });
|
|
349
|
+
pluginLogger.info(`[senpi-runtime] gen_ai span hooks registered (${spanHookCount} hooks)`);
|
|
294
350
|
}
|
|
295
351
|
catch (err) {
|
|
296
352
|
pluginLogger.warn("[senpi-runtime] failed to register span hooks", {
|
|
@@ -309,14 +365,133 @@ const senpiRuntimePlugin = {
|
|
|
309
365
|
err: err instanceof Error ? err.message : String(err),
|
|
310
366
|
});
|
|
311
367
|
}
|
|
368
|
+
// senpi__ crib sheet (OpenClaw 10.x tool-search directory mode only): the
|
|
369
|
+
// directory folds every MCP tool into one sentence, so the runtime puts
|
|
370
|
+
// the names back as prependSystemContext. Registers nothing on 5.x.
|
|
371
|
+
// Its `before_prompt_build` hook needs the same host grant as the approval
|
|
372
|
+
// turn classification below; without it 10.x drops the hook, so the line
|
|
373
|
+
// says the crib is inactive and why instead of "registered".
|
|
374
|
+
try {
|
|
375
|
+
if (registerCribSheet({
|
|
376
|
+
api: api,
|
|
377
|
+
baseStateDir,
|
|
378
|
+
pluginConfig: config,
|
|
379
|
+
logger: pluginLogger,
|
|
380
|
+
})) {
|
|
381
|
+
// Registered, so the host is modern; only the hook grant is left to check.
|
|
382
|
+
const cribHook = turnClassificationAvailable({ modernHost: true, config: api.config, pluginId: api.id });
|
|
383
|
+
pluginLogger.info(cribHook.available
|
|
384
|
+
? "[senpi-runtime] senpi__ crib sheet registered (directory mode only)"
|
|
385
|
+
: `[senpi-runtime] senpi__ crib inactive: ${cribHook.reason}` +
|
|
386
|
+
(cribHook.configFix ? `; fix: ${cribHook.configFix}` : ""));
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
catch (err) {
|
|
390
|
+
pluginLogger.warn("[senpi-runtime] failed to register the senpi__ crib sheet", {
|
|
391
|
+
err: err instanceof Error ? err.message : String(err),
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
// Skill router — on an eligible user turn, asks senpi-backend which installed skill the
|
|
395
|
+
// prompt needs and (mode `on`) points the model at its SKILL.md. Registered after the seed
|
|
396
|
+
// hook so the seed instruction comes first if both inject. Off unless SENPI_SKILL_ROUTER is
|
|
397
|
+
// `shadow` or `on`; see src/prompt/skill-router-hook.ts.
|
|
398
|
+
try {
|
|
399
|
+
const skillRouter = registerSkillRouterHook({
|
|
400
|
+
api,
|
|
401
|
+
token: userToken,
|
|
402
|
+
searchPath: resolveSkillsManagerConfig(config?.skillsManager).skillsDir,
|
|
403
|
+
logger: pluginLogger,
|
|
404
|
+
});
|
|
405
|
+
if (skillRouter !== "off") {
|
|
406
|
+
pluginLogger.info(`[senpi-runtime] skill router hook registered (${skillRouter})`);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
catch (err) {
|
|
410
|
+
pluginLogger.warn("[senpi-runtime] failed to register skill router hook", {
|
|
411
|
+
err: err instanceof Error ? err.message : String(err),
|
|
412
|
+
});
|
|
413
|
+
}
|
|
312
414
|
// MCP tool approval gate — state-changing senpi MCP tools require an
|
|
313
415
|
// interactive user approval before executing. Prompts reach senpi-web via
|
|
314
416
|
// the bridge's operator.approvals-scoped gateway connection; allow-always
|
|
315
417
|
// decisions persist in <stateDir>/tool-approvals.json.
|
|
316
418
|
// See docs/mcp-tool-approvals-design.md.
|
|
419
|
+
// Open trade-approval prompts, read by the self-update idle gate (R2).
|
|
420
|
+
// This and the turn tracker are process state: a 10.x reload re-registers in the same process
|
|
421
|
+
// while a prompt is open or a run is in flight (r4467406809, r4427720076).
|
|
422
|
+
processState.pendingApprovals ??= new PendingApprovalTracker();
|
|
423
|
+
const pendingApprovalTracker = processState.pendingApprovals;
|
|
424
|
+
// The turn kind (chat / cron / heartbeat) and session key of each gated
|
|
425
|
+
// call, for approval telemetry and the 10.x scheduled-turn block (R6, D13).
|
|
426
|
+
processState.turnContext ??= new TurnContextTracker();
|
|
427
|
+
const turnContextTracker = processState.turnContext;
|
|
428
|
+
// One boot-time fact (D15): can this host classify runs at all? Only then
|
|
429
|
+
// does the gate stop prompts outside a direct chat turn. Without it every
|
|
430
|
+
// run reads unknown and keeps the pre-10.x prompt, so a box missing the
|
|
431
|
+
// setting never blocks chat trades; it is reported loudly instead.
|
|
432
|
+
let turnClassification = turnClassificationAvailable({
|
|
433
|
+
modernHost: openClawHost.modern,
|
|
434
|
+
config: api.config,
|
|
435
|
+
pluginId: api.id,
|
|
436
|
+
});
|
|
437
|
+
try {
|
|
438
|
+
registerTurnContextHooks({ api, tracker: turnContextTracker });
|
|
439
|
+
}
|
|
440
|
+
catch (err) {
|
|
441
|
+
turnClassification = { available: false, reason: "the turn-context hooks failed to register" };
|
|
442
|
+
pluginLogger.warn("[senpi-runtime] failed to register the approval turn-context hooks", {
|
|
443
|
+
err: err instanceof Error ? err.message : String(err),
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
// Only the logging and the status flag differ by host; the gate below reads the same boolean
|
|
447
|
+
// either way. On 10.x it is an ERROR at every registration (a box config to fix, or hooks that
|
|
448
|
+
// failed to register). On 5.x it is a host limit no config can fix, so it is one info line per
|
|
449
|
+
// process, logged from the service start below: that runs in the gateway only, so the
|
|
450
|
+
// `openclaw senpi …` CLI children (deploy.py, close.py, an agent exec) register without
|
|
451
|
+
// printing it.
|
|
452
|
+
const turnClassificationHostLimit = !turnClassification.available && !openClawHost.modern;
|
|
453
|
+
const turnClassificationNotice = turnClassification.available
|
|
454
|
+
? undefined
|
|
455
|
+
: `[senpi-tool-approvals] cannot tell chat turns from scheduled or background runs: ${turnClassification.reason}. ` +
|
|
456
|
+
"Trade approvals are requested in every run, scheduled ones included, " +
|
|
457
|
+
(turnClassification.configFix
|
|
458
|
+
? `until the box config is fixed (${turnClassification.configFix}).`
|
|
459
|
+
: turnClassificationHostLimit
|
|
460
|
+
? "on this OpenClaw version; a 10.x host lifts this."
|
|
461
|
+
: "until the runtime registers its turn-context hooks.");
|
|
462
|
+
const legacyTurnClassificationNotice = turnClassificationHostLimit ? turnClassificationNotice : undefined;
|
|
463
|
+
if (turnClassificationNotice !== undefined && !turnClassificationHostLimit && fullRegistration) {
|
|
464
|
+
pluginLogger.error(turnClassificationNotice);
|
|
465
|
+
}
|
|
466
|
+
const approvalsHostStatus = turnClassification.available
|
|
467
|
+
? { turnClassification: "available" }
|
|
468
|
+
: {
|
|
469
|
+
turnClassification: "unavailable",
|
|
470
|
+
reason: turnClassification.reason,
|
|
471
|
+
...(turnClassificationHostLimit ? { hostLimit: true } : {}),
|
|
472
|
+
};
|
|
473
|
+
// Process state, like the run-kind tracker beside it: a reload must not zero the count that
|
|
474
|
+
// `senpi status` warns about while chat trades are being refused.
|
|
475
|
+
const approvalsStatus = () => approvalsHostStatus.turnClassification === "available"
|
|
476
|
+
? {
|
|
477
|
+
...approvalsHostStatus,
|
|
478
|
+
runsRecorded: turnContextTracker.runsRecorded,
|
|
479
|
+
unclassifiedBlocks: processState.unclassifiedBlocks,
|
|
480
|
+
...(processState.lastUnclassifiedBlockAt
|
|
481
|
+
? { lastUnclassifiedBlockAt: processState.lastUnclassifiedBlockAt }
|
|
482
|
+
: {}),
|
|
483
|
+
}
|
|
484
|
+
: approvalsHostStatus;
|
|
317
485
|
try {
|
|
318
486
|
registerToolApprovalGate({
|
|
319
487
|
api,
|
|
488
|
+
pendingApprovals: pendingApprovalTracker,
|
|
489
|
+
turnContext: turnContextTracker,
|
|
490
|
+
turnClassification: turnClassification.available,
|
|
491
|
+
onUnclassifiedBlock: (at) => {
|
|
492
|
+
processState.unclassifiedBlocks += 1;
|
|
493
|
+
processState.lastUnclassifiedBlockAt = new Date(at).toISOString();
|
|
494
|
+
},
|
|
320
495
|
mode: resolveToolApprovalsMode({
|
|
321
496
|
pluginConfig: config,
|
|
322
497
|
env: process.env,
|
|
@@ -438,8 +613,21 @@ const senpiRuntimePlugin = {
|
|
|
438
613
|
* row, sees no live handle, deletes it and reinstalls — and the first install then lands on top,
|
|
439
614
|
* clobbering `runtimeHandles` under a runtime id both installs derive identically. Two exit
|
|
440
615
|
* engines, one margin account: the exact state `[E_WALLET_HAS_RUNTIME]` exists to prevent.
|
|
616
|
+
*
|
|
617
|
+
* Process state (`runtime/process-state.ts`), not this registration: a 10.x plugin reload
|
|
618
|
+
* re-registers in the same process while a deploy job's install from the previous registration
|
|
619
|
+
* runs on, and the new registration must still refuse a second install on that wallet.
|
|
441
620
|
*/
|
|
442
|
-
const installsInFlight =
|
|
621
|
+
const installsInFlight = processState.installsInFlight;
|
|
622
|
+
/**
|
|
623
|
+
* This registration's service lifecycle, for an install or adoption that outlives it. A 10.x
|
|
624
|
+
* plugin reload stops this service and starts the next registration's in the same process;
|
|
625
|
+
* `serviceStops` counts this registration's stops, so a stop followed by a later start is still
|
|
626
|
+
* seen. Only a stop counts: an install that began before the first start (the gateway may call
|
|
627
|
+
* installRuntime before start()) and spans it is not orphaned.
|
|
628
|
+
*/
|
|
629
|
+
let serviceState = "idle";
|
|
630
|
+
let serviceStops = 0;
|
|
443
631
|
// Dedicated logger for the runtime-api subtree — required because the
|
|
444
632
|
// PluginLogger surface (info/warn/error) lacks `debug`, while the
|
|
445
633
|
// Logger contract used by `runtime-api/` includes it.
|
|
@@ -480,26 +668,106 @@ const senpiRuntimePlugin = {
|
|
|
480
668
|
stateDir: join(baseStateDir, "skills-manager"),
|
|
481
669
|
logger: withEventLogger(pluginLogger, "[senpi-core][skills-manager]"),
|
|
482
670
|
});
|
|
483
|
-
const autoUpdateLogger = withEventLogger(pluginLogger, "[senpi-core][auto-update]");
|
|
484
671
|
const autoUpdateConfig = resolveAutoUpdateConfig(config?.autoUpdate);
|
|
672
|
+
// OpenClaw 10.x (>= 2026.8.1): restart-to-apply (R2). The runtime cannot
|
|
673
|
+
// install itself there, so it waits for its spread slot and an idle box,
|
|
674
|
+
// writes the install marker, and restarts through mutateConfigFile; the
|
|
675
|
+
// senpi-agent wrapper installs before the next gateway spawn. On 5.7 and
|
|
676
|
+
// 5.12 the wiring is the in-process install + config-bump restart.
|
|
677
|
+
const modernHost = openClawHost.modern;
|
|
678
|
+
// 10.x: every `auto_update.*` event is also written to the gateway log as one key=value line,
|
|
679
|
+
// so a box with no collector still keeps the update's fields (F8). 5.x keeps OTel only.
|
|
680
|
+
const autoUpdateLogger = withEventLogger(pluginLogger, "[senpi-core][auto-update]", modernHost ? { mirrorTag: "[senpi-auto-update]" } : {});
|
|
681
|
+
let idleGate;
|
|
682
|
+
if (modernHost) {
|
|
683
|
+
// Money calls on every route: the runtime's own in-process MCP calls, plus
|
|
684
|
+
// the agent's senpi__ calls (direct or through the dispatcher), seen at the
|
|
685
|
+
// tool hooks. A deploy job is read from the controller (this process) and
|
|
686
|
+
// its journals (any process).
|
|
687
|
+
// Process state, like the approval trackers: a call that started under the previous
|
|
688
|
+
// registration still counts, and its after-hook (now this registration's) closes it.
|
|
689
|
+
processState.moneyCalls ??= new MoneyCallTracker();
|
|
690
|
+
const moneyCalls = processState.moneyCalls;
|
|
691
|
+
try {
|
|
692
|
+
registerMoneyCallHooks({
|
|
693
|
+
api: api,
|
|
694
|
+
tracker: moneyCalls,
|
|
695
|
+
isMoneyTool: isMoneyCallTool,
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
catch (err) {
|
|
699
|
+
pluginLogger.warn("[senpi-runtime] failed to register the self-update money-call hooks", {
|
|
700
|
+
err: err instanceof Error ? err.message : String(err),
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
idleGate = new UpdateIdleGate({
|
|
704
|
+
pendingApprovals: () => pendingApprovalTracker.count(),
|
|
705
|
+
ordersInFlight: () => senpiOrderCallsInFlight() + moneyCalls.count(Date.now()),
|
|
706
|
+
// Read only from ticks, after register() has constructed the controller below.
|
|
707
|
+
deploysInFlight: () => deployController.inFlight(Date.now()),
|
|
708
|
+
// The process start, not this registration: a config edit under `plugins` re-registers in
|
|
709
|
+
// the same process (10.10 reloadGatewayPlugins), and repeated reloads under 15 min apart
|
|
710
|
+
// must not hold an update until the forced window.
|
|
711
|
+
startedAt: Date.now() - Math.round(process.uptime() * 1000),
|
|
712
|
+
// Process state: a reload builds this gate again, and must not forget a user turn that is
|
|
713
|
+
// running, a message that is queued, or when the user last wrote.
|
|
714
|
+
activity: (processState.idleGateActivity ??= createIdleGateActivity()),
|
|
715
|
+
logger: pluginLogger,
|
|
716
|
+
});
|
|
717
|
+
try {
|
|
718
|
+
registerIdleGateHooks({ api: api, gate: idleGate, logger: pluginLogger });
|
|
719
|
+
}
|
|
720
|
+
catch (err) {
|
|
721
|
+
pluginLogger.warn("[senpi-runtime] failed to register the self-update idle gate hooks", {
|
|
722
|
+
err: err instanceof Error ? err.message : String(err),
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
const openclawStateDir = typeof api.runtime?.state?.resolveStateDir === "function" ? api.runtime.state.resolveStateDir() : undefined;
|
|
485
727
|
const autoUpdateCoordinator = new AutoUpdateCoordinator({
|
|
486
728
|
enabled: true,
|
|
487
729
|
config: autoUpdateConfig,
|
|
488
730
|
packageName: PLUGIN_PACKAGE_NAME,
|
|
489
731
|
currentVersion: VERSION,
|
|
732
|
+
// The version this process loaded; "applied" is decided from it alone.
|
|
733
|
+
loadedVersion: VERSION,
|
|
490
734
|
stateDir: join(baseStateDir, "auto-update"),
|
|
491
735
|
logger: autoUpdateLogger,
|
|
492
736
|
// Use the resolved npm package name (not a hardcoded plugin id) so
|
|
493
737
|
// the update follows the same npm channel as the version check —
|
|
494
|
-
// see runtime/auto-update/run-update-command.ts.
|
|
495
|
-
|
|
738
|
+
// see runtime/auto-update/run-update-command.ts. Not on 10.x, which
|
|
739
|
+
// refuses plugins update while the gateway runs.
|
|
740
|
+
runUpdateCommand: modernHost ? undefined : runOpenClawPluginsUpdate,
|
|
496
741
|
configFromApi: api.config,
|
|
497
|
-
loadConfig: api.runtime?.config
|
|
742
|
+
loadConfig: !modernHost && api.runtime?.config
|
|
498
743
|
? () => api.runtime.config.loadConfig()
|
|
499
744
|
: undefined,
|
|
500
|
-
writeConfigFile: api.runtime?.config
|
|
745
|
+
writeConfigFile: !modernHost && api.runtime?.config
|
|
501
746
|
? (c) => api.runtime.config.writeConfigFile(c)
|
|
502
747
|
: undefined,
|
|
748
|
+
modernHost,
|
|
749
|
+
mutateConfigFile: modernHost && typeof api.runtime?.config?.mutateConfigFile === "function"
|
|
750
|
+
? (p) => api.runtime.config.mutateConfigFile(p)
|
|
751
|
+
: undefined,
|
|
752
|
+
readLiveConfig: modernHost ? openClawHost.currentConfig : undefined,
|
|
753
|
+
idleGate,
|
|
754
|
+
mid: modernHost
|
|
755
|
+
? resolveUpdateMid({
|
|
756
|
+
token: apiKey ?? process.env.SENPI_AUTH_TOKEN ?? process.env.SENPI_API_KEY,
|
|
757
|
+
env: process.env,
|
|
758
|
+
hostname,
|
|
759
|
+
})
|
|
760
|
+
: undefined,
|
|
761
|
+
updateMarkerPath: modernHost && openclawStateDir ? resolveUpdateMarkerPath(openclawStateDir) : undefined,
|
|
762
|
+
// The wrapper's install outcomes, reported once per coordinator start (gateway only),
|
|
763
|
+
// with auto-update on or off. The report runs off the start path: it waits for the OTel
|
|
764
|
+
// init register() started (else the events go to the no-op logger and the file is gone)
|
|
765
|
+
// and flushes the logs before deleting the file.
|
|
766
|
+
installResultsPath: modernHost && openclawStateDir ? resolveInstallResultsPath(openclawStateDir) : undefined,
|
|
767
|
+
installResultsTelemetry: {
|
|
768
|
+
ready: () => waitForOtelInit(INSTALL_RESULTS_OTEL_READY_MS),
|
|
769
|
+
flush: () => flushOtelLogs(INSTALL_RESULTS_OTEL_FLUSH_MS),
|
|
770
|
+
},
|
|
503
771
|
pluginId: api.id,
|
|
504
772
|
// Drive skills-manager off the auto-update tick. Both success and
|
|
505
773
|
// failure branches of auto-update's tick fire this hook so skills
|
|
@@ -537,11 +805,20 @@ const senpiRuntimePlugin = {
|
|
|
537
805
|
// boot scan: declaring it after would leave that reference in the temporal dead zone for any
|
|
538
806
|
// future refactor that starts the service earlier. The rest of the deploy wiring lives in
|
|
539
807
|
// src/deploy/register.ts behind an explicit context; this closure contributes collaborators only.
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
808
|
+
//
|
|
809
|
+
// One controller per deploys dir per process (process state): a full re-registration (10.10
|
|
810
|
+
// reloadGatewayPlugins, same process) reuses the one that may be running a deploy, so its
|
|
811
|
+
// `running()` keeps single-flight and `inFlight()` keeps the idle gate's deploy blocker. It
|
|
812
|
+
// logs through `processLog`, the current registration's logger, so a job that outlives its
|
|
813
|
+
// registration still narrates and writes its terminal journal line.
|
|
814
|
+
const deploysDir = join(baseStateDir, "deploys");
|
|
815
|
+
const deployController = processState.deployControllers.get(deploysDir) ??
|
|
816
|
+
new DeployJobController({
|
|
817
|
+
deploysDir,
|
|
818
|
+
now: () => Date.now(),
|
|
819
|
+
log: (line) => processLog.info(`[senpi-runtime] ${line}`),
|
|
820
|
+
});
|
|
821
|
+
processState.deployControllers.set(deploysDir, deployController);
|
|
545
822
|
// ── lifecycle reaper ─────────────────────────────────────────────────────────────────────────
|
|
546
823
|
// A runtime exists iff its strategy is open. Every close path ends at the backend and none of
|
|
547
824
|
// them tells this box, so the reaper asks: once after boot, hourly, and whenever the backend
|
|
@@ -579,10 +856,20 @@ const senpiRuntimePlugin = {
|
|
|
579
856
|
api.registerService({
|
|
580
857
|
id: "senpi-runtime",
|
|
581
858
|
async start() {
|
|
859
|
+
serviceState = "running";
|
|
860
|
+
// The 5.x classification notice (see the approval gate above), once per process.
|
|
861
|
+
if (legacyTurnClassificationNotice !== undefined && !processState.legacyTurnClassificationNoticeLogged) {
|
|
862
|
+
processState.legacyTurnClassificationNoticeLogged = true;
|
|
863
|
+
pluginLogger.info(legacyTurnClassificationNotice);
|
|
864
|
+
}
|
|
582
865
|
// Deploy-journal janitor: stamp anything a restart left unterminated as `interrupted`.
|
|
583
866
|
// It never re-enters a deploy state machine — discovery is pull-based via
|
|
584
|
-
// `senpi deploy status`.
|
|
585
|
-
|
|
867
|
+
// `senpi deploy status`. Once per process: after a reload an unterminated journal may be
|
|
868
|
+
// the deploy this process is still running (r4469086155).
|
|
869
|
+
if (!processState.bootScanned.has(deploysDir)) {
|
|
870
|
+
processState.bootScanned.add(deploysDir);
|
|
871
|
+
await deployController.scanOnBoot();
|
|
872
|
+
}
|
|
586
873
|
await autoUpdateCoordinator.start();
|
|
587
874
|
// SENPI_RUNTIME_API_DISABLED=true also disables the skills coordinator.
|
|
588
875
|
// Skills bootstrap performs a real `git clone` synchronously during
|
|
@@ -902,6 +1189,17 @@ const senpiRuntimePlugin = {
|
|
|
902
1189
|
}
|
|
903
1190
|
}
|
|
904
1191
|
}
|
|
1192
|
+
// This registration now runs the box's runtimes: publish it, then start what an install from a
|
|
1193
|
+
// stopped registration handed over while none was live (see `handOffRuntime`). Detached and
|
|
1194
|
+
// never throwing, like the facts send: one adoption must not hold or fail the boot.
|
|
1195
|
+
processState.runtimeHost = runtimeHost;
|
|
1196
|
+
const pendingHandOffs = [...processState.pendingRuntimeHandOffs];
|
|
1197
|
+
processState.pendingRuntimeHandOffs.clear();
|
|
1198
|
+
for (const [runtimeId, walletKey] of pendingHandOffs) {
|
|
1199
|
+
void runtimeHost.adoptRuntime({ runtimeId, walletKey }).then((handOff) => {
|
|
1200
|
+
pluginLogger.info("[senpi-runtime] handed-over runtime settled at service start", { runtimeId, outcome: handOff.outcome });
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
905
1203
|
// Ticks once now, with every booted runtime in the store, then every 30 s.
|
|
906
1204
|
strategiesPublisher.start();
|
|
907
1205
|
// Sends the events added since the previous send, every 1 s.
|
|
@@ -923,6 +1221,12 @@ const senpiRuntimePlugin = {
|
|
|
923
1221
|
}
|
|
924
1222
|
},
|
|
925
1223
|
async stop() {
|
|
1224
|
+
// First: an install or adoption still running in this registration sees the stop from here
|
|
1225
|
+
// on and hands its runtime to the next registration instead of keeping it in this one.
|
|
1226
|
+
serviceState = "stopped";
|
|
1227
|
+
serviceStops += 1;
|
|
1228
|
+
if (processState.runtimeHost === runtimeHost)
|
|
1229
|
+
processState.runtimeHost = null;
|
|
926
1230
|
// Stop the reaper first so no pass starts deleting while the runtimes are torn down below,
|
|
927
1231
|
// and wait (bounded) for a pass already under way, so its delete cannot stop a handle the
|
|
928
1232
|
// teardown below is stopping too.
|
|
@@ -974,7 +1278,310 @@ const senpiRuntimePlugin = {
|
|
|
974
1278
|
* `senpi deploy` installs through the SAME gates (wallet ownership, one-runtime-per-wallet,
|
|
975
1279
|
* scanner-path resolution) instead of a parallel path that could drift.
|
|
976
1280
|
*/
|
|
1281
|
+
/**
|
|
1282
|
+
* Start an already-registered runtime in THIS registration while its service runs: `run()`,
|
|
1283
|
+
* the handle in `runtimeHandles`, then the hot-install scanner wire (the API is already
|
|
1284
|
+
* listening, so the launcher starts at once). Shared by `installRuntimeCore` and by
|
|
1285
|
+
* {@link runtimeHost}'s adoption of a runtime another registration handed over.
|
|
1286
|
+
*
|
|
1287
|
+
* `orphaned` says whether this registration's service stopped since the caller began (a 10.x
|
|
1288
|
+
* plugin reload). It is read after `run()` returns and again after the wire: a stopped
|
|
1289
|
+
* registration's `stop()` has already torn its runtimes down, so a runtime started here now
|
|
1290
|
+
* would keep ticking in a registration nothing can stop or delete. In that case this stops what
|
|
1291
|
+
* it started (the launcher, then the handle), removes them from this registration's maps, and
|
|
1292
|
+
* returns `orphaned`; the caller hands the runtime to the live registration.
|
|
1293
|
+
*
|
|
1294
|
+
* Throws what `run()` throws. Wire failures do not throw: they are reported as `unwiredPhase`,
|
|
1295
|
+
* exactly as the install has always reported them.
|
|
1296
|
+
*/
|
|
1297
|
+
async function startRuntimeLive(spec, orphaned,
|
|
1298
|
+
/** Called once the runtime runs in this registration, before the scanner wire. */
|
|
1299
|
+
onRunning) {
|
|
1300
|
+
const { runtimeId, pathOrContent, fromPath, recipeDir, wallet, parsedConfig } = spec;
|
|
1301
|
+
/**
|
|
1302
|
+
* The unwired verdict for THIS start, tracked locally rather than read back out of
|
|
1303
|
+
* `unwiredRuntimes`, so the result reports what this call did and never a leftover verdict
|
|
1304
|
+
* from an earlier runtime that happened to share the id. Set at each of the three sites that
|
|
1305
|
+
* leave the runtime without live entry scanners; cleared by the wire-success path.
|
|
1306
|
+
*/
|
|
1307
|
+
let unwiredPhase;
|
|
1308
|
+
let hotLauncher = null;
|
|
1309
|
+
const scannerProviders = await createScannerProvidersForRun({
|
|
1310
|
+
mcpTransport,
|
|
1311
|
+
apiKey,
|
|
1312
|
+
});
|
|
1313
|
+
const entryStateDir = buildRuntimeStateDir(baseStateDir, runtimeId, wallet);
|
|
1314
|
+
const handle = await run(pathOrContent, {
|
|
1315
|
+
fromPath,
|
|
1316
|
+
stateDir: entryStateDir,
|
|
1317
|
+
mcpTransport,
|
|
1318
|
+
apiKey,
|
|
1319
|
+
scannerProviders,
|
|
1320
|
+
runtimeId,
|
|
1321
|
+
onStrategyNotActive: (address) => reaper.checkWallet(address),
|
|
1322
|
+
});
|
|
1323
|
+
/** Stops what this call started and leaves this registration's maps as they were. */
|
|
1324
|
+
const abandon = async () => {
|
|
1325
|
+
if (hotLauncher) {
|
|
1326
|
+
await hotLauncher.stop().catch(() => { });
|
|
1327
|
+
if (launchers.get(runtimeId) === hotLauncher)
|
|
1328
|
+
launchers.delete(runtimeId);
|
|
1329
|
+
}
|
|
1330
|
+
await handle.stop().catch((err) => {
|
|
1331
|
+
pluginLogger.warn("[senpi-runtime] could not stop a runtime started by a stopped registration", {
|
|
1332
|
+
runtimeId,
|
|
1333
|
+
err: err instanceof Error ? err.message : String(err),
|
|
1334
|
+
});
|
|
1335
|
+
});
|
|
1336
|
+
if (runtimeHandles.get(runtimeId) === handle) {
|
|
1337
|
+
runtimeHandles.delete(runtimeId);
|
|
1338
|
+
unwiredRuntimes.delete(runtimeId);
|
|
1339
|
+
}
|
|
1340
|
+
return { status: "orphaned" };
|
|
1341
|
+
};
|
|
1342
|
+
if (orphaned())
|
|
1343
|
+
return abandon();
|
|
1344
|
+
runtimeHandles.set(runtimeId, handle);
|
|
1345
|
+
onRunning?.();
|
|
1346
|
+
// ── hot-install supervised scanner wire ───────────────────────────────
|
|
1347
|
+
// Live-install path: used when a runtime is registered after boot via
|
|
1348
|
+
// senpi.installRuntime, while the API is already listening — the
|
|
1349
|
+
// counterpart to the boot-time `launcher` above. A runtime takes exactly
|
|
1350
|
+
// one path: boot-present → `launcher` (deferred start); installed live →
|
|
1351
|
+
// `hotLauncher` (immediate start). The two are mutually exclusive because
|
|
1352
|
+
// installRuntime rejects any id/wallet already in the registry before
|
|
1353
|
+
// wiring (the hasId guard), so a boot-present runtime never re-enters here;
|
|
1354
|
+
// an adoption starts only a row the live registration does not run.
|
|
1355
|
+
// The API is already listening at this point, so we wire and start
|
|
1356
|
+
// immediately (no deferred start needed). Any failure is swallowed so
|
|
1357
|
+
// the install itself is not rolled back — the runtime is already up.
|
|
1358
|
+
// Gate on the same API-disabled flag as the boot path: when the HTTP API
|
|
1359
|
+
// is off (a test-only seam), the /signals route is never mounted, so
|
|
1360
|
+
// starting scanners would only spawn children that POST to a closed port.
|
|
1361
|
+
if (parsedConfig &&
|
|
1362
|
+
sharedIntakeContext &&
|
|
1363
|
+
process.env.SENPI_RUNTIME_API_DISABLED !== "true") {
|
|
1364
|
+
try {
|
|
1365
|
+
const apiConfig = loadApiConfig(api.pluginConfig);
|
|
1366
|
+
const scaffoldPackageDir = fileURLToPath(new URL("./scanners/external", import.meta.url));
|
|
1367
|
+
hotLauncher = wireRuntime({
|
|
1368
|
+
runtimeConfig: parsedConfig,
|
|
1369
|
+
recipeDir,
|
|
1370
|
+
runtimeId,
|
|
1371
|
+
wallet,
|
|
1372
|
+
sharedCtx: sharedIntakeContext,
|
|
1373
|
+
runtimeHandles,
|
|
1374
|
+
intakeUrl: intakeUrlFor(apiConfig.host, apiConfig.port),
|
|
1375
|
+
scaffoldPackageDir,
|
|
1376
|
+
runtimeStateDir: entryStateDir,
|
|
1377
|
+
logger: apiLogger,
|
|
1378
|
+
});
|
|
1379
|
+
if (hotLauncher) {
|
|
1380
|
+
const launcher = hotLauncher;
|
|
1381
|
+
try {
|
|
1382
|
+
await launcher.start();
|
|
1383
|
+
launchers.set(runtimeId, launcher);
|
|
1384
|
+
unwiredRuntimes.delete(runtimeId);
|
|
1385
|
+
unwiredPhase = undefined;
|
|
1386
|
+
runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
|
|
1387
|
+
unwired: false,
|
|
1388
|
+
rows: launcher.describeSupervision(),
|
|
1389
|
+
}));
|
|
1390
|
+
}
|
|
1391
|
+
catch (startErr) {
|
|
1392
|
+
await launcher.stop().catch(() => { });
|
|
1393
|
+
hotLauncher = null;
|
|
1394
|
+
unwiredRuntimes.set(runtimeId, "install_launch");
|
|
1395
|
+
unwiredPhase = "install_launch";
|
|
1396
|
+
runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
|
|
1397
|
+
unwired: true,
|
|
1398
|
+
unwiredPhase: "install_launch",
|
|
1399
|
+
rows: [],
|
|
1400
|
+
}));
|
|
1401
|
+
eventScannersUnwired("install_launch", runtimeId, wallet, appendCause("[senpi-runtime] hot-install supervised scanner launch failed — runtime running without it", startErr), startErr);
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
catch (wireErr) {
|
|
1406
|
+
// Wire failure must NOT fail the install — the runtime is already up. It IS reported
|
|
1407
|
+
// across the result boundary (payload.unwired) so a funding caller can refuse it.
|
|
1408
|
+
unwiredRuntimes.set(runtimeId, "install_wire");
|
|
1409
|
+
unwiredPhase = "install_wire";
|
|
1410
|
+
runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
|
|
1411
|
+
unwired: true,
|
|
1412
|
+
unwiredPhase: "install_wire",
|
|
1413
|
+
rows: [],
|
|
1414
|
+
}));
|
|
1415
|
+
eventScannersUnwired("install_wire", runtimeId, wallet, appendCause("[senpi-runtime] hot-install wiring failed — runtime running without supervised scanners", wireErr), wireErr);
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
else if (parsedConfig && !sharedIntakeContext && selectScanners(parsedConfig).length > 0) {
|
|
1419
|
+
// Supervised intake is DISABLED for the whole box (corrupt acceptance record).
|
|
1420
|
+
// The wire block above is skipped, so this hot-installed runtime declares
|
|
1421
|
+
// external scanners but has NO live entry scanners. Record that fail-closed
|
|
1422
|
+
// state (state only, no new event) so listRuntimes/health don't lie.
|
|
1423
|
+
unwiredRuntimes.set(runtimeId, "no_intake");
|
|
1424
|
+
unwiredPhase = "no_intake";
|
|
1425
|
+
runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
|
|
1426
|
+
unwired: true,
|
|
1427
|
+
unwiredPhase: "no_intake",
|
|
1428
|
+
rows: [],
|
|
1429
|
+
}));
|
|
1430
|
+
}
|
|
1431
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
1432
|
+
// The stop may have landed during the wire: its teardown then missed the launcher above.
|
|
1433
|
+
if (orphaned())
|
|
1434
|
+
return abandon();
|
|
1435
|
+
return unwiredPhase ? { status: "started", unwiredPhase } : { status: "started" };
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* Give a runtime an orphaned install (or adoption) started to the live registration
|
|
1439
|
+
* ({@link RuntimeProcessState.runtimeHost}), or queue it for the next service start when no
|
|
1440
|
+
* registration is live. Never throws.
|
|
1441
|
+
*/
|
|
1442
|
+
async function handOffRuntime(runtimeId, walletKey) {
|
|
1443
|
+
const host = processState.runtimeHost;
|
|
1444
|
+
if (!host) {
|
|
1445
|
+
// The strategies store is left as it is: a registration that is starting may already run this
|
|
1446
|
+
// row from its boot, and the next start's boot or adoption sets the entry either way.
|
|
1447
|
+
processState.pendingRuntimeHandOffs.set(runtimeId, walletKey);
|
|
1448
|
+
pluginLogger.info("[senpi-runtime] runtime handed to the next service start (no live registration)", { runtimeId });
|
|
1449
|
+
return { outcome: "pending" };
|
|
1450
|
+
}
|
|
1451
|
+
try {
|
|
1452
|
+
return await host.adoptRuntime({ runtimeId, walletKey });
|
|
1453
|
+
}
|
|
1454
|
+
catch (err) {
|
|
1455
|
+
// Nothing runs it: drop the entry the stopped start wrote, so the apps do not draw it.
|
|
1456
|
+
strategiesStore.delete(runtimeId);
|
|
1457
|
+
return { outcome: "failed", message: err instanceof Error ? err.message : String(err) };
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* The live registration, when this registration's service has stopped (a 10.x plugin reload)
|
|
1462
|
+
* and another one is running. A deploy job from before the reload keeps this registration's
|
|
1463
|
+
* closures; its deletes and liveness reads go to the registration that holds the runtimes.
|
|
1464
|
+
*/
|
|
1465
|
+
function liveHostIfStopped() {
|
|
1466
|
+
if (serviceState !== "stopped")
|
|
1467
|
+
return undefined;
|
|
1468
|
+
const host = processState.runtimeHost;
|
|
1469
|
+
return host && host !== runtimeHost ? host : undefined;
|
|
1470
|
+
}
|
|
1471
|
+
/**
|
|
1472
|
+
* The install result for a runtime this install handed over. A stopped runtime is never
|
|
1473
|
+
* reported as running here: `handedOff` names who runs it, and the result is an error when
|
|
1474
|
+
* nothing does.
|
|
1475
|
+
*/
|
|
1476
|
+
function installHandOffResult(handOff, runtime) {
|
|
1477
|
+
switch (handOff.outcome) {
|
|
1478
|
+
case "running":
|
|
1479
|
+
case "booted":
|
|
1480
|
+
return {
|
|
1481
|
+
ok: true,
|
|
1482
|
+
payload: {
|
|
1483
|
+
...runtime,
|
|
1484
|
+
id: handOff.runtimeId,
|
|
1485
|
+
...(handOff.unwired ? { unwired: handOff.unwired } : {}),
|
|
1486
|
+
handedOff: "The runtime plugin's service stopped during this install (a plugin reload or a gateway " +
|
|
1487
|
+
"stop), so the plugin registration that is running now runs this runtime " +
|
|
1488
|
+
`(runtime "${handOff.runtimeId}"). Check it: openclaw senpi runtime list.`,
|
|
1489
|
+
},
|
|
1490
|
+
};
|
|
1491
|
+
case "pending":
|
|
1492
|
+
return {
|
|
1493
|
+
ok: true,
|
|
1494
|
+
payload: {
|
|
1495
|
+
...runtime,
|
|
1496
|
+
handedOff: "The runtime plugin's service stopped during this install (a plugin reload or a gateway " +
|
|
1497
|
+
"stop), and no plugin registration had finished starting when it ended. The runtime is " +
|
|
1498
|
+
"installed; the plugin's service runs it when its start finishes. Check it: " +
|
|
1499
|
+
"openclaw senpi runtime list.",
|
|
1500
|
+
},
|
|
1501
|
+
};
|
|
1502
|
+
case "no-row":
|
|
1503
|
+
return { ok: false, error: {
|
|
1504
|
+
code: "UNAVAILABLE",
|
|
1505
|
+
message: `The runtime plugin's service stopped during this install and runtime "${runtime.id}" is no ` +
|
|
1506
|
+
"longer in the registry, so nothing runs it. Nothing is trading on this wallet from this " +
|
|
1507
|
+
"install. Check: openclaw senpi runtime list.",
|
|
1508
|
+
} };
|
|
1509
|
+
case "failed":
|
|
1510
|
+
return { ok: false, error: {
|
|
1511
|
+
code: "UNAVAILABLE",
|
|
1512
|
+
message: `The runtime plugin's service stopped during this install and the running plugin ` +
|
|
1513
|
+
`registration could not start runtime "${runtime.id}": ${handOff.message}. It is installed; ` +
|
|
1514
|
+
"the next restart tries to start it. Check: openclaw senpi runtime list.",
|
|
1515
|
+
} };
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* This registration as the process's {@link RuntimeHost}: published at the end of the service
|
|
1520
|
+
* start, withdrawn at the start of its stop.
|
|
1521
|
+
*/
|
|
1522
|
+
const runtimeHost = {
|
|
1523
|
+
async adoptRuntime(request) {
|
|
1524
|
+
const handOff = await adoptRuntimeCore(request);
|
|
1525
|
+
// Nothing runs it here: drop the entry the stopped registration's start wrote (run() sets it,
|
|
1526
|
+
// and that start's abandon does not clear it), so the apps do not draw a strategy that is not
|
|
1527
|
+
// running. A different id on the wallet leaves this id's entry just as stale.
|
|
1528
|
+
if (handOff.outcome === "no-row" ||
|
|
1529
|
+
handOff.outcome === "failed" ||
|
|
1530
|
+
(handOff.outcome === "running" && handOff.runtimeId !== request.runtimeId)) {
|
|
1531
|
+
strategiesStore.delete(request.runtimeId);
|
|
1532
|
+
}
|
|
1533
|
+
return handOff;
|
|
1534
|
+
},
|
|
1535
|
+
deleteRuntime: (params) => deleteRuntimeCore(params),
|
|
1536
|
+
runtimeIsLive: async (id) => runtimeHandles.has(id) && !unwiredRuntimes.has(id),
|
|
1537
|
+
getScannerRows: (id) => readScannerRows(id),
|
|
1538
|
+
};
|
|
1539
|
+
async function adoptRuntimeCore({ runtimeId, walletKey }) {
|
|
1540
|
+
const stopsAtAdopt = serviceStops;
|
|
1541
|
+
const orphaned = () => serviceState !== "running" || serviceStops !== stopsAtAdopt;
|
|
1542
|
+
try {
|
|
1543
|
+
const onWallet = runtimeHandles.has(runtimeId)
|
|
1544
|
+
? runtimeId
|
|
1545
|
+
: walletKey
|
|
1546
|
+
? [...runtimeHandles].find(([, h]) => (h.wallet ?? "").trim().toLowerCase() === walletKey)?.[0]
|
|
1547
|
+
: undefined;
|
|
1548
|
+
if (onWallet !== undefined) {
|
|
1549
|
+
// The live verdict, as for a start: a runtime running blind is not a clean install.
|
|
1550
|
+
const unwired = unwiredRuntimes.get(onWallet);
|
|
1551
|
+
return unwired ? { outcome: "running", runtimeId: onWallet, unwired } : { outcome: "running", runtimeId: onWallet };
|
|
1552
|
+
}
|
|
1553
|
+
const { readRegistry } = await import("./runtime/strategy-registry.js");
|
|
1554
|
+
const entry = (await readRegistry(baseStateDir)).runtimes.find((e) => e.id === runtimeId);
|
|
1555
|
+
if (!entry)
|
|
1556
|
+
return { outcome: "no-row" };
|
|
1557
|
+
const inputs = factsPlanInputs(entry);
|
|
1558
|
+
if (!inputs)
|
|
1559
|
+
return { outcome: "failed", message: "its registry row has no readable recipe" };
|
|
1560
|
+
const parsedConfig = await loadRuntimeConfig(inputs.pathOrContent, { fromPath: inputs.fromPath });
|
|
1561
|
+
const started = await startRuntimeLive({
|
|
1562
|
+
runtimeId: entry.id,
|
|
1563
|
+
pathOrContent: inputs.pathOrContent,
|
|
1564
|
+
fromPath: inputs.fromPath,
|
|
1565
|
+
recipeDir: inputs.runtimeYamlDir,
|
|
1566
|
+
wallet: entry.wallet ?? "",
|
|
1567
|
+
parsedConfig,
|
|
1568
|
+
}, orphaned);
|
|
1569
|
+
if (started.status === "orphaned")
|
|
1570
|
+
return handOffRuntime(runtimeId, walletKey);
|
|
1571
|
+
pluginLogger.info("[senpi-runtime] started a runtime handed over by a stopped registration", {
|
|
1572
|
+
runtimeId: entry.id,
|
|
1573
|
+
});
|
|
1574
|
+
return started.unwiredPhase
|
|
1575
|
+
? { outcome: "booted", runtimeId: entry.id, unwired: started.unwiredPhase }
|
|
1576
|
+
: { outcome: "booted", runtimeId: entry.id };
|
|
1577
|
+
}
|
|
1578
|
+
catch (err) {
|
|
1579
|
+
return { outcome: "failed", message: err instanceof Error ? err.message : String(err) };
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
977
1582
|
async function installRuntimeCore(params) {
|
|
1583
|
+
// How many times this registration's service had stopped when this install began; see `orphaned` below.
|
|
1584
|
+
const stopsAtInstall = serviceStops;
|
|
978
1585
|
const toError = (message) => ({ code: "INVALID_REQUEST", message });
|
|
979
1586
|
const toUnavailable = (message) => ({ code: "UNAVAILABLE", message });
|
|
980
1587
|
const { readRegistry, writeRegistry, withRegistryLock, validateEntry, hasId, findByWallet, deriveRuntimeId, sanitizeId } = await import("./runtime/strategy-registry.js");
|
|
@@ -1242,127 +1849,64 @@ const senpiRuntimePlugin = {
|
|
|
1242
1849
|
const current = await readRegistry(baseStateDir);
|
|
1243
1850
|
await writeRegistry(baseStateDir, { ...current, runtimes: [...current.runtimes, entry] });
|
|
1244
1851
|
});
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1852
|
+
// The registration's service stopped since this install began (a 10.x plugin reload): the
|
|
1853
|
+
// runtime belongs to the live registration, so this install hands it over instead of keeping
|
|
1854
|
+
// one in a stopped registration that nothing can stop or delete.
|
|
1855
|
+
const orphaned = () => serviceState === "stopped" || serviceStops !== stopsAtInstall;
|
|
1856
|
+
// Registry create fact — distinct from the runtime.started boot transition (which also fires
|
|
1857
|
+
// on a transient restart). Once per install, as soon as a registration runs the row: right
|
|
1858
|
+
// after run() here, or at the hand-off. Inside emitEvent's guard so telemetry never fails the
|
|
1859
|
+
// install.
|
|
1860
|
+
let createdEmitted = false;
|
|
1861
|
+
const emitCreated = () => {
|
|
1862
|
+
if (createdEmitted)
|
|
1863
|
+
return;
|
|
1864
|
+
createdEmitted = true;
|
|
1865
|
+
emitEvent(apiLogger, () => buildRuntimeCreatedEvent({ runtimeId: resolvedId, address: wallet, recipeName: runtimeName }));
|
|
1866
|
+
};
|
|
1867
|
+
const handOffInstall = async () => {
|
|
1868
|
+
const handOff = await handOffRuntime(resolvedId, walletKey);
|
|
1869
|
+
if (handOff.outcome === "running" || handOff.outcome === "booted" || handOff.outcome === "pending")
|
|
1870
|
+
emitCreated();
|
|
1871
|
+
return installHandOffResult(handOff, { id: resolvedId, name: runtimeName, wallet });
|
|
1872
|
+
};
|
|
1252
1873
|
try {
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
|
|
1258
|
-
const handle = await run(pathOrContent, {
|
|
1259
|
-
fromPath: hasPath,
|
|
1260
|
-
stateDir: entryStateDir,
|
|
1261
|
-
mcpTransport,
|
|
1262
|
-
apiKey,
|
|
1263
|
-
scannerProviders,
|
|
1874
|
+
// Stopped before the start: do not start a runtime here at all.
|
|
1875
|
+
if (orphaned())
|
|
1876
|
+
return await handOffInstall();
|
|
1877
|
+
const started = await startRuntimeLive({
|
|
1264
1878
|
runtimeId: resolvedId,
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
// senpi.installRuntime, while the API is already listening — the
|
|
1274
|
-
// counterpart to the boot-time `launcher` above. A runtime takes exactly
|
|
1275
|
-
// one path: boot-present → `launcher` (deferred start); installed live →
|
|
1276
|
-
// `hotLauncher` (immediate start). The two are mutually exclusive because
|
|
1277
|
-
// installRuntime rejects any id/wallet already in the registry before
|
|
1278
|
-
// wiring (the hasId guard), so a boot-present runtime never re-enters here.
|
|
1279
|
-
// The API is already listening at this point, so we wire and start
|
|
1280
|
-
// immediately (no deferred start needed). Any failure is swallowed so
|
|
1281
|
-
// the install itself is not rolled back — the runtime is already up.
|
|
1282
|
-
// Gate on the same API-disabled flag as the boot path: when the HTTP API
|
|
1283
|
-
// is off (a test-only seam), the /signals route is never mounted, so
|
|
1284
|
-
// starting scanners would only spawn children that POST to a closed port.
|
|
1285
|
-
if (parsedConfig &&
|
|
1286
|
-
sharedIntakeContext &&
|
|
1287
|
-
process.env.SENPI_RUNTIME_API_DISABLED !== "true") {
|
|
1288
|
-
try {
|
|
1289
|
-
const apiConfig = loadApiConfig(api.pluginConfig);
|
|
1290
|
-
const scaffoldPackageDir = fileURLToPath(new URL("./scanners/external", import.meta.url));
|
|
1291
|
-
const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
|
|
1292
|
-
const hotLauncher = wireRuntime({
|
|
1293
|
-
runtimeConfig: parsedConfig,
|
|
1294
|
-
recipeDir: hasPath ? dirname(pathOrContent) : runtimeYamlDir,
|
|
1295
|
-
runtimeId: resolvedId,
|
|
1296
|
-
wallet,
|
|
1297
|
-
sharedCtx: sharedIntakeContext,
|
|
1298
|
-
runtimeHandles,
|
|
1299
|
-
intakeUrl: intakeUrlFor(apiConfig.host, apiConfig.port),
|
|
1300
|
-
scaffoldPackageDir,
|
|
1301
|
-
runtimeStateDir: entryStateDir,
|
|
1302
|
-
logger: apiLogger,
|
|
1303
|
-
});
|
|
1304
|
-
if (hotLauncher) {
|
|
1305
|
-
try {
|
|
1306
|
-
await hotLauncher.start();
|
|
1307
|
-
launchers.set(resolvedId, hotLauncher);
|
|
1308
|
-
unwiredRuntimes.delete(resolvedId);
|
|
1309
|
-
unwiredPhase = undefined;
|
|
1310
|
-
runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
|
|
1311
|
-
unwired: false,
|
|
1312
|
-
rows: hotLauncher.describeSupervision(),
|
|
1313
|
-
}));
|
|
1314
|
-
}
|
|
1315
|
-
catch (startErr) {
|
|
1316
|
-
await hotLauncher.stop().catch(() => { });
|
|
1317
|
-
unwiredRuntimes.set(resolvedId, "install_launch");
|
|
1318
|
-
unwiredPhase = "install_launch";
|
|
1319
|
-
runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
|
|
1320
|
-
unwired: true,
|
|
1321
|
-
unwiredPhase: "install_launch",
|
|
1322
|
-
rows: [],
|
|
1323
|
-
}));
|
|
1324
|
-
eventScannersUnwired("install_launch", resolvedId, wallet, appendCause("[senpi-runtime] hot-install supervised scanner launch failed — runtime running without it", startErr), startErr);
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1328
|
-
catch (wireErr) {
|
|
1329
|
-
// Wire failure must NOT fail the install — the runtime is already up. It IS reported
|
|
1330
|
-
// across the result boundary (payload.unwired) so a funding caller can refuse it.
|
|
1331
|
-
unwiredRuntimes.set(resolvedId, "install_wire");
|
|
1332
|
-
unwiredPhase = "install_wire";
|
|
1333
|
-
runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
|
|
1334
|
-
unwired: true,
|
|
1335
|
-
unwiredPhase: "install_wire",
|
|
1336
|
-
rows: [],
|
|
1337
|
-
}));
|
|
1338
|
-
eventScannersUnwired("install_wire", resolvedId, wallet, appendCause("[senpi-runtime] hot-install wiring failed — runtime running without supervised scanners", wireErr), wireErr);
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
else if (parsedConfig && !sharedIntakeContext && selectScanners(parsedConfig).length > 0) {
|
|
1342
|
-
// Supervised intake is DISABLED for the whole box (corrupt acceptance record).
|
|
1343
|
-
// The wire block above is skipped, so this hot-installed runtime declares
|
|
1344
|
-
// external scanners but has NO live entry scanners. Record that fail-closed
|
|
1345
|
-
// state (state only, no new event) so listRuntimes/health don't lie.
|
|
1346
|
-
unwiredRuntimes.set(resolvedId, "no_intake");
|
|
1347
|
-
unwiredPhase = "no_intake";
|
|
1348
|
-
runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
|
|
1349
|
-
unwired: true,
|
|
1350
|
-
unwiredPhase: "no_intake",
|
|
1351
|
-
rows: [],
|
|
1352
|
-
}));
|
|
1353
|
-
}
|
|
1354
|
-
// ──────────────────────────────────────────────────────────────────────
|
|
1879
|
+
pathOrContent,
|
|
1880
|
+
fromPath: hasPath,
|
|
1881
|
+
recipeDir: hasPath ? dirname(pathOrContent) : runtimeYamlDir,
|
|
1882
|
+
wallet,
|
|
1883
|
+
parsedConfig,
|
|
1884
|
+
}, orphaned, emitCreated);
|
|
1885
|
+
if (started.status === "orphaned")
|
|
1886
|
+
return await handOffInstall();
|
|
1355
1887
|
return {
|
|
1356
1888
|
ok: true,
|
|
1357
1889
|
payload: {
|
|
1358
1890
|
id: resolvedId,
|
|
1359
1891
|
name: runtimeName,
|
|
1360
1892
|
wallet,
|
|
1361
|
-
...(unwiredPhase ? { unwired: unwiredPhase } : {}),
|
|
1893
|
+
...(started.unwiredPhase ? { unwired: started.unwiredPhase } : {}),
|
|
1362
1894
|
},
|
|
1363
1895
|
};
|
|
1364
1896
|
}
|
|
1365
1897
|
catch (err) {
|
|
1898
|
+
// run() threw after this registration's service stopped: the live registration may already
|
|
1899
|
+
// run this row (its boot read it), so it decides, not this catch. It runs it, or starts it,
|
|
1900
|
+
// or (no registration live yet) the next start does; only when it cannot start the row
|
|
1901
|
+
// either is the row removed, as below for an install with no reload.
|
|
1902
|
+
if (orphaned()) {
|
|
1903
|
+
const handOff = await handOffRuntime(resolvedId, walletKey);
|
|
1904
|
+
if (handOff.outcome !== "failed") {
|
|
1905
|
+
if (handOff.outcome !== "no-row")
|
|
1906
|
+
emitCreated();
|
|
1907
|
+
return installHandOffResult(handOff, { id: resolvedId, name: runtimeName, wallet });
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1366
1910
|
await withRegistryLock(baseStateDir, async () => {
|
|
1367
1911
|
const current = await readRegistry(baseStateDir);
|
|
1368
1912
|
await writeRegistry(baseStateDir, { ...current, runtimes: current.runtimes.filter((e) => e.id !== resolvedId) });
|
|
@@ -1427,6 +1971,12 @@ const senpiRuntimePlugin = {
|
|
|
1427
1971
|
* unwired-verdict cleanup all happen exactly once, here.
|
|
1428
1972
|
*/
|
|
1429
1973
|
async function deleteRuntimeCore(params) {
|
|
1974
|
+
// This registration's service stopped (a 10.x reload) and holds no runtimes; the live one does.
|
|
1975
|
+
// A delete from here (a deploy job from before the reload) would remove the row and archive the
|
|
1976
|
+
// state dir under a runtime that keeps trading.
|
|
1977
|
+
const live = liveHostIfStopped();
|
|
1978
|
+
if (live)
|
|
1979
|
+
return live.deleteRuntime(params);
|
|
1430
1980
|
let targetId = typeof params?.id === "string" ? params.id : undefined;
|
|
1431
1981
|
const targetAddress = typeof params?.address === "string" ? params.address : undefined;
|
|
1432
1982
|
// Set only by the lifecycle reaper: why the strategy counts as gone (stamped on runtime.deleted)
|
|
@@ -1664,7 +2214,7 @@ const senpiRuntimePlugin = {
|
|
|
1664
2214
|
* the strategy id is read for this one wallet; a failed read logs its reason and sends nothing.
|
|
1665
2215
|
*/
|
|
1666
2216
|
function queueFactsSend(runtimeId, strategyIds) {
|
|
1667
|
-
return factsSendLock.withKeyLock(runtimeId, async () => {
|
|
2217
|
+
return factsSendLock().withKeyLock(runtimeId, async () => {
|
|
1668
2218
|
const { readRegistry } = await import("./runtime/strategy-registry.js");
|
|
1669
2219
|
const entry = (await readRegistry(baseStateDir)).runtimes.find((e) => e.id === runtimeId);
|
|
1670
2220
|
const inputs = entry ? factsPlanInputs(entry) : null;
|
|
@@ -1923,16 +2473,21 @@ const senpiRuntimePlugin = {
|
|
|
1923
2473
|
},
|
|
1924
2474
|
registryFindByWallet: findRegistryEntryByWallet,
|
|
1925
2475
|
registryFindById: findRegistryEntryById,
|
|
1926
|
-
|
|
2476
|
+
// A deploy job outlives a reload; it reads the runtime where it runs (see `liveHostIfStopped`).
|
|
2477
|
+
getScannerRows: (id) => liveHostIfStopped()?.getScannerRows(id) ?? readScannerRows(id),
|
|
1927
2478
|
// H4: `runtimeHandles` holds the live `run()` handles. A registry row without one is a
|
|
1928
2479
|
// previous install whose runtime died before start — deploy must reinstall, not report it
|
|
1929
2480
|
// adopted. `unwiredRuntimes` is the same judgement one step further in: a runtime that is up
|
|
1930
2481
|
// but whose entry scanners never wired is running BLIND (the health surface already renders
|
|
1931
2482
|
// it "running — NO ENTRY SCANNERS"), and reporting `install: skipped` over it would be the
|
|
1932
2483
|
// same clean line over a runtime that cannot tick.
|
|
1933
|
-
runtimeIsLive: async (id) => runtimeHandles.has(id) && !unwiredRuntimes.has(id),
|
|
2484
|
+
runtimeIsLive: async (id) => liveHostIfStopped()?.runtimeIsLive(id) ?? (runtimeHandles.has(id) && !unwiredRuntimes.has(id)),
|
|
1934
2485
|
installPendingOnWallet: async (wallet) => installsInFlight.has(wallet.trim().toLowerCase()),
|
|
1935
|
-
logger
|
|
2486
|
+
// The process logger, not this registration's: a deploy job outlives a reload.
|
|
2487
|
+
logger: {
|
|
2488
|
+
info: (line) => processLog.info(`[senpi-runtime] ${line}`),
|
|
2489
|
+
warn: (line) => processLog.warn(`[senpi-runtime] ${line}`),
|
|
2490
|
+
},
|
|
1936
2491
|
});
|
|
1937
2492
|
/**
|
|
1938
2493
|
* Gateway shim for `senpi.ingestExternalScannerData`.
|
|
@@ -2135,6 +2690,8 @@ const senpiRuntimePlugin = {
|
|
|
2135
2690
|
respond(true, {
|
|
2136
2691
|
status: status ? { ...status, runtimeId } : null,
|
|
2137
2692
|
updater,
|
|
2693
|
+
approvals: approvalsStatus(),
|
|
2694
|
+
deploy: { capabilities: DEPLOY_CAPABILITIES },
|
|
2138
2695
|
});
|
|
2139
2696
|
}
|
|
2140
2697
|
catch (err) {
|
|
@@ -2147,7 +2704,7 @@ const senpiRuntimePlugin = {
|
|
|
2147
2704
|
return;
|
|
2148
2705
|
}
|
|
2149
2706
|
const statuses = await collectRuntimeHealthStatuses(runtimeHandles, api.logger);
|
|
2150
|
-
respond(true, { statuses, updater });
|
|
2707
|
+
respond(true, { statuses, updater, approvals: approvalsStatus(), deploy: { capabilities: DEPLOY_CAPABILITIES } });
|
|
2151
2708
|
}, { scope: "operator.read" });
|
|
2152
2709
|
api.registerGatewayMethod("senpi.getSystemState", async (ctx) => {
|
|
2153
2710
|
const respond = ctx.respond;
|