@coinrithm/mcp-trading 0.7.15 → 0.7.16

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 (53) hide show
  1. package/CHANGELOG.md +127 -8
  2. package/README.md +18 -3
  3. package/dist/agent/bench/bench.d.ts +59 -0
  4. package/dist/agent/bench/bench.js +319 -0
  5. package/dist/agent/bench/cassette.d.ts +97 -0
  6. package/dist/agent/bench/cassette.js +181 -0
  7. package/dist/agent/bench/costs.d.ts +28 -0
  8. package/dist/agent/bench/costs.js +60 -0
  9. package/dist/agent/bench/labelBuilder.d.ts +123 -0
  10. package/dist/agent/bench/labelBuilder.js +282 -0
  11. package/dist/agent/bench/labels.d.ts +75 -0
  12. package/dist/agent/bench/labels.js +259 -0
  13. package/dist/agent/bench/recordingClient.d.ts +51 -0
  14. package/dist/agent/bench/recordingClient.js +193 -0
  15. package/dist/agent/bench/replayClient.d.ts +41 -0
  16. package/dist/agent/bench/replayClient.js +262 -0
  17. package/dist/agent/bench/report.d.ts +115 -0
  18. package/dist/agent/bench/report.js +435 -0
  19. package/dist/agent/cli.d.ts +25 -0
  20. package/dist/agent/cli.js +300 -2
  21. package/dist/agent/client.d.ts +1 -0
  22. package/dist/agent/client.js +6 -0
  23. package/dist/agent/configurationWarnings.js +11 -0
  24. package/dist/agent/decision.d.ts +3 -0
  25. package/dist/agent/decision.js +85 -3
  26. package/dist/agent/decisionValidator.d.ts +30 -0
  27. package/dist/agent/decisionValidator.js +147 -2
  28. package/dist/agent/engine.d.ts +3 -3
  29. package/dist/agent/engine.js +3 -3
  30. package/dist/agent/observe.d.ts +27 -2
  31. package/dist/agent/observe.js +529 -89
  32. package/dist/agent/prompt.d.ts +4 -1
  33. package/dist/agent/prompt.js +98 -7
  34. package/dist/agent/promptTables.d.ts +1 -0
  35. package/dist/agent/promptTables.js +33 -0
  36. package/dist/agent/providerCapabilities.d.ts +6 -0
  37. package/dist/agent/providerCapabilities.js +23 -0
  38. package/dist/agent/providers.d.ts +25 -7
  39. package/dist/agent/providers.js +188 -48
  40. package/dist/agent/resolve.js +3 -0
  41. package/dist/agent/runner.d.ts +8 -0
  42. package/dist/agent/runner.js +59 -15
  43. package/dist/agent/setups.d.ts +2 -1
  44. package/dist/agent/setups.js +17 -16
  45. package/dist/agent/signals.d.ts +33 -0
  46. package/dist/agent/signals.js +89 -0
  47. package/dist/agent/skill.js +37 -0
  48. package/dist/agent/skillValidator.js +33 -0
  49. package/dist/agent/strictLint.js +29 -0
  50. package/dist/agent/types.d.ts +149 -12
  51. package/dist/agent/universe.d.ts +78 -0
  52. package/dist/agent/universe.js +215 -0
  53. package/package.json +3 -2
@@ -4,6 +4,46 @@
4
4
  // market text cannot widen a limit or force a trade. Covers futures + spot + PM.
5
5
  import { ok, fail, actionVenue, spotBuyCost, } from "./types.js";
6
6
  import { checkEntryPredicates } from "./entryPredicates.js";
