@senpi-ai/runtime 3.0.77 → 3.0.80

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 (167) hide show
  1. package/README.md +76 -2
  2. package/dist/cli/deploy-render.d.ts +93 -0
  3. package/dist/cli/deploy-render.d.ts.map +1 -0
  4. package/dist/cli/deploy-render.js +438 -0
  5. package/dist/cli/deploy-render.js.map +1 -0
  6. package/dist/cli/guide-commands.d.ts.map +1 -1
  7. package/dist/cli/guide-commands.js +94 -9
  8. package/dist/cli/guide-commands.js.map +1 -1
  9. package/dist/cli/senpi-commands.d.ts +6 -1
  10. package/dist/cli/senpi-commands.d.ts.map +1 -1
  11. package/dist/cli/senpi-commands.js +290 -41
  12. package/dist/cli/senpi-commands.js.map +1 -1
  13. package/dist/cli/validate-command.d.ts.map +1 -1
  14. package/dist/cli/validate-command.js +10 -1
  15. package/dist/cli/validate-command.js.map +1 -1
  16. package/dist/deploy/deadlines.d.ts +107 -0
  17. package/dist/deploy/deadlines.d.ts.map +1 -0
  18. package/dist/deploy/deadlines.js +139 -0
  19. package/dist/deploy/deadlines.js.map +1 -0
  20. package/dist/deploy/error-text.d.ts +25 -0
  21. package/dist/deploy/error-text.d.ts.map +1 -0
  22. package/dist/deploy/error-text.js +42 -0
  23. package/dist/deploy/error-text.js.map +1 -0
  24. package/dist/deploy/funding.d.ts +125 -0
  25. package/dist/deploy/funding.d.ts.map +1 -0
  26. package/dist/deploy/funding.js +268 -0
  27. package/dist/deploy/funding.js.map +1 -0
  28. package/dist/deploy/install-gate-runner.d.ts +12 -0
  29. package/dist/deploy/install-gate-runner.d.ts.map +1 -0
  30. package/dist/deploy/install-gate-runner.js +17 -0
  31. package/dist/deploy/install-gate-runner.js.map +1 -0
  32. package/dist/deploy/job.d.ts +215 -0
  33. package/dist/deploy/job.d.ts.map +1 -0
  34. package/dist/deploy/job.js +484 -0
  35. package/dist/deploy/job.js.map +1 -0
  36. package/dist/deploy/messages.d.ts +603 -0
  37. package/dist/deploy/messages.d.ts.map +1 -0
  38. package/dist/deploy/messages.js +1388 -0
  39. package/dist/deploy/messages.js.map +1 -0
  40. package/dist/deploy/min-budget.d.ts +68 -0
  41. package/dist/deploy/min-budget.d.ts.map +1 -0
  42. package/dist/deploy/min-budget.js +297 -0
  43. package/dist/deploy/min-budget.js.map +1 -0
  44. package/dist/deploy/orchestrator.d.ts +314 -0
  45. package/dist/deploy/orchestrator.d.ts.map +1 -0
  46. package/dist/deploy/orchestrator.js +2171 -0
  47. package/dist/deploy/orchestrator.js.map +1 -0
  48. package/dist/deploy/package.d.ts +228 -0
  49. package/dist/deploy/package.d.ts.map +1 -0
  50. package/dist/deploy/package.js +542 -0
  51. package/dist/deploy/package.js.map +1 -0
  52. package/dist/deploy/proof-gate.d.ts +86 -0
  53. package/dist/deploy/proof-gate.d.ts.map +1 -0
  54. package/dist/deploy/proof-gate.js +278 -0
  55. package/dist/deploy/proof-gate.js.map +1 -0
  56. package/dist/deploy/python-float.d.ts +34 -0
  57. package/dist/deploy/python-float.d.ts.map +1 -0
  58. package/dist/deploy/python-float.js +46 -0
  59. package/dist/deploy/python-float.js.map +1 -0
  60. package/dist/deploy/recheck-commands.d.ts +50 -0
  61. package/dist/deploy/recheck-commands.d.ts.map +1 -0
  62. package/dist/deploy/recheck-commands.js +77 -0
  63. package/dist/deploy/recheck-commands.js.map +1 -0
  64. package/dist/deploy/register.d.ts +101 -0
  65. package/dist/deploy/register.d.ts.map +1 -0
  66. package/dist/deploy/register.js +714 -0
  67. package/dist/deploy/register.js.map +1 -0
  68. package/dist/deploy/taxonomy.d.ts +43 -0
  69. package/dist/deploy/taxonomy.d.ts.map +1 -0
  70. package/dist/deploy/taxonomy.js +59 -0
  71. package/dist/deploy/taxonomy.js.map +1 -0
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +467 -222
  74. package/dist/index.js.map +1 -1
  75. package/dist/runtime/env-resolve.d.ts +13 -0
  76. package/dist/runtime/env-resolve.d.ts.map +1 -1
  77. package/dist/runtime/env-resolve.js +14 -1
  78. package/dist/runtime/env-resolve.js.map +1 -1
  79. package/dist/runtime/runtime-descriptor.d.ts +37 -0
  80. package/dist/runtime/runtime-descriptor.d.ts.map +1 -0
  81. package/dist/runtime/runtime-descriptor.js +163 -0
  82. package/dist/runtime/runtime-descriptor.js.map +1 -0
  83. package/dist/runtime/runtime-schema.d.ts +100 -100
  84. package/dist/runtime/strategy-registry.d.ts +8 -0
  85. package/dist/runtime/strategy-registry.d.ts.map +1 -1
  86. package/dist/runtime/strategy-registry.js +14 -1
  87. package/dist/runtime/strategy-registry.js.map +1 -1
  88. package/dist/runtime-api/intake/intake-mount.d.ts.map +1 -1
  89. package/dist/runtime-api/intake/intake-mount.js +7 -4
  90. package/dist/runtime-api/intake/intake-mount.js.map +1 -1
  91. package/dist/scanners/external/scaffold/preflight.py +39 -0
  92. package/dist/scanners/implementations/market-regime.d.ts +1 -1
  93. package/dist/senpi/client.d.ts +58 -4
  94. package/dist/senpi/client.d.ts.map +1 -1
  95. package/dist/senpi/client.js +262 -18
  96. package/dist/senpi/client.js.map +1 -1
  97. package/dist/senpi/strategy-status.d.ts +32 -0
  98. package/dist/senpi/strategy-status.d.ts.map +1 -0
  99. package/dist/senpi/strategy-status.js +70 -0
  100. package/dist/senpi/strategy-status.js.map +1 -0
  101. package/dist/senpi/types.d.ts +65 -3
  102. package/dist/senpi/types.d.ts.map +1 -1
  103. package/dist/skills-manager/manifest.d.ts.map +1 -1
  104. package/dist/skills-manager/manifest.js +4 -3
  105. package/dist/skills-manager/manifest.js.map +1 -1
  106. package/dist/skills-manager/skills-manifest.json +4 -3
  107. package/dist/telemetry/metrics.d.ts +30 -0
  108. package/dist/telemetry/metrics.d.ts.map +1 -1
  109. package/dist/telemetry/metrics.js +72 -0
  110. package/dist/telemetry/metrics.js.map +1 -1
  111. package/dist/types/strategy.d.ts +9 -1
  112. package/dist/types/strategy.d.ts.map +1 -1
  113. package/dist/universe/package-universe.d.ts +97 -0
  114. package/dist/universe/package-universe.d.ts.map +1 -0
  115. package/dist/universe/package-universe.js +304 -0
  116. package/dist/universe/package-universe.js.map +1 -0
  117. package/dist/validate/codes.d.ts +30 -0
  118. package/dist/validate/codes.d.ts.map +1 -1
  119. package/dist/validate/codes.js +74 -1
  120. package/dist/validate/codes.js.map +1 -1
  121. package/dist/validate/index.d.ts +1 -1
  122. package/dist/validate/index.d.ts.map +1 -1
  123. package/dist/validate/index.js.map +1 -1
  124. package/dist/validate/install-gate.d.ts.map +1 -1
  125. package/dist/validate/install-gate.js +10 -2
  126. package/dist/validate/install-gate.js.map +1 -1
  127. package/dist/validate/live-instruments.d.ts +44 -0
  128. package/dist/validate/live-instruments.d.ts.map +1 -0
  129. package/dist/validate/live-instruments.js +71 -0
  130. package/dist/validate/live-instruments.js.map +1 -0
  131. package/dist/validate/live-stage.d.ts +8 -0
  132. package/dist/validate/live-stage.d.ts.map +1 -1
  133. package/dist/validate/live-stage.js +87 -18
  134. package/dist/validate/live-stage.js.map +1 -1
  135. package/dist/validate/package-gates-stage.d.ts +61 -0
  136. package/dist/validate/package-gates-stage.d.ts.map +1 -0
  137. package/dist/validate/package-gates-stage.js +215 -0
  138. package/dist/validate/package-gates-stage.js.map +1 -0
  139. package/dist/validate/proof.d.ts +11 -1
  140. package/dist/validate/proof.d.ts.map +1 -1
  141. package/dist/validate/proof.js +10 -6
  142. package/dist/validate/proof.js.map +1 -1
  143. package/dist/validate/recipe-checks.d.ts.map +1 -1
  144. package/dist/validate/recipe-checks.js +6 -4
  145. package/dist/validate/recipe-checks.js.map +1 -1
  146. package/dist/validate/run.d.ts +29 -1
  147. package/dist/validate/run.d.ts.map +1 -1
  148. package/dist/validate/run.js +65 -6
  149. package/dist/validate/run.js.map +1 -1
  150. package/dist/validate/target.d.ts +41 -0
  151. package/dist/validate/target.d.ts.map +1 -1
  152. package/dist/validate/target.js +192 -16
  153. package/dist/validate/target.js.map +1 -1
  154. package/dist/validate/taxonomy-finding.d.ts +22 -0
  155. package/dist/validate/taxonomy-finding.d.ts.map +1 -0
  156. package/dist/validate/taxonomy-finding.js +25 -0
  157. package/dist/validate/taxonomy-finding.js.map +1 -0
  158. package/dist/validate/universe-stage.d.ts +71 -0
  159. package/dist/validate/universe-stage.d.ts.map +1 -0
  160. package/dist/validate/universe-stage.js +165 -0
  161. package/dist/validate/universe-stage.js.map +1 -0
  162. package/dist/validate/wallet-binding-stage.d.ts +44 -0
  163. package/dist/validate/wallet-binding-stage.d.ts.map +1 -0
  164. package/dist/validate/wallet-binding-stage.js +92 -0
  165. package/dist/validate/wallet-binding-stage.js.map +1 -0
  166. package/openclaw.plugin.json +1 -1
  167. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -14,8 +14,13 @@
