@senpi-ai/runtime 3.0.179 → 3.0.189

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.
Files changed (212) hide show
  1. package/dist/actions/close-position/close-position.action.d.ts.map +1 -1
  2. package/dist/actions/close-position/close-position.action.js +1 -6
  3. package/dist/actions/close-position/close-position.action.js.map +1 -1
  4. package/dist/actions/llm-decision/openclaw-llm-decision.d.ts +8 -0
  5. package/dist/actions/llm-decision/openclaw-llm-decision.d.ts.map +1 -1
  6. package/dist/actions/llm-decision/openclaw-llm-decision.js +56 -1
  7. package/dist/actions/llm-decision/openclaw-llm-decision.js.map +1 -1
  8. package/dist/actions/position-tracker/position-tracker.action.d.ts.map +1 -1
  9. package/dist/actions/position-tracker/position-tracker.action.js +0 -1
  10. package/dist/actions/position-tracker/position-tracker.action.js.map +1 -1
  11. package/dist/approvals/approval-store.d.ts +37 -7
  12. package/dist/approvals/approval-store.d.ts.map +1 -1
  13. package/dist/approvals/approval-store.js +127 -23
  14. package/dist/approvals/approval-store.js.map +1 -1
  15. package/dist/approvals/telemetry.d.ts +28 -3
  16. package/dist/approvals/telemetry.d.ts.map +1 -1
  17. package/dist/approvals/telemetry.js +8 -4
  18. package/dist/approvals/telemetry.js.map +1 -1
  19. package/dist/approvals/tool-approval-gate.d.ts +85 -0
  20. package/dist/approvals/tool-approval-gate.d.ts.map +1 -1
  21. package/dist/approvals/tool-approval-gate.js +197 -15
  22. package/dist/approvals/tool-approval-gate.js.map +1 -1
  23. package/dist/approvals/turn-context.d.ts +296 -0
  24. package/dist/approvals/turn-context.d.ts.map +1 -0
  25. package/dist/approvals/turn-context.js +594 -0
  26. package/dist/approvals/turn-context.js.map +1 -0
  27. package/dist/cli/guide-commands.d.ts.map +1 -1
  28. package/dist/cli/guide-commands.js +18 -3
  29. package/dist/cli/guide-commands.js.map +1 -1
  30. package/dist/cli/senpi-commands.d.ts.map +1 -1
  31. package/dist/cli/senpi-commands.js +80 -5
  32. package/dist/cli/senpi-commands.js.map +1 -1
  33. package/dist/deploy/job.d.ts +32 -0
  34. package/dist/deploy/job.d.ts.map +1 -1
  35. package/dist/deploy/job.js +72 -7
  36. package/dist/deploy/job.js.map +1 -1
  37. package/dist/deploy/register.d.ts +12 -0
  38. package/dist/deploy/register.d.ts.map +1 -1
  39. package/dist/deploy/register.js +85 -2
  40. package/dist/deploy/register.js.map +1 -1
  41. package/dist/dsl/events/build-closed-event.d.ts +0 -11
  42. package/dist/dsl/events/build-closed-event.d.ts.map +1 -1
  43. package/dist/dsl/events/build-closed-event.js +0 -13
  44. package/dist/dsl/events/build-closed-event.js.map +1 -1
  45. package/dist/dsl/events/handlers.d.ts.map +1 -1
  46. package/dist/dsl/events/handlers.js +5 -9
  47. package/dist/dsl/events/handlers.js.map +1 -1
  48. package/dist/dsl/monitor/dsl-failure-events.d.ts +38 -2
  49. package/dist/dsl/monitor/dsl-failure-events.d.ts.map +1 -1
  50. package/dist/dsl/monitor/dsl-failure-events.js +67 -4
  51. package/dist/dsl/monitor/dsl-failure-events.js.map +1 -1
  52. package/dist/dsl/monitor/process-one-position.d.ts.map +1 -1
  53. package/dist/dsl/monitor/process-one-position.js +33 -13
  54. package/dist/dsl/monitor/process-one-position.js.map +1 -1
  55. package/dist/host/openclaw-host.d.ts +138 -0
  56. package/dist/host/openclaw-host.d.ts.map +1 -0
  57. package/dist/host/openclaw-host.js +177 -0
  58. package/dist/host/openclaw-host.js.map +1 -0
  59. package/dist/host/plugin-logger.d.ts +99 -0
  60. package/dist/host/plugin-logger.d.ts.map +1 -0
  61. package/dist/host/plugin-logger.js +142 -0
  62. package/dist/host/plugin-logger.js.map +1 -0
  63. package/dist/index.d.ts +56 -8
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +688 -177
  66. package/dist/index.js.map +1 -1
  67. package/dist/prompt/session-context-seed-hook.d.ts +0 -7
  68. package/dist/prompt/session-context-seed-hook.d.ts.map +1 -1
  69. package/dist/prompt/session-context-seed-hook.js +1 -1
  70. package/dist/prompt/session-context-seed-hook.js.map +1 -1
  71. package/dist/runtime/auto-update/coordinator.d.ts +220 -0
  72. package/dist/runtime/auto-update/coordinator.d.ts.map +1 -1
  73. package/dist/runtime/auto-update/coordinator.js +715 -22
  74. package/dist/runtime/auto-update/coordinator.js.map +1 -1
  75. package/dist/runtime/auto-update/gateway-restart.d.ts +60 -1
  76. package/dist/runtime/auto-update/gateway-restart.d.ts.map +1 -1
  77. package/dist/runtime/auto-update/gateway-restart.js +95 -21
  78. package/dist/runtime/auto-update/gateway-restart.js.map +1 -1
  79. package/dist/runtime/auto-update/idle-gate.d.ts +175 -0
  80. package/dist/runtime/auto-update/idle-gate.d.ts.map +1 -0
  81. package/dist/runtime/auto-update/idle-gate.js +229 -0
  82. package/dist/runtime/auto-update/idle-gate.js.map +1 -0
  83. package/dist/runtime/auto-update/install-results.d.ts +130 -0
  84. package/dist/runtime/auto-update/install-results.d.ts.map +1 -0
  85. package/dist/runtime/auto-update/install-results.js +264 -0
  86. package/dist/runtime/auto-update/install-results.js.map +1 -0
  87. package/dist/runtime/auto-update/money-call-tracker.d.ts +36 -0
  88. package/dist/runtime/auto-update/money-call-tracker.d.ts.map +1 -0
  89. package/dist/runtime/auto-update/money-call-tracker.js +129 -0
  90. package/dist/runtime/auto-update/money-call-tracker.js.map +1 -0
  91. package/dist/runtime/auto-update/register-idle-gate.d.ts +70 -0
  92. package/dist/runtime/auto-update/register-idle-gate.d.ts.map +1 -0
  93. package/dist/runtime/auto-update/register-idle-gate.js +127 -0
  94. package/dist/runtime/auto-update/register-idle-gate.js.map +1 -0
  95. package/dist/runtime/auto-update/run-update-command.d.ts +13 -0
  96. package/dist/runtime/auto-update/run-update-command.d.ts.map +1 -1
  97. package/dist/runtime/auto-update/run-update-command.js +18 -0
  98. package/dist/runtime/auto-update/run-update-command.js.map +1 -1
  99. package/dist/runtime/auto-update/state-store.d.ts +14 -1
  100. package/dist/runtime/auto-update/state-store.d.ts.map +1 -1
  101. package/dist/runtime/auto-update/state-store.js +37 -3
  102. package/dist/runtime/auto-update/state-store.js.map +1 -1
  103. package/dist/runtime/auto-update/types.d.ts +52 -0
  104. package/dist/runtime/auto-update/types.d.ts.map +1 -1
  105. package/dist/runtime/auto-update/types.js.map +1 -1
  106. package/dist/runtime/auto-update/update-marker.d.ts +95 -0
  107. package/dist/runtime/auto-update/update-marker.d.ts.map +1 -0
  108. package/dist/runtime/auto-update/update-marker.js +185 -0
  109. package/dist/runtime/auto-update/update-marker.js.map +1 -0
  110. package/dist/runtime/auto-update/update-schedule.d.ts +67 -0
  111. package/dist/runtime/auto-update/update-schedule.d.ts.map +1 -0
  112. package/dist/runtime/auto-update/update-schedule.js +91 -0
  113. package/dist/runtime/auto-update/update-schedule.js.map +1 -0
  114. package/dist/runtime/decision-errors.d.ts +7 -0
  115. package/dist/runtime/decision-errors.d.ts.map +1 -1
  116. package/dist/runtime/decision-errors.js +15 -0
  117. package/dist/runtime/decision-errors.js.map +1 -1
  118. package/dist/runtime/process-state.d.ts +168 -0
  119. package/dist/runtime/process-state.d.ts.map +1 -0
  120. package/dist/runtime/process-state.js +81 -0
  121. package/dist/runtime/process-state.js.map +1 -0
  122. package/dist/runtime/reconcile-state.d.ts.map +1 -1
  123. package/dist/runtime/reconcile-state.js +18 -7
  124. package/dist/runtime/reconcile-state.js.map +1 -1
  125. package/dist/runtime/strategy-registry.d.ts +16 -0
  126. package/dist/runtime/strategy-registry.d.ts.map +1 -1
  127. package/dist/runtime/strategy-registry.js +7 -3
  128. package/dist/runtime/strategy-registry.js.map +1 -1
  129. package/dist/runtime/update-apply-deps.d.ts +5 -3
  130. package/dist/runtime/update-apply-deps.d.ts.map +1 -1
  131. package/dist/runtime/update-apply-deps.js +15 -3
  132. package/dist/runtime/update-apply-deps.js.map +1 -1
  133. package/dist/senpi/client.d.ts +29 -0
  134. package/dist/senpi/client.d.ts.map +1 -1
  135. package/dist/senpi/client.js +71 -2
  136. package/dist/senpi/client.js.map +1 -1
  137. package/dist/skills-manager/version-manager.d.ts +0 -14
  138. package/dist/skills-manager/version-manager.d.ts.map +1 -1
  139. package/dist/skills-manager/version-manager.js +3 -31
  140. package/dist/skills-manager/version-manager.js.map +1 -1
  141. package/dist/strategy/strategy-state.d.ts +3 -11
  142. package/dist/strategy/strategy-state.d.ts.map +1 -1
  143. package/dist/strategy/strategy-state.js +8 -18
  144. package/dist/strategy/strategy-state.js.map +1 -1
  145. package/dist/telemetry/event-builders.d.ts +2 -4
  146. package/dist/telemetry/event-builders.d.ts.map +1 -1
  147. package/dist/telemetry/event-builders.js +2 -4
  148. package/dist/telemetry/event-builders.js.map +1 -1
  149. package/dist/telemetry/metrics.d.ts +15 -1
  150. package/dist/telemetry/metrics.d.ts.map +1 -1
  151. package/dist/telemetry/metrics.js +25 -1
  152. package/dist/telemetry/metrics.js.map +1 -1
  153. package/dist/telemetry/otel-sdk.d.ts +12 -0
  154. package/dist/telemetry/otel-sdk.d.ts.map +1 -1
  155. package/dist/telemetry/otel-sdk.js +47 -1
  156. package/dist/telemetry/otel-sdk.js.map +1 -1
  157. package/dist/telemetry/spans/span-hooks.d.ts +18 -1
  158. package/dist/telemetry/spans/span-hooks.d.ts.map +1 -1
  159. package/dist/telemetry/spans/span-hooks.js +304 -103
  160. package/dist/telemetry/spans/span-hooks.js.map +1 -1
  161. package/dist/telemetry/tool-plane.d.ts +2 -0
  162. package/dist/telemetry/tool-plane.d.ts.map +1 -1
  163. package/dist/telemetry/tool-plane.js +1 -0
  164. package/dist/telemetry/tool-plane.js.map +1 -1
  165. package/dist/test-setup.js +7 -1
  166. package/dist/test-setup.js.map +1 -1
  167. package/dist/tool-surface/crib-cache.d.ts +21 -0
  168. package/dist/tool-surface/crib-cache.d.ts.map +1 -0
  169. package/dist/tool-surface/crib-cache.js +54 -0
  170. package/dist/tool-surface/crib-cache.js.map +1 -0
  171. package/dist/tool-surface/crib-hook.d.ts +78 -0
  172. package/dist/tool-surface/crib-hook.d.ts.map +1 -0
  173. package/dist/tool-surface/crib-hook.js +225 -0
  174. package/dist/tool-surface/crib-hook.js.map +1 -0
  175. package/dist/tool-surface/crib-sheet.d.ts +56 -0
  176. package/dist/tool-surface/crib-sheet.d.ts.map +1 -0
  177. package/dist/tool-surface/crib-sheet.js +129 -0
  178. package/dist/tool-surface/crib-sheet.js.map +1 -0
  179. package/dist/tool-surface/mcp-tool-source.d.ts +64 -0
  180. package/dist/tool-surface/mcp-tool-source.d.ts.map +1 -0
  181. package/dist/tool-surface/mcp-tool-source.js +189 -0
  182. package/dist/tool-surface/mcp-tool-source.js.map +1 -0
  183. package/dist/utils/event-catalog.d.ts +144 -90
  184. package/dist/utils/event-catalog.d.ts.map +1 -1
  185. package/dist/utils/event-catalog.js +25 -7
  186. package/dist/utils/event-catalog.js.map +1 -1
  187. package/dist/widgets/tool.d.ts +9 -0
  188. package/dist/widgets/tool.d.ts.map +1 -1
  189. package/dist/widgets/tool.js +1 -0
  190. package/dist/widgets/tool.js.map +1 -1
  191. package/openclaw.plugin.json +11 -1
  192. package/package.json +5 -2
  193. package/dist/prompt/skill-router-hook.d.ts +0 -24
  194. package/dist/prompt/skill-router-hook.d.ts.map +0 -1
  195. package/dist/prompt/skill-router-hook.js +0 -381
  196. package/dist/prompt/skill-router-hook.js.map +0 -1
  197. package/dist/skill-router/catalog.d.ts +0 -30
  198. package/dist/skill-router/catalog.d.ts.map +0 -1
  199. package/dist/skill-router/catalog.js +0 -131
  200. package/dist/skill-router/catalog.js.map +0 -1
  201. package/dist/skill-router/classify-client.d.ts +0 -80
  202. package/dist/skill-router/classify-client.d.ts.map +0 -1
  203. package/dist/skill-router/classify-client.js +0 -283
  204. package/dist/skill-router/classify-client.js.map +0 -1
  205. package/dist/skill-router/prompt.d.ts +0 -36
  206. package/dist/skill-router/prompt.d.ts.map +0 -1
  207. package/dist/skill-router/prompt.js +0 -318
  208. package/dist/skill-router/prompt.js.map +0 -1
  209. package/dist/skill-router/resolve.d.ts +0 -41
  210. package/dist/skill-router/resolve.d.ts.map +0 -1
  211. package/dist/skill-router/resolve.js +0 -43
  212. package/dist/skill-router/resolve.js.map +0 -1
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,15 +49,20 @@ 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";
52
- import { registerSkillRouterHook } from "./prompt/skill-router-hook.js";
58
+ import { registerCribSheet } from "./tool-surface/crib-hook.js";
53
59
  import { getDefaultPiiRedactor, initDefaultPiiRedactor } from "./telemetry/spans/redact-pii.js";
