Skip to content

Commit d1a245a

Browse files
feat(trading): entry quotes, exits, and the receipts that make a run provable
Adds the execution-harness pieces the trading run was missing across contracts, server, and web: contracts: decision, exit, policy, quote, recovery, replay, and setupEvidence modules in packages/trading-contracts, with tests. server: TradingQuoteService, TradingExitService, TradingRunTelemetry, TradingExecutionReceipts, TradingExecutionSequence, TradingReplayFixtures, RetryTransient, TradingSessionProfile; migrations 051-053 for run decisions, entry quotes, and execution sequences. web: TradingAssetPicker and a MissionLivePanel state refactor; drops the now-unused missionLockedProviderMessages path.
1 parent 8a48f8d commit d1a245a

100 files changed

Lines changed: 9260 additions & 1322 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/server/integration/TradingExecutionReachability.integration.test.ts‎

Lines changed: 67 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import type {
5656
ResolvedMarket,
5757
} from "@t3tools/trading-contracts/market";
5858
import type { AgentOpenOrder } from "@t3tools/trading-contracts/account-snapshot";
59+
import * as Clock from "effect/Clock";
5960
import * as Effect from "effect/Effect";
6061
import * as Exit from "effect/Exit";
6162
import * as Layer from "effect/Layer";
@@ -138,8 +139,14 @@ const NOW = "2026-08-01T00:00:00.000Z";
138139
// --- recording fake exchange ------------------------------------------------
139140
interface RecordingExchange {
140141
submitted: SignedAction[];
142+
positionSize: number;
143+
filledAt: number | null;
141144
}
142-
const recordingExchange: RecordingExchange = { submitted: [] };
145+
const recordingExchange: RecordingExchange = {
146+
submitted: [],
147+
positionSize: 0,
148+
filledAt: null,
149+
};
143150

