@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
@@ -264,6 +264,45 @@ function extractEngineMessage(data) {
264
264
  return data.errorCode;
265
265
  return "Trading engine reported failure";
266
266
  }
267
+ /**
268
+ * A short, quotable account of an unrecognizable read-tool payload, for the throw a fail-closed
269
+ * read raises. Prefers whatever the tool said about itself (an error envelope's message) and falls
270
+ * back to naming the shape — the reader has to be able to tell a backend outage from a schema
271
+ * change without reading the raw response.
272
+ */
273
+ function describeToolFailure(data) {
274
+ if (data === null || data === undefined)
275
+ return "response was empty";
276
+ if (typeof data !== "object")
277
+ return `response was ${typeof data}: ${String(data).slice(0, 200)}`;
278
+ const rec = data;
279
+ if (rec.success === false)
280
+ return `tool reported failure: ${extractEngineMessage(rec)}`;
281
+ return `response keys: ${Object.keys(rec).join(", ") || "(none)"}`;
282
+ }
283
+ /**
284
+ * The attribution stamp on a `strategy_list` row, tolerant of a JSON-encoded metadata payload.
285
+ *
286
+ * Serializer drift delivering `strategyMetadata` as a string would otherwise read as "no stamp",
287
+ * which is the fail-OPEN direction here: an unstamped candidate is one deploy's gate cannot see, so
288
+ * it would create a second wallet beside a live one. An unparseable or non-object payload stays
289
+ * `undefined` — unknown, never "not ours". See {@link StrategySummary.skillName}.
290
+ */
291
+ function readSkillName(raw) {
292
+ let meta = raw;
293
+ if (typeof meta === "string") {
294
+ try {
295
+ meta = JSON.parse(meta);
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ }
301
+ if (!isRecord(meta))
302
+ return undefined;
303
+ const name = asString(meta.skillName)?.trim();
304
+ return name ? name : undefined;
305
+ }
267
306
  /**
268
307
  * Enforces success at both response layers and returns the unwrapped
269
308
  * inner data. Throws `SenpiClientError` on any reported failure.
@@ -374,6 +413,47 @@ function assertClosePositionSucceeded(raw, ctx) {
374
413
  });
375
414
  }
376
415
  }
416
+ /**
417
+ * The error an abandoned MCP call reports. Deliberately says the outcome is UNKNOWN rather than
418
+ * "failed": the request may well have landed, and a caller that moves money must not read a
419
+ * timeout as "nothing happened".
420
+ */
421
+ function abortedCallError(toolName, signal) {
422
+ const reason = signal.reason;
423
+ if (reason instanceof Error && reason.name !== "TimeoutError")
424
+ return reason;
425
+ const err = new Error(`MCP call ${toolName} exceeded its deadline and was abandoned — the request may still be ` +
426
+ `in flight on the server, so nothing about its outcome is known`);
427
+ err.name = "AbortError";
428
+ return err;
429
+ }
430
+ /**
431
+ * Stop awaiting `promise` once `signal` aborts.
432
+ *
433
+ * Used for the gateway-injected MCP transport, which accepts no abort options: the remote call
434
+ * keeps running, so this bounds the WAIT, not the work. That is still the property callers need —
435
+ * a deploy step boundary becomes reachable, and the job watchdog can free the single-flight slot
436
+ * instead of parking on a call that never answers. The orphaned promise always keeps a rejection
437
+ * handler attached, so a late failure can never surface as an unhandled rejection.
438
+ */
439
+ function boundAwait(promise, signal, toolName) {
440
+ if (signal.aborted) {
441
+ // Never wait on work we are already unwilling to wait for.
442
+ promise.catch(() => { });
443
+ return Promise.reject(abortedCallError(toolName, signal));
444
+ }
445
+ return new Promise((resolve, reject) => {
446
+ const onAbort = () => reject(abortedCallError(toolName, signal));
447
+ signal.addEventListener("abort", onAbort, { once: true });
448
+ promise.then((value) => {
449
+ signal.removeEventListener("abort", onAbort);
450
+ resolve(value);
451
+ }, (err) => {
452
+ signal.removeEventListener("abort", onAbort);
453
+ reject(err);
454
+ });
455
+ });
456
+ }
377
457
  export class SenpiClient {
378
458
  // Injected mode
379
459
  injectedTransport;
@@ -549,9 +629,16 @@ export class SenpiClient {
549
629
  { kind: SpanKind.CLIENT });
550
630
  }
551
631
  async callToolInner(toolName, args, opts) {
552
- // Injected mode: delegate directly
632
+ // Injected mode: delegate directly. `McpTransport` takes no options, so an abort cannot
633
+ // cancel the remote work — but the AWAIT is still bounded, which is the half that matters to
634
+ // a caller with a deadline (`senpi deploy`'s D-5 per-call bound runs on this path in
635
+ // production). Without this, `opts.signal` was silently dropped here and the bound was a
636
+ // no-op on every agent box.
553
637
  if (this.injectedTransport) {
554
- return this.injectedTransport(toolName, args);
638
+ if (opts?.signal?.aborted)
639
+ throw abortedCallError(toolName, opts.signal);
640
+ const call = this.injectedTransport(toolName, args);
641
+ return opts?.signal ? boundAwait(call, opts.signal, toolName) : call;
555
642
  }
556
643
  // Self-managed mode: lazily (re)connect on demand, then call via MCP client.
557
644
  await this.ensureConnected();
@@ -831,8 +918,12 @@ export class SenpiClient {
831
918
  */
832
919
  async getClearingHouseState(wallet, opts) {
833
920
  const retryUnreadable = opts?.retryUnreadable === true;
921
+ // One signal deliberately SHARED across every attempt: this ladder bounds attempt COUNT, not
922
+ // wall time, so without a shared deadline a caller has no bound at all. An
923
+ // `AbortSignal.timeout(N)` fires N ms after creation however many attempts have run — which is
924
+ // exactly the wall-clock bound wanted here.
834
925
  for (let attempt = 1; attempt <= this.staleRetryMaxAttempts; attempt++) {
835
- const result = await this.fetchClearingHouseStateOnce(wallet, retryUnreadable);
926
+ const result = await this.fetchClearingHouseStateOnce(wallet, retryUnreadable, opts?.signal);
836
927
  if (result.outcome === "ok")
837
928
  return result.data;
838
929
  const retryable = result.outcome === "stale" || (result.outcome === "unreadable" && retryUnreadable);
@@ -883,12 +974,17 @@ export class SenpiClient {
883
974
  * Only the trade path (`retryUnreadable` true) folds those forms into the
884
975
  * single retryable "unreadable" outcome.
885
976
  */
886
- async fetchClearingHouseStateOnce(wallet, retryUnreadable) {
977
+ async fetchClearingHouseStateOnce(wallet, retryUnreadable, signal) {
887
978
  let raw;
888
979
  try {
889
- raw = await this.callTool("strategy_get_clearinghouse_state", { strategy_wallet: wallet });
980
+ raw = await this.callTool("strategy_get_clearinghouse_state", { strategy_wallet: wallet }, signal ? { signal } : undefined);
890
981
  }
891
982
  catch (err) {
983
+ // A blown deadline is terminal for the whole ladder — retrying cannot beat a clock that has
984
+ // already run out, and swallowing it into `unreadable` would hand the caller a silent null
985
+ // where it needs a loud throw.
986
+ if (signal?.aborted === true)
987
+ throw err;
892
988
  if (!retryUnreadable)
893
989
  throw err;
894
990
  logger.warn("getClearingHouseState: transport threw", {
@@ -971,8 +1067,8 @@ export class SenpiClient {
971
1067
  * {@link getPosition} / getPositionsForAssets). Does not call `list_open_positions`.
972
1068
  * DEX keys `main` map to reconciler dex `""` to match DSL state paths; `xyz` stays `xyz`.
973
1069
  */
974
- async listOpenPositions(wallet) {
975
- const state = await this.getClearingHouseState(wallet);
1070
+ async listOpenPositions(wallet, opts) {
1071
+ const state = await this.getClearingHouseState(wallet, opts);
976
1072
  if (state == null) {
977
1073
  logger.warn("listOpenPositions: clearing house state null", { wallet });
978
1074
  throw new Error("strategy_get_clearinghouse_state: empty or invalid response");
@@ -987,6 +1083,15 @@ export class SenpiClient {
987
1083
  return openPositionsFromClearingHouseState(state);
988
1084
  }
989
1085
  // ─── New MCP methods ────────────────────────────────────────────────────────
1086
+ /**
1087
+ * The strategy behind a wallet, or `null` when the backend lists none for it.
1088
+ *
1089
+ * `initialBudget` is `totalFunded` VERBATIM, including its `undefined`: an amount the backend did
1090
+ * not report is carried through as unread, never as `0`. This result is the strategy-details
1091
+ * surface (`StrategyState.fetchDetails` → the `strategy: details` context slice), and a `0` there
1092
+ * tells an agent the wallet is empty — the unreadable-renders-as-zero failure `[W_BUDGET_FUNDED_UNREADABLE]`
1093
+ * closes on the deploy report, one surface over.
1094
+ */
990
1095
  async getStrategy(wallet) {
991
1096
  // The backend `strategy_get` tool requires a strategy_id, not a wallet address.
992
1097
  // Look up by wallet via `strategy_list` with an address filter instead.
@@ -1006,7 +1111,18 @@ export class SenpiClient {
1006
1111
  createdAt: match.createdAt,
1007
1112
  };
1008
1113
  }
1009
- async listStrategies(filters) {
1114
+ /**
1115
+ * `opts.signal` bounds ONE MCP call (H6). Deploy passes `AbortSignal.timeout(...)` on every call
1116
+ * it makes, so a backend that never answers cannot hold the deploy job's single-flight slot.
1117
+ *
1118
+ * FAILS CLOSED, like {@link listOpenPositions}: `callTool` throws only on an RPC fault, so a
1119
+ * tool-level error envelope (`{success:false,…}`) or an isError text payload RESOLVES here. Read
1120
+ * as `[]` those became "you own zero strategies" — and every caller treats zero as proof of
1121
+ * absence: deploy's reconcile falls through to `needsWallet`, so one transient backend failure
1122
+ * created and funded a second wallet beside every live one and then reported `live`. An empty
1123
+ * `strategies` array is still a real answer and is returned as one; anything else throws.
1124
+ */
1125
+ async listStrategies(filters, opts) {
1010
1126
  const args = {};
1011
1127
  if (filters?.strategyAddresses)
1012
1128
  args.strategy_addresses = filters.strategyAddresses;
@@ -1016,11 +1132,15 @@ export class SenpiClient {
1016
1132
  args.strategy_ids = filters.strategyIds;
1017
1133
  if (filters?.strategyType)
1018
1134
  args.strategy_type = filters.strategyType;
1019
- const raw = await this.callTool("strategy_list", args);
1135
+ const raw = await this.callTool("strategy_list", args, opts);
1020
1136
  const data = unwrapEnvelope(raw);
1021
- const strategies = isRecord(data) && Array.isArray(data.strategies)
1022
- ? data.strategies
1023
- : [];
1137
+ if (!isRecord(data) || !Array.isArray(data.strategies)) {
1138
+ const detail = describeToolFailure(data);
1139
+ logger.warn("listStrategies: strategy_list response not recognizable", { detail });
1140
+ throw new Error(`strategy_list: no strategies array in the response — the strategy list is UNKNOWN, ` +
1141
+ `not empty (${detail})`);
1142
+ }
1143
+ const strategies = data.strategies;
1024
1144
  return strategies.filter(isRecord).map((s) => ({
1025
1145
  id: asString(s.id) ?? "",
1026
1146
  strategyWalletAddress: asString(s.strategyWalletAddress) ?? "",
@@ -1029,7 +1149,10 @@ export class SenpiClient {
1029
1149
  strategyType: asString(s.strategyType) ?? "",
1030
1150
  strategyName: asString(s.strategyName) ?? asString(s.name) ?? "",
1031
1151
  createdAt: asString(s.createdAt) ?? "",
1032
- totalFunded: asNumber(s.totalFunded) ?? 0,
1152
+ // NOT `?? 0`: a missing or unparseable figure stays undefined so the report layer can say
1153
+ // "unreadable" instead of asserting an empty wallet. See StrategySummary.totalFunded.
1154
+ totalFunded: asNumber(s.totalFunded) ?? undefined,
1155
+ skillName: readSkillName(s.strategyMetadata),
1033
1156
  }));
1034
1157
  }
1035
1158
  async getOpenOrders(wallet) {
@@ -1089,21 +1212,66 @@ export class SenpiClient {
1089
1212
  const data = unwrapEnvelope(raw);
1090
1213
  if (!isRecord(data))
1091
1214
  return { success: false };
1092
- return { success: data.success === true, message: asString(data.message) ?? undefined };
1215
+ return { success: data.success === true, ...readFailureFields(data) };
1216
+ }
1217
+ /**
1218
+ * Raw portfolio from account_get_portfolio. Interpretation (the funding
1219
+ * waterfall) lives in deploy/funding.ts — this method only fetches.
1220
+ * Returns null on a non-record payload; throws on transport error.
1221
+ */
1222
+ async getPortfolio(opts) {
1223
+ const raw = await this.callTool("account_get_portfolio", { ...(opts?.forceFetch ? { forceFetch: true } : {}) }, opts);
1224
+ const data = unwrapEnvelope(raw);
1225
+ return isRecord(data) ? data : null;
1226
+ }
1227
+ /**
1228
+ * Create (and backend-fund) a custom strategy wallet. skillName/skillVersion
1229
+ * attribution is mandatory: strategies created without it are unattributable.
1230
+ */
1231
+ async createCustomStrategy(params, opts) {
1232
+ const raw = await this.callTool("strategy_create_custom_strategy", {
1233
+ initialBudget: params.initialBudget,
1234
+ positions: [],
1235
+ ...(params.strategyName ? { strategyName: params.strategyName } : {}),
1236
+ skillName: params.skillName,
1237
+ skillVersion: params.skillVersion,
1238
+ }, opts);
1239
+ const data = unwrapEnvelope(raw);
1240
+ if (!isRecord(data))
1241
+ return { success: false };
1242
+ // The MCP nests the created record: `data.strategy.{id,strategyWalletAddress,status,…}` beside
1243
+ // an async-start `data.message` — there is no top-level id (senpi-hyperliquid-mcp
1244
+ // `execution.tools.ts`, `createResponse(tool, 'create', { strategy, message })`). Reading only
1245
+ // the flat keys returned `strategyId: undefined` for a create that had already made AND FUNDED
1246
+ // a wallet, which the deploy then reported as a failure.
1247
+ //
1248
+ // The nested record WINS over a flat id when both appear. It is the object the backend
1249
+ // actually created — the same one `strategy_list` returns, carrying the wallet and status the
1250
+ // rest of the deploy binds to — so its id is guaranteed to belong to the wallet that just took
1251
+ // the money. A flat id sitting beside it could only be a second, unattached identifier, and on
1252
+ // a money call the expensive mistake is attaching a funded wallet to the wrong id. Flat shapes
1253
+ // stay accepted for the reason the Python lifecycle reader keeps them (senpi-skills
1254
+ // `_cli.py` `strategy_obj`: list entries "may be flat or wrapped").
1255
+ // Read UNCONDITIONALLY, not only on `success: true`: a create that made and funded a wallet
1256
+ // and then reported it oddly must still hand back the id — losing it is the defect 6f2cd917
1257
+ // fixed, and it costs a funded wallet. A refusal envelope carries no id at any of these keys
1258
+ // (`{ success, error, meta }`), so there is nothing there to mint one out of.
1259
+ const strategyId = readStrategyId(isRecord(data.strategy) ? data.strategy : undefined) ?? readStrategyId(data);
1260
+ return { success: data.success === true, strategyId, ...readFailureFields(data) };
1093
1261
  }
1094
1262
  async withdrawFunds(wallet, amount) {
1095
1263
  const raw = await this.callTool("strategy_withdraw_funds", { strategy_wallet: wallet, amount });
1096
1264
  const data = unwrapEnvelope(raw);
1097
1265
  if (!isRecord(data))
1098
1266
  return { success: false };
1099
- return { success: data.success === true, message: asString(data.message) ?? undefined };
1267
+ return { success: data.success === true, ...readFailureFields(data) };
1100
1268
  }
1101
- async closeStrategy(wallet) {
1102
- const raw = await this.callTool("strategy_close", { strategy_wallet: wallet });
1269
+ async closeStrategy(wallet, opts) {
1270
+ const raw = await this.callTool("strategy_close", { strategy_wallet: wallet }, opts);
1103
1271
  const data = unwrapEnvelope(raw);
1104
1272
  if (!isRecord(data))
1105
1273
  return { success: false };
1106
- return { success: data.success === true, message: asString(data.message) ?? undefined };
1274
+ return { success: data.success === true, ...readFailureFields(data) };
1107
1275
  }
1108
1276
  /**
1109
1277
  * Submit a batch close_positions MCP call.
@@ -1174,6 +1342,32 @@ export class SenpiClient {
1174
1342
  }
1175
1343
  return result;
1176
1344
  }
1345
+ /**
1346
+ * Non-delisted instrument NAMES from `market_list_instruments` — the live-universe gate's read.
1347
+ * Distinct from {@link listInstruments} on purpose: that projection requires `max_leverage` and
1348
+ * ignores `is_delisted`, both wrong for a liveness question (an instrument without a leverage
1349
+ * figure is still live; a delisted one is not). Returns [] when the response carries no
1350
+ * recognizable instruments — callers MUST treat an empty list as "could not read", never as
1351
+ * "everything is dead" (a real read always contains at least the majors).
1352
+ */
1353
+ async listInstrumentNames(opts) {
1354
+ const raw = await this.callTool("market_list_instruments", {}, opts);
1355
+ const unwrapped = unwrapEnvelope(raw) ?? raw;
1356
+ if (unwrapped == null || typeof unwrapped !== "object")
1357
+ return [];
1358
+ const instrumentsRaw = unwrapped.instruments;
1359
+ if (!Array.isArray(instrumentsRaw))
1360
+ return [];
1361
+ const names = [];
1362
+ for (const row of instrumentsRaw) {
1363
+ if (!isRecord(row))
1364
+ continue;
1365
+ const name = asString(row.name);
1366
+ if (name != null && row.is_delisted !== true)
1367
+ names.push(name);
1368
+ }
1369
+ return names;
1370
+ }
1177
1371
  /**
1178
1372
  * Fetch PnL and account value history plus the today_snapshot (UTC-day-scoped metrics)
1179
1373
  * via MCP `strategy_get_pnl_and_account_value_history`.
@@ -1288,6 +1482,56 @@ function extractSlOrderId(unwrapped, raw) {
1288
1482
  }
1289
1483
  return null;
1290
1484
  }
1485
+ /**
1486
+ * The `errorCode`/`message` pair for the strategy lifecycle calls that report failure by RETURNING
1487
+ * rather than throwing (`topUp`, `createCustomStrategy`, `withdrawFunds`, `closeStrategy`).
1488
+ *
1489
+ * A backend refusal reaches these methods as `{ success: false, error: { code, message, … }, meta }`
1490
+ * — `createErrorResponse` in senpi-hyperliquid-mcp `src/services/response.service.ts`, returned by
1491
+ * `server.ts` as an ordinary tool result with no `isError`, so nothing throws. That shape has **no
1492
+ * `data` key**, and `unwrapEnvelope` returns any payload without one untouched: `data` therefore IS
1493
+ * the envelope, and the old flat `asString(data.message)` read was looking one level above the
1494
+ * text. Every backend refusal arrived as `message: undefined`, and deploy reported "backend
1495
+ * returned no strategyId" over a refusal that had said exactly why it refused.
1496
+ *
1497
+ * `data.message` stays as the fallback because that is where a SUCCESS envelope puts its text (the
1498
+ * create's async-start message arrives that way), and a string-shaped `error` is read only after it
1499
+ * — `unwrapEnvelope` hoists such an `error` onto the inner record, and other parsers in this client
1500
+ * accept that legacy shape (`parseCreatePositionResult`, `parseClosePositionResult`), though these
1501
+ * four methods never did: at `cfecb432` they read `data.message` and nothing else.
1502
+ *
1503
+ * That last point is why the order is `error.message` → `data.message` → string `error`, and not
1504
+ * the other way round — deliberately UNLIKE `extractEngineMessage` and `parseCreatePositionResult`,
1505
+ * which rank a string `error` above `data.message`. Those read engine mutation results, where
1506
+ * `error` is the failure channel and `message` is often the generic line beside it. These four read
1507
+ * a lifecycle envelope whose `message` is the real text on the success path, and they read nothing
1508
+ * else at `cfecb432`. A payload carrying BOTH a top-level string `error` and a `data.message` is a
1509
+ * shape no MCP response produces (`createResponse` never emits a top-level `error`), so no evidence
1510
+ * decides the tie: what decides it is that ranking the legacy string first would silently change
1511
+ * which text these four answer with — on a SUCCESS envelope — as a side effect of a change about
1512
+ * refusals. The legacy arm keeps its value where it is the ONLY text (`{ success: false,
1513
+ * error: "…" }`, no `data` key and no error object) and takes nothing away where it is not.
1514
+ *
1515
+ * The code is returned as its own field and never concatenated into the message: `deploy`'s
1516
+ * unnamed-create retry branches on it, and a guard that re-derives a code by scanning prose is the
1517
+ * guard this repo already had.
1518
+ */
1519
+ function readFailureFields(data) {
1520
+ const err = isRecord(data.error) ? data.error : undefined;
1521
+ return {
1522
+ errorCode: (err && asString(err.code)) ?? undefined,
1523
+ message: (err && asString(err.message)) ?? asString(data.message) ?? asString(data.error) ?? undefined,
1524
+ };
1525
+ }
1526
+ /**
1527
+ * The strategy id out of a strategy-shaped record, trying the key spellings the strategy surface
1528
+ * uses in the order the Python lifecycle reader tries them (`_cli.py` `strategy_id_of`).
1529
+ */
1530
+ function readStrategyId(obj) {
1531
+ if (obj == null)
1532
+ return undefined;
1533
+ return asString(obj.strategyId) ?? asString(obj.id) ?? asString(obj.strategy_id) ?? undefined;
1534
+ }
1291
1535
  function parseCreatePositionResult(raw) {
1292
1536
  const data = unwrapEnvelope(raw);
1293
1537
  if (!isRecord(data)) {