54
- import { initOtelSdk, shutdownOtelSdk } from "./telemetry/otel-sdk.js";
60
+ import { flushOtelLogs, initOtelSdk, shutdownOtelSdk, waitForOtelInit } from "./telemetry/otel-sdk.js";
55
61
  import { getLogLevel, getLogLevelSource, parseLogLevel, setLogLevel, } from "./utils/logger.js";
56
62
  import { ExternalScannerIngestError, } from "./scanners/external-scanner-receiver.js";
57
63
  import { createLogger } from "./utils/logger.js";
58
- import { registerToolApprovalGate, resolveToolApprovalsMode, } from "./approvals/tool-approval-gate.js";
64
+ import { PendingApprovalTracker, registerToolApprovalGate, resolveToolApprovalsMode, } from "./approvals/tool-approval-gate.js";
65
+ import { registerTurnContextHooks, turnClassificationAvailable, TurnContextTracker, } from "./approvals/turn-context.js";
59
66
  import { registerShowWidgetTool } from "./widgets/index.js";
60
67
  import { EVENT_NAME, SENPI_ERROR_CODE, eventAttrs, scannerUnwiredErrorCode } from "./utils/event-catalog.js";
61
68
  import { emitEvent } from "./actions/event-derivation.js";
@@ -72,6 +79,9 @@ import { ingestDispatchMutex, ingestDispatchKey } from "./runtime-api/intake/ing
72
79
  import { buildScaffoldErrorRouter } from "./runtime-api/intake/scaffold-error-router.js";
73
80
  import { loadRuntimeConfig } from "./runtime/load-runtime-config.js";
74
81
  import { errorText } from "./deploy/error-text.js";
82
+ import { getOpenClawHost, initOpenClawHost } from "./host/openclaw-host.js";
83
+ import { createRegisterPluginLogger, withEventLogger } from "./host/plugin-logger.js";
84
+ import { hostname } from "node:os";
75
85
  import { BOOT_FACTS_CALL_TIMEOUT_MS, planBootFacts, syncBootFacts, } from "./strategy/facts-sync.js";
76
86
  /** Initialize all core features (DSL, risk, health) on the given event bus. */