7
+ import { universeEntryBlock } from "./universe.js";
8
+ /**
9
+ * Edge (points) risk.pmMinEdgeGapPct requires at a fee-inclusive entry cost:
10
+ * pct% of the room left to 100. Cost at or above 100 leaves no room, so any
11
+ * positive gap rule makes the requirement unreachable rather than zero.
12
+ */
13
+ export function requiredGapEdgePoints(entryPct, gapPct) {
14
+ const room = 100 - entryPct;
15
+ if (room <= 0)
16
+ return gapPct > 0 ? Number.POSITIVE_INFINITY : 0;
17
+ return (gapPct / 100) * room;
18
+ }
19
+ /** Ends within this of each other share a coin horizon (venue date splits). */
20
+ export const PM_COIN_HORIZON_WINDOW_MS = 24 * 60 * 60 * 1000;
21
+ /** An end beyond this is a venue sentinel, never a real horizon. */
22
+ export const PM_PLAUSIBLE_END_MAX_MS = 5 * 365 * 24 * 60 * 60 * 1000;
23
+ /** The later of observation.asOf and the validation clock, when known. */
24
+ export function pmReferenceMs(asOf, nowMs) {
25
+ return Math.max(...[Date.parse(asOf), nowMs ?? NaN].filter((t) => Number.isFinite(t)));
26
+ }
27
+ /**
28
+ * The coin horizon of a market or held position, or null when it cannot be
29
+ * grouped: no linked coin, or an end that is missing, unparseable, not after
30
+ * the reference time, or more than 5 years after it (venue sentinels).
31
+ */
32
+ export function pmCoinHorizonOf(item, refMs) {
33
+ const coins = item.coins ?? [];
34
+ if (coins.length === 0 || !item.endDate || !Number.isFinite(refMs))
35
+ return null;
36
+ const endMs = Date.parse(item.endDate);
37
+ if (!Number.isFinite(endMs) ||
38
+ endMs <= refMs ||
39
+ endMs - refMs > PM_PLAUSIBLE_END_MAX_MS)
40
+ return null;
41
+ return { coins, endMs };
42
+ }
43
+ /** Event key shared by pm_open actions, held positions and markets. */
44
+ export function pmEventKey(source, slug) {
45
+ return `${source.toLowerCase()}/${slug.toLowerCase()}`;
46
+ }
7
47
  const SERVER_MAX_LEVERAGE = 20;
8
48
  // Minimum edge, in probability POINTS, between the model's own forecast for
9
49
  // the outcome it is backing and what that outcome currently costs. Live