14
14
  import { readFileSync } from "node:fs";
15
15
  import { join, dirname } from "node:path";
16
16
  import { SenpiClient } from "./senpi/client.js";
17
+ import { buildWalletStatusHint } from "./senpi/strategy-status.js";
18
+ import { DeployJobController } from "./deploy/job.js";
19
+ import { registerDeployGatewayMethods } from "./deploy/register.js";
20
+ import { INSTALL_DEADLINE_MS, WALLET_INSTALL_IN_FLIGHT_CODE } from "./deploy/deadlines.js";
17
21
  import { AuditQueryError } from "./runtime/audit-query.types.js";
18
22
  import { buildRuntimeStateDir, archiveStateDir } from "./runtime/state-layout.js";
23
+ import { describeRuntimeEntry } from "./runtime/runtime-descriptor.js";
19
24
  import { registerSenpiCli } from "./cli/senpi-commands.js";
20
25
  import { readSenpiCliStore, resolveSenpiApiKeyFromStore, resolveSenpiBaseStateDir, } from "./cli/senpi-cli-config.js";
21
26
  import { getDefaultStateDir } from "./runtime/default-state-dir.js";
@@ -113,6 +118,42 @@ const PLUGIN_MANIFEST_VERSION = readPluginManifestVersion();
113
118
  * See `runtime/auto-update/resolve-package-name.ts`.
114
119
  */
115
120
  const PLUGIN_PACKAGE_NAME = resolvePackageName();
121
+ /**
122
+ * The taxonomy code both one-runtime-per-wallet refusals lead with.
123
+ *
124
+ * `openclaw gateway call` collapses two different worlds into one process status — it catches
125
+ * whatever its RPC throws, prints `Gateway call failed: <error>` and exits 1, whether the gateway
126
+ * was unreachable or the gateway ANSWERED with a refusal. So the CLI separates them by message
127
+ * taxonomy instead: `isRefusalMessage` (`deploy/taxonomy.ts`) reads a leading bracketed code, and
128
+ * no transport failure carries one. These two refusals were bare prose, so the classifier could not
129
+ * see them and a deliberate policy decision reached its reader framed as a broken gateway — the one
130
+ * conclusion that is false here, and the one that sends whoever reads it to look at infrastructure
131
+ * instead of at their own action.
132
+ *
133
+ * ONE code for both branches. The condition is identical — this wallet already has a runtime, and
134
+ * two exit engines on one wallet's margin disagree about what is protected and stop each other's
135
+ * positions out on different floors. What differs between the two messages is only how much this
136
+ * gateway could see (a live handle, or a registry row), which the prose states and which changes
137
+ * nothing about the decision a caller has to make.
138
+ */
139
+ const WALLET_HAS_RUNTIME = "[E_WALLET_HAS_RUNTIME]";
140
+ /**
141
+ * The fence refusal's code, IMPORTED rather than spelled here — `deploy/messages.ts` renders the
142
+ * same code for the same condition on the deploy path, and two module-private literals were one
143
+ * edit away from answering two different codes for one condition. See its doc in `deadlines.ts`
144
+ * for why it lives beside the install bound both copies quote.
145
+ */
146
+ const WALLET_INSTALL_IN_FLIGHT = `[${WALLET_INSTALL_IN_FLIGHT_CODE}]`;
147
+ /**
148
+ * The id-collision refusal's code — the third gate on the same `senpi runtime create` path, and
149
+ * plausibly the one hit most often, since re-running create with the same id lands on it.
150
+ *
151
+ * A SEPARATE code from `WALLET_HAS_RUNTIME`, where those two share one: the condition here is an
152
+ * id already taken, not a wallet already under management, and the remedy differs with it — pick
153
+ * another id, rather than stop or inspect the runtime holding a margin account. Nothing about
154
+ * anyone's money is being claimed, which is precisely why it must not answer with the wallet code.
155
+ */
156
+ const RUNTIME_ID_TAKEN = "[E_RUNTIME_ID_TAKEN]";
116
157
  /**
117
158
  * OpenClaw plugin entry.
118
159
  * Boots from internal registry (installed_runtimes.json) in stateDir; does not read runtime list from config.
@@ -284,6 +325,23 @@ const senpiRuntimePlugin = {
284
325
  // cleared on a successful wire/install. senpi.listRuntimes reads it to render
285
326
  // "running — NO ENTRY SCANNERS" instead of a bare "running" for a blind runtime.
286
327
  const unwiredRuntimes = new Map();
328
+ /**
329
+ * Wallets with an install IN FLIGHT in this process, keyed by lowercased address.
330
+ *
331
+ * IN MEMORY, never persisted — the same reasoning `deploy/job.ts` gives for the single-flight
332
+ * slot. `installRuntimeCore` is in-process work, so a pending install cannot outlive this
333
+ * process: if the gateway dies mid-install, the install dies with it and the row it left
334
+ * behind is the ordinary "registry row with no live handle" case that deploy already handles by
335
+ * deleting and reinstalling. A persisted marker would need a liveness heuristic to tell those
336
+ * apart, and would wedge every install on the box after one crash.
337
+ *
338
+ * What it prevents: a deploy whose wait on an install expired (or whose job was force-
339
+ * terminated) frees its slot while the install runs on. Without this, the next deploy finds the
340
+ * row, sees no live handle, deletes it and reinstalls — and the first install then lands on top,
341
+ * clobbering `runtimeHandles` under a runtime id both installs derive identically. Two exit
342
+ * engines, one margin account: the exact state `[E_WALLET_HAS_RUNTIME]` exists to prevent.
343
+ */
344
+ const installsInFlight = new Map();
287
345
  // Dedicated logger for the runtime-api subtree — required because the