77
87
  export function initCore(bus) {
@@ -102,21 +112,6 @@ export { createScannerRuntimeModule, createSenpiScannerProviders, emergingMovers
102
112
  export { run } from "./runtime/run.js";
103
113
  export { loadRuntimeConfig } from "./runtime/load-runtime-config.js";
104
114
  export { Runtime } from "./runtime/runtime.js";
105
- /**
106
- * A coordinator logger: info/warn/error route through `pluginLogger` unchanged (the gateway's own
107
- * sink), and `event()` goes to a dedicated OTel-backed logger tagged `tag`. `PluginLogger`
108
- * (api.logger) predates the event catalog and has no `event()`, so coordinators that emit
109
- * first-class events (auto-update, skills-manager) get this split.
110
- */
111
- function withEventLogger(pluginLogger, tag) {
112
- const eventLogger = createLogger(tag);
113
- return {
114
- info: (...args) => pluginLogger.info(...args),
115
- warn: (...args) => pluginLogger.warn(...args),
116
- error: (message, meta) => pluginLogger.error(message, meta),
117
- event: eventLogger.event,
118
- };
119
- }
120
115
  /**
121
116
  * Read the plugin version from the sibling `openclaw.plugin.json` manifest.
122
117
  * Performed once at module load — the manifest is shipped alongside the
@@ -185,11 +180,50 @@ const WALLET_INSTALL_IN_FLIGHT = `[${WALLET_INSTALL_IN_FLIGHT_CODE}]`;
185
180
  */
186
181
  const RUNTIME_ID_TAKEN = "[E_RUNTIME_ID_TAKEN]";
187
182
  /**
188
- * One StrategyFacts send per runtime at a time, keyed on runtime id, across the whole process: a
189
- * second `register()` in the same process shares it. Separate from `runtimeChangeLock`. Delete does
190
- * not take it; an apply queues its send here and does not wait.
183
+ * One StrategyFacts send per runtime at a time, keyed on runtime id, across the whole process.
184
+ * Held in the process state (`runtime/process-state.ts`), not this module: a 10.x plugin reload
185
+ * evaluates a new copy of this module, and the previous registration's send may still be running.
186
+ * Separate from `runtimeChangeLock`. Delete does not take it; an apply queues its send here and
187
+ * does not wait.
188
+ */
189
+ function factsSendLock() {
190
+ const state = runtimeProcessState();
191
+ state.factsSendLock ??= new KeyedMutex();
192
+ return state.factsSendLock;
193
+ }
194
+ /**
195
+ * Clears the process-state latch for the 5.x "cannot classify runs" notice
196
+ * (`legacyTurnClassificationNoticeLogged`). Tests only.
197
+ *
198
+ * The latch lives in the process state so a plugin reload (which re-registers the plugin and
199
+ * restarts its service in the same process, from a new copy of this module) does not repeat the
200
+ * notice. The 5.x case is a host-version limit with no config fix, so one info line per process is
201
+ * the whole message; the fixable 10.x case stays an ERROR at every registration and does not read
202
+ * this latch.
191
203
  */
192
- const factsSendLock = new KeyedMutex();
204
+ export function resetLegacyTurnClassificationNoticeForTests() {
205
+ runtimeProcessState().legacyTurnClassificationNoticeLogged = false;
206
+ }
207
+ /**
208
+ * The whole of `register()` in the `"cli-metadata"` pass: the `senpi` CLI root, under the same
209
+ * preconditions and with the same metadata as the full pass, and nothing else.
210
+ *
211
+ * Reads no `api.runtime`: on 10.x that pass's runtime throws on any read, and the host prints the
212
+ * throw as `runtime failed during register` on every `openclaw senpi …` call (RT566-04). Logs
213
+ * nothing: a skipped precondition is reported by the full pass, which follows in the same process.
214
+ */
215
+ function registerSenpiCliMetadata(api) {
216
+ const config = api.pluginConfig;
217
+ if (!config)
218
+ return;
219
+ const mcpTransport = api.mcpTransport;
220
+ const apiKey = resolveSenpiApiKeyFromStore(readSenpiCliStore(), typeof config.apiKey === "string" && config.apiKey.length > 0 ? config.apiKey : undefined);
221
+ if (!mcpTransport && !apiKey)
222
+ return;
223
+ api.registerCli((ctx) => {
224
+ registerSenpiCli(ctx.program);
225
+ }, { commands: ["senpi"] });
226
+ }
193
227
  /**
194
228
  * OpenClaw plugin entry.
195
229
  * Boots from internal registry (installed_runtimes.json) in stateDir; does not read runtime list from config.
@@ -220,16 +254,34 @@ const senpiRuntimePlugin = {
220
254
  // The diagnostics are not dropped, only moved to stderr where diagnostics belong. Warnings and
221
255
  // errors are left on the logger untouched: those are not routine chatter, and a caller piping
222
256
  // stdout to a parser still wants them visible.
223
- const jsonMode = process.argv.includes("--json");
224
- const pluginLogger = {
225
- info: (...args) =>
226
- // No added prefix: these messages already carry their own `[senpi-runtime]` /
227
- // `[senpi-tool-approvals]` tag, and prepending another produced doubled labels on stderr.
228
- jsonMode ? console.error(...args) : api.logger.info(...args),
229
- warn: (...args) => api.logger.warn(...args),
230
- error: (message, meta) => api.logger.error(message, meta),
231
- };
257
+ //
258
+ // OpenClaw 2026.5.20+ (every modern host) moves plugin logs to stderr itself under `--json` and
259
+ // files them at their real level, so the reroute is kept for 5.x only: on 10.x it made the
260
+ // console capture file every registration line at ERROR (F5). See host/plugin-logger.ts.
261
+ //
262
+ // The cli-metadata pass only collects CLI command roots. 10.x hands it a runtime that throws on
263
+ // any read (RT566-04), so register the `senpi` root and nothing else — and read no api.runtime.
264
+ if (api.registrationMode === "cli-metadata") {
265
+ registerSenpiCliMetadata(api);
266
+ return;
267
+ }
268
+ // Host facts first: the logger and every version-gated registration below read them. 10.x also
269
+ // registers plugins in non-full modes inside the gateway (`tool-discovery` for tools.catalog);
270
+ // that pass must keep registering tools, but its throwaway api must not replace the record the
271
+ // live registration made.
272
+ const fullRegistration = api.registrationMode === undefined || api.registrationMode === "full";
273
+ const openClawHost = (!fullRegistration && getOpenClawHost()) || initOpenClawHost(api);
274
+ // State kept across a reload (the deploy controller, the gate trackers) logs through the latest
275
+ // full registration's logger, never through an `api` a reload has replaced.
276
+ const processState = runtimeProcessState();
277
+ if (fullRegistration)
278
+ bindProcessLogger(api.logger);
279
+ const pluginLogger = createRegisterPluginLogger(api.logger, {
280
+ jsonMode: process.argv.includes("--json"),
281
+ hostRoutesJsonLogsToStderr: openClawHost.modern,
282
+ });
232
283
  pluginLogger.info("[senpi-runtime] register(api) invoked");
284
+ pluginLogger.info(`[senpi-runtime] host OpenClaw ${openClawHost.version ?? "unknown"} (${openClawHost.modern ? "modern" : "legacy"})`);
233
285
  const config = api.pluginConfig;
234
286
  if (!config) {
235
287
  pluginLogger.warn("[senpi-runtime] No plugin config found — skipping registration");
@@ -279,10 +331,8 @@ const senpiRuntimePlugin = {
279
331
  // loader doesn't await it; awaiting init would defer the registrations below), so it's
280
332
  // fire-and-forget — the hooks resolve their tracer lazily at fire time, by which point
281
333
  // init has run. Self-guarding; see src/telemetry/otel-sdk.ts.
282
- // The box's per-user Senpi token: the OTel user token and the skill router's bearer.
283
- const userToken = apiKey ?? process.env.SENPI_AUTH_TOKEN ?? process.env.SENPI_API_KEY;
284
334
  void initOtelSdk({
285
- userToken,
335
+ userToken: apiKey ?? process.env.SENPI_AUTH_TOKEN ?? process.env.SENPI_API_KEY,
286
336
  serviceVersion: VERSION,
287
337
  }).catch((err) => {
288
338
  pluginLogger.warn("[senpi-runtime] OTel SDK init failed", {
@@ -292,8 +342,8 @@ const senpiRuntimePlugin = {
292
342
  // Agent telemetry — gateway hooks emit gen_ai spans (llm/tool/subagent) through
293
343
  // the shared tracer; on-site MCP calls emit their own spans from SenpiClient.
294
344
  try {
295
- registerSpanHooks({ api });
296
- pluginLogger.info("[senpi-runtime] gen_ai span hooks registered (9 hooks)");
345
+ const spanHookCount = registerSpanHooks({ api, modernHost: openClawHost.modern });
346
+ pluginLogger.info(`[senpi-runtime] gen_ai span hooks registered (${spanHookCount} hooks)`);
297
347
  }
298
348
  catch (err) {
299
349
  pluginLogger.warn("[senpi-runtime] failed to register span hooks", {
@@ -312,23 +362,29 @@ const senpiRuntimePlugin = {
312
362
  err: err instanceof Error ? err.message : String(err),
313
363
  });
314
364
  }
315
- // Skill router — on an eligible user turn, asks senpi-backend which installed skill the
316
- // prompt needs and (mode `on`) points the model at its SKILL.md. Registered after the seed
317
- // hook so the seed instruction comes first if both inject. Off unless SENPI_SKILL_ROUTER is
318
- // `shadow` or `on`; see src/prompt/skill-router-hook.ts.
365
+ // senpi__ crib sheet (OpenClaw 10.x tool-search directory mode only): the
366
+ // directory folds every MCP tool into one sentence, so the runtime puts
367
+ // the names back as prependSystemContext. Registers nothing on 5.x.
368
+ // Its `before_prompt_build` hook needs the same host grant as the approval
369
+ // turn classification below; without it 10.x drops the hook, so the line
370
+ // says the crib is inactive and why instead of "registered".
319
371
  try {
320
- const skillRouter = registerSkillRouterHook({
321
- api,
322
- token: userToken,
323
- searchPath: resolveSkillsManagerConfig(config?.skillsManager).skillsDir,
372
+ if (registerCribSheet({
373
+ api: api,
374
+ baseStateDir,
375
+ pluginConfig: config,
324
376
  logger: pluginLogger,
325
- });
326
- if (skillRouter !== "off") {
327
- pluginLogger.info(`[senpi-runtime] skill router hook registered (${skillRouter})`);
377
+ })) {
378
+ // Registered, so the host is modern; only the hook grant is left to check.
379
+ const cribHook = turnClassificationAvailable({ modernHost: true, config: api.config, pluginId: api.id });
380
+ pluginLogger.info(cribHook.available
381
+ ? "[senpi-runtime] senpi__ crib sheet registered (directory mode only)"
382
+ : `[senpi-runtime] senpi__ crib inactive: ${cribHook.reason}` +
383
+ (cribHook.configFix ? `; fix: ${cribHook.configFix}` : ""));
328
384
  }
329
385
  }
330
386
  catch (err) {
331
- pluginLogger.warn("[senpi-runtime] failed to register skill router hook", {
387
+ pluginLogger.warn("[senpi-runtime] failed to register the senpi__ crib sheet", {
332
388
  err: err instanceof Error ? err.message : String(err),
333
389
  });
334
390
  }
@@ -337,9 +393,82 @@ const senpiRuntimePlugin = {
337
393
  // the bridge's operator.approvals-scoped gateway connection; allow-always
338
394
  // decisions persist in <stateDir>/tool-approvals.json.
339
395
  // See docs/mcp-tool-approvals-design.md.
396
+ // Open trade-approval prompts, read by the self-update idle gate (R2).
397
+ // This and the turn tracker are process state: a 10.x reload re-registers in the same process
398
+ // while a prompt is open or a run is in flight (r4467406809, r4427720076).
399
+ processState.pendingApprovals ??= new PendingApprovalTracker();
400
+ const pendingApprovalTracker = processState.pendingApprovals;
401
+ // The turn kind (chat / cron / heartbeat) and session key of each gated
402
+ // call, for approval telemetry and the 10.x scheduled-turn block (R6, D13).
403
+ processState.turnContext ??= new TurnContextTracker();
404
+ const turnContextTracker = processState.turnContext;
405
+ // One boot-time fact (D15): can this host classify runs at all? Only then
406
+ // does the gate stop prompts outside a direct chat turn. Without it every
407
+ // run reads unknown and keeps the pre-10.x prompt, so a box missing the
408
+ // setting never blocks chat trades; it is reported loudly instead.
409
+ let turnClassification = turnClassificationAvailable({
410
+ modernHost: openClawHost.modern,
411
+ config: api.config,
412
+ pluginId: api.id,
413
+ });
414
+ try {
415
+ registerTurnContextHooks({ api, tracker: turnContextTracker });
416
+ }
417
+ catch (err) {
418
+ turnClassification = { available: false, reason: "the turn-context hooks failed to register" };
419
+ pluginLogger.warn("[senpi-runtime] failed to register the approval turn-context hooks", {
420
+ err: err instanceof Error ? err.message : String(err),
421
+ });
422
+ }
423
+ // Only the logging and the status flag differ by host; the gate below reads the same boolean
424
+ // either way. On 10.x it is an ERROR at every registration (a box config to fix, or hooks that
425
+ // failed to register). On 5.x it is a host limit no config can fix, so it is one info line per
426
+ // process, logged from the service start below: that runs in the gateway only, so the
427
+ // `openclaw senpi …` CLI children (deploy.py, close.py, an agent exec) register without
428
+ // printing it.
429
+ const turnClassificationHostLimit = !turnClassification.available && !openClawHost.modern;
430
+ const turnClassificationNotice = turnClassification.available
431
+ ? undefined
432
+ : `[senpi-tool-approvals] cannot tell chat turns from scheduled or background runs: ${turnClassification.reason}. ` +
433
+ "Trade approvals are requested in every run, scheduled ones included, " +
434
+ (turnClassification.configFix
435
+ ? `until the box config is fixed (${turnClassification.configFix}).`
436
+ : turnClassificationHostLimit
437
+ ? "on this OpenClaw version; a 10.x host lifts this."
438
+ : "until the runtime registers its turn-context hooks.");
439
+ const legacyTurnClassificationNotice = turnClassificationHostLimit ? turnClassificationNotice : undefined;
440
+ if (turnClassificationNotice !== undefined && !turnClassificationHostLimit && fullRegistration) {
441
+ pluginLogger.error(turnClassificationNotice);
442
+ }
443
+ const approvalsHostStatus = turnClassification.available
444
+ ? { turnClassification: "available" }
445
+ : {
446
+ turnClassification: "unavailable",
447
+ reason: turnClassification.reason,
448
+ ...(turnClassificationHostLimit ? { hostLimit: true } : {}),
449
+ };
450
+ // Process state, like the run-kind tracker beside it: a reload must not zero the count that
451
+ // `senpi status` warns about while chat trades are being refused.
452
+ const approvalsStatus = () => approvalsHostStatus.turnClassification === "available"
453
+ ? {
454
+ ...approvalsHostStatus,
455
+ runsRecorded: turnContextTracker.runsRecorded,
456
+ unclassifiedBlocks: processState.unclassifiedBlocks,
457
+ ...(processState.lastUnclassifiedBlockAt
458
+ ? { lastUnclassifiedBlockAt: processState.lastUnclassifiedBlockAt }
459
+ : {}),
460
+ }
461
+ : approvalsHostStatus;
340
462
  try {
341
463
  registerToolApprovalGate({
342
464
  api,
465
+ pendingApprovals: pendingApprovalTracker,
466
+ turnContext: turnContextTracker,
467
+ turnClassification: turnClassification.available,
468
+ onUnclassifiedBlock: (at) => {
469
+ processState.unclassifiedBlocks += 1;
470
+ processState.lastUnclassifiedBlockAt = new Date(at).toISOString();
471
+ },
343
472
  mode: resolveToolApprovalsMode({
344
473
  pluginConfig: config,
345
474
  env: process.env,
@@ -461,8 +590,21 @@ const senpiRuntimePlugin = {
461
590
  * row, sees no live handle, deletes it and reinstalls — and the first install then lands on top,
462
591
  * clobbering `runtimeHandles` under a runtime id both installs derive identically. Two exit
463
592
  * engines, one margin account: the exact state `[E_WALLET_HAS_RUNTIME]` exists to prevent.
593
+ *
594
+ * Process state (`runtime/process-state.ts`), not this registration: a 10.x plugin reload
595
+ * re-registers in the same process while a deploy job's install from the previous registration
596
+ * runs on, and the new registration must still refuse a second install on that wallet.
464
597
  */
465
- const installsInFlight = new Map();
598
+ const installsInFlight = processState.installsInFlight;
599
+ /**
600
+ * This registration's service lifecycle, for an install or adoption that outlives it. A 10.x
601
+ * plugin reload stops this service and starts the next registration's in the same process;
602
+ * `serviceStops` counts this registration's stops, so a stop followed by a later start is still
603
+ * seen. Only a stop counts: an install that began before the first start (the gateway may call
604
+ * installRuntime before start()) and spans it is not orphaned.
605
+ */
606
+ let serviceState = "idle";
607
+ let serviceStops = 0;
466
608
  // Dedicated logger for the runtime-api subtree — required because the
467
609
  // PluginLogger surface (info/warn/error) lacks `debug`, while the
468
610
  // Logger contract used by `runtime-api/` includes it.
@@ -503,26 +645,106 @@ const senpiRuntimePlugin = {
503
645
  stateDir: join(baseStateDir, "skills-manager"),
504
646
  logger: withEventLogger(pluginLogger, "[senpi-core][skills-manager]"),
505
647
  });
506
- const autoUpdateLogger = withEventLogger(pluginLogger, "[senpi-core][auto-update]");
507
648
  const autoUpdateConfig = resolveAutoUpdateConfig(config?.autoUpdate);
649
+ // OpenClaw 10.x (>= 2026.8.1): restart-to-apply (R2). The runtime cannot
650
+ // install itself there, so it waits for its spread slot and an idle box,
651
+ // writes the install marker, and restarts through mutateConfigFile; the
652
+ // senpi-agent wrapper installs before the next gateway spawn. On 5.7 and
653
+ // 5.12 the wiring is the in-process install + config-bump restart.
654
+ const modernHost = openClawHost.modern;
655
+ // 10.x: every `auto_update.*` event is also written to the gateway log as one key=value line,
656
+ // so a box with no collector still keeps the update's fields (F8). 5.x keeps OTel only.
657
+ const autoUpdateLogger = withEventLogger(pluginLogger, "[senpi-core][auto-update]", modernHost ? { mirrorTag: "[senpi-auto-update]" } : {});
658
+ let idleGate;
659
+ if (modernHost) {
660
+ // Money calls on every route: the runtime's own in-process MCP calls, plus
661
+ // the agent's senpi__ calls (direct or through the dispatcher), seen at the
662
+ // tool hooks. A deploy job is read from the controller (this process) and
663
+ // its journals (any process).
664
+ // Process state, like the approval trackers: a call that started under the previous
665
+ // registration still counts, and its after-hook (now this registration's) closes it.
666
+ processState.moneyCalls ??= new MoneyCallTracker();
667
+ const moneyCalls = processState.moneyCalls;
668
+ try {
669
+ registerMoneyCallHooks({
670
+ api: api,
671
+ tracker: moneyCalls,
672
+ isMoneyTool: isMoneyCallTool,
673
+ });
674
+ }
675
+ catch (err) {
676
+ pluginLogger.warn("[senpi-runtime] failed to register the self-update money-call hooks", {
677
+ err: err instanceof Error ? err.message : String(err),
678
+ });
679
+ }
680
+ idleGate = new UpdateIdleGate({
681
+ pendingApprovals: () => pendingApprovalTracker.count(),
682
+ ordersInFlight: () => senpiOrderCallsInFlight() + moneyCalls.count(Date.now()),
683
+ // Read only from ticks, after register() has constructed the controller below.
684
+ deploysInFlight: () => deployController.inFlight(Date.now()),
685
+ // The process start, not this registration: a config edit under `plugins` re-registers in
686
+ // the same process (10.10 reloadGatewayPlugins), and repeated reloads under 15 min apart
687
+ // must not hold an update until the forced window.
688
+ startedAt: Date.now() - Math.round(process.uptime() * 1000),
689
+ // Process state: a reload builds this gate again, and must not forget a user turn that is
690
+ // running, a message that is queued, or when the user last wrote.
691
+ activity: (processState.idleGateActivity ??= createIdleGateActivity()),
692
+ logger: pluginLogger,
693
+ });
694
+ try {
695
+ registerIdleGateHooks({ api: api, gate: idleGate, logger: pluginLogger });
696
+ }
697
+ catch (err) {
698
+ pluginLogger.warn("[senpi-runtime] failed to register the self-update idle gate hooks", {
699
+ err: err instanceof Error ? err.message : String(err),
700
+ });
701
+ }
702
+ }
703
+ const openclawStateDir = typeof api.runtime?.state?.resolveStateDir === "function" ? api.runtime.state.resolveStateDir() : undefined;
508
704
  const autoUpdateCoordinator = new AutoUpdateCoordinator({
509
705
  enabled: true,
510
706
  config: autoUpdateConfig,
511
707
  packageName: PLUGIN_PACKAGE_NAME,
512
708
  currentVersion: VERSION,
709
+ // The version this process loaded; "applied" is decided from it alone.
710
+ loadedVersion: VERSION,
513
711
  stateDir: join(baseStateDir, "auto-update"),
514
712
  logger: autoUpdateLogger,
515
713
  // Use the resolved npm package name (not a hardcoded plugin id) so
516
714
  // the update follows the same npm channel as the version check —
517
- // see runtime/auto-update/run-update-command.ts.
518
- runUpdateCommand: runOpenClawPluginsUpdate,
715
+ // see runtime/auto-update/run-update-command.ts. Not on 10.x, which
716
+ // refuses plugins update while the gateway runs.
717
+ runUpdateCommand: modernHost ? undefined : runOpenClawPluginsUpdate,
519
718
  configFromApi: api.config,
520
- loadConfig: api.runtime?.config
719
+ loadConfig: !modernHost && api.runtime?.config
521
720
  ? () => api.runtime.config.loadConfig()
522
721
  : undefined,
523
- writeConfigFile: api.runtime?.config
722
+ writeConfigFile: !modernHost && api.runtime?.config
524
723
  ? (c) => api.runtime.config.writeConfigFile(c)
525
724
  : undefined,
725
+ modernHost,
726
+ mutateConfigFile: modernHost && typeof api.runtime?.config?.mutateConfigFile === "function"
727
+ ? (p) => api.runtime.config.mutateConfigFile(p)
728
+ : undefined,
729
+ readLiveConfig: modernHost ? openClawHost.currentConfig : undefined,
730
+ idleGate,
731
+ mid: modernHost
732
+ ? resolveUpdateMid({
733
+ token: apiKey ?? process.env.SENPI_AUTH_TOKEN ?? process.env.SENPI_API_KEY,
734
+ env: process.env,
735
+ hostname,
736
+ })
737
+ : undefined,
738
+ updateMarkerPath: modernHost && openclawStateDir ? resolveUpdateMarkerPath(openclawStateDir) : undefined,
739
+ // The wrapper's install outcomes, reported once per coordinator start (gateway only),
740
+ // with auto-update on or off. The report runs off the start path: it waits for the OTel
741
+ // init register() started (else the events go to the no-op logger and the file is gone)
742
+ // and flushes the logs before deleting the file.
743
+ installResultsPath: modernHost && openclawStateDir ? resolveInstallResultsPath(openclawStateDir) : undefined,
744
+ installResultsTelemetry: {
745
+ ready: () => waitForOtelInit(INSTALL_RESULTS_OTEL_READY_MS),
746
+ flush: () => flushOtelLogs(INSTALL_RESULTS_OTEL_FLUSH_MS),
747
+ },
526
748
  pluginId: api.id,
527
749
  // Drive skills-manager off the auto-update tick. Both success and
528
750
  // failure branches of auto-update's tick fire this hook so skills
@@ -560,11 +782,20 @@ const senpiRuntimePlugin = {
560
782
  // boot scan: declaring it after would leave that reference in the temporal dead zone for any
561
783
  // future refactor that starts the service earlier. The rest of the deploy wiring lives in
562
784
  // src/deploy/register.ts behind an explicit context; this closure contributes collaborators only.
563
- const deployController = new DeployJobController({
564
- deploysDir: join(baseStateDir, "deploys"),
565
- now: () => Date.now(),
566
- log: (line) => api.logger.info(`[senpi-runtime] ${line}`),
567
- });
785
+ //
786
+ // One controller per deploys dir per process (process state): a full re-registration (10.10
787
+ // reloadGatewayPlugins, same process) reuses the one that may be running a deploy, so its
788
+ // `running()` keeps single-flight and `inFlight()` keeps the idle gate's deploy blocker. It
789
+ // logs through `processLog`, the current registration's logger, so a job that outlives its
790
+ // registration still narrates and writes its terminal journal line.
791
+ const deploysDir = join(baseStateDir, "deploys");
792
+ const deployController = processState.deployControllers.get(deploysDir) ??
793
+ new DeployJobController({
794
+ deploysDir,
795
+ now: () => Date.now(),
796
+ log: (line) => processLog.info(`[senpi-runtime] ${line}`),
797
+ });
798
+ processState.deployControllers.set(deploysDir, deployController);
568
799
  // ── lifecycle reaper ─────────────────────────────────────────────────────────────────────────
569
800
  // A runtime exists iff its strategy is open. Every close path ends at the backend and none of
570
801
  // them tells this box, so the reaper asks: once after boot, hourly, and whenever the backend
@@ -602,10 +833,20 @@ const senpiRuntimePlugin = {
602
833
  api.registerService({
603
834
  id: "senpi-runtime",
604
835
  async start() {
836
+ serviceState = "running";
837
+ // The 5.x classification notice (see the approval gate above), once per process.
838
+ if (legacyTurnClassificationNotice !== undefined && !processState.legacyTurnClassificationNoticeLogged) {
839
+ processState.legacyTurnClassificationNoticeLogged = true;
840
+ pluginLogger.info(legacyTurnClassificationNotice);
841
+ }
605
842
  // Deploy-journal janitor: stamp anything a restart left unterminated as `interrupted`.
606
843
  // It never re-enters a deploy state machine — discovery is pull-based via
607
- // `senpi deploy status`.
608
- await deployController.scanOnBoot();
844
+ // `senpi deploy status`. Once per process: after a reload an unterminated journal may be
845
+ // the deploy this process is still running (r4469086155).
846
+ if (!processState.bootScanned.has(deploysDir)) {
847
+ processState.bootScanned.add(deploysDir);
848
+ await deployController.scanOnBoot();
849
+ }
609
850
  await autoUpdateCoordinator.start();
610
851
  // SENPI_RUNTIME_API_DISABLED=true also disables the skills coordinator.
611
852
  // Skills bootstrap performs a real `git clone` synchronously during
@@ -925,6 +1166,17 @@ const senpiRuntimePlugin = {
925
1166
  }
926
1167
  }
927
1168
  }
1169
+ // This registration now runs the box's runtimes: publish it, then start what an install from a
1170
+ // stopped registration handed over while none was live (see `handOffRuntime`). Detached and
1171
+ // never throwing, like the facts send: one adoption must not hold or fail the boot.
1172
+ processState.runtimeHost = runtimeHost;
1173
+ const pendingHandOffs = [...processState.pendingRuntimeHandOffs];
1174
+ processState.pendingRuntimeHandOffs.clear();
1175
+ for (const [runtimeId, walletKey] of pendingHandOffs) {
1176
+ void runtimeHost.adoptRuntime({ runtimeId, walletKey }).then((handOff) => {
1177
+ pluginLogger.info("[senpi-runtime] handed-over runtime settled at service start", { runtimeId, outcome: handOff.outcome });
1178
+ });
1179
+ }
928
1180
  // Ticks once now, with every booted runtime in the store, then every 30 s.
929
1181
  strategiesPublisher.start();
930
1182
  // Sends the events added since the previous send, every 1 s.
@@ -946,6 +1198,12 @@ const senpiRuntimePlugin = {
946
1198
  }
947
1199
  },
948
1200
  async stop() {
1201
+ // First: an install or adoption still running in this registration sees the stop from here
1202
+ // on and hands its runtime to the next registration instead of keeping it in this one.
1203
+ serviceState = "stopped";
1204
+ serviceStops += 1;
1205
+ if (processState.runtimeHost === runtimeHost)
1206
+ processState.runtimeHost = null;
949
1207
  // Stop the reaper first so no pass starts deleting while the runtimes are torn down below,
950
1208
  // and wait (bounded) for a pass already under way, so its delete cannot stop a handle the
951
1209
  // teardown below is stopping too.
@@ -997,7 +1255,310 @@ const senpiRuntimePlugin = {
997
1255
  * `senpi deploy` installs through the SAME gates (wallet ownership, one-runtime-per-wallet,
998
1256
  * scanner-path resolution) instead of a parallel path that could drift.
999
1257
  */
1258
+ /**
1259
+ * Start an already-registered runtime in THIS registration while its service runs: `run()`,
1260
+ * the handle in `runtimeHandles`, then the hot-install scanner wire (the API is already
1261
+ * listening, so the launcher starts at once). Shared by `installRuntimeCore` and by
1262
+ * {@link runtimeHost}'s adoption of a runtime another registration handed over.
1263
+ *
1264
+ * `orphaned` says whether this registration's service stopped since the caller began (a 10.x
1265
+ * plugin reload). It is read after `run()` returns and again after the wire: a stopped
1266
+ * registration's `stop()` has already torn its runtimes down, so a runtime started here now
1267
+ * would keep ticking in a registration nothing can stop or delete. In that case this stops what
1268
+ * it started (the launcher, then the handle), removes them from this registration's maps, and
1269
+ * returns `orphaned`; the caller hands the runtime to the live registration.
1270
+ *
1271
+ * Throws what `run()` throws. Wire failures do not throw: they are reported as `unwiredPhase`,
1272
+ * exactly as the install has always reported them.
1273
+ */
1274
+ async function startRuntimeLive(spec, orphaned,
1275
+ /** Called once the runtime runs in this registration, before the scanner wire. */
1276
+ onRunning) {
1277
+ const { runtimeId, pathOrContent, fromPath, recipeDir, wallet, parsedConfig } = spec;
1278
+ /**
1279
+ * The unwired verdict for THIS start, tracked locally rather than read back out of
1280
+ * `unwiredRuntimes`, so the result reports what this call did and never a leftover verdict
1281
+ * from an earlier runtime that happened to share the id. Set at each of the three sites that
1282
+ * leave the runtime without live entry scanners; cleared by the wire-success path.
1283
+ */
1284
+ let unwiredPhase;
1285
+ let hotLauncher = null;
1286
+ const scannerProviders = await createScannerProvidersForRun({
1287
+ mcpTransport,
1288
+ apiKey,
1289
+ });
1290
+ const entryStateDir = buildRuntimeStateDir(baseStateDir, runtimeId, wallet);
1291
+ const handle = await run(pathOrContent, {
1292
+ fromPath,
1293
+ stateDir: entryStateDir,
1294
+ mcpTransport,
1295
+ apiKey,
1296
+ scannerProviders,
1297
+ runtimeId,
1298
+ onStrategyNotActive: (address) => reaper.checkWallet(address),
1299
+ });
1300
+ /** Stops what this call started and leaves this registration's maps as they were. */
1301
+ const abandon = async () => {
1302
+ if (hotLauncher) {
1303
+ await hotLauncher.stop().catch(() => { });
1304
+ if (launchers.get(runtimeId) === hotLauncher)
1305
+ launchers.delete(runtimeId);
1306
+ }
1307
+ await handle.stop().catch((err) => {
1308
+ pluginLogger.warn("[senpi-runtime] could not stop a runtime started by a stopped registration", {
1309
+ runtimeId,
1310
+ err: err instanceof Error ? err.message : String(err),
1311
+ });
1312
+ });
1313
+ if (runtimeHandles.get(runtimeId) === handle) {
1314
+ runtimeHandles.delete(runtimeId);
1315
+ unwiredRuntimes.delete(runtimeId);
1316
+ }
1317
+ return { status: "orphaned" };
1318
+ };
1319
+ if (orphaned())
1320
+ return abandon();
1321
+ runtimeHandles.set(runtimeId, handle);
1322
+ onRunning?.();
1323
+ // ── hot-install supervised scanner wire ───────────────────────────────
1324
+ // Live-install path: used when a runtime is registered after boot via
1325
+ // senpi.installRuntime, while the API is already listening — the
1326
+ // counterpart to the boot-time `launcher` above. A runtime takes exactly
1327
+ // one path: boot-present → `launcher` (deferred start); installed live →
1328
+ // `hotLauncher` (immediate start). The two are mutually exclusive because
1329
+ // installRuntime rejects any id/wallet already in the registry before
1330
+ // wiring (the hasId guard), so a boot-present runtime never re-enters here;
1331
+ // an adoption starts only a row the live registration does not run.
1332
+ // The API is already listening at this point, so we wire and start
1333
+ // immediately (no deferred start needed). Any failure is swallowed so
1334
+ // the install itself is not rolled back — the runtime is already up.
1335
+ // Gate on the same API-disabled flag as the boot path: when the HTTP API
1336
+ // is off (a test-only seam), the /signals route is never mounted, so
1337
+ // starting scanners would only spawn children that POST to a closed port.
1338
+ if (parsedConfig &&
1339
+ sharedIntakeContext &&
1340
+ process.env.SENPI_RUNTIME_API_DISABLED !== "true") {
1341
+ try {
1342
+ const apiConfig = loadApiConfig(api.pluginConfig);
1343
+ const scaffoldPackageDir = fileURLToPath(new URL("./scanners/external", import.meta.url));
1344
+ hotLauncher = wireRuntime({
1345
+ runtimeConfig: parsedConfig,
1346
+ recipeDir,
1347
+ runtimeId,
1348
+ wallet,
1349
+ sharedCtx: sharedIntakeContext,
1350
+ runtimeHandles,
1351
+ intakeUrl: intakeUrlFor(apiConfig.host, apiConfig.port),
1352
+ scaffoldPackageDir,
1353
+ runtimeStateDir: entryStateDir,
1354
+ logger: apiLogger,
1355
+ });
1356
+ if (hotLauncher) {
1357
+ const launcher = hotLauncher;
1358
+ try {
1359
+ await launcher.start();
1360
+ launchers.set(runtimeId, launcher);
1361
+ unwiredRuntimes.delete(runtimeId);
1362
+ unwiredPhase = undefined;
1363
+ runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
1364
+ unwired: false,
1365
+ rows: launcher.describeSupervision(),
1366
+ }));
1367
+ }
1368
+ catch (startErr) {
1369
+ await launcher.stop().catch(() => { });
1370
+ hotLauncher = null;
1371
+ unwiredRuntimes.set(runtimeId, "install_launch");
1372
+ unwiredPhase = "install_launch";
1373
+ runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
1374
+ unwired: true,
1375
+ unwiredPhase: "install_launch",
1376
+ rows: [],
1377
+ }));
1378
+ eventScannersUnwired("install_launch", runtimeId, wallet, appendCause("[senpi-runtime] hot-install supervised scanner launch failed — runtime running without it", startErr), startErr);
1379
+ }
1380
+ }
1381
+ }
1382
+ catch (wireErr) {
1383
+ // Wire failure must NOT fail the install — the runtime is already up. It IS reported
1384
+ // across the result boundary (payload.unwired) so a funding caller can refuse it.
1385
+ unwiredRuntimes.set(runtimeId, "install_wire");
1386
+ unwiredPhase = "install_wire";
1387
+ runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
1388
+ unwired: true,
1389
+ unwiredPhase: "install_wire",
1390
+ rows: [],
1391
+ }));
1392
+ eventScannersUnwired("install_wire", runtimeId, wallet, appendCause("[senpi-runtime] hot-install wiring failed — runtime running without supervised scanners", wireErr), wireErr);
1393
+ }
1394
+ }
1395
+ else if (parsedConfig && !sharedIntakeContext && selectScanners(parsedConfig).length > 0) {
1396
+ // Supervised intake is DISABLED for the whole box (corrupt acceptance record).
1397
+ // The wire block above is skipped, so this hot-installed runtime declares
1398
+ // external scanners but has NO live entry scanners. Record that fail-closed
1399
+ // state (state only, no new event) so listRuntimes/health don't lie.
1400
+ unwiredRuntimes.set(runtimeId, "no_intake");
1401
+ unwiredPhase = "no_intake";
1402
+ runtimeHandles.get(runtimeId)?.attachSupervisionSource(() => ({
1403
+ unwired: true,
1404
+ unwiredPhase: "no_intake",
1405
+ rows: [],
1406
+ }));
1407
+ }
1408
+ // ──────────────────────────────────────────────────────────────────────
1409
+ // The stop may have landed during the wire: its teardown then missed the launcher above.
1410
+ if (orphaned())
1411
+ return abandon();
1412
+ return unwiredPhase ? { status: "started", unwiredPhase } : { status: "started" };
1413
+ }
1414
+ /**
1415
+ * Give a runtime an orphaned install (or adoption) started to the live registration
1416
+ * ({@link RuntimeProcessState.runtimeHost}), or queue it for the next service start when no
1417
+ * registration is live. Never throws.
1418
+ */
1419
+ async function handOffRuntime(runtimeId, walletKey) {
1420
+ const host = processState.runtimeHost;
1421
+ if (!host) {
1422
+ // The strategies store is left as it is: a registration that is starting may already run this
1423
+ // row from its boot, and the next start's boot or adoption sets the entry either way.
1424
+ processState.pendingRuntimeHandOffs.set(runtimeId, walletKey);
1425
+ pluginLogger.info("[senpi-runtime] runtime handed to the next service start (no live registration)", { runtimeId });
1426
+ return { outcome: "pending" };
1427
+ }
1428
+ try {
1429
+ return await host.adoptRuntime({ runtimeId, walletKey });
1430
+ }
1431
+ catch (err) {
1432
+ // Nothing runs it: drop the entry the stopped start wrote, so the apps do not draw it.
1433
+ strategiesStore.delete(runtimeId);
1434
+ return { outcome: "failed", message: err instanceof Error ? err.message : String(err) };
1435
+ }
1436
+ }
1437
+ /**
1438
+ * The live registration, when this registration's service has stopped (a 10.x plugin reload)
1439
+ * and another one is running. A deploy job from before the reload keeps this registration's
1440
+ * closures; its deletes and liveness reads go to the registration that holds the runtimes.
1441
+ */
1442
+ function liveHostIfStopped() {
1443
+ if (serviceState !== "stopped")
1444
+ return undefined;
1445
+ const host = processState.runtimeHost;
1446
+ return host && host !== runtimeHost ? host : undefined;
1447
+ }
1448
+ /**
1449
+ * The install result for a runtime this install handed over. A stopped runtime is never
1450
+ * reported as running here: `handedOff` names who runs it, and the result is an error when
1451
+ * nothing does.
1452
+ */
1453
+ function installHandOffResult(handOff, runtime) {
1454
+ switch (handOff.outcome) {
1455
+ case "running":
1456
+ case "booted":
1457
+ return {
1458
+ ok: true,
1459
+ payload: {
1460
+ ...runtime,
1461
+ id: handOff.runtimeId,
1462
+ ...(handOff.unwired ? { unwired: handOff.unwired } : {}),
1463
+ handedOff: "The runtime plugin's service stopped during this install (a plugin reload or a gateway " +
1464
+ "stop), so the plugin registration that is running now runs this runtime " +
1465
+ `(runtime "${handOff.runtimeId}"). Check it: openclaw senpi runtime list.`,
1466
+ },
1467
+ };
1468
+ case "pending":
1469
+ return {
1470
+ ok: true,
1471
+ payload: {
1472
+ ...runtime,
1473
+ handedOff: "The runtime plugin's service stopped during this install (a plugin reload or a gateway " +
1474
+ "stop), and no plugin registration had finished starting when it ended. The runtime is " +
1475
+ "installed; the plugin's service runs it when its start finishes. Check it: " +
1476
+ "openclaw senpi runtime list.",
1477
+ },
1478
+ };
1479
+ case "no-row":
1480
+ return { ok: false, error: {
1481
+ code: "UNAVAILABLE",
1482
+ message: `The runtime plugin's service stopped during this install and runtime "${runtime.id}" is no ` +
1483
+ "longer in the registry, so nothing runs it. Nothing is trading on this wallet from this " +
1484
+ "install. Check: openclaw senpi runtime list.",
1485
+ } };
1486
+ case "failed":
1487
+ return { ok: false, error: {
1488
+ code: "UNAVAILABLE",
1489
+ message: `The runtime plugin's service stopped during this install and the running plugin ` +
1490
+ `registration could not start runtime "${runtime.id}": ${handOff.message}. It is installed; ` +
1491
+ "the next restart tries to start it. Check: openclaw senpi runtime list.",
1492
+ } };
1493
+ }
1494
+ }
1495
+ /**
1496
+ * This registration as the process's {@link RuntimeHost}: published at the end of the service
1497
+ * start, withdrawn at the start of its stop.
1498
+ */
1499
+ const runtimeHost = {
1500
+ async adoptRuntime(request) {
1501
+ const handOff = await adoptRuntimeCore(request);
1502
+ // Nothing runs it here: drop the entry the stopped registration's start wrote (run() sets it,
1503
+ // and that start's abandon does not clear it), so the apps do not draw a strategy that is not
1504
+ // running. A different id on the wallet leaves this id's entry just as stale.
1505
+ if (handOff.outcome === "no-row" ||
1506
+ handOff.outcome === "failed" ||
1507
+ (handOff.outcome === "running" && handOff.runtimeId !== request.runtimeId)) {
1508
+ strategiesStore.delete(request.runtimeId);
1509
+ }
1510
+ return handOff;
1511
+ },
1512
+ deleteRuntime: (params) => deleteRuntimeCore(params),
1513
+ runtimeIsLive: async (id) => runtimeHandles.has(id) && !unwiredRuntimes.has(id),
1514
+ getScannerRows: (id) => readScannerRows(id),
1515
+ };
1516
+ async function adoptRuntimeCore({ runtimeId, walletKey }) {
1517
+ const stopsAtAdopt = serviceStops;
1518
+ const orphaned = () => serviceState !== "running" || serviceStops !== stopsAtAdopt;
1519
+ try {
1520
+ const onWallet = runtimeHandles.has(runtimeId)
1521
+ ? runtimeId
1522
+ : walletKey
1523
+ ? [...runtimeHandles].find(([, h]) => (h.wallet ?? "").trim().toLowerCase() === walletKey)?.[0]
1524
+ : undefined;
1525
+ if (onWallet !== undefined) {
1526
+ // The live verdict, as for a start: a runtime running blind is not a clean install.
1527
+ const unwired = unwiredRuntimes.get(onWallet);
1528
+ return unwired ? { outcome: "running", runtimeId: onWallet, unwired } : { outcome: "running", runtimeId: onWallet };
1529
+ }
1530
+ const { readRegistry } = await import("./runtime/strategy-registry.js");
1531
+ const entry = (await readRegistry(baseStateDir)).runtimes.find((e) => e.id === runtimeId);
1532
+ if (!entry)
1533
+ return { outcome: "no-row" };
1534
+ const inputs = factsPlanInputs(entry);
1535
+ if (!inputs)
1536
+ return { outcome: "failed", message: "its registry row has no readable recipe" };
1537
+ const parsedConfig = await loadRuntimeConfig(inputs.pathOrContent, { fromPath: inputs.fromPath });
1538
+ const started = await startRuntimeLive({
1539
+ runtimeId: entry.id,
1540
+ pathOrContent: inputs.pathOrContent,
1541
+ fromPath: inputs.fromPath,
1542
+ recipeDir: inputs.runtimeYamlDir,
1543
+ wallet: entry.wallet ?? "",
1544
+ parsedConfig,
1545
+ }, orphaned);
1546
+ if (started.status === "orphaned")
1547
+ return handOffRuntime(runtimeId, walletKey);
1548
+ pluginLogger.info("[senpi-runtime] started a runtime handed over by a stopped registration", {
1549
+ runtimeId: entry.id,
1550
+ });
1551
+ return started.unwiredPhase
1552
+ ? { outcome: "booted", runtimeId: entry.id, unwired: started.unwiredPhase }
1553
+ : { outcome: "booted", runtimeId: entry.id };
1554
+ }
1555
+ catch (err) {
1556
+ return { outcome: "failed", message: err instanceof Error ? err.message : String(err) };
1557
+ }
1558
+ }
1000
1559
  async function installRuntimeCore(params) {
1560
+ // How many times this registration's service had stopped when this install began; see `orphaned` below.
1561
+ const stopsAtInstall = serviceStops;
1001
1562
  const toError = (message) => ({ code: "INVALID_REQUEST", message });
1002
1563
  const toUnavailable = (message) => ({ code: "UNAVAILABLE", message });
1003
1564
  const { readRegistry, writeRegistry, withRegistryLock, validateEntry, hasId, findByWallet, deriveRuntimeId, sanitizeId } = await import("./runtime/strategy-registry.js");
@@ -1265,127 +1826,64 @@ const senpiRuntimePlugin = {
1265
1826
  const current = await readRegistry(baseStateDir);
1266
1827
  await writeRegistry(baseStateDir, { ...current, runtimes: [...current.runtimes, entry] });
1267
1828
  });