@@ -151,6 +191,9 @@ export function validateAction(action, ctx) {
151
191
  return fail("unknown_symbol", `${action.symbol} is not on the watchlist`);
152
192
  if (!entry.coinId)
153
193
  return fail("unresolved_symbol", `${action.symbol} did not resolve to a coin`);
194
+ const outsideUniverse = universeEntryBlock(spec, entry);
195
+ if (outsideUniverse)
196
+ return fail("outside_universe", `${action.symbol} is ${outsideUniverse}`);
154
197
  // A futures_open on a symbol you ALREADY hold is treated as an ADD by the
155
198
  // server, which REJECTS any SL/TP on an add (sl_tp_not_supported_on_add) and
156
199
  // fails the whole open — the single biggest rejection class (e.g. Sam 61/61).
@@ -267,6 +310,11 @@ export function validateAction(action, ctx) {
267
310
  return fail("unknown_symbol", `${action.symbol} is not on the watchlist`);
268
311
  if (!entry.coinId)
269
312
  return fail("unresolved_symbol", `${action.symbol} did not resolve to a coin`);
313
+ if (action.side === "buy") {
314
+ const outside = universeEntryBlock(spec, entry);
315
+ if (outside)
316
+ return fail("outside_universe", `${action.symbol} is ${outside}`);
317
+ }
270
318
  if (action.orderType === "limit" &&
271
319
  !(typeof action.limitPrice === "number" && action.limitPrice > 0)) {
272
320
  return fail("missing_limit_price", "a limit order needs a positive limitPrice");
@@ -333,6 +381,68 @@ export function validateAction(action, ctx) {
333
381
  if (!mkt) {
334
382
  return fail("pm_market_not_discovered", `${action.source}/${action.slug} is not in the discovered PM markets`);
335
383
  }
384
+ const perEventCap = spec.risk.pmMaxOpenPerEvent;
385
+ if (perEventCap !== undefined) {
386
+ if (typeof perEventCap !== "number" ||
387
+ !Number.isInteger(perEventCap) ||
388
+ perEventCap < 1) {
389
+ return fail("pm_event_cap_invalid", `risk.pmMaxOpenPerEvent ${JSON.stringify(perEventCap)} is not a whole number of at least 1`);
390
+ }
391
+ const key = pmEventKey(mkt.source, mkt.slug);
392
+ const held = observation.pmPositions.filter((p) => (p.status ?? "open") === "open" &&
393
+ p.source !== undefined &&
394
+ p.slug !== undefined &&
395
+ pmEventKey(p.source, p.slug) === key).length;
396
+ const thisCycle = (ctx.pmEventsOpenedThisCycle ?? []).filter((k) => k === key).length;
397
+ if (held + thisCycle >= perEventCap) {
398
+ return fail("pm_event_cap", `${held + thisCycle} open bet(s) on ${key} >= per-event cap ${perEventCap}`);
399
+ }
400
+ }
401
+ const coinHorizonCap = spec.risk.pmMaxOpenPerCoinHorizon;
402
+ if (coinHorizonCap !== undefined) {
403
+ if (typeof coinHorizonCap !== "number" ||
404
+ !Number.isInteger(coinHorizonCap) ||
405
+ coinHorizonCap < 1 ||
406
+ coinHorizonCap > 50) {
407
+ return fail("pm_coin_horizon_cap_invalid", `risk.pmMaxOpenPerCoinHorizon ${JSON.stringify(coinHorizonCap)} is not a whole number from 1 to 50`);
408
+ }
409
+ const refMs = pmReferenceMs(observation.asOf, ctx.nowMs);
410
+ const candidate = pmCoinHorizonOf(mkt, refMs);
411
+ // Unknown coin or end: never grouped, never blocked.
412
+ if (candidate) {
413
+ const near = (endMs) => Math.abs(endMs - candidate.endMs) <= PM_COIN_HORIZON_WINDOW_MS;
414
+ for (const coin of candidate.coins) {
415
+ const held = observation.pmPositions.filter((p) => {
416
+ if ((p.status ?? "open") !== "open")
417
+ return false;
418
+ const h = pmCoinHorizonOf(p, refMs);
419
+ return !!h && h.coins.includes(coin) && near(h.endMs);
420
+ }).length;
421
+ const thisCycle = (ctx.pmCoinHorizonsOpenedThisCycle ?? []).filter((h) => h.coins.includes(coin) && near(h.endMs)).length;
422
+ if (held + thisCycle >= coinHorizonCap) {
423
+ return fail("pm_coin_horizon_cap", `${held + thisCycle} open bet(s) on ${coin} ending within 24 h of ${new Date(candidate.endMs).toISOString()} >= per-coin-horizon cap ${coinHorizonCap}`);
424
+ }
425
+ }
426
+ }
427
+ }
428
+ const closeCutoff = spec.risk.pmMinMinutesToClose;
429
+ if (closeCutoff !== undefined) {
430
+ if (typeof closeCutoff !== "number" ||
431
+ !Number.isFinite(closeCutoff) ||
432
+ closeCutoff < 0) {
433
+ return fail("pm_close_cutoff_invalid", `risk.pmMinMinutesToClose ${JSON.stringify(closeCutoff)} is not a non-negative number`);
434
+ }
435
+ // Only a KNOWN close can trip the cutoff: venues publish null/sentinel
436
+ // end dates, and an unparseable one is unknown, never "closing now".
437
+ const endMs = mkt.endDate ? Date.parse(mkt.endDate) : NaN;
438
+ const refMs = Math.max(...[Date.parse(observation.asOf), ctx.nowMs ?? NaN].filter((t) => Number.isFinite(t)));
439
+ if (Number.isFinite(endMs) && Number.isFinite(refMs)) {
440
+ const minutesLeft = (endMs - refMs) / 60_000;
441
+ if (minutesLeft < closeCutoff) {
442
+ return fail("pm_closes_too_soon", `market closes in ${minutesLeft.toFixed(1)} min, inside the ${closeCutoff} min cutoff`);
443
+ }
444
+ }
445
+ }
336
446
  if (action.stakeMusd < PM_MIN_STAKE_MUSD) {
337
447
  return fail("pm_stake_below_min", `stake ${action.stakeMusd} < $${PM_MIN_STAKE_MUSD} minimum`);
338
448
  }
@@ -393,11 +503,37 @@ export function validateAction(action, ctx) {
393
503
  // Forecast consistency. By prompt contract forecastProbability is the
394
504
  // model's own probability (1-99) that the outcome IT IS BACKING wins, so
395
505
  // buying that outcome only makes sense when the forecast clears what the
396
- // market charges for it. An ABSENT forecast still never blocks a bet (the
397
- // prompt promises that); a PRESENT one that contradicts the trade does.
506
+ // market charges for it. A forecast is optional unless a configured edge
507
+ // rule requires one; a present forecast must satisfy the enforced rules.
398
508
  // The API's entryProbability is the RAW mid, and executionModel's effective
399
509
  // probability excludes fee. Total stake / net shares is the fee-inclusive
400
510
  // break-even cost. Do not guess units or fall back to a discovery mid.
511
+ const maxEdge = spec.risk.pmMaxEdgePoints;
512
+ if (!ctx.mechanical && maxEdge !== undefined) {
513
+ if (typeof maxEdge !== "number" ||
514
+ !Number.isFinite(maxEdge) ||
515
+ maxEdge < 0 ||
516
+ maxEdge > 100) {
517
+ return fail("pm_max_edge_invalid", `risk.pmMaxEdgePoints ${JSON.stringify(maxEdge)} is not a number between 0 and 100`);
518
+ }
519
+ // An overconfidence cap cannot be checked against a missing number.
520
+ if (action.forecastProbability == null) {
521
+ return fail("pm_forecast_required", `risk.pmMaxEdgePoints ${maxEdge} needs forecastProbability on every pm_open`);
522
+ }
523
+ }
524
+ const edgeGapPct = spec.risk.pmMinEdgeGapPct;
525
+ if (!ctx.mechanical && edgeGapPct !== undefined) {
526
+ if (typeof edgeGapPct !== "number" ||
527
+ !Number.isFinite(edgeGapPct) ||
528
+ edgeGapPct < 0 ||
529
+ edgeGapPct > 100) {
530
+ return fail("pm_edge_gap_invalid", `risk.pmMinEdgeGapPct ${JSON.stringify(edgeGapPct)} is not a number between 0 and 100`);
531
+ }
532
+ // An edge rule cannot be checked against a missing number.
533
+ if (action.forecastProbability == null) {
534
+ return fail("pm_forecast_required", `risk.pmMinEdgeGapPct ${edgeGapPct} needs forecastProbability on every pm_open`);
535
+ }
536
+ }
401
537
  if (!ctx.mechanical && action.forecastProbability != null) {
402
538
  const stake = ctx.quote.stakeMusd;
403
539
  const shares = ctx.quote.sharesEstimate;
@@ -418,6 +554,15 @@ export function validateAction(action, ctx) {
418
554
  if (edge + 1e-9 < PM_MIN_FORECAST_EDGE_POINTS) {
419
555
  return fail("forecast_no_positive_edge", `forecast ${action.forecastProbability} vs entry ${entryPct.toFixed(1)} = ${edge.toFixed(1)}pt edge, under the ${PM_MIN_FORECAST_EDGE_POINTS}pt minimum`);
420
556
  }
557
+ if (maxEdge !== undefined && edge > maxEdge + 1e-9) {
558
+ return fail("pm_edge_overconfident", `forecast ${action.forecastProbability} vs entry ${entryPct.toFixed(1)} = ${edge.toFixed(1)}pt edge, over the ${maxEdge}pt cap`);
559
+ }
560
+ if (edgeGapPct !== undefined) {
561
+ const required = requiredGapEdgePoints(entryPct, edgeGapPct);
562
+ if (edge + 1e-9 < required) {
563
+ return fail("pm_edge_below_gap_rule", `forecast ${action.forecastProbability} vs entry ${entryPct.toFixed(1)} = ${edge.toFixed(1)}pt edge, under the ${required.toFixed(1)}pt required by ${edgeGapPct}% of the gap to 100`);
564
+ }
565
+ }
421
566
  }
422
567
  if (thesisContradictsOutcome(action.thesis?.summary, mkt.outcomeName)) {
423
568
  return fail("thesis_action_conflict", `thesis bets against ${mkt.outcomeName}, which this action buys`);
@@ -1,9 +1,9 @@
1
1
  export { runCycle, type RunnerDeps } from "./runner.js";
2
2
  export { buildAgentDefinitionSnapshot, type AgentDefinitionSnapshot, } from "./definitionSnapshot.js";
3
3
  export { DECISION_INPUT_MAX_BYTES, sanitizeDecisionInputRecord, type DecisionInputRecord, } from "./decisionReceipt.js";
4
- export { selectProvider, providerForRoute, classifyProviderFailure, type ProviderEnv, type Provider, type DecideInput, type DecideResult, type DecideRouteAttempt, type DecideRouteMeta, } from "./providers.js";
5
- export { parseDecision } from "./decision.js";
6
- export { chatShapeFor, buildChatBody, type ChatShape, } from "./providerCapabilities.js";
4
+ export { selectProvider, providerForRoute, classifyProviderFailure, anthropicUsage, type ProviderUsage, type ProviderEnv, type ProviderRouteOptions, type Provider, type DecideInput, type DecideResult, type DecideRouteAttempt, type DecideRouteMeta, } from "./providers.js";
5
+ export { parseDecision, ACTIONS_STRING_DIAGNOSTICS, type ActionsStringDiagnostic, } from "./decision.js";
6
+ export { chatShapeFor, buildChatBody, canRetrySuperToolOutput, type ChatShape, } from "./providerCapabilities.js";
7
7
  export { probeDecisionContract, type ProbeRoute, type ProbeDecisionResult, } from "./decisionProbe.js";
8
8
  export { CoinRithmClient } from "./client.js";
9
9
  export { loadAgent, buildSpec, type LoadedAgent } from "./skill.js";
@@ -8,12 +8,12 @@
8
8
  export { runCycle } from "./runner.js";
9
9
  export { buildAgentDefinitionSnapshot, } from "./definitionSnapshot.js";
10
10
  export { DECISION_INPUT_MAX_BYTES, sanitizeDecisionInputRecord, } from "./decisionReceipt.js";
11
- export { selectProvider, providerForRoute, classifyProviderFailure, } from "./providers.js";
12
- export { parseDecision } from "./decision.js";
11
+ export { selectProvider, providerForRoute, classifyProviderFailure, anthropicUsage, } from "./providers.js";
12
+ export { parseDecision, ACTIONS_STRING_DIAGNOSTICS, } from "./decision.js";
13
13
  // Reliability slice A: the declarative request-capability table and the
14
14
  // representative decision probe (route eligibility = a REAL parsed decision,
15
15
  // never a bare HTTP 200 — the 62f3a12 lesson).
16
- export { chatShapeFor, buildChatBody, } from "./providerCapabilities.js";
16
+ export { chatShapeFor, buildChatBody, canRetrySuperToolOutput, } from "./providerCapabilities.js";
17
17
  export { probeDecisionContract, } from "./decisionProbe.js";
18
18
  export { CoinRithmClient } from "./client.js";
19
19
  export { loadAgent, buildSpec } from "./skill.js";
@@ -1,5 +1,5 @@
1
1
  import { CoinRithmClient } from "./client.js";
2
- import { AgentSpec, RunState, Observation, AgentTrace, PmCalibration, WhaleContext } from "./types.js";
2
+ import { AgentSpec, RunState, Observation, OpenInterestContext, PositioningContext, LiquidationContext, MacroContext, ChainTvlContext, StablecoinSupplyContext, DepthContext, FundingByVenueContext, AgentTrace, PmCalibration, WhaleContext } from "./types.js";
3
3
  export interface ObserveOutput {
4
4
  observation: Observation;
5
5
  skip?: string;
@@ -16,4 +16,29 @@ export declare function isCalibrationChurnMarket(market: {
16
16
  slug?: string;
17
17
  title?: string;
18
18
  }): boolean;
19
- export declare function observe(client: CoinRithmClient, spec: AgentSpec, state: RunState, trace?: AgentTrace): Promise<ObserveOutput>;
19
+ export declare function openInterestOf(m: Record<string, unknown>, nowMs?: number): OpenInterestContext | undefined;
20
+ export declare function positioningOf(m: Record<string, unknown>, nowMs?: number): PositioningContext | undefined;
21
+ export declare function liquidationsOf(m: Record<string, unknown>, nowMs?: number): LiquidationContext | undefined;
22
+ /**
23
+ * `{ coins }` from an additive `relatedCoins` array (direct coin slugs), or
24
+ * nothing: non-arrays and non-string/blank entries are dropped, duplicates
25
+ * merged. Every valid slug is kept: the API never truncates the list, and
26
+ * dropping a linked coin could let a bet bypass that coin's cap. An empty
27
+ * result adds no field.
28
+ */
29
+ export declare function coinsField(value: unknown): {
30
+ coins?: string[];
31
+ };
32
+ export declare function fundingByVenueOf(m: Record<string, unknown>, nowMs?: number): FundingByVenueContext | undefined;
33
+ export declare function depthOf(m: Record<string, unknown>, nowMs?: number): DepthContext | undefined;
34
+ export declare function chainTvlOf(m: Record<string, unknown>, nowMs?: number): ChainTvlContext | undefined;
35
+ export declare function stablecoinSupplyOf(m: Record<string, unknown>, nowMs?: number): StablecoinSupplyContext | undefined;
36
+ export declare function macroOf(m: Record<string, unknown>, nowMs?: number): MacroContext | undefined;
37
+ /** Bench-only observation overrides; live callers pass none. */
38
+ export interface ObserveOptions {
39
+ /** Read the curated PM board (depth 30, churn removed, calibration read)
40
+ * even for a mechanical spec, so a bench baseline sees the recorded
41
+ * agent opportunity set. Default: non-mechanical only. */
42
+ curatedPmBoard?: boolean;
43
+ }
44
+ export declare function observe(client: CoinRithmClient, spec: AgentSpec, state: RunState, trace?: AgentTrace, options?: ObserveOptions): Promise<ObserveOutput>;