144151
/**
145152
* The real `/exchange` order response: rows nested under `response.data`,
@@ -203,16 +210,32 @@ const recordProtectiveLegs = (signed: SignedAction): void => {
203210
}
204211
};
205212

213+
/** Apply the filled entry leg to the fake's canonical account state. */
214+
const recordFilledEntry = (signed: SignedAction, filledAt: number): void => {
215+
const orders = (signed.action as { orders?: ReadonlyArray<unknown> }).orders ?? [];
216+
const entry = orders.find((leg) => {
217+
const order = leg as { r?: boolean; t?: { trigger?: unknown } };
218+
return order.r !== true && order.t?.trigger === undefined;
219+
}) as { b?: boolean; s?: string } | undefined;
220+
if (entry === undefined) return;
221+
222+
const size = Number(entry.s ?? 0);
223+
recordingExchange.positionSize += entry.b === true ? size : -size;
224+
recordingExchange.filledAt = filledAt;
225+
};
226+
206227
const recordingExchangeLayer = Layer.succeed(HyperliquidExchangeClient, {
207228
submit: (signed: SignedAction) =>
208-
Effect.sync(() => {
229+
Effect.gen(function* () {
230+
const filledAt = yield* Clock.currentTimeMillis;
209231
recordingExchange.submitted.push(signed);
232+
recordFilledEntry(signed, filledAt);
210233
recordProtectiveLegs(signed);
211234
return OK_FILLED;
212235
}),
213236
} as unknown as HyperliquidExchangeClient["Service"]);
214237

215-
// --- fake gateway: ETH market + fresh BBO + a filled position ---------------
238+
// --- fake gateway: ETH market + fresh BBO + exchange-owned position state ---
216239
const ethMarket = {
217240
symbol: "ETH",
218241
assetIndex: 1,
@@ -250,22 +273,26 @@ const fakeGatewayLayer = Layer.succeed(HyperliquidGateway, {
250273
getMarketSnapshot: (() => Effect.die("not used")) as never,
251274
getMarketHistory: (() => Effect.die("not used")) as never,
252275
getAccountSnapshot: () =>
253-
Effect.succeed({
276+
Effect.sync(() => ({
254277
masterAddress: MASTER_ADDR,
278+
accountValue: 100,
255279
marginSummary: { accountValue: "100", totalMarginUsed: "1500" },
256280
withdrawable: "0",
257-
positions: [
258-
{
259-
market: "ETH",
260-
size: 0.5,
261-
entryPrice: 3001,
262-
unrealisedPnl: 0,
263-
cumulativeFunding: "0",
264-
marginUsed: "1500",
265-
liquidationPx: undefined,
266-
},
267-
],
268-
}),
281+
positions:
282+
recordingExchange.positionSize === 0
283+
? []
284+
: [
285+
{
286+
market: "ETH",
287+
size: recordingExchange.positionSize,
288+
entryPrice: 3001,
289+
unrealisedPnl: 0,
290+
cumulativeFunding: "0",
291+
marginUsed: "1500",
292+
liquidationPx: undefined,
293+
},
294+
],
295+
})),
269296
getPosition: (() => Effect.die("not used")) as never,
270297
getOpenOrders: () => Effect.sync(() => restingProtection),
271298
getTakerFeeRateBps: () => Effect.succeed({ feeBps: 4.5, observedAt: 1_000 }),
@@ -303,19 +330,23 @@ const fakeInfoClientLayer = Layer.succeed(HyperliquidInfoClient, {
303330
}),
304331
openOrders: () => Effect.succeed([]),
305332
userFills: () =>
306-
Effect.succeed([
307-
{
308-
coin: "ETH",
309-
side: "B",
310-
px: "3001",
311-
sz: "0.5",
312-
time: 1_000,
313-
fee: "0.07",
314-
oid: 999,
315-
cloid: undefined,
316-
hash: "0xtestfillreach",
317-
},
318-
]),
333+
Effect.sync(() =>
334+
recordingExchange.filledAt === null
335+
? []
336+
: [
337+
{
338+
coin: "ETH",
339+
side: "B",
340+
px: "3001",
341+
sz: "0.5",
342+
time: recordingExchange.filledAt,
343+
fee: "0.07",
344+
oid: 999,
345+
cloid: undefined,
346+
hash: "0xtestfillreach",
347+
},
348+
],
349+
),
319350
userFees: () => Effect.succeed({ userCrossRate: "0.00045" }),
320351
} as unknown as HyperliquidInfoClient["Service"]);
321352

@@ -338,6 +369,7 @@ const fakeWebSocketLayer = Layer.succeed(HyperliquidWebSocketClient, {
338369
// (mirroring runtimeLayer.ts, swapping the HTTP clients for the recording
339370
// fakes). This does not modify runtimeLayer.ts; it composes the same live
340371
// service layers around a faked foundation.
372+
import { TradingExecutionReceiptsLive } from "../src/trading/TradingExecutionReceipts.ts";
341373
import { TradingMissionServiceLive } from "../src/trading/TradingMissionService.ts";
342374
import { TradingStrategyServiceLive } from "../src/trading/TradingStrategyService.ts";
343375
import { TradingWatchServiceLive } from "../src/trading/TradingWatchService.ts";
@@ -376,6 +408,9 @@ const tradingFoundationWithFakes = Layer.mergeAll(
376408
fakeGatewayLayer,
377409
fakeInfoClientLayer,
378410
fakeWebSocketLayer,
411+
// The reactor opens an execution latch; the outcome service waits on it. One
412+
// instance, as in runtimeLayer.ts, or the two never meet.
413+
TradingExecutionReceiptsLive,
379414
HyperliquidNonceCoordinatorLive(),
380415
NodeCrypto.layer,
381416
);
@@ -703,6 +738,9 @@ it.live(
703738
// commandId generation; the command shape is identical — see
704739
// handlers.ts trading_request_entry.)
705740
recordingExchange.submitted.length = 0;
741+
recordingExchange.positionSize = 0;
742+
recordingExchange.filledAt = null;
743+
restingProtection.length = 0;
706744
yield* engine.dispatch({
707745
type: "trading.execution.requested",
708746
commandId: commandId("exec-request"),

‎apps/server/src/mcp/McpHttpServer.ts‎

Lines changed: 95 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as Schema from "effect/Schema";
77
import * as Sink from "effect/Sink";
88
import * as Stream from "effect/Stream";
99
import type * as Types from "effect/Types";
10+
import * as SqlClient from "effect/unstable/sql/SqlClient";
1011
import { AiError, McpSchema, McpServer, Tool, Toolkit } from "effect/unstable/ai";
1112
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
1213

@@ -26,6 +27,7 @@ import {
2627
} from "./toolkits/preview/tools.ts";
2728
import { TradingToolkitHandlersLive } from "./toolkits/trading/handlers.ts";
2829
import { TradingToolkit } from "./toolkits/trading/tools.ts";
30+
import * as TradingRunTelemetry from "../trading/TradingRunTelemetry.ts";
2931

3032
const unauthorized = HttpServerResponse.jsonUnsafe(
3133
{
@@ -234,6 +236,22 @@ const toolErrorResult = (message: string) =>
234236
content: [{ type: "text", text: message }],
235237
});
236238

239+
/** In-band tool outcomes that mean the requested operation did not succeed. */
240+
const isRejectedToolResult = (result: McpSchema.CallToolResult): boolean => {
241+
if (result.isError === true) return true;
242+
const content = result.structuredContent;
243+
if (content === undefined) return false;
244+
const outcome = content["outcome"];
245+
const status = content["status"];
246+
return (
247+
outcome === "rejected" ||
248+
outcome === "refused" ||
249+
status === "rejected" ||
250+
status === "refused" ||
251+
status === "failed"
252+
);
253+
};
254+
237255
/**
238256
* Register a toolkit with argument coercion at the boundary.
239257
*
@@ -257,6 +275,10 @@ const registerToolkitLenient = Effect.fnUntraced(function* <Tools extends Record
257275
const registry = yield* McpServer.McpServer;
258276
const built = yield* toolkit;
259277
const services = yield* Effect.context();
278+
// The decision funnel's tool-call hook. This boundary is the only place that
279+
// sees every trading tool call with its outcome, which is what makes "the
280+
// model never called execute" distinguishable from "the call failed".
281+
const sql = yield* SqlClient.SqlClient;
260282
for (const tool of Object.values(built.tools)) {
261283
const annotations = tool.annotations;
262284
const toolMeta = Context.getOrUndefined(annotations, Tool.Meta);
@@ -281,51 +303,79 @@ const registerToolkitLenient = Effect.fnUntraced(function* <Tools extends Record
281303
}),
282304
annotations,
283305
handle: (payload: unknown) =>
284-
built
285-
.handle(
286-
tool.name,
287-
// Coercion returns `unknown`; the toolkit's handle expects the
288-
// tool's decoded input type. The cast mirrors the upstream
289-
// registration, which receives `payload: any` — coercion only
290-
// rewrites values that satisfy the schema, so validation below is
291-
// unchanged.
292-
coerceToolArguments(inputSchema, payload) as never,
293-
)
294-
.pipe(
295-
Stream.unwrap,
296-
Stream.run(Sink.last()),
297-
Effect.flatMap(Effect.fromOption),
298-
Effect.provideContext(services),
299-
Effect.map(
300-
(result) =>
301-
new McpSchema.CallToolResult({
302-
isError: false,
303-
structuredContent:
304-
typeof result.encodedResult === "object"
305-
? (result.encodedResult as Record<string, unknown>)
306-
: undefined,
307-
content: [{ type: "text", text: JSON.stringify(result.encodedResult) }],
308-
}),
309-
),
310-
Effect.tapCause(Effect.logError),
311-
Effect.catch((error: unknown) => {
312-
if (AiError.isAiError(error)) {
313-
const reason = error.reason;
314-
return Effect.succeed(
315-
reason._tag === "ToolParameterValidationError"
316-
? toolErrorResult(reason.message)
317-
: toolErrorResult(INTERNAL_TOOL_ERROR_MESSAGE),
318-
);
319-
}
320-
if (isDeclaredFailure(error)) {
321-
const message =
322-
error instanceof Error ? error.message : INTERNAL_TOOL_ERROR_MESSAGE;
323-
return Effect.succeed(toolErrorResult(message));
324-
}
325-
return Effect.succeed(toolErrorResult(INTERNAL_TOOL_ERROR_MESSAGE));
326-
}),
327-
Effect.catchDefect(() => Effect.succeed(toolErrorResult(INTERNAL_TOOL_ERROR_MESSAGE))),
328-
),
306+
Effect.withFiber((fiber) => {
307+
const invocation = Context.getOrUndefined(
308+
fiber.context,
309+
McpInvocationContext.McpInvocationContext,
310+
);
311+
return built
312+
.handle(
313+
tool.name,
314+
// Coercion returns `unknown`; the toolkit's handle expects the
315+
// tool's decoded input type. The cast mirrors the upstream
316+
// registration, which receives `payload: any` — coercion only
317+
// rewrites values that satisfy the schema, so validation below is
318+
// unchanged.
319+
coerceToolArguments(inputSchema, payload) as never,
320+
)
321+
.pipe(
322+
Stream.unwrap,
323+
Stream.run(Sink.last()),
324+
Effect.flatMap(Effect.fromOption),
325+
Effect.provideContext(services),
326+
Effect.map(
327+
(result) =>
328+
new McpSchema.CallToolResult({
329+
isError: false,
330+
structuredContent:
331+
typeof result.encodedResult === "object"
332+
? (result.encodedResult as Record<string, unknown>)
333+
: undefined,
334+
content: [{ type: "text", text: JSON.stringify(result.encodedResult) }],
335+
}),
336+
),
337+
Effect.tapCause(Effect.logError),
338+
Effect.catch((error: unknown) => {
339+
if (AiError.isAiError(error)) {
340+
const reason = error.reason;
341+
return Effect.succeed(
342+
reason._tag === "ToolParameterValidationError"
343+
? toolErrorResult(reason.message)
344+
: toolErrorResult(INTERNAL_TOOL_ERROR_MESSAGE),
345+
);
346+
}
347+
if (isDeclaredFailure(error)) {
348+
const message =
349+
error instanceof Error ? error.message : INTERNAL_TOOL_ERROR_MESSAGE;
350+
return Effect.succeed(toolErrorResult(message));
351+
}
352+
return Effect.succeed(toolErrorResult(INTERNAL_TOOL_ERROR_MESSAGE));
353+
}),
354+
Effect.catchDefect(() =>
355+
Effect.succeed(toolErrorResult(INTERNAL_TOOL_ERROR_MESSAGE)),
356+
),
357+
// Every call is now a `CallToolResult`, error or not — the one
358+
// place that knows both the tool name and what the agent was told.
359+
Effect.tap((result) =>
360+
invocation === undefined
361+
? Effect.void
362+
: TradingRunTelemetry.recordToolCall(sql, {
363+
threadId: invocation.threadId,
364+
tool: tool.name,
365+
ok: result.isError !== true,
366+
accepted: !isRejectedToolResult(result),
367+
...(result.isError === true
368+
? {
369+
errorMessage:
370+
result.content[0]?.type === "text"
371+
? result.content[0].text
372+
: JSON.stringify(result.structuredContent ?? {}),
373+
}
374+
: {}),
375+
}).pipe(Effect.catchCause(() => Effect.void)),
376+
),
377+
);
378+
}),
329379
});
330380
}
331381
});

0 commit comments

Comments
 (0)