1268
- /**
1269
- * The unwired verdict for THIS install, tracked locally rather than read back out of
1270
- * `unwiredRuntimes`, so the result reports what this call did and never a leftover verdict
1271
- * from an earlier runtime that happened to share the id. Set at each of the three sites that
1272
- * leave the runtime without live entry scanners; cleared by the wire-success path.
1273
- */
1274
- let unwiredPhase;
1829
+ // The registration's service stopped since this install began (a 10.x plugin reload): the
1830
+ // runtime belongs to the live registration, so this install hands it over instead of keeping
1831
+ // one in a stopped registration that nothing can stop or delete.
1832
+ const orphaned = () => serviceState === "stopped" || serviceStops !== stopsAtInstall;
1833
+ // Registry create fact — distinct from the runtime.started boot transition (which also fires
1834
+ // on a transient restart). Once per install, as soon as a registration runs the row: right
1835
+ // after run() here, or at the hand-off. Inside emitEvent's guard so telemetry never fails the
1836
+ // install.
1837
+ let createdEmitted = false;
1838
+ const emitCreated = () => {
1839
+ if (createdEmitted)
1840
+ return;
1841
+ createdEmitted = true;
1842
+ emitEvent(apiLogger, () => buildRuntimeCreatedEvent({ runtimeId: resolvedId, address: wallet, recipeName: runtimeName }));
1843
+ };
1844
+ const handOffInstall = async () => {
1845
+ const handOff = await handOffRuntime(resolvedId, walletKey);
1846
+ if (handOff.outcome === "running" || handOff.outcome === "booted" || handOff.outcome === "pending")
1847
+ emitCreated();
1848
+ return installHandOffResult(handOff, { id: resolvedId, name: runtimeName, wallet });
1849
+ };
1275
1850
  try {
1276
- const scannerProviders = await createScannerProvidersForRun({
1277
- mcpTransport,
1278
- apiKey,
1279
- });
1280
- const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
1281
- const handle = await run(pathOrContent, {
1282
- fromPath: hasPath,
1283
- stateDir: entryStateDir,
1284
- mcpTransport,
1285
- apiKey,
1286
- scannerProviders,
1851
+ // Stopped before the start: do not start a runtime here at all.
1852
+ if (orphaned())
1853
+ return await handOffInstall();
1854
+ const started = await startRuntimeLive({
1287
1855
  runtimeId: resolvedId,
1288
- onStrategyNotActive: (address) => reaper.checkWallet(address),
1289
- });
1290
- runtimeHandles.set(resolvedId, handle);
1291
- // Registry create fact — distinct from the runtime.started boot transition (which also fires
1292
- // on a transient restart). Emitted inside emitEvent's guard so telemetry never fails the install.
1293
- emitEvent(apiLogger, () => buildRuntimeCreatedEvent({ runtimeId: resolvedId, address: wallet, recipeName: runtimeName }));
1294
- // ── hot-install supervised scanner wire ───────────────────────────────
1295
- // Live-install path: used when a runtime is registered after boot via
1296
- // senpi.installRuntime, while the API is already listening — the
1297
- // counterpart to the boot-time `launcher` above. A runtime takes exactly
1298
- // one path: boot-present → `launcher` (deferred start); installed live →
1299
- // `hotLauncher` (immediate start). The two are mutually exclusive because
1300
- // installRuntime rejects any id/wallet already in the registry before
1301
- // wiring (the hasId guard), so a boot-present runtime never re-enters here.
1302
- // The API is already listening at this point, so we wire and start
1303
- // immediately (no deferred start needed). Any failure is swallowed so
1304
- // the install itself is not rolled back — the runtime is already up.
1305
- // Gate on the same API-disabled flag as the boot path: when the HTTP API
1306
- // is off (a test-only seam), the /signals route is never mounted, so
1307
- // starting scanners would only spawn children that POST to a closed port.
1308
- if (parsedConfig &&
1309
- sharedIntakeContext &&
1310
- process.env.SENPI_RUNTIME_API_DISABLED !== "true") {
1311
- try {
1312
- const apiConfig = loadApiConfig(api.pluginConfig);
1313
- const scaffoldPackageDir = fileURLToPath(new URL("./scanners/external", import.meta.url));
1314
- const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
1315
- const hotLauncher = wireRuntime({
1316
- runtimeConfig: parsedConfig,
1317
- recipeDir: hasPath ? dirname(pathOrContent) : runtimeYamlDir,
1318
- runtimeId: resolvedId,
1319
- wallet,
1320
- sharedCtx: sharedIntakeContext,
1321
- runtimeHandles,
1322
- intakeUrl: intakeUrlFor(apiConfig.host, apiConfig.port),
1323
- scaffoldPackageDir,
1324
- runtimeStateDir: entryStateDir,
1325
- logger: apiLogger,
1326
- });
1327
- if (hotLauncher) {
1328
- try {
1329
- await hotLauncher.start();
1330
- launchers.set(resolvedId, hotLauncher);
1331
- unwiredRuntimes.delete(resolvedId);
1332
- unwiredPhase = undefined;
1333
- runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1334
- unwired: false,
1335
- rows: hotLauncher.describeSupervision(),
1336
- }));
1337
- }
1338
- catch (startErr) {
1339
- await hotLauncher.stop().catch(() => { });
1340
- unwiredRuntimes.set(resolvedId, "install_launch");
1341
- unwiredPhase = "install_launch";
1342
- runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1343
- unwired: true,
1344
- unwiredPhase: "install_launch",
1345
- rows: [],
1346
- }));
1347
- eventScannersUnwired("install_launch", resolvedId, wallet, appendCause("[senpi-runtime] hot-install supervised scanner launch failed — runtime running without it", startErr), startErr);
1348
- }
1349
- }
1350
- }
1351
- catch (wireErr) {
1352
- // Wire failure must NOT fail the install — the runtime is already up. It IS reported
1353
- // across the result boundary (payload.unwired) so a funding caller can refuse it.
1354
- unwiredRuntimes.set(resolvedId, "install_wire");
1355
- unwiredPhase = "install_wire";
1356
- runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1357
- unwired: true,
1358
- unwiredPhase: "install_wire",
1359
- rows: [],
1360
- }));
1361
- eventScannersUnwired("install_wire", resolvedId, wallet, appendCause("[senpi-runtime] hot-install wiring failed — runtime running without supervised scanners", wireErr), wireErr);
1362
- }
1363
- }
1364
- else if (parsedConfig && !sharedIntakeContext && selectScanners(parsedConfig).length > 0) {
1365
- // Supervised intake is DISABLED for the whole box (corrupt acceptance record).
1366
- // The wire block above is skipped, so this hot-installed runtime declares
1367
- // external scanners but has NO live entry scanners. Record that fail-closed
1368
- // state (state only, no new event) so listRuntimes/health don't lie.
1369
- unwiredRuntimes.set(resolvedId, "no_intake");
1370
- unwiredPhase = "no_intake";
1371
- runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1372
- unwired: true,
1373
- unwiredPhase: "no_intake",
1374
- rows: [],
1375
- }));
1376
- }
1377
- // ──────────────────────────────────────────────────────────────────────
1856
+ pathOrContent,
1857
+ fromPath: hasPath,
1858
+ recipeDir: hasPath ? dirname(pathOrContent) : runtimeYamlDir,
1859
+ wallet,
1860
+ parsedConfig,
1861
+ }, orphaned, emitCreated);
1862
+ if (started.status === "orphaned")
1863
+ return await handOffInstall();
1378
1864
  return {
1379
1865
  ok: true,
1380
1866
  payload: {
1381
1867
  id: resolvedId,
1382
1868
  name: runtimeName,
1383
1869
  wallet,
1384
- ...(unwiredPhase ? { unwired: unwiredPhase } : {}),
1870
+ ...(started.unwiredPhase ? { unwired: started.unwiredPhase } : {}),
1385
1871
  },
1386
1872
  };
