@senpi-ai/runtime 3.0.106 → 3.0.110

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 (34) 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 +5 -3
  3. package/dist/actions/close-position/close-position.action.js.map +1 -1
  4. package/dist/actions/open-position/open-position.action.d.ts +44 -0
  5. package/dist/actions/open-position/open-position.action.d.ts.map +1 -1
  6. package/dist/actions/open-position/open-position.action.js +266 -62
  7. package/dist/actions/open-position/open-position.action.js.map +1 -1
  8. package/dist/runtime/__tests__/helpers/runtime-gateway-harness.d.ts +6 -0
  9. package/dist/runtime/__tests__/helpers/runtime-gateway-harness.d.ts.map +1 -1
  10. package/dist/runtime/__tests__/helpers/runtime-gateway-harness.js +25 -0
  11. package/dist/runtime/__tests__/helpers/runtime-gateway-harness.js.map +1 -1
  12. package/dist/runtime/create-runtime-context.d.ts.map +1 -1
  13. package/dist/runtime/create-runtime-context.js +5 -0
  14. package/dist/runtime/create-runtime-context.js.map +1 -1
  15. package/dist/runtime/pending-opens-ledger.d.ts +93 -0
  16. package/dist/runtime/pending-opens-ledger.d.ts.map +1 -0
  17. package/dist/runtime/pending-opens-ledger.js +118 -0
  18. package/dist/runtime/pending-opens-ledger.js.map +1 -0
  19. package/dist/runtime/runtime.d.ts.map +1 -1
  20. package/dist/runtime/runtime.js.map +1 -1
  21. package/dist/senpi/client.d.ts +13 -2
  22. package/dist/senpi/client.d.ts.map +1 -1
  23. package/dist/senpi/client.js +32 -6
  24. package/dist/senpi/client.js.map +1 -1
  25. package/dist/strategy/strategy-state.d.ts +32 -0
  26. package/dist/strategy/strategy-state.d.ts.map +1 -1
  27. package/dist/strategy/strategy-state.js +53 -20
  28. package/dist/strategy/strategy-state.js.map +1 -1
  29. package/dist/types/runtime.d.ts +9 -0
  30. package/dist/types/runtime.d.ts.map +1 -1
  31. package/dist/types/strategy.d.ts +7 -0
  32. package/dist/types/strategy.d.ts.map +1 -1
  33. package/openclaw.plugin.json +1 -1
  34. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"close-position.action.d.ts","sourceRoot":"","sources":["../../../src/actions/close-position/close-position.action.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,MAAM,EACN,YAAY,EACZ,aAAa,EACb,cAAc,EACd,YAAY,EACZ,SAAS,EAEV,MAAM,aAAa,CAAC;AAIrB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAe3D,qBAAa,mBAAoB,YAAW,MAAM;IAO9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IAPjB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAG,gBAAgB,CAAU;IAEhD,OAAO,CAAC,cAAc,CAAiB;gBAG7B,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,cAAc;IASjC,OAAO,CAAC,QAAQ;IAYV,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC;IAgLrD,OAAO,CAAC,gBAAgB;YAQV,aAAa;CA4J5B;AAID,eAAO,MAAM,oBAAoB,EAAE,aACO,CAAC;AAE3C,eAAO,MAAM,qBAAqB,EAAE,cAMnC,CAAC"}
1
+ {"version":3,"file":"close-position.action.d.ts","sourceRoot":"","sources":["../../../src/actions/close-position/close-position.action.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,MAAM,EACN,YAAY,EACZ,aAAa,EACb,cAAc,EACd,YAAY,EACZ,SAAS,EAEV,MAAM,aAAa,CAAC;AAIrB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAe3D,qBAAa,mBAAoB,YAAW,MAAM;IAO9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IAPjB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAG,gBAAgB,CAAU;IAEhD,OAAO,CAAC,cAAc,CAAiB;gBAG7B,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,cAAc;IASjC,OAAO,CAAC,QAAQ;IAYV,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC;IAkLrD,OAAO,CAAC,gBAAgB;YAQV,aAAa;CA4J5B;AAID,eAAO,MAAM,oBAAoB,EAAE,aACO,CAAC;AAE3C,eAAO,MAAM,qBAAqB,EAAE,cAMnC,CAAC"}
@@ -75,9 +75,11 @@ export class ClosePositionAction {
75
75
  error: 'strategy_address_mismatch',
76
76
  };
77
77
  }
78
- // Refresh clearinghouse so hasOpenPosition reflects live positions — recipes
79
- // without a DSL monitor or open-position action never populate this cache
80
- // otherwise, and every close would short-circuit as 'no_open_position'.
78
+ // Refresh clearinghouse so hasOpenPosition reflects live positions. Nothing else
79
+ // refreshes THIS object: the DSL monitor holds a different StrategyState instance (the
80
+ // one in the shared `strategyStates` map), so its per-tick fetches never reach this
81
+ // cache. Without this line every close would read a view written by some earlier action
82
+ // on this context, or none at all, and short-circuit as 'no_open_position'.
81
83
  await strategyState.fetchClearinghouseState();
82
84
  // ── Static params path (bypasses decision engine) ──
83
85
  if (this.config.decision_mode === 'none' && typeof this.config.params?.asset === 'string') {
@@ -1 +1 @@
1
- {"version":3,"file":"close-position.action.js","sourceRoot":"","sources":["../../../src/actions/close-position/close-position.action.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEtH,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,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EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACxC,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,cAAc,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACzE;SACF,CAAC;QACF,sBAAsB,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;QACtF,OAAO,YAAY,CAAC;IACtB,CAAC;CACF;AAED,+EAA+E;AAE/E,MAAM,CAAC,MAAM,oBAAoB,GAAkB,CAAC,MAAoB,EAAE,OAAuB,EAAE,EAAE,CACnG,IAAI,mBAAmB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE3C,MAAM,CAAC,MAAM,qBAAqB,GAAmB;IACnD,IAAI,EAAE,uBAAuB;IAC7B,IAAI,EAAE,gBAAgB;IACtB,WAAW,EAAE,qDAAqD;IAClE,cAAc,EAAE,CAAC,UAAU,CAAC,kBAAkB,CAAC;IAC/C,aAAa,EAAE,CAAC,UAAU,CAAC,kBAAkB,CAAC;CAC/C,CAAC"}
1
+ {"version":3,"file":"close-position.action.js","sourceRoot":"","sources":["../../../src/actions/close-position/close-position.action.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEtH,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAC3G,OAA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AAE,eAAe,EAAE,cAAc,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACzE;SACF,CAAC;QACF,sBAAsB,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,cAAc,CAAC,CAAC;QACtF,OAAO,YAAY,CAAC;IACtB,CAAC;CACF;AAED,+EAA+E;AAE/E,MAAM,CAAC,MAAM,oBAAoB,GAAkB,CAAC,MAAoB,EAAE,OAAuB,EAAE,EAAE,CACnG,IAAI,mBAAmB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE3C,MAAM,CAAC,MAAM,qBAAqB,GAAmB;IACnD,IAAI,EAAE,uBAAuB;IAC7B,IAAI,EAAE,gBAAgB;IACtB,WAAW,EAAE,qDAAqD;IAClE,cAAc,EAAE,CAAC,UAAU,CAAC,kBAAkB,CAAC;IAC/C,aAAa,EAAE,CAAC,UAAU,CAAC,kBAAkB,CAAC;CAC/C,CAAC"}
@@ -1,14 +1,58 @@
1
1
  import type { Action, ActionConfig, ActionFactory, ActionManifest, ActionResult, HookEvent } from '../types.js';
2
2
  import { RuntimeContext } from 'src/types/runtime.js';
3
+ /**
4
+ * Wall-clock bound on the clearing-house reads this action makes.
5
+ *
6
+ * These reads run inside the runtime's `reconcile` key-lock, which the DSL monitor's own
7
+ * reconcile waits on. The client's retry ladder bounds attempt COUNT, not time — three 45s
8
+ * attempts plus backoff is ~2.5 min of held lock, and it holds exactly when the MCP is
9
+ * degraded, which is when the exit engine can least afford to wait. 20s sits under the DSL
10
+ * tick's 30s default (a recipe on a faster tick loses at most one tick) while leaving a
11
+ * healthy read, which lands in 1–5s, several attempts of headroom.
12
+ */
13
+ export declare const CLEARINGHOUSE_READ_TIMEOUT_MS = 20000;
3
14
  export declare class OpenPositionAction implements Action {
4
15
  private config;
5
16
  private context;
6
17
  readonly name: string;
7
18
  readonly actionType: "OPEN_POSITION";
8
19
  private decisionEngine;
20
+ /**
21
+ * Ledger of last resort for a context that carries none (standalone scripts, older call
22
+ * sites). Private to this action, so it still counts this action's own in-flight opens.
23
+ */
24
+ private readonly ownPendingOpens;
25
+ /**
26
+ * Edge-trigger state for the full-book log: `full` is the level, the rest bound the repeat
27
+ * rate while it stays full. Instance state on purpose — a full book is a property of this
28
+ * strategy, and the action is one per recipe.
29
+ */
30
+ private noSlotsLog;
9
31
  constructor(config: ActionConfig, context: RuntimeContext);
10
32
  private eventCtx;
11
33
  handle(event: HookEvent): Promise<ActionResult>;
34
+ /** The pending-opens ledger this action counts against — the context's when it has one. */
35
+ private pendingOpens;
36
+ /**
37
+ * Edge-triggered full-book log: once on the transition into full, then at most once per
38
+ * {@link NO_SLOTS_LOG_INTERVAL_MS} with the count it suppressed in between.
39
+ *
40
+ * The early `no_slots` skip used to return silently, so a strategy that had stopped
41
+ * entering looked identical in the logs to one with no signals — the single hardest state
42
+ * to diagnose from a box. Logging every signal instead would bury the log, which is how it
43
+ * came to be silent in the first place.
44
+ */
45
+ private logBookFull;
46
+ /**
47
+ * Never open against an unknown exchange view. If the view is undefined after retries we
48
+ * cannot tell what is already open or how much free margin exists — skip every signal
49
+ * rather than risk a duplicate or an over-margined open.
50
+ *
51
+ * Shared by both read sites (the gate at the top of `handle`, and the stale-view refetch in
52
+ * the signal loop). `sorted` is empty at the early site — there is no decision, hence no
53
+ * candidates, yet — which is why the entries are built from it rather than assumed.
54
+ */
55
+ private skipClearinghouseUnknown;
12
56
  private normalizeSignals;
13
57
  private handleSignals;
14
58
  }
@@ -1 +1 @@
1
- {"version":3,"file":"open-position.action.d.ts","sourceRoot":"","sources":["../../../src/actions/open-position/open-position.action.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,MAAM,EACN,YAAY,EAEZ,aAAa,EACb,cAAc,EACd,YAAY,EACZ,SAAS,EAEV,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AA6BtD,qBAAa,kBAAmB,YAAW,MAAM;IAO7C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IAPjB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAG,eAAe,CAAU;IAE/C,OAAO,CAAC,cAAc,CAAiB;gBAG7B,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,cAAc;IASjC,OAAO,CAAC,QAAQ;IAYV,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC;IA4MrD,OAAO,CAAC,gBAAgB;YAaV,aAAa;CAke5B;AAID,eAAO,MAAM,mBAAmB,EAAE,aACO,CAAC;AAE1C,eAAO,MAAM,oBAAoB,EAAE,cAMlC,CAAC"}
1
+ {"version":3,"file":"open-position.action.d.ts","sourceRoot":"","sources":["../../../src/actions/open-position/open-position.action.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,MAAM,EACN,YAAY,EAEZ,aAAa,EACb,cAAc,EACd,YAAY,EACZ,SAAS,EAEV,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AA4BtD;;;;;;;;;GASG;AACH,eAAO,MAAM,6BAA6B,QAAS,CAAC;AAyDpD,qBAAa,kBAAmB,YAAW,MAAM;IAwB7C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IAxBjB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,UAAU,EAAG,eAAe,CAAU;IAE/C,OAAO,CAAC,cAAc,CAAiB;IAEvC;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAkD;IAElF;;;;OAIG;IACH,OAAO,CAAC,UAAU,CAIhB;gBAGQ,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,cAAc;IASjC,OAAO,CAAC,QAAQ;IAYV,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC;IAyOrD,2FAA2F;IAC3F,OAAO,CAAC,YAAY;IAIpB;;;;;;;;OAQG;IACH,OAAO,CAAC,WAAW;IA4BnB;;;;;;;;OAQG;IACH,OAAO,CAAC,wBAAwB;IAwChC,OAAO,CAAC,gBAAgB;YAaV,aAAa;CAugB5B;AAID,eAAO,MAAM,mBAAmB,EAAE,aACO,CAAC;AAE1C,eAAO,MAAM,oBAAoB,EAAE,cAMlC,CAAC"}
@@ -6,7 +6,7 @@ import { emitDecisionErrorNotification } from '../decision-error-notification.js
6
6
  import { emitEvent } from '../event-derivation.js';
7
7
  import { buildRuntimePausedEvent } from '../../runtime/lifecycle-events.js';
8
8
  import { resolveLeverage } from '../../leverage/resolve-leverage.js';
9
- import { SenpiTimeoutError } from '../../senpi/client.js';
9
+ import { SenpiTimeoutError, isOutcomeUnknownCode } from '../../senpi/client.js';
10
10
  import { resolveMarginWithSource } from './resolve-margin.js';
11
11
  import { createLogger } from '../../utils/logger.js';
12
12
  import { positionRegistryKey } from '../../runtime/position-id-registry.js';
@@ -15,11 +15,63 @@ import { emitActionResultEvents, emitOrderPlaced, emitOrderFilled, emitOrderFail
15
15
  import { withSpan } from '../../telemetry/tracing.js';
16
16
  import { SpanStatusCode } from '@opentelemetry/api';
17
17
  import { classifyToolError } from '../../senpi/tool-errors.js';
18
+ import { hasOpenPositionIn } from '../../strategy/strategy-state.js';
19
+ import { createPendingOpensLedger, pendingOpenKey } from '../../runtime/pending-opens-ledger.js';
20
+ import { recordSignalOutcome } from '../../telemetry/metrics.js';
18
21
  const logger = createLogger("[actions][open-position]");
19
22
  /** Hyperliquid minimum notional value (margin × leverage) required to open a position. */
20
23
  const MIN_NOTIONAL_VALUE = 10;
24
+ /**
25
+ * Wall-clock bound on the clearing-house reads this action makes.
26
+ *
27
+ * These reads run inside the runtime's `reconcile` key-lock, which the DSL monitor's own
28
+ * reconcile waits on. The client's retry ladder bounds attempt COUNT, not time — three 45s
29
+ * attempts plus backoff is ~2.5 min of held lock, and it holds exactly when the MCP is
30
+ * degraded, which is when the exit engine can least afford to wait. 20s sits under the DSL
31
+ * tick's 30s default (a recipe on a faster tick loses at most one tick) while leaving a
32
+ * healthy read, which lands in 1–5s, several attempts of headroom.
33
+ */
34
+ export const CLEARINGHOUSE_READ_TIMEOUT_MS = 20_000;
35
+ /**
36
+ * A deadline for one clearing-house read. `AbortSignal.timeout` would do, but its timer is
37
+ * invisible to test fake-timers and never cleared — this one is both controllable and
38
+ * cancelled on the happy path, so a bounded read leaves nothing pending behind it.
39
+ */
40
+ function readDeadline(ms) {
41
+ const controller = new AbortController();
42
+ const timer = setTimeout(() => {
43
+ controller.abort(new Error(`clearinghouse read exceeded ${ms}ms`));
44
+ }, ms);
45
+ return { signal: controller.signal, clear: () => clearTimeout(timer) };
46
+ }
47
+ /** Run one clearing-house read under {@link CLEARINGHOUSE_READ_TIMEOUT_MS}. Fails closed. */
48
+ async function readBookBounded(strategyState) {
49
+ const deadline = readDeadline(CLEARINGHOUSE_READ_TIMEOUT_MS);
50
+ try {
51
+ return await strategyState.fetchClearinghouseState({
52
+ retryUnreadable: true,
53
+ signal: deadline.signal,
54
+ });
55
+ }
56
+ finally {
57
+ deadline.clear();
58
+ }
59
+ }
21
60
  /** Minimum leverage floor — positions cannot go below 1x. */
22
61
  const MIN_LEVERAGE = 1;
62
+ /**
63
+ * How long the view fetched at the top of `handle` is trusted before the signal loop
64
+ * refetches it.
65
+ *
66
+ * The gap between the two is a decision, and an LLM decision takes seconds — long enough
67
+ * for a fill, a liquidation or a manual close to move the book underneath the numbers the
68
+ * entry is about to be sized against. Five seconds is the order of the snapshot's own age,
69
+ * so anything older is worth a second read; the rule-decision path resolves well inside it
70
+ * and never pays for one.
71
+ */
72
+ const CLEARINGHOUSE_VIEW_MAX_AGE_MS = 5_000;
73
+ /** Minimum gap between repeats of the full-book log while the book STAYS full. */
74
+ const NO_SLOTS_LOG_INTERVAL_MS = 30 * 60 * 1000;
23
75
  // ─── Open Position Action ───────────────────────────────────────────────────
24
76
  export class OpenPositionAction {
25
77
  config;
@@ -27,6 +79,21 @@ export class OpenPositionAction {
27
79
  name;
28
80
  actionType = 'OPEN_POSITION';
29
81
  decisionEngine;
82
+ /**
83
+ * Ledger of last resort for a context that carries none (standalone scripts, older call
84
+ * sites). Private to this action, so it still counts this action's own in-flight opens.
85
+ */
86
+ ownPendingOpens = createPendingOpensLedger();
87
+ /**
88
+ * Edge-trigger state for the full-book log: `full` is the level, the rest bound the repeat
89
+ * rate while it stays full. Instance state on purpose — a full book is a property of this
90
+ * strategy, and the action is one per recipe.
91
+ */
92
+ noSlotsLog = {
93
+ full: false,
94
+ lastLoggedAt: 0,
95
+ suppressed: 0,
96
+ };
30
97
  constructor(config, context) {
31
98
  this.config = config;
32
99
  this.context = context;
@@ -101,25 +168,53 @@ export class OpenPositionAction {
101
168
  skipReason: 'strategy_backend_paused',
102
169
  };
103
170
  }
104
- // Early exit: no slots.
171
+ // The exchange view for THIS pass. Read here, once, and threaded through the rest of it.
172
+ //
173
+ // This context's StrategyState is not the instance the DSL monitor refreshes each tick —
174
+ // they are two objects built from the same config — so its cached view was only ever
175
+ // written by an earlier pass through this action, if at all. Reading the cache therefore
176
+ // froze the slot gate, the dedupe check and the margin budget at whatever the first
177
+ // signal after boot happened to see: a full snapshot skipped every later signal forever,
178
+ // an empty one let the slot cap and the dedupe never bind at all.
179
+ const view = await readBookBounded(strategyState);
180
+ if (view === undefined) {
181
+ return this.skipClearinghouseUnknown(event, address, [], undefined, undefined, { scanResult });
182
+ }
183
+ const snapshot = { view, fetchedAt: Date.now() };
184
+ // Early exit: no slots. Counted as snapshot positions PLUS opens this runtime has already
185
+ // submitted that the snapshot is too old to show (see PendingOpensLedger).
186
+ //
105
187
  // NOTE re "zero slots skips cap alerts": we intentionally do NOT evaluate risk
106
188
  // halts/cap self-pause here. It would add a per-signal getPnlHistoryWithSnapshot
107
189
  // MCP call on the full-book path (costly on a full + high-signal-rate strategy),
108
190
  // and that halt data is fetched nowhere else to reuse (only risk-guard.checkGate
109
- // fetches it; the DSL monitor fetches clearinghouse = different data). Self-pause
191
+ // fetches it — the clearinghouse read above is different data). Self-pause
110
192
  // alerts still fire via the normal open path once a slot frees and a signal
111
193
  // arrives (delayed, not lost). A durable fix — a periodic lifecycle driven off
112
194
  // the monitor tick / bus events (also catches a fully-silent producer) — is
113
195
  // deliberately out of scope here.
114
- if (!strategyState.getAvailableSlots?.()) {
196
+ const ledger = this.pendingOpens();
197
+ ledger.reconcile(view.positions);
198
+ const pending = ledger.unseen(view.positions);
199
+ const slots = strategyState.config.slots;
200
+ const openCount = view.positions.length + pending.length;
201
+ if (openCount >= slots) {
202
+ this.logBookFull(address, openCount, slots, pending.map((p) => p.coin), view.positions);
203
+ // The per-signal `results[]`/event fan-out is deliberately NOT built here: a full book
204
+ // on a high-signal-rate strategy is the loudest path there is, and the outcome is one
205
+ // fact about the strategy, not one per candidate. The counter still carries it.
206
+ recordSignalOutcome({ result: 'skipped', reasonCode: 'no_slots' });
115
207
  return {
116
208
  success: true,
117
209
  action_type: this.actionType,
118
- summary: 'No slots available',
210
+ summary: `No slots available (${openCount}/${slots} open)`,
119
211
  skipped: true,
120
212
  skipReason: 'no_slots',
213
+ data: { openCount, slots, pendingCount: pending.length },
121
214
  };
122
215
  }
216
+ // A pass with room re-arms the edge, so the next time the book fills it is logged again.
217
+ this.noSlotsLog.full = false;
123
218
  logger.info('building context');
124
219
  // Build context
125
220
  const providerRequest = {
@@ -235,7 +330,82 @@ export class OpenPositionAction {
235
330
  emitActionResultEvents(eventCtx, event, address, invalidPayloadResult, trackingExtras);
236
331
  return invalidPayloadResult;
237
332
  }
238
- return this.handleSignals(signals, event, strategyState, decision.reasoning, meta, interpolatedPrompt, trackingExtras);
333
+ return this.handleSignals(signals, event, strategyState, snapshot, decision.reasoning, meta, interpolatedPrompt, trackingExtras);
334
+ }
335
+ /** The pending-opens ledger this action counts against — the context's when it has one. */
336
+ pendingOpens() {
337
+ return this.context.pendingOpensLedger ?? this.ownPendingOpens;
338
+ }
339
+ /**
340
+ * Edge-triggered full-book log: once on the transition into full, then at most once per
341
+ * {@link NO_SLOTS_LOG_INTERVAL_MS} with the count it suppressed in between.
342
+ *
343
+ * The early `no_slots` skip used to return silently, so a strategy that had stopped
344
+ * entering looked identical in the logs to one with no signals — the single hardest state
345
+ * to diagnose from a box. Logging every signal instead would bury the log, which is how it
346
+ * came to be silent in the first place.
347
+ */
348
+ logBookFull(address, openCount, slots, pendingCoins, positions) {
349
+ const now = Date.now();
350
+ const attributes = {
351
+ wallet: address,
352
+ open: openCount,
353
+ slots,
354
+ pending: pendingCoins.length,
355
+ coins: [...positions.map((p) => p.coin), ...pendingCoins],
356
+ };
357
+ if (!this.noSlotsLog.full) {
358
+ this.noSlotsLog = { full: true, lastLoggedAt: now, suppressed: 0 };
359
+ logger.info('skipping: no_slots', attributes);
360
+ return;
361
+ }
362
+ this.noSlotsLog.suppressed++;
363
+ if (now - this.noSlotsLog.lastLoggedAt >= NO_SLOTS_LOG_INTERVAL_MS) {
364
+ logger.info('skipping: no_slots', { ...attributes, suppressed: this.noSlotsLog.suppressed });
365
+ this.noSlotsLog.lastLoggedAt = now;
366
+ this.noSlotsLog.suppressed = 0;
367
+ }
368
+ }
369
+ /**
370
+ * Never open against an unknown exchange view. If the view is undefined after retries we
371
+ * cannot tell what is already open or how much free margin exists — skip every signal
372
+ * rather than risk a duplicate or an over-margined open.
373
+ *
374
+ * Shared by both read sites (the gate at the top of `handle`, and the stale-view refetch in
375
+ * the signal loop). `sorted` is empty at the early site — there is no decision, hence no
376
+ * candidates, yet — which is why the entries are built from it rather than assumed.
377
+ */
378
+ skipClearinghouseUnknown(event, address, sorted, meta, decisionPrompt, trackingExtras) {
379
+ const skippedResults = sorted.map((signal) => ({
380
+ asset: signal.asset,
381
+ direction: signal.direction,
382
+ dex: typeof signal.dex === 'string' && signal.dex.trim() !== '' ? signal.dex.trim() : 'main',
383
+ score: signal.score,
384
+ success: true,
385
+ reason: 'clearinghouse_unknown',
386
+ }));
387
+ logger.error('Skipping open: clearinghouse view unknown after retries', {
388
+ wallet: address,
389
+ skippedCount: skippedResults.length,
390
+ assets: skippedResults.map((r) => r.asset),
391
+ });
392
+ const skipResult = {
393
+ success: true,
394
+ action_type: this.actionType,
395
+ summary: 'Clearinghouse view unknown — skipped open',
396
+ skipped: true,
397
+ skipReason: 'clearinghouse_unknown',
398
+ data: {
399
+ results: skippedResults,
400
+ submittedCount: 0,
401
+ failedCount: 0,
402
+ skippedCount: skippedResults.length,
403
+ ...(meta ? { _decisionMeta: meta } : {}),
404
+ _decisionPrompt: decisionPrompt ?? null,
405
+ },
406
+ };
407
+ emitActionResultEvents(this.eventCtx(), event, address, skipResult, trackingExtras);
408
+ return skipResult;
239
409
  }
240
410
  normalizeSignals(payload) {
241
411
  if (Array.isArray(payload.signals))
@@ -250,7 +420,7 @@ export class OpenPositionAction {
250
420
  }
251
421
  return [];
252
422
  }
253
- async handleSignals(signals, event, strategyState, reasoning, meta, decisionPrompt, trackingExtras) {
423
+ async handleSignals(signals, event, strategyState, snapshot, reasoning, meta, decisionPrompt, trackingExtras) {
254
424
  const address = event.address;
255
425
  const orderType = resolveOpenOrderType(this.config.params?.order_type);
256
426
  const feeOptimizedLimitOptions = orderType === 'FEE_OPTIMIZED_LIMIT'
@@ -277,58 +447,39 @@ export class OpenPositionAction {
277
447
  return undefined;
278
448
  })(),
279
449
  (async () => {
280
- // Resolve the exchange view once: it sizes margin_pct AND feeds the
281
- // free-margin pre-flight below. A cached defined view is trusted;
282
- // otherwise fetch with retry-on-unreadable so a transient unreadable
283
- // response is retried rather than treated as an unknown book.
284
- return strategyState.getClearinghouseState()
285
- ?? await strategyState.fetchClearinghouseState({ retryUnreadable: true });
450
+ // The view handed down from the slot gate, re-read only if the decision took long
451
+ // enough for it to go stale. No cached-getter fallback: the only view this action
452
+ // trusts is one it read itself, on this pass.
453
+ if (Date.now() - snapshot.fetchedAt <= CLEARINGHOUSE_VIEW_MAX_AGE_MS)
454
+ return snapshot.view;
455
+ return readBookBounded(strategyState);
286
456
  })(),
287
457
  ]);
288
458
  riskSnapshot = riskSnapResult;
289
- // Never open against an unknown exchange view. If the view is still
290
- // undefined after retries, we cannot tell what is already open or how much
291
- // free margin exists — skip every signal rather than risk a duplicate or
292
- // over-margined open.
293
459
  if (clearinghouseView === undefined) {
294
- const skippedResults = sorted.map((signal) => ({
295
- asset: signal.asset,
296
- direction: signal.direction,
297
- dex: typeof signal.dex === 'string' && signal.dex.trim() !== '' ? signal.dex.trim() : 'main',
298
- score: signal.score,
299
- success: true,
300
- reason: 'clearinghouse_unknown',
301
- }));
302
- logger.error('Skipping open: clearinghouse view unknown after retries', {
303
- wallet: address,
304
- skippedCount: skippedResults.length,
305
- assets: skippedResults.map((r) => r.asset),
306
- });
307
- const skipResult = {
308
- success: true,
309
- action_type: this.actionType,
310
- summary: 'Clearinghouse view unknown — skipped open',
311
- skipped: true,
312
- skipReason: 'clearinghouse_unknown',
313
- data: {
314
- results: skippedResults,
315
- submittedCount: 0,
316
- failedCount: 0,
317
- skippedCount: skippedResults.length,
318
- ...(meta ? { _decisionMeta: meta } : {}),
319
- _decisionPrompt: decisionPrompt ?? null,
320
- },
321
- };
322
- emitActionResultEvents(this.eventCtx(), event, address, skipResult, trackingExtras);
323
- return skipResult;
460
+ return this.skipClearinghouseUnknown(event, address, sorted, meta, decisionPrompt, trackingExtras);
324
461
  }
325
- const withdrawable = clearinghouseView.withdrawable;
326
- let remainingSlots = strategyState.getAvailableSlots?.() ?? 0;
327
- // Free-margin pre-flight budget. Undefined when withdrawable is unknown
328
- // (no clearinghouse read) — in that case we do NOT block, preserving prior behavior.
462
+ // ONE snapshot decides everything below: slots, dedupe and margin. Mixing a second read
463
+ // in mid-batch is how the counts stopped agreeing with each other in the first place.
464
+ const view = clearinghouseView;
465
+ const withdrawable = view.withdrawable;
466
+ const ledger = this.pendingOpens();
467
+ ledger.reconcile(view.positions);
468
+ const pendingEntries = ledger.unseen(view.positions);
469
+ // Keys of opens already in flight: a dedupe hit the snapshot cannot produce yet.
470
+ const pendingKeys = new Set(pendingEntries.map((entry) => entry.key));
471
+ const pendingMargin = pendingEntries.reduce((sum, entry) => sum + entry.marginAmount, 0);
472
+ let remainingSlots = Math.max(0, strategyState.config.slots - (view.positions.length + pendingEntries.length));
473
+ // Free-margin pre-flight budget, and the basis `margin_pct` sizes off. Undefined when
474
+ // withdrawable is unknown — in that case we do NOT block, preserving prior behavior.
475
+ // Margin already committed by in-flight opens is subtracted: the snapshot still counts it
476
+ // as free, so sizing off the raw figure would size two positions out of one pot. Erring
477
+ // small is the safe direction — an undersized entry is a worse fill, an oversized one is
478
+ // a rejection or a liquidation-adjacent position.
479
+ const availableWithdrawable = withdrawable != null ? withdrawable - pendingMargin : undefined;
329
480
  // Decremented per submitted signal so later signals in the same batch are
330
481
  // evaluated against the margin already consumed by earlier ones.
331
- let remainingMargin = withdrawable;
482
+ let remainingMargin = availableWithdrawable;
332
483
  const results = [];
333
484
  let submittedCount = 0;
334
485
  let failedCount = 0;
@@ -364,7 +515,9 @@ export class OpenPositionAction {
364
515
  outcome("failed", 'invalid_direction');
365
516
  return;
366
517
  }
367
- if (strategyState.hasOpenPosition(asset, dexForLookup)) {
518
+ // Dedupe against THIS snapshot plus the in-flight opens it is too old to show.
519
+ const pendingKey = pendingOpenKey(asset, dexForLookup);
520
+ if (hasOpenPositionIn(view.positions, asset, dexForLookup) || pendingKeys.has(pendingKey)) {
368
521
  results.push({ asset, direction, dex: submittedDex, score: signalScore, success: true, reason: 'position_already_exists', startedAt: signalStartedAt, endedAt: Date.now() });
369
522
  outcome("skipped", 'position_already_exists');
370
523
  return;
@@ -399,7 +552,9 @@ export class OpenPositionAction {
399
552
  const { amount: marginAmount, source: marginSource } = resolveMarginWithSource({
400
553
  signalMarginPct,
401
554
  marginPct: strategyState.config.marginPct,
402
- withdrawable,
555
+ // The pending-adjusted figure, not the raw snapshot one: a percent of a balance that
556
+ // an in-flight open has already claimed sizes the same dollars twice.
557
+ withdrawable: availableWithdrawable,
403
558
  marginPerSlot: strategyState.config.marginPerSlot,
404
559
  budget: strategyState.config.budget,
405
560
  slots: strategyState.config.slots,
@@ -464,11 +619,23 @@ export class OpenPositionAction {
464
619
  direction,
465
620
  source: marginSource,
466
621
  withdrawable,
467
- accountValue: clearinghouseView.accountValue,
622
+ availableWithdrawable,
623
+ accountValue: view.accountValue,
468
624
  marginAmount,
469
625
  leverage,
470
626
  notional: notionalValue,
471
627
  });
628
+ // Reserved BEFORE the await: between the submit and its outcome the next signal can
629
+ // already be evaluating, and the exchange snapshot will not show this for seconds.
630
+ ledger.reserve(asset, submittedDex, marginAmount);
631
+ pendingKeys.add(pendingKey);
632
+ // Charge the batch counters here, not on the success path: the reservation just made
633
+ // stands for every outcome below except an outright rejection (resting, filled, and
634
+ // even a throw all keep the slot/margin held). Refund only where the reservation is
635
+ // actually released.
636
+ remainingSlots--;
637
+ if (remainingMargin != null)
638
+ remainingMargin -= marginAmount;
472
639
  const result = await withSpan("mcp.createPosition", { "senpi.signal.asset": asset, "senpi.signal.direction": direction }, async (mcpSpan) => {
473
640
  const r = await this.context.senpi.createPosition({
474
641
  strategyWalletAddress: address,
@@ -517,6 +684,40 @@ export class OpenPositionAction {
517
684
  .map((o) => `${o.coin}: ${o.error}`)
518
685
  .join('; ');
519
686
  const detail = result.error || orderErrors || 'unknown error';
687
+ // A resting maker order is NOT a rejection: the order is live on the book and will
688
+ // consume this slot and this margin the moment it fills. The reservation therefore
689
+ // stands (on the longer resting TTL) while the result entry still reports the open
690
+ // as unfilled. The code arrives either as the top-level envelope code or, when the
691
+ // venue reported it per-order, only inside the joined order errors — hence both.
692
+ const restingOrder = result.errorCode === 'CREATE_ORDER_RESTING' || /ORDER_RESTING/i.test(detail);
693
+ // The server aborting its own trading-engine call (UNAVAILABLE, or the unclassified
694
+ // INTERNAL) is not a rejection either: it says nothing about whether the venue
695
+ // accepted the order, and the next pass's book is too young to answer. Freeing the
696
+ // slot here is how one ambiguous failure becomes two positions on one slot — the
697
+ // same class this fix closes. Hold it on the ambiguous TTL, exactly as the thrown
698
+ // timeout path below does.
699
+ const outcomeUnknown = !restingOrder && isOutcomeUnknownCode(result.errorCode);
700
+ if (restingOrder) {
701
+ ledger.settle(pendingKey, 'resting', result.orders[0]?.orderId ?? undefined);
702
+ }
703
+ else if (outcomeUnknown) {
704
+ logger.error('open outcome unknown — order may be live', new Error(detail), {
705
+ asset,
706
+ errorCode: result.errorCode,
707
+ });
708
+ ledger.settle(pendingKey, 'ambiguous');
709
+ }
710
+ else {
711
+ // A rejected submit holds nothing — free the slot and the margin immediately.
712
+ ledger.release(pendingKey);
713
+ pendingKeys.delete(pendingKey);
714
+ remainingSlots++;
715
+ if (remainingMargin != null)
716
+ remainingMargin += marginAmount;
717
+ }
718
+ // Same reason code the thrown timeout uses: downstream (and the agent reading it)
719
+ // must reconcile against real position state, not treat a live order as rejected.
720
+ const failureReason = outcomeUnknown ? 'timeout' : 'position_open_failed';
520
721
  // Backend says the strategy is PAUSED/CLOSED: arm the pause registry so
521
722
  // subsequent signals skip instead of re-submitting (2026-07 storm class),
522
723
  // and tell the user once. Classify with the structured envelope fields
@@ -543,24 +744,26 @@ export class OpenPositionAction {
543
744
  results.push({
544
745
  asset, direction, dex: submittedDex, score: signalScore,
545
746
  leverage, marginAmount, marginSource, marginPct, orderType,
546
- success: false, reason: 'position_open_failed', error: detail,
747
+ success: false, reason: failureReason, error: detail,
547
748
  startedAt: signalStartedAt, endedAt: Date.now(),
548
749
  });
549
- // Task 8a: the venue rejected the open submit.
750
+ // Task 8a: the venue rejected the open submit (or left it unresolved).
550
751
  emitOrderFailed(this.context.hookSystem, event, address, {
551
752
  asset,
552
753
  direction,
553
- reason: 'position_open_failed',
754
+ reason: failureReason,
554
755
  error: detail,
555
756
  reduceOnly: false,
556
757
  });
557
758
  failedCount++;
558
- outcome("failed", 'position_open_failed');
759
+ outcome("failed", failureReason);
559
760
  return;
560
761
  }
561
762
  // A successful submit proves the strategy is active again — re-arm immediately.
562
763
  this.context.backendPauseRegistry?.clear(address);
563
764
  const submittedOrder = result.orders[0];
765
+ // Accepted: hold the slot and the margin until a snapshot carries the position.
766
+ ledger.settle(pendingKey, 'filled', submittedOrder?.orderId ?? undefined);
564
767
  // Mint the position.id at intent — the moment the open order is submitted,
565
768
  // before the position is confirmed open — so the id rides the action.open
566
769
  // emit and the open trace correlates by position.id directly (no ~60s
@@ -632,9 +835,6 @@ export class OpenPositionAction {
632
835
  });
633
836
  }
634
837
  submittedCount++;
635
- remainingSlots--;
636
- if (remainingMargin != null)
637
- remainingMargin -= marginAmount;
638
838
  outcome("submitted", 'submitted');
639
839
  }
640
840
  catch (error) {
@@ -645,6 +845,10 @@ export class OpenPositionAction {
645
845
  const timedOut = error instanceof SenpiTimeoutError;
646
846
  const reason = timedOut ? 'timeout' : 'exception';
647
847
  logger.error(timedOut ? 'open timed out — order may be live' : 'open failed', error, { asset });
848
+ // The submit may have landed server-side; nothing here proves it did not. The
849
+ // reservation stands on the ambiguous TTL so the next signal counts it rather than
850
+ // opening a second position on the same margin.
851
+ ledger.settle(pendingKey, 'ambiguous');
648
852
  results.push({
649
853
  asset, direction, dex: submittedDex, score: signalScore,
650
854
  leverage, marginAmount, marginSource, marginPct, orderType,