288
346
  // PluginLogger surface (info/warn/error) lacks `debug`, while the
289
347
  // Logger contract used by `runtime-api/` includes it.
@@ -382,9 +440,23 @@ const senpiRuntimePlugin = {
382
440
  restartPrefixes: [`plugins.entries.${api.id}.config.autoUpdate.lastRestartTrigger`],
383
441
  });
384
442
  }
443
+ // ── senpi deploy (detached job) ───────────────────────────────────────────
444
+ // Constructed here, ahead of registerService, because the service `start` hook below runs its
445
+ // boot scan: declaring it after would leave that reference in the temporal dead zone for any
446
+ // future refactor that starts the service earlier. The rest of the deploy wiring lives in
447
+ // src/deploy/register.ts behind an explicit context; this closure contributes collaborators only.
448
+ const deployController = new DeployJobController({
449
+ deploysDir: join(baseStateDir, "deploys"),
450
+ now: () => Date.now(),
451
+ log: (line) => api.logger.info(`[senpi-runtime] ${line}`),
452
+ });
385
453
  api.registerService({
386
454
  id: "senpi-runtime",
387
455
  async start() {
456
+ // Deploy-journal janitor: stamp anything a restart left unterminated as `interrupted`.
457
+ // It never re-enters a deploy state machine — discovery is pull-based via
458
+ // `senpi deploy status`.
459
+ await deployController.scanOnBoot();
388
460
  await autoUpdateCoordinator.start();
389
461
  // SENPI_RUNTIME_API_DISABLED=true also disables the skills coordinator.
390
462
  // Skills bootstrap performs a real `git clone` synchronously during
@@ -696,13 +768,15 @@ const senpiRuntimePlugin = {
696
768
  pluginLogger.info("[senpi-runtime] CLI registrar callback invoked — attaching senpi subcommands to program");
697
769
  registerSenpiCli(ctx.program);
698
770
  }, { commands: ["senpi"] });
699
- /** Gateway respond accepts (ok, payload?, error?) with error as { code, message }; plugin SDK types may omit the third arg. */
700
- api.registerGatewayMethod("senpi.installRuntime", async (ctx) => {
701
- const { params } = ctx;
702
- const respond = ctx.respond;
771
+ /**
772
+ * The whole `senpi.installRuntime` behaviour, callable without a gateway ctx so
773
+ * `senpi deploy` installs through the SAME gates (wallet ownership, one-runtime-per-wallet,
774
+ * scanner-path resolution) instead of a parallel path that could drift.
775
+ */
776
+ async function installRuntimeCore(params) {
703
777
  const toError = (message) => ({ code: "INVALID_REQUEST", message });
704
778
  const toUnavailable = (message) => ({ code: "UNAVAILABLE", message });
705
- const { readRegistry, writeRegistry, validateEntry, hasId, deriveRuntimeId, sanitizeId } = await import("./runtime/strategy-registry.js");
779
+ const { readRegistry, writeRegistry, validateEntry, hasId, findByWallet, deriveRuntimeId, sanitizeId } = await import("./runtime/strategy-registry.js");
706
780
  const id = typeof params?.id === "string" ? params.id : undefined;
707
781
  const runtimeYamlPath = typeof params?.runtimeYamlPath === "string" ? params.runtimeYamlPath : undefined;
708
782
  const runtimeYamlContent = typeof params?.runtimeYamlContent === "string" ? params.runtimeYamlContent : undefined;
@@ -715,12 +789,10 @@ const senpiRuntimePlugin = {
715
789
  const hasPath = runtimeYamlPath !== undefined && runtimeYamlPath.length > 0;
716
790
  const hasContent = runtimeYamlContent !== undefined;
717
791
  if (!hasPath && !hasContent) {
718
- respond(false, undefined, toError("Please provide your runtime YAML: use the create command with --path <file> or --content \"<yaml text>\"."));
719
- return;
792
+ return { ok: false, error: toError("Please provide your runtime YAML: use the create command with --path <file> or --content \"<yaml text>\".") };
720
793
  }
721
794
  if (hasPath && hasContent) {
722
- respond(false, undefined, toError("Please provide either a file path (--path) or YAML content (--content), not both."));
723
- return;
795
+ return { ok: false, error: toError("Please provide either a file path (--path) or YAML content (--content), not both.") };
724
796
  }
725
797
  const pathOrContent = runtimeYamlPath ?? runtimeYamlContent;
726
798
  // Parse YAML first to extract name, version, and wallet for ID derivation.
@@ -739,10 +811,15 @@ const senpiRuntimePlugin = {
739
811
  }
740
812
  catch (err) {
741
813
  const msg = err instanceof Error ? err.message : String(err);
742
- respond(false, undefined, toUnavailable(`Could not start the runtime. This is usually due to invalid or incomplete YAML.\n\n${msg}`));
743
- return;
814
+ return { ok: false, error: toUnavailable(`Could not start the runtime. This is usually due to invalid or incomplete YAML.\n\n${msg}`) };
744
815
  }
745
816
  // ── install gate ────────────────────────────────────────────────────
817
+ // The cwd-resolution trap (M226926 inline -c, M279357 --path) is closed by this gate's
818
+ // E_VALIDATE_UNRESOLVABLE_SCANNER_PATH: a relative scanner path with no source dir would
819
+ // silently resolve against the process cwd (intake-mount.ts selectScanners baseDir=undefined)
820
+ // and mount a dead scanner. A second check for the same condition used to sit immediately
821
+ // above this one; two gates on one boundary meant the message a caller saw depended on which
822
+ // ran first, so it was folded into the finding's own `fix`.
746
823
  // The schema accepts recipes that cannot trade: an entry action with no
747
824
  // reachable margin source declines every signal it will ever see, one with
748
825
  // no guardrails trades with no daily-loss ceiling, and a declared scanner
@@ -752,9 +829,12 @@ const senpiRuntimePlugin = {
752
829
  // running runtime is untouched. Deliberately NOT done at boot: that loop
753
830
  // stops every started runtime on a throw, so refusing there would take the
754
831
  // box down over one bad recipe.
755
- // Decide inside the guard, act outside it. A `return` within the `try`
756
- // would let a throw from `respond` be swallowed by the catch below and the
757
- // install proceed after we had decided to refuse it.
832
+ // Decide inside the guard, act outside it. The catch below exists to keep a
833
+ // defect in the CHECKS from failing an install, and it cannot tell one of
834
+ // those from a fault raised while acting on a refusal it already decided.
835
+ // Returning after the guard keeps the two apart, so no future statement
836
+ // added on the refusal path can be swallowed into "the gate could not run"
837
+ // and let the install proceed.
758
838
  let gateRefusal;
759
839
  try {
760
840
  const { collectRecipeFindings } = await import("./validate/recipe.js");
@@ -784,6 +864,13 @@ const senpiRuntimePlugin = {
784
864
  // themselves — log it and let the install proceed rather than blocking a
785
865
  // good recipe on our own bug.
786
866
  //
867
+ // This side fails OPEN and `runDeploy`'s pre-money install gate
868
+ // (deploy/orchestrator.ts, the `deploy.install_gate` span) fails CLOSED on
869
+ // the SAME fault, deliberately: refusing a good recipe HERE blocks a
870
+ // working install, while refusing a deploy costs only a re-run, before any
871
+ // money has moved. Two boundaries, one predicate — neither branch may be
872
+ // flipped on its own.
873
+ //
787
874
  // But say so on the ledger, not only in a log line. Proceeding ungated is
788
875
  // silent by construction: the install succeeds, nothing looks wrong, and
789
876
  // protection has reverted to what it was before the gate existed — for
@@ -800,223 +887,294 @@ const senpiRuntimePlugin = {
800
887
  pluginLogger.warn(appendCause("[senpi-runtime] install gate could not run — proceeding without it", gateErr));
801
888
  }
802
889
  if (gateRefusal !== undefined) {
803
- respond(false, undefined, toError(gateRefusal));
804
- return;
890
+ return { ok: false, error: toError(gateRefusal) };
805
891
  }
806
892
  const registry = await readRegistry(baseStateDir);
807
893
  const resolvedId = id && id.length > 0
808
894
  ? (sanitizeId(id) || "runtime")
809
895
  : deriveRuntimeId(runtimeName, wallet);
896
+ const walletKey = (wallet ?? "").trim().toLowerCase();
810
897
  if (hasId(registry, resolvedId)) {
811
- respond(false, undefined, toError(`A runtime with id "${resolvedId}" already exists. Use a different id (e.g. --runtime-id another-name) or remove the existing one first: openclaw senpi runtime delete ${resolvedId}`));
812
- return;
813
- }
814
- // Enforce one running runtime per wallet address
815
- if (wallet) {
816
- for (const [existingId, existingHandle] of runtimeHandles) {
817
- if (existingHandle.wallet === wallet) {
818
- respond(false, undefined, toError(`A runtime for wallet "${wallet}" is already running (runtime "${existingId}"). ` +
819
- `Stop it first: openclaw senpi runtime delete --id ${existingId}`));
820
- return;
898
+ return { ok: false, error: toError(`${RUNTIME_ID_TAKEN} A runtime with id "${resolvedId}" already exists. Use a different id (e.g. --runtime-id another-name) or remove the existing one first: openclaw senpi runtime delete ${resolvedId}`) };
899
+ }
900
+ /**
901
+ * One runtime per wallet address — asked of PERSISTED state, not only of this process.
902
+ *
903
+ * Two engines on one wallet is not a tidiness problem: each keeps its own high-water state,
904
+ * so they disagree about what is protected and stop each other's positions out on different
905
+ * floors, against one margin account.
906
+ *
907
+ * The live-handle half alone could not carry that guarantee, because it is blind in exactly
908
+ * the window where it is needed. A runtime that is INSTALLED but not running right now — its
909
+ * boot failed, or the box came up and it never started — has a registry row and no handle,
910
+ * so the loop below sees nothing and lets a second row land on the same wallet. Nothing
911
+ * reconciles the two afterwards: the registry has no uniqueness on `wallet`, and the boot
912
+ * loop starts every row it can resolve. The restart that fixes the first runtime is the one
913
+ * that brings up both.
914
+ *
915
+ * Both halves are kept because they answer different questions and the answers differ:
916
+ * a live handle proves a runtime is trading NOW (and names the stop-it-first step), while a
917
+ * registry row proves one is installed and will be started at the next boot. Case-folded on
918
+ * both, because the registry stores `strategy.wallet` verbatim from the YAML and a
919
+ * checksummed address is the same margin account as its lowercase spelling.
920
+ */
921
+ // Gated on the FOLDED key, not on the raw field. `strategy.wallet` only has to be
922
+ // `z.string().min(1)`, so a whitespace-only value reaches here with `walletKey === ""` — and
923
+ // an empty key is not an identity: the live-handle compare below folds the same way, so `""`
924
+ // matched every handle carrying no wallet at all and refused the install with
925
+ // `[E_WALLET_HAS_RUNTIME]` naming an unrelated runtime. (`findByWallet` already refuses to
926
+ // match on an empty address for exactly this reason, and the fence is keyed on `walletKey`
927
+ // too, so a blank one is never set.) Nothing is skipped that could have matched.
928
+ if (walletKey) {
929
+ const inFlight = installsInFlight.get(walletKey);
930
+ if (inFlight) {
931
+ const heldSec = Math.round((Date.now() - inFlight.startedAtMs) / 1000);
932
+ const boundSec = Math.round(INSTALL_DEADLINE_MS / 1000);
933
+ return { ok: false, error: toError(`${WALLET_INSTALL_IN_FLIGHT} An install is already running on wallet "${wallet}" ` +
934
+ `(runtime "${inFlight.runtimeId}", started ${heldSec}s ago) in this gateway. Installing a ` +
935
+ `second runtime on the same wallet would put two exit engines on one margin account. ` +
936
+ `Nothing was installed and nothing was changed. This normally clears on its own once that ` +
937
+ `install finishes. A deploy's own install bound is ${boundSec}s — well past that, this install ` +
938
+ `is more likely wedged than merely slow, and if so the fence on this wallet will not clear ` +
939
+ `until this gateway process restarts. Check what it produced before installing anything here: ` +
940
+ `openclaw senpi deploy status, then openclaw senpi runtime list.`) };
941
+ }
942
+ const liveId = [...runtimeHandles].find(([, handle]) => (handle.wallet ?? "").trim().toLowerCase() === walletKey)?.[0];
943
+ // Which runtime holds this wallet, from either read. The live half matches on
944
+ // `handle.wallet`, the registry half on `entry.wallet`, so the id is what they have in
945
+ // common — and it is the id, not which read matched, that the two messages differ on.
946
+ const holderId = liveId ?? findByWallet(registry, wallet)?.id;
947
+ if (holderId !== undefined) {
948
+ // "running" vs "installed and not running" is asked of THAT id — the same predicate
949
+ // `senpi.listRuntimes` renders "stopped" from — rather than inferred from which of the
950
+ // two reads found it. They agree in practice; the refusal has to agree with the surface
951
+ // it sends the reader to, because that is where the reader checks it.
952
+ if (runtimeHandles.has(holderId)) {
953
+ return { ok: false, error: toError(`${WALLET_HAS_RUNTIME} A runtime for wallet "${wallet}" is already running (runtime "${holderId}"). ` +
954
+ `Stop it first: openclaw senpi runtime delete --id ${holderId}`) };
821
955
  }
956
+ return { ok: false, error: toError(
957
+ // What is CLAIMED here is only what the two reads above prove: a registry row exists,
958
+ // and this gateway has no live handle under its id. Not "it crashed", not "it is
959
+ // broken" — neither was read, and the boot loop will not necessarily manage to start
960
+ // it either (a boot that already failed once fails again), so the claim is that the
961
+ // next restart TRIES. The next step leads with the read, because the operator has to
962
+ // find out which of the two runtimes they actually want before removing either, and
963
+ // deleting the wrong one leaves a funded wallet watched by nothing.
964
+ `${WALLET_HAS_RUNTIME} A runtime for wallet "${wallet}" is already installed (runtime "${holderId}"). ` +
965
+ `It is not running in this gateway right now, but it is in the registry, so the next ` +
966
+ `restart will try to start it — installing a second runtime on the same wallet would ` +
967
+ `put two exit engines on one wallet's margin, each tracking its own high-water floor. ` +
968
+ `Nothing was installed. See what that runtime is before removing anything: ` +
969
+ `openclaw senpi runtime list. If it is genuinely unwanted, remove it first: ` +
970
+ `openclaw senpi runtime delete --id ${holderId}`) };
822
971
  }
823
972
  }
824
- // Best-effort wallet ownership validation: calls the MCP server to check
825
- // whether the wallet belongs to the authenticated user's strategies.
826
- // If the MCP call fails (network issue, bad apiKey, server down), we warn
827
- // and allow the install to proceed rather than blocking the user.
828
- if (wallet) {
829
- try {
830
- const client = mcpTransport
831
- ? new SenpiClient(mcpTransport)
832
- : new SenpiClient({ apiKey });
833
- if (!mcpTransport)
834
- await client.connect();
973
+ if (walletKey)
974
+ installsInFlight.set(walletKey, { runtimeId: resolvedId, startedAtMs: Date.now() });
975
+ try {
976
+ // Best-effort wallet ownership validation: calls the MCP server to check
977
+ // whether the wallet belongs to the authenticated user's strategies.
978
+ // If the MCP call fails (network issue, bad apiKey, server down), we warn
979
+ // and allow the install to proceed rather than blocking the user.
980
+ if (wallet) {
835
981
  try {
836
- const strategies = await client.listStrategies({ strategyAddresses: [wallet] });
837
- const match = strategies.find((s) => s.strategyWalletAddress.toLowerCase() === wallet.toLowerCase());
838
- if (!match) {
839
- pluginLogger.info("[senpi-runtime] Wallet validation failed: not owned", { wallet });
840
- respond(false, undefined, toError(`Strategy wallet "${wallet}" (YAML field: strategy.wallet) was not found in your Senpi account's strategies. ` +
841
- `Check the address for typos. ` +
842
- `To list all your strategies and their wallet addresses, call the MCP tool: strategy_list (no arguments needed). ` +
843
- `Each result includes "strategyWalletAddress" — use that value as strategy.wallet in your YAML.`));
844
- // `return` triggers the inner `finally` (disconnect) before exiting.
845
- return;
982
+ const client = mcpTransport
983
+ ? new SenpiClient(mcpTransport)
984
+ : new SenpiClient({ apiKey });
985
+ if (!mcpTransport)
986
+ await client.connect();
987
+ try {
988
+ const strategies = await client.listStrategies({ strategyAddresses: [wallet] });
989
+ const match = strategies.find((s) => s.strategyWalletAddress.toLowerCase() === wallet.toLowerCase());
990
+ if (!match) {
991
+ pluginLogger.info("[senpi-runtime] Wallet validation failed: not owned", { wallet });
992
+ // `return` triggers the inner `finally` (disconnect) before exiting.
993
+ return { ok: false, error: toError(`Strategy wallet "${wallet}" (YAML field: strategy.wallet) was not found in your Senpi account's strategies. ` +
994
+ `Check the address for typos. ` +
995
+ `To list all your strategies and their wallet addresses, call the MCP tool: strategy_list (no arguments needed). ` +
996
+ `Each result includes "strategyWalletAddress" — use that value as strategy.wallet in your YAML.`) };
997
+ }
998
+ if (match.status !== "ACTIVE") {
999
+ pluginLogger.info("[senpi-runtime] Wallet validation failed: strategy not active", { wallet, status: match.status, strategyId: match.id });
1000
+ return { ok: false, error: toError(
1001
+ // H7/D-10: the status vocabulary lives in one module, shared with deploy's
1002
+ // reconcile. This gate's private copy was already missing TERMINATED and
1003
+ // CLOSING_DONE, so a gone strategy fell to the generic "only ACTIVE" hint.
1004
+ `Strategy wallet "${wallet}" (YAML field: strategy.wallet) has status "${match.status}" — a runtime requires ACTIVE status. ` +
1005
+ buildWalletStatusHint(match.status) +
1006
+ ` To check the latest status, call the MCP tool: strategy_list.`) };
1007
+ }
1008
+ pluginLogger.info("[senpi-runtime] Wallet validation passed", { wallet, strategyId: match.id, status: match.status });
846
1009
  }
847
- if (match.status !== "ACTIVE") {
848
- pluginLogger.info("[senpi-runtime] Wallet validation failed: strategy not active", { wallet, status: match.status, strategyId: match.id });
849
- respond(false, undefined, toError((() => {
850
- const initializingStatuses = new Set([
851
- "SET_REFERRER_CODE", "SET_BUILDER_FEE", "SUBSCRIBE_TRADER",
852
- "CREATE_WALLET", "FUND_WALLET", "INITIALIZE_POSITIONS",
853
- ]);
854
- const terminalStatuses = new Set([
855
- "CLOSED", "FAILED", "CLOSING_POSITIONS", "CLOSE_STRATEGY",
856
- "UNSUBSCRIBE_TRADER", "FUND_SOURCE_WALLET", "INACTIVE",
857
- ]);
858
- let hint;
859
- if (initializingStatuses.has(match.status)) {
860
- hint =
861
- `The strategy is still initializing (${match.status}). ` +
862
- `It will reach ACTIVE automatically — wait a few minutes, then retry. ` +
863
- `Initialization order: CREATE_WALLET → FUND_WALLET → INITIALIZE_POSITIONS → ACTIVE.`;
864
- }
865
- else if (match.status === "PAUSED") {
866
- hint =
867
- `The strategy is paused and cannot be used to create a runtime — please create a new strategy instead.`;
868
- }
869
- else if (terminalStatuses.has(match.status)) {
870
- hint =
871
- `The strategy is closing or already closed (${match.status}). ` +
872
- `A runtime cannot be created for a closed strategy — please create a new strategy instead.`;
873
- }
874
- else {
875
- hint = `Only ACTIVE strategies can run a runtime.`;
876
- }
877
- return (`Strategy wallet "${wallet}" (YAML field: strategy.wallet) has status "${match.status}" — a runtime requires ACTIVE status. ` +
878
- hint +
879
- ` To check the latest status, call the MCP tool: strategy_list.`);
880
- })()));
881
- return;
1010
+ finally {
1011
+ if (!mcpTransport)
1012
+ await client.disconnect().catch(() => { });
882
1013
  }
883
- pluginLogger.info("[senpi-runtime] Wallet validation passed", { wallet, strategyId: match.id, status: match.status });
884
1014
  }
885
- finally {
886
- if (!mcpTransport)
887
- await client.disconnect().catch(() => { });
1015
+ catch (err) {
1016
+ // Soft-fail: validation is best-effort. If connect() or listStrategies()
1017
+ // throws, log a warning and let the install proceed.
1018
+ const msg = err instanceof Error ? err.message : String(err);
1019
+ pluginLogger.warn("[senpi-runtime] Could not validate strategy wallet ownership", { wallet, err: msg });
888
1020
  }
889
1021
  }
890
- catch (err) {
891
- // Soft-fail: validation is best-effort. If connect() or listStrategies()
892
- // throws, log a warning and let the install proceed.
893
- const msg = err instanceof Error ? err.message : String(err);
894
- pluginLogger.warn("[senpi-runtime] Could not validate strategy wallet ownership", { wallet, err: msg });
1022
+ const entry = hasPath
1023
+ ? { id: resolvedId, runtimeYamlPath, schemaVersion: parsedSchemaVersion, wallet }
1024
+ : {
1025
+ id: resolvedId,
1026
+ runtimeYamlContent: runtimeYamlContent,
1027
+ schemaVersion: parsedSchemaVersion,
1028
+ wallet,
1029
+ // Persist the recipe dir so a gateway restart can resolve an
1030
+ // external scanner's relative `path: ./` (content installs drop it).
1031
+ ...(runtimeYamlDir ? { runtimeYamlDir } : {}),
1032
+ };
1033
+ const valid = validateEntry(entry);
1034
+ if (!valid.ok) {
1035
+ return { ok: false, error: toError(valid.error) };
895
1036
  }
896
- }
897
- const entry = hasPath
898
- ? { id: resolvedId, runtimeYamlPath, schemaVersion: parsedSchemaVersion, wallet }
899
- : {
900
- id: resolvedId,
901
- runtimeYamlContent: runtimeYamlContent,
902
- schemaVersion: parsedSchemaVersion,
903
- wallet,
904
- // Persist the recipe dir so a gateway restart can resolve an
905
- // external scanner's relative `path: ./` (content installs drop it).
906
- ...(runtimeYamlDir ? { runtimeYamlDir } : {}),
907
- };
908
- const valid = validateEntry(entry);
909
- if (!valid.ok) {
910
- respond(false, undefined, toError(valid.error));
911
- return;
912
- }
913
- registry.runtimes.push(entry);
914
- await writeRegistry(baseStateDir, registry);
915
- try {
916
- const scannerProviders = await createScannerProvidersForRun({
917
- mcpTransport,
918
- apiKey,
919
- });
920
- const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
921
- const handle = await run(pathOrContent, {
922
- fromPath: hasPath,
923
- stateDir: entryStateDir,
924
- mcpTransport,
925
- apiKey,
926
- scannerProviders,
927
- runtimeId: resolvedId,
928
- });
929
- runtimeHandles.set(resolvedId, handle);
930
- // Registry create fact — distinct from the runtime.started boot transition (which also fires
931
- // on a transient restart). Emitted inside emitEvent's guard so telemetry never fails the install.
932
- emitEvent(apiLogger, () => buildRuntimeCreatedEvent({ runtimeId: resolvedId, address: wallet, recipeName: runtimeName }));
933
- // ── hot-install supervised scanner wire ───────────────────────────────
934
- // Live-install path: used when a runtime is registered after boot via
935
- // senpi.installRuntime, while the API is already listening — the
936
- // counterpart to the boot-time `launcher` above. A runtime takes exactly
937
- // one path: boot-present → `launcher` (deferred start); installed live →
938
- // `hotLauncher` (immediate start). The two are mutually exclusive because
939
- // installRuntime rejects any id/wallet already in the registry before
940
- // wiring (the hasId guard), so a boot-present runtime never re-enters here.
941
- // The API is already listening at this point, so we wire and start
942
- // immediately (no deferred start needed). Any failure is swallowed so
943
- // the install itself is not rolled back — the runtime is already up.
944
- // Gate on the same API-disabled flag as the boot path: when the HTTP API
945
- // is off (a test-only seam), the /signals route is never mounted, so
946
- // starting scanners would only spawn children that POST to a closed port.
947
- if (parsedConfig &&
948
- sharedIntakeContext &&
949
- process.env.SENPI_RUNTIME_API_DISABLED !== "true") {
950
- try {
951
- const apiConfig = loadApiConfig(api.pluginConfig);
952
- const scaffoldPackageDir = fileURLToPath(new URL("./scanners/external", import.meta.url));
953
- const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
954
- const hotLauncher = wireRuntime({
955
- runtimeConfig: parsedConfig,
956
- recipeDir: hasPath ? dirname(pathOrContent) : runtimeYamlDir,
957
- runtimeId: resolvedId,
958
- wallet,
959
- sharedCtx: sharedIntakeContext,
960
- runtimeHandles,
961
- intakeUrl: intakeUrlFor(apiConfig.host, apiConfig.port),
962
- scaffoldPackageDir,
963
- runtimeStateDir: entryStateDir,
964
- logger: apiLogger,
965
- });
966
- if (hotLauncher) {
967
- try {
968
- await hotLauncher.start();
969
- launchers.set(resolvedId, hotLauncher);
970
- unwiredRuntimes.delete(resolvedId);
971
- runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
972
- unwired: false,
973
- rows: hotLauncher.describeSupervision(),
974
- }));
975
- }
976
- catch (startErr) {
977
- await hotLauncher.stop().catch(() => { });
978
- unwiredRuntimes.set(resolvedId, "install_launch");
979
- runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
980
- unwired: true,
981
- unwiredPhase: "install_launch",
982
- rows: [],
983
- }));
984
- eventScannersUnwired("install_launch", resolvedId, wallet, appendCause("[senpi-runtime] hot-install supervised scanner launch failed — runtime running without it", startErr), startErr);
1037
+ registry.runtimes.push(entry);
1038
+ await writeRegistry(baseStateDir, registry);
1039
+ /**
1040
+ * The unwired verdict for THIS install, tracked locally rather than read back out of
1041
+ * `unwiredRuntimes`, so the result reports what this call did and never a leftover verdict
1042
+ * from an earlier runtime that happened to share the id. Set at each of the three sites that
1043
+ * leave the runtime without live entry scanners; cleared by the wire-success path.
1044
+ */
1045
+ let unwiredPhase;
1046
+ try {
1047
+ const scannerProviders = await createScannerProvidersForRun({
1048
+ mcpTransport,
1049
+ apiKey,
1050
+ });
1051
+ const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
1052
+ const handle = await run(pathOrContent, {
1053
+ fromPath: hasPath,
1054
+ stateDir: entryStateDir,
1055
+ mcpTransport,
1056
+ apiKey,
1057
+ scannerProviders,
1058
+ runtimeId: resolvedId,
1059
+ });
1060
+ runtimeHandles.set(resolvedId, handle);
1061
+ // Registry create fact — distinct from the runtime.started boot transition (which also fires
1062
+ // on a transient restart). Emitted inside emitEvent's guard so telemetry never fails the install.
1063
+ emitEvent(apiLogger, () => buildRuntimeCreatedEvent({ runtimeId: resolvedId, address: wallet, recipeName: runtimeName }));
1064
+ // ── hot-install supervised scanner wire ───────────────────────────────
1065
+ // Live-install path: used when a runtime is registered after boot via
1066
+ // senpi.installRuntime, while the API is already listening — the
1067
+ // counterpart to the boot-time `launcher` above. A runtime takes exactly
1068
+ // one path: boot-present → `launcher` (deferred start); installed live →
1069
+ // `hotLauncher` (immediate start). The two are mutually exclusive because
1070
+ // installRuntime rejects any id/wallet already in the registry before
1071
+ // wiring (the hasId guard), so a boot-present runtime never re-enters here.
1072
+ // The API is already listening at this point, so we wire and start
1073
+ // immediately (no deferred start needed). Any failure is swallowed so
1074
+ // the install itself is not rolled back — the runtime is already up.
1075
+ // Gate on the same API-disabled flag as the boot path: when the HTTP API
1076
+ // is off (a test-only seam), the /signals route is never mounted, so
1077
+ // starting scanners would only spawn children that POST to a closed port.
1078
+ if (parsedConfig &&
1079
+ sharedIntakeContext &&
1080
+ process.env.SENPI_RUNTIME_API_DISABLED !== "true") {
1081
+ try {
1082
+ const apiConfig = loadApiConfig(api.pluginConfig);
1083
+ const scaffoldPackageDir = fileURLToPath(new URL("./scanners/external", import.meta.url));
1084
+ const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
1085
+ const hotLauncher = wireRuntime({
1086
+ runtimeConfig: parsedConfig,
1087
+ recipeDir: hasPath ? dirname(pathOrContent) : runtimeYamlDir,
1088
+ runtimeId: resolvedId,
1089
+ wallet,
1090
+ sharedCtx: sharedIntakeContext,
1091
+ runtimeHandles,
1092
+ intakeUrl: intakeUrlFor(apiConfig.host, apiConfig.port),
1093
+ scaffoldPackageDir,
1094
+ runtimeStateDir: entryStateDir,
1095
+ logger: apiLogger,
1096
+ });
1097
+ if (hotLauncher) {
1098
+ try {
1099
+ await hotLauncher.start();
1100
+ launchers.set(resolvedId, hotLauncher);
1101
+ unwiredRuntimes.delete(resolvedId);
1102
+ unwiredPhase = undefined;
1103
+ runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1104
+ unwired: false,
1105
+ rows: hotLauncher.describeSupervision(),
1106
+ }));
1107
+ }
1108
+ catch (startErr) {
1109
+ await hotLauncher.stop().catch(() => { });
1110
+ unwiredRuntimes.set(resolvedId, "install_launch");
1111
+ unwiredPhase = "install_launch";
1112
+ runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1113
+ unwired: true,
1114
+ unwiredPhase: "install_launch",
1115
+ rows: [],
1116
+ }));
1117
+ eventScannersUnwired("install_launch", resolvedId, wallet, appendCause("[senpi-runtime] hot-install supervised scanner launch failed — runtime running without it", startErr), startErr);
1118
+ }
985
1119
  }
986
1120
  }
1121
+ catch (wireErr) {
1122
+ // Wire failure must NOT fail the install — the runtime is already up. It IS reported
1123
+ // across the result boundary (payload.unwired) so a funding caller can refuse it.
1124
+ unwiredRuntimes.set(resolvedId, "install_wire");
1125
+ unwiredPhase = "install_wire";
1126
+ runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1127
+ unwired: true,
1128
+ unwiredPhase: "install_wire",
1129
+ rows: [],
1130
+ }));
1131
+ eventScannersUnwired("install_wire", resolvedId, wallet, appendCause("[senpi-runtime] hot-install wiring failed — runtime running without supervised scanners", wireErr), wireErr);
1132
+ }
987
1133
  }
988
- catch (wireErr) {
989
- // Wire failure must NOT fail the install — the runtime is already up.
990
- unwiredRuntimes.set(resolvedId, "install_wire");
1134
+ else if (parsedConfig && !sharedIntakeContext && selectScanners(parsedConfig).length > 0) {
1135
+ // Supervised intake is DISABLED for the whole box (corrupt acceptance record).
1136
+ // The wire block above is skipped, so this hot-installed runtime declares
1137
+ // external scanners but has NO live entry scanners. Record that fail-closed
1138
+ // state (state only, no new event) so listRuntimes/health don't lie.
1139
+ unwiredRuntimes.set(resolvedId, "no_intake");
1140
+ unwiredPhase = "no_intake";
991
1141
  runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
992
1142
  unwired: true,
993
- unwiredPhase: "install_wire",
1143
+ unwiredPhase: "no_intake",
994
1144
  rows: [],
995
1145
  }));
996
- eventScannersUnwired("install_wire", resolvedId, wallet, appendCause("[senpi-runtime] hot-install wiring failed — runtime running without supervised scanners", wireErr), wireErr);
997
1146
  }
1147
+ // ──────────────────────────────────────────────────────────────────────
1148
+ return {
1149
+ ok: true,
1150
+ payload: {
1151
+ id: resolvedId,
1152
+ name: runtimeName,
1153
+ wallet,
1154
+ ...(unwiredPhase ? { unwired: unwiredPhase } : {}),
1155
+ },
1156
+ };
998
1157
  }
999
- else if (parsedConfig && !sharedIntakeContext && selectScanners(parsedConfig).length > 0) {
1000
- // Supervised intake is DISABLED for the whole box (corrupt acceptance record).
1001
- // The wire block above is skipped, so this hot-installed runtime declares
1002
- // external scanners but has NO live entry scanners. Record that fail-closed
1003
- // state (state only, no new event) so listRuntimes/health don't lie.
1004
- unwiredRuntimes.set(resolvedId, "no_intake");
1005
- runtimeHandles.get(resolvedId)?.attachSupervisionSource(() => ({
1006
- unwired: true,
1007
- unwiredPhase: "no_intake",
1008
- rows: [],
1009
- }));
1158
+ catch (err) {
1159
+ const next = registry.runtimes.filter((e) => e.id !== resolvedId);
1160
+ await writeRegistry(baseStateDir, { ...registry, runtimes: next });
1161
+ const msg = err instanceof Error ? err.message : String(err);
1162
+ return { ok: false, error: toUnavailable(`Could not start the runtime. This is usually due to invalid or incomplete YAML.\n\n${msg}`) };
1010
1163
  }
1011
- // ──────────────────────────────────────────────────────────────────────
1012
- respond(true, { id: resolvedId, name: runtimeName, wallet });
1013
1164
  }
1014
- catch (err) {
1015
- const next = registry.runtimes.filter((e) => e.id !== resolvedId);
1016
- await writeRegistry(baseStateDir, { ...registry, runtimes: next });
1017
- const msg = err instanceof Error ? err.message : String(err);
1018
- respond(false, undefined, toUnavailable(`Could not start the runtime. This is usually due to invalid or incomplete YAML.\n\n${msg}`));
1165
+ finally {
1166
+ if (walletKey)
1167
+ installsInFlight.delete(walletKey);
1019
1168
  }
1169
+ }
1170
+ /** Gateway respond accepts (ok, payload?, error?) with error as { code, message }; plugin SDK types may omit the third arg. */
1171
+ api.registerGatewayMethod("senpi.installRuntime", async (ctx) => {
1172
+ const respond = ctx.respond;
1173
+ const result = await installRuntimeCore(ctx.params);
1174
+ if (result.ok)
1175
+ respond(true, result.payload);
1176
+ else
1177
+ respond(false, undefined, result.error);
1020
1178
  }, { scope: "operator.write" });
1021
1179
  api.registerGatewayMethod("senpi.listRuntimes", async (ctx) => {
1022
1180
  const respond = ctx.respond;
@@ -1039,13 +1197,20 @@ const senpiRuntimePlugin = {
1039
1197
  ? e.runtimeYamlPath
1040
1198
  : "(inline)",
1041
1199
  status,
1200
+ // The deploy path installs by CONTENT, not path (orchestrator.ts installRuntime), so
1201
+ // `source` is "(inline)" for every deployed strategy and the YAML is unreachable through
1202
+ // it. The engine renders the facts instead of shipping a blob to re-interpret.
1203
+ descriptor: describeRuntimeEntry(e),
1042
1204
  };
1043
1205
  });
1044
1206
  respond(true, { runtimes });
1045
1207
  }, { scope: "operator.read" });
1046
- api.registerGatewayMethod("senpi.deleteRuntime", async (ctx) => {
1047
- const { params } = ctx;
1048
- const respond = ctx.respond;
1208
+ /**
1209
+ * The whole `senpi.deleteRuntime` behaviour, callable without a gateway ctx. `senpi deploy`
1210
+ * reuses it to retire a runtime bound to an old wallet, so archival, launcher teardown and the
1211
+ * unwired-verdict cleanup all happen exactly once, here.
1212
+ */
1213
+ async function deleteRuntimeCore(params) {
1049
1214
  const { readRegistry, writeRegistry } = await import("./runtime/strategy-registry.js");
1050
1215
  const registry = await readRegistry(baseStateDir);
1051
1216
  let targetId = typeof params?.id === "string" ? params.id : undefined;
@@ -1054,29 +1219,26 @@ const senpiRuntimePlugin = {
1054
1219
  if (!targetId && targetAddress) {
1055
1220
  const entry = registry.runtimes.find((e) => e.wallet === targetAddress);
1056
1221
  if (!entry) {
1057
- respond(false, undefined, {
1058
- code: "NOT_FOUND",
1059
- message: `No runtime found for wallet address "${targetAddress}".`,
1060
- });
1061
- return;
1222
+ return { ok: false, error: {
1223
+ code: "NOT_FOUND",
1224
+ message: `No runtime found for wallet address "${targetAddress}".`,
1225
+ } };
1062
1226
  }
1063
1227
  targetId = entry.id;
1064
1228
  }
1065
1229
  if (!targetId) {
1066
- respond(false, undefined, {
1067
- code: "INVALID_REQUEST",
1068
- message: "Please provide the runtime id or wallet address. Example: openclaw senpi runtime delete --id my-runtime",
1069
- });
1070
- return;
1230
+ return { ok: false, error: {
1231
+ code: "INVALID_REQUEST",
1232
+ message: "Please provide the runtime id or wallet address. Example: openclaw senpi runtime delete --id my-runtime",
1233
+ } };
1071
1234
  }
1072
1235
  const deletedEntry = registry.runtimes.find((e) => e.id === targetId);
1073
1236
  const handle = runtimeHandles.get(targetId);
1074
1237
  if (!deletedEntry && !handle) {
1075
- respond(false, undefined, {
1076
- code: "NOT_FOUND",
1077
- message: `No runtime found with id "${targetId}".`,
1078
- });
1079
- return;
1238
+ return { ok: false, error: {
1239
+ code: "NOT_FOUND",
1240
+ message: `No runtime found with id "${targetId}".`,
1241
+ } };
1080
1242
  }
1081
1243
  if (handle) {
1082
1244
  await handle.teardownDslForRuntimeDeletion();
@@ -1121,8 +1283,91 @@ const senpiRuntimePlugin = {
1121
1283
  address: deletedEntry?.wallet,
1122
1284
  hadLiveHandle: Boolean(handle),
1123
1285
  }));
1124
- respond(true, { id: targetId });
1286
+ return { ok: true, payload: { id: targetId } };
1287
+ }
1288
+ api.registerGatewayMethod("senpi.deleteRuntime", async (ctx) => {
1289
+ const respond = ctx.respond;
1290
+ const result = await deleteRuntimeCore(ctx.params);
1291
+ if (result.ok)
1292
+ respond(true, result.payload);
1293
+ else
1294
+ respond(false, undefined, result.error);
1125
1295
  }, { scope: "operator.write" });
1296
+ /** One connected SenpiClient per job; always disconnected, even on failure. */
1297
+ async function withSenpiClient(fn) {
1298
+ const client = mcpTransport ? new SenpiClient(mcpTransport) : new SenpiClient({ apiKey });
1299
+ if (!mcpTransport)
1300
+ await client.connect();
1301
+ try {
1302
+ return await fn(client);
1303
+ }
1304
+ finally {
1305
+ if (!mcpTransport)
1306
+ await client.disconnect().catch(() => { });
1307
+ }
1308
+ }
1309
+ async function findRegistryEntryByWallet(wallet) {
1310
+ const { readRegistry, findByWallet } = await import("./runtime/strategy-registry.js");
1311
+ const entry = findByWallet(await readRegistry(baseStateDir), wallet);
1312
+ return entry ? { id: entry.id, wallet: entry.wallet } : undefined;
1313
+ }
1314
+ async function findRegistryEntryById(id) {
1315
+ const { readRegistry } = await import("./runtime/strategy-registry.js");
1316
+ const entry = (await readRegistry(baseStateDir)).runtimes.find((e) => e.id === id);
1317
+ return entry ? { id: entry.id, wallet: entry.wallet } : undefined;
1318
+ }
1319
+ /** Narrow a live runtime's system state to the scanner columns the deploy report quotes. */
1320
+ async function readScannerRows(runtimeId) {
1321
+ const handle = runtimeHandles.get(runtimeId);
1322
+ if (!handle)
1323
+ return null;
1324
+ try {
1325
+ const state = await handle.getSystemState();
1326
+ const rows = state?.components?.scanners?.state?.scanners;
1327
+ if (!Array.isArray(rows))
1328
+ return null;
1329
+ return rows.map((row) => ({
1330
+ scannerId: row.scannerId,
1331
+ health: row.health,
1332
+ enabled: row.enabled,
1333
+ scheduleMode: row.scheduleMode,
1334
+ lastRunStatus: row.lastRunStatus,
1335
+ lastRunFinishedAt: row.lastRunFinishedAt,
1336
+ lastAliveAt: row.lastAliveAt,
1337
+ nextRunAt: row.nextRunAt,
1338
+ runCount: row.runCount,
1339
+ errorCount: row.errorCount,
1340
+ signalsProduced: row.signalsProduced,
1341
+ lastError: row.lastError,
1342
+ }));
1343
+ }
1344
+ catch (err) {
1345
+ api.logger.warn("[senpi-runtime] deploy: could not read scanner rows", { runtimeId, err });
1346
+ return null;
1347
+ }
1348
+ }
1349
+ registerDeployGatewayMethods(api, {
1350
+ controller: deployController,
1351
+ withSenpiClient,
1352
+ installRuntime: (params) => installRuntimeCore(params),
1353
+ deleteRuntime: async (id) => {
1354
+ const result = await deleteRuntimeCore({ id });
1355
+ if (!result.ok)
1356
+ throw new Error(`${result.error.code}: ${result.error.message}`);
1357
+ },
1358
+ registryFindByWallet: findRegistryEntryByWallet,
1359
+ registryFindById: findRegistryEntryById,
1360
+ getScannerRows: readScannerRows,
1361
+ // H4: `runtimeHandles` holds the live `run()` handles. A registry row without one is a
1362
+ // previous install whose runtime died before start — deploy must reinstall, not report it
1363
+ // adopted. `unwiredRuntimes` is the same judgement one step further in: a runtime that is up
1364
+ // but whose entry scanners never wired is running BLIND (the health surface already renders
1365
+ // it "running — NO ENTRY SCANNERS"), and reporting `install: skipped` over it would be the
1366
+ // same clean line over a runtime that cannot tick.
1367
+ runtimeIsLive: async (id) => runtimeHandles.has(id) && !unwiredRuntimes.has(id),
1368
+ installPendingOnWallet: async (wallet) => installsInFlight.has(wallet.trim().toLowerCase()),
1369
+ logger: { info: (line) => api.logger.info(`[senpi-runtime] ${line}`) },
1370
+ });
1126
1371
  /**
1127
1372
  * Gateway shim for `senpi.ingestExternalScannerData`.
1128
1373
  *