1387
1873
  }
1388
1874
  catch (err) {
1875
+ // run() threw after this registration's service stopped: the live registration may already
1876
+ // run this row (its boot read it), so it decides, not this catch. It runs it, or starts it,
1877
+ // or (no registration live yet) the next start does; only when it cannot start the row
1878
+ // either is the row removed, as below for an install with no reload.
1879
+ if (orphaned()) {
1880
+ const handOff = await handOffRuntime(resolvedId, walletKey);
1881
+ if (handOff.outcome !== "failed") {
1882
+ if (handOff.outcome !== "no-row")
1883
+ emitCreated();
1884
+ return installHandOffResult(handOff, { id: resolvedId, name: runtimeName, wallet });
1885
+ }
1886
+ }
1389
1887
  await withRegistryLock(baseStateDir, async () => {
1390
1888
  const current = await readRegistry(baseStateDir);
1391
1889
  await writeRegistry(baseStateDir, { ...current, runtimes: current.runtimes.filter((e) => e.id !== resolvedId) });
@@ -1450,6 +1948,12 @@ const senpiRuntimePlugin = {
1450
1948
  * unwired-verdict cleanup all happen exactly once, here.
1451
1949
  */
1452
1950
  async function deleteRuntimeCore(params) {
1951
+ // This registration's service stopped (a 10.x reload) and holds no runtimes; the live one does.
1952
+ // A delete from here (a deploy job from before the reload) would remove the row and archive the
1953
+ // state dir under a runtime that keeps trading.
1954
+ const live = liveHostIfStopped();
1955
+ if (live)
1956
+ return live.deleteRuntime(params);
1453
1957
  let targetId = typeof params?.id === "string" ? params.id : undefined;
1454
1958
  const targetAddress = typeof params?.address === "string" ? params.address : undefined;
1455
1959
  // Set only by the lifecycle reaper: why the strategy counts as gone (stamped on runtime.deleted)
@@ -1687,7 +2191,7 @@ const senpiRuntimePlugin = {
1687
2191
  * the strategy id is read for this one wallet; a failed read logs its reason and sends nothing.
1688
2192
  */
1689
2193
  function queueFactsSend(runtimeId, strategyIds) {
1690
- return factsSendLock.withKeyLock(runtimeId, async () => {
2194
+ return factsSendLock().withKeyLock(runtimeId, async () => {
1691
2195
  const { readRegistry } = await import("./runtime/strategy-registry.js");
1692
2196
  const entry = (await readRegistry(baseStateDir)).runtimes.find((e) => e.id === runtimeId);
1693
2197
  const inputs = entry ? factsPlanInputs(entry) : null;
@@ -1946,16 +2450,21 @@ const senpiRuntimePlugin = {
1946
2450
  },
1947
2451
  registryFindByWallet: findRegistryEntryByWallet,
1948
2452
  registryFindById: findRegistryEntryById,
1949
- getScannerRows: readScannerRows,
2453
+ // A deploy job outlives a reload; it reads the runtime where it runs (see `liveHostIfStopped`).
2454
+ getScannerRows: (id) => liveHostIfStopped()?.getScannerRows(id) ?? readScannerRows(id),
1950
2455
  // H4: `runtimeHandles` holds the live `run()` handles. A registry row without one is a
1951
2456
  // previous install whose runtime died before start — deploy must reinstall, not report it
1952
2457
  // adopted. `unwiredRuntimes` is the same judgement one step further in: a runtime that is up
1953
2458
  // but whose entry scanners never wired is running BLIND (the health surface already renders
1954
2459
  // it "running — NO ENTRY SCANNERS"), and reporting `install: skipped` over it would be the
1955
2460
  // same clean line over a runtime that cannot tick.
1956
- runtimeIsLive: async (id) => runtimeHandles.has(id) && !unwiredRuntimes.has(id),
2461
+ runtimeIsLive: async (id) => liveHostIfStopped()?.runtimeIsLive(id) ?? (runtimeHandles.has(id) && !unwiredRuntimes.has(id)),
1957
2462
  installPendingOnWallet: async (wallet) => installsInFlight.has(wallet.trim().toLowerCase()),
1958
- logger: { info: (line) => api.logger.info(`[senpi-runtime] ${line}`) },
2463
+ // The process logger, not this registration's: a deploy job outlives a reload.
2464
+ logger: {
2465
+ info: (line) => processLog.info(`[senpi-runtime] ${line}`),
2466
+ warn: (line) => processLog.warn(`[senpi-runtime] ${line}`),
2467
+ },
1959
2468
  });
1960
2469
  /**
1961
2470
  * Gateway shim for `senpi.ingestExternalScannerData`.
@@ -2158,6 +2667,8 @@ const senpiRuntimePlugin = {
2158
2667
  respond(true, {
2159
2668
  status: status ? { ...status, runtimeId } : null,
2160
2669
  updater,
2670
+ approvals: approvalsStatus(),
2671
+ deploy: { capabilities: DEPLOY_CAPABILITIES },
2161
2672
  });
2162
2673
  }
2163
2674
  catch (err) {
@@ -2170,7 +2681,7 @@ const senpiRuntimePlugin = {
2170
2681
  return;
2171
2682
  }
2172
2683
  const statuses = await collectRuntimeHealthStatuses(runtimeHandles, api.logger);
2173
- respond(true, { statuses, updater });
2684
+ respond(true, { statuses, updater, approvals: approvalsStatus(), deploy: { capabilities: DEPLOY_CAPABILITIES } });
2174
2685
  }, { scope: "operator.read" });
2175
2686
  api.registerGatewayMethod("senpi.getSystemState", async (ctx) => {
2176
2687
  const respond = ctx.respond;