@pgnio/helios-mcp 0.2.4 → 0.2.6

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.
@@ -0,0 +1,3042 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // ../agent/dist/index.mjs
6
+ import { z } from "zod";
7
+ import { z as z2 } from "zod";
8
+ import { z as z3 } from "zod";
9
+ var __defProp2 = Object.defineProperty;
10
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
12
+ var AGENT_SCOPES = {
13
+ ACCOUNT_READ: "account:read",
14
+ MARKET_READ: "market:read",
15
+ ORDERS_WRITE: "orders:write",
16
+ ORDERS_CANCEL: "orders:cancel"
17
+ };
18
+ var AGENT_SCOPE_VALUES = [
19
+ AGENT_SCOPES.ACCOUNT_READ,
20
+ AGENT_SCOPES.MARKET_READ,
21
+ AGENT_SCOPES.ORDERS_WRITE,
22
+ AGENT_SCOPES.ORDERS_CANCEL
23
+ ];
24
+ var agentScopeSchema = z.enum(AGENT_SCOPE_VALUES);
25
+ var agentGrantStatusSchema = z.enum(["active", "revoked"]);
26
+ var agentDeviceRequestStatusSchema = z.enum(["pending", "approved", "rejected", "exchanged", "expired"]);
27
+ var agentConstraintsSchema = z.record(z.string(), z.unknown()).default({});
28
+ var agentGrantMetadataSchema = z.object({
29
+ id: z.string(),
30
+ userId: z.string(),
31
+ clientName: z.string(),
32
+ status: agentGrantStatusSchema,
33
+ scope: z.array(agentScopeSchema).min(1),
34
+ constraints: agentConstraintsSchema,
35
+ tokenVersion: z.number().int().nonnegative(),
36
+ createdAt: z.string(),
37
+ approvedAt: z.string().optional(),
38
+ lastUsedAt: z.string().optional(),
39
+ revokedAt: z.string().optional()
40
+ });
41
+ var agentDeviceStartInputSchema = z.object({
42
+ clientName: z.string().min(1).max(64),
43
+ scope: z.array(agentScopeSchema).min(1),
44
+ constraints: agentConstraintsSchema.optional()
45
+ });
46
+ var agentDeviceStartOutputSchema = z.object({
47
+ deviceCode: z.string(),
48
+ userCode: z.string(),
49
+ verificationUri: z.string().url(),
50
+ verificationUriComplete: z.string().url(),
51
+ expiresInSeconds: z.number().int().positive(),
52
+ pollIntervalSeconds: z.number().int().positive()
53
+ });
54
+ var agentDeviceTokenInputSchema = z.object({
55
+ deviceCode: z.string().min(1)
56
+ });
57
+ var agentDeviceRequestViewSchema = z.object({
58
+ userCode: z.string(),
59
+ clientName: z.string(),
60
+ scope: z.array(agentScopeSchema).min(1),
61
+ constraints: agentConstraintsSchema,
62
+ status: agentDeviceRequestStatusSchema,
63
+ expiresAt: z.string()
64
+ });
65
+ var agentTokenResponseSchema = z.object({
66
+ accessToken: z.string(),
67
+ refreshToken: z.string(),
68
+ tokenType: z.literal("Bearer"),
69
+ expiresInSeconds: z.number().int().positive(),
70
+ scope: z.array(agentScopeSchema).min(1),
71
+ ownerUserId: z.string(),
72
+ agentGrantId: z.string()
73
+ });
74
+ var agentRefreshInputSchema = z.object({
75
+ refreshToken: z.string().min(1)
76
+ });
77
+ var agentApprovalResponseSchema = z.object({
78
+ request: agentDeviceRequestViewSchema,
79
+ grant: agentGrantMetadataSchema
80
+ });
81
+ var agentSessionStateSchema = z.object({
82
+ status: z.enum(["pending", "authorized", "rejected", "revoked"]),
83
+ request: agentDeviceRequestViewSchema.optional(),
84
+ grant: agentGrantMetadataSchema.optional()
85
+ });
86
+ var providerSchema = z.enum(["hyperliquid"]);
87
+ var walletStateSchema = z.object({
88
+ provider: z.literal("hyperliquid"),
89
+ accountValue: z.number(),
90
+ availableBalance: z.number(),
91
+ withdrawable: z.number(),
92
+ totalMarginUsed: z.number(),
93
+ totalNotionalPosition: z.number(),
94
+ crossMarginAccountValue: z.number(),
95
+ isActivated: z.boolean(),
96
+ fetchedAt: z.string().datetime()
97
+ });
98
+ var openPositionSchema = z.object({
99
+ symbol: z.string(),
100
+ side: z.enum(["LONG", "SHORT"]),
101
+ size: z.number(),
102
+ entryPrice: z.number(),
103
+ markPrice: z.number(),
104
+ unrealizedPnl: z.number(),
105
+ margin: z.number(),
106
+ leverage: z.number(),
107
+ liquidationPrice: z.number().optional()
108
+ });
109
+ var openPositionsSnapshotSchema = z.object({
110
+ provider: z.literal("hyperliquid"),
111
+ fetchedAt: z.string().datetime(),
112
+ totalUnrealizedPnl: z.number(),
113
+ positions: z.array(openPositionSchema)
114
+ });
115
+ var protectiveOrderKindSchema = z.enum(["STOP_LOSS", "TAKE_PROFIT"]);
116
+ var protectiveOrderSideSchema = z.enum(["BUY", "SELL"]);
117
+ var protectiveOrderPositionSideSchema = z.enum(["BOTH", "LONG", "SHORT"]);
118
+ var protectiveOrderSchema = z.object({
119
+ id: z.string(),
120
+ binanceOrderId: z.number().int().nonnegative().optional(),
121
+ clientOrderId: z.string().optional(),
122
+ symbol: z.string(),
123
+ side: protectiveOrderSideSchema,
124
+ positionSide: protectiveOrderPositionSideSchema,
125
+ status: z.string(),
126
+ kind: protectiveOrderKindSchema,
127
+ groupId: z.string(),
128
+ stopPrice: z.string().optional(),
129
+ parentClientOrderId: z.string().optional(),
130
+ assetId: z.number().int().nonnegative().optional(),
131
+ createdAt: z.string().datetime()
132
+ });
133
+ var hyperliquidPortfolioSnapshotSchema = z.object({
134
+ provider: z.literal("hyperliquid"),
135
+ totalBalance: z.number(),
136
+ availableBalance: z.number(),
137
+ totalMargin: z.number(),
138
+ unrealizedPnl: z.number(),
139
+ positions: z.array(openPositionSchema),
140
+ protectiveOrders: z.array(protectiveOrderSchema)
141
+ });
142
+ var portfolioInputSchema = z.object({
143
+ provider: providerSchema
144
+ });
145
+ var portfolioSnapshotSchema = hyperliquidPortfolioSnapshotSchema;
146
+ var ledgerWindowSchema = z.enum(["24h", "7d", "30d"]);
147
+ var ledgerFillsInputSchema = z.object({
148
+ window: ledgerWindowSchema.optional(),
149
+ limit: z.number().int().positive().max(200).optional(),
150
+ before: z.number().int().nonnegative().optional()
151
+ });
152
+ var ledgerFillSchema = z.object({
153
+ coin: z.string(),
154
+ px: z.number(),
155
+ sz: z.number(),
156
+ side: z.enum(["B", "A"]),
157
+ time: z.number().int().nonnegative(),
158
+ dir: z.string(),
159
+ closedPnl: z.number(),
160
+ fee: z.number(),
161
+ crossed: z.boolean(),
162
+ oid: z.number().int().nonnegative(),
163
+ tid: z.number().int().nonnegative()
164
+ });
165
+ var ledgerFillsPageSchema = z.object({
166
+ window: ledgerWindowSchema,
167
+ limit: z.number().int().positive(),
168
+ before: z.number().int().nonnegative().optional(),
169
+ hasMore: z.boolean(),
170
+ nextBefore: z.number().int().nonnegative().optional(),
171
+ fetchedAt: z.string().datetime(),
172
+ fills: z.array(ledgerFillSchema)
173
+ });
174
+ var ledgerPeriodSummarySchema = z.object({
175
+ realizedPnl: z.number(),
176
+ totalFees: z.number(),
177
+ fillCount: z.number().int().nonnegative(),
178
+ closeCount: z.number().int().nonnegative(),
179
+ winCount: z.number().int().nonnegative(),
180
+ lossCount: z.number().int().nonnegative(),
181
+ averageWin: z.number(),
182
+ averageLoss: z.number()
183
+ });
184
+ var ledgerSummaryInputSchema = z.object({
185
+ window: ledgerWindowSchema.optional()
186
+ });
187
+ var ledgerSummarySchema = ledgerPeriodSummarySchema.extend({
188
+ window: ledgerWindowSchema,
189
+ generatedAt: z.string().datetime(),
190
+ periods: z.object({
191
+ "24h": ledgerPeriodSummarySchema,
192
+ "7d": ledgerPeriodSummarySchema
193
+ })
194
+ });
195
+ var marketSnapshotScopeSchema = z.enum(["selected", "all"]);
196
+ var marketSnapshotResolvedScopeSchema = z.enum(["selected", "all", "explicit"]);
197
+ var marketSnapshotValueSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
198
+ var marketSnapshotInputSchema = z.object({
199
+ scope: marketSnapshotScopeSchema.optional(),
200
+ symbols: z.array(z.string().min(1)).min(1).optional(),
201
+ fields: z.array(z.string().min(1)).min(1).optional().describe("Table columns to return; sym and base always come back. Ids: rank, lp, bv, qv, ts, r1m, r3m, r5m, r15m, r30m, r1h, r2h, r4h, r6h, r8h, r12h, r24h, r3d, r7d, hmi, hmiv, reg, ob, de, hfi, ar, ms, vcc, vcp, obosd, obosp, vwap, vwz, poc, pocd, vap, macdh, macds, macdd, srs, srr, fh24, fl24, fh7, fl7, sr, az, hfiw, trv, tri, trh, hs."),
202
+ sort: z.enum(["rank"]).optional().describe('"rank" orders rows by market cap rank, unranked last.')
203
+ });
204
+ var marketSnapshotChunkInputSchema = marketSnapshotInputSchema.extend({
205
+ offset: z.number().int().nonnegative().optional(),
206
+ limit: z.number().int().positive().max(100).optional()
207
+ });
208
+ var marketFieldBlockSchema = z.object({
209
+ fieldIds: z.array(z.string()).min(1),
210
+ values: z.array(marketSnapshotValueSchema),
211
+ symbolLists: z.record(z.string(), z.array(z.string())).optional()
212
+ });
213
+ var marketMatrixSchema = z.object({
214
+ fieldIds: z.array(z.string()).min(1),
215
+ rows: z.array(z.array(marketSnapshotValueSchema))
216
+ });
217
+ var marketFieldSemanticsSchema = z.object({
218
+ nullMeans: z.literal("unavailable"),
219
+ percentScale: z.literal("already_percent"),
220
+ percentFields: z.array(z.string()).min(1),
221
+ changeMapPercentKeys: z.array(z.string()).min(1)
222
+ });
223
+ var marketSnapshotSchema = z.object({
224
+ schema: z.literal("helios.market_snapshot.v1"),
225
+ view: z.literal("market_overview"),
226
+ scope: marketSnapshotResolvedScopeSchema,
227
+ symbolCount: z.number().int().nonnegative(),
228
+ generatedAt: z.string().datetime(),
229
+ returnedSymbols: z.array(z.string()),
230
+ semantics: marketFieldSemanticsSchema,
231
+ market: marketFieldBlockSchema,
232
+ table: marketMatrixSchema,
233
+ legend: z.record(z.string(), z.union([z.string(), z.array(z.string())]))
234
+ });
235
+ var marketSnapshotChunkSchema = z.object({
236
+ schema: z.literal("helios.market_snapshot_chunk.v1"),
237
+ view: z.literal("market_overview_chunk"),
238
+ scope: marketSnapshotResolvedScopeSchema,
239
+ totalSymbolCount: z.number().int().nonnegative(),
240
+ generatedAt: z.string().datetime(),
241
+ offset: z.number().int().nonnegative(),
242
+ limit: z.number().int().positive(),
243
+ chunkSymbolCount: z.number().int().nonnegative(),
244
+ hasMore: z.boolean(),
245
+ nextOffset: z.number().int().nonnegative().optional(),
246
+ returnedSymbols: z.array(z.string()),
247
+ semantics: marketFieldSemanticsSchema,
248
+ market: marketFieldBlockSchema,
249
+ table: marketMatrixSchema,
250
+ legend: z.record(z.string(), z.union([z.string(), z.array(z.string())]))
251
+ });
252
+ var marketSymbolDetailInputSchema = z.object({
253
+ symbol: z.string().min(1)
254
+ });
255
+ var marketSymbolDetailSchema = z.object({
256
+ schema: z.literal("helios.market_symbol_detail.v1"),
257
+ generatedAt: z.string().datetime(),
258
+ symbol: z.string(),
259
+ semantics: marketFieldSemanticsSchema,
260
+ market: marketFieldBlockSchema,
261
+ row: z.record(z.string(), marketSnapshotValueSchema),
262
+ symbolCtx: z.record(z.string(), marketSnapshotValueSchema),
263
+ changeMap: z.record(z.string(), z.number().nullable()),
264
+ metrics: z.record(z.string(), z.unknown()).nullable(),
265
+ legend: z.record(z.string(), z.union([z.string(), z.array(z.string())]))
266
+ });
267
+ var tradingDirectionSchema = z.enum(["LONG", "SHORT"]);
268
+ var tradingExecutionStyleSchema = z.enum(["MARKET", "LIMIT_TAKER", "LIMIT_MAKER", "LIMIT_GTC"]);
269
+ var tradingSizeSchema = z.object({
270
+ mode: z.enum(["MARGIN_USD", "BASE_QUANTITY"]),
271
+ value: z.number().positive()
272
+ });
273
+ var tradingProtectionLegSchema = z.object({
274
+ kind: z.enum(["LIMIT", "MARKET"]),
275
+ triggerPrice: z.number().positive(),
276
+ limitPrice: z.number().positive().optional()
277
+ });
278
+ var tradingProtectionSchema = z.object({
279
+ takeProfit: tradingProtectionLegSchema.optional(),
280
+ stopLoss: tradingProtectionLegSchema.optional()
281
+ });
282
+ var tradeIntentTypeSchema = z.enum(["OPEN", "DCA", "REVERSE", "CLOSE"]);
283
+ var submitTradeIntentInputSchema = z.object({
284
+ provider: providerSchema.optional(),
285
+ symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
286
+ intentType: tradeIntentTypeSchema,
287
+ direction: tradingDirectionSchema,
288
+ size: tradingSizeSchema,
289
+ execution: z.object({
290
+ style: tradingExecutionStyleSchema,
291
+ timeInForce: z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
292
+ limitPrice: z.number().positive().optional()
293
+ }),
294
+ maxSlippageBps: z.number().int().nonnegative().max(1e3).optional(),
295
+ leverageOverride: z.number().positive().optional(),
296
+ marginModeOverride: z.enum(["ISOLATED", "CROSS"]).optional(),
297
+ reduceOnly: z.boolean().optional(),
298
+ protection: tradingProtectionSchema.optional(),
299
+ /** One per user action, reused on retries: the data-bridge never places a second order for the same key. */
300
+ idempotencyKey: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional()
301
+ });
302
+ var submitTradeIntentResultSchema = z.object({
303
+ status: z.literal("submitted"),
304
+ /** `replayed`: an earlier attempt of this action already placed the order; nothing new was sent. */
305
+ outcome: z.enum(["placed", "replayed"]).optional(),
306
+ clientOrderId: z.string().optional(),
307
+ orderStatus: z.string().optional(),
308
+ /** TP/SL legs Hyperliquid refused while the entry went through: the position is open without them. */
309
+ rejectedProtection: z.array(z.object({ kind: z.string(), reason: z.string() })).optional(),
310
+ provider: providerSchema.optional(),
311
+ symbol: z.string(),
312
+ intentType: tradeIntentTypeSchema,
313
+ direction: tradingDirectionSchema,
314
+ size: tradingSizeSchema,
315
+ execution: z.object({
316
+ style: tradingExecutionStyleSchema,
317
+ timeInForce: z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
318
+ limitPrice: z.number().positive().optional()
319
+ }),
320
+ maxSlippageBps: z.number().int().nonnegative().max(1e3).optional(),
321
+ leverageOverride: z.number().positive().optional(),
322
+ marginModeOverride: z.enum(["ISOLATED", "CROSS"]).optional(),
323
+ reduceOnly: z.boolean(),
324
+ hasProtection: z.boolean()
325
+ });
326
+ var closePositionInputSchema = z.object({
327
+ provider: providerSchema.optional(),
328
+ symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
329
+ maxSlippageBps: z.number().int().nonnegative().max(1e3).optional()
330
+ });
331
+ var closePositionResultSchema = z.object({
332
+ status: z.literal("submitted"),
333
+ provider: providerSchema.optional(),
334
+ symbol: z.string(),
335
+ mode: z.literal("FULL"),
336
+ maxSlippageBps: z.number().int().nonnegative().max(1e3).optional()
337
+ });
338
+ var setTpSlInputSchema = z.object({
339
+ provider: providerSchema.optional(),
340
+ symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
341
+ applyTo: z.enum(["FULL_POSITION", "CUSTOM_QUANTITY"]),
342
+ quantity: z.number().positive().optional(),
343
+ parentClientOrderId: z.string(),
344
+ takeProfit: tradingProtectionLegSchema.optional(),
345
+ stopLoss: tradingProtectionLegSchema.optional()
346
+ });
347
+ var setTpSlResultSchema = z.object({
348
+ status: z.literal("submitted"),
349
+ provider: providerSchema.optional(),
350
+ symbol: z.string(),
351
+ applyTo: z.enum(["FULL_POSITION", "CUSTOM_QUANTITY"]),
352
+ quantity: z.number().positive().optional(),
353
+ parentClientOrderId: z.string(),
354
+ hasTakeProfit: z.boolean(),
355
+ hasStopLoss: z.boolean()
356
+ });
357
+ var deleteTpSlInputSchema = z.object({
358
+ provider: providerSchema.optional(),
359
+ symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
360
+ orderId: z.string()
361
+ });
362
+ var deleteTpSlResultSchema = z.object({
363
+ status: z.literal("deleted"),
364
+ provider: providerSchema.optional(),
365
+ symbol: z.string(),
366
+ orderId: z.string()
367
+ });
368
+ var openOrderSchema = z.object({
369
+ coin: z.string(),
370
+ side: z.enum(["B", "A"]),
371
+ limitPx: z.string(),
372
+ sz: z.string(),
373
+ oid: z.number().int().nonnegative(),
374
+ timestamp: z.number().int().nonnegative(),
375
+ origSz: z.string(),
376
+ orderType: z.string(),
377
+ tif: z.string().nullable(),
378
+ reduceOnly: z.boolean(),
379
+ isTrigger: z.boolean(),
380
+ triggerPx: z.string(),
381
+ cloid: z.string().nullable(),
382
+ assetId: z.number().int().nonnegative().optional()
383
+ });
384
+ var cancelOrderInputSchema = z.object({
385
+ symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
386
+ oid: z.number().int().nonnegative()
387
+ });
388
+ var cancelOrderResultSchema = z.object({
389
+ status: z.literal("cancelled"),
390
+ symbol: z.string(),
391
+ oid: z.number().int().nonnegative()
392
+ });
393
+ var heliosAgentErrorResponseSchema = z2.object({
394
+ error: z2.string().optional(),
395
+ errorDescription: z2.string().optional(),
396
+ message: z2.string().optional()
397
+ });
398
+ var HeliosAgentApiError = class extends Error {
399
+ constructor(options) {
400
+ super(options.message);
401
+ __publicField2(this, "status");
402
+ __publicField2(this, "code");
403
+ __publicField2(this, "errorDescription");
404
+ __publicField2(this, "payload");
405
+ this.name = "HeliosAgentApiError";
406
+ this.status = options.status;
407
+ this.code = options.code;
408
+ this.errorDescription = options.errorDescription;
409
+ this.payload = options.payload;
410
+ if (options.cause !== void 0) {
411
+ Object.defineProperty(this, "cause", {
412
+ configurable: true,
413
+ enumerable: false,
414
+ value: options.cause,
415
+ writable: true
416
+ });
417
+ }
418
+ }
419
+ };
420
+ function isHeliosAgentApiError(error) {
421
+ return error instanceof HeliosAgentApiError;
422
+ }
423
+ var HeliosAgentAuthClient = class {
424
+ constructor(options) {
425
+ __publicField2(this, "baseUrl");
426
+ __publicField2(this, "fetchImpl");
427
+ __publicField2(this, "headers");
428
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
429
+ this.fetchImpl = options.fetch ?? fetch;
430
+ this.headers = options.headers ?? {};
431
+ }
432
+ async startLogin(input) {
433
+ const parsed = agentDeviceStartInputSchema.parse(input);
434
+ return this.post("/api/agents/device/start", parsed, agentDeviceStartOutputSchema);
435
+ }
436
+ async exchangeDeviceCode(deviceCode) {
437
+ const parsed = agentDeviceStartOutputSchema.shape.deviceCode.parse(deviceCode);
438
+ return this.post("/api/agents/device/token", { deviceCode: parsed }, agentTokenResponseSchema);
439
+ }
440
+ async refreshSession(refreshToken) {
441
+ const parsed = agentRefreshInputSchema.parse({ refreshToken });
442
+ return this.post("/api/agents/auth/refresh", parsed, agentTokenResponseSchema);
443
+ }
444
+ async post(path3, body, schema) {
445
+ let response;
446
+ try {
447
+ response = await this.fetchImpl(`${this.baseUrl}${path3}`, {
448
+ method: "POST",
449
+ headers: {
450
+ Accept: "application/json",
451
+ "Content-Type": "application/json",
452
+ ...this.headers
453
+ },
454
+ body: JSON.stringify(body)
455
+ });
456
+ } catch (error) {
457
+ throw new HeliosAgentApiError({
458
+ status: 0,
459
+ code: "network_error",
460
+ message: error instanceof Error ? error.message : "Network error",
461
+ cause: error
462
+ });
463
+ }
464
+ const payload = await this.parseJson(response);
465
+ if (!response.ok) {
466
+ const parsed = heliosAgentErrorResponseSchema.safeParse(payload);
467
+ throw new HeliosAgentApiError({
468
+ status: response.status,
469
+ code: parsed.success ? parsed.data.error ?? "request_failed" : "request_failed",
470
+ message: parsed.success ? parsed.data.errorDescription ?? parsed.data.message ?? `Request failed with status ${response.status}` : `Request failed with status ${response.status}`,
471
+ errorDescription: parsed.success ? parsed.data.errorDescription : void 0,
472
+ payload
473
+ });
474
+ }
475
+ return schema.parse(payload);
476
+ }
477
+ async parseJson(response) {
478
+ const text = await response.text();
479
+ if (!text) {
480
+ return null;
481
+ }
482
+ try {
483
+ return JSON.parse(text);
484
+ } catch (error) {
485
+ throw new HeliosAgentApiError({
486
+ status: response.status,
487
+ code: "invalid_json",
488
+ message: "Received an invalid JSON response from Helios",
489
+ cause: error
490
+ });
491
+ }
492
+ }
493
+ };
494
+ var HeliosAgentDataBridgeClient = class {
495
+ constructor(options) {
496
+ __publicField2(this, "baseUrl");
497
+ __publicField2(this, "fetchImpl");
498
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
499
+ this.fetchImpl = options.fetch ?? fetch;
500
+ }
501
+ async getWalletState(accessToken) {
502
+ const payload = await this.request(accessToken, "account.getWalletState");
503
+ return walletStateSchema.parse(this.unwrapResult(payload));
504
+ }
505
+ async getOpenPositions(accessToken) {
506
+ const payload = await this.request(accessToken, "positions.getOpen");
507
+ return openPositionsSnapshotSchema.parse(this.unwrapResult(payload));
508
+ }
509
+ async getPortfolio(accessToken, input) {
510
+ const parsedInput = portfolioInputSchema.parse(input);
511
+ const payload = await this.request(accessToken, "positions.getPortfolio", parsedInput);
512
+ const result = this.unwrapResult(payload);
513
+ if (!result || typeof result !== "object" || Array.isArray(result)) {
514
+ throw new HeliosAgentApiError({
515
+ status: 200,
516
+ code: "invalid_response",
517
+ message: "Helios data bridge returned an invalid portfolio payload",
518
+ payload
519
+ });
520
+ }
521
+ return portfolioSnapshotSchema.parse({
522
+ ...result,
523
+ provider: parsedInput.provider
524
+ });
525
+ }
526
+ async getLedgerFills(accessToken, input = {}) {
527
+ const parsedInput = ledgerFillsInputSchema.parse(input);
528
+ const payload = await this.request(accessToken, "ledger.getFills", parsedInput);
529
+ return ledgerFillsPageSchema.parse(this.unwrapResult(payload));
530
+ }
531
+ async getLedgerSummary(accessToken, input = {}) {
532
+ const parsedInput = ledgerSummaryInputSchema.parse(input);
533
+ const payload = await this.request(accessToken, "ledger.getSummary", parsedInput);
534
+ return ledgerSummarySchema.parse(this.unwrapResult(payload));
535
+ }
536
+ async getMarketSnapshot(accessToken, input = {}) {
537
+ const parsedInput = marketSnapshotInputSchema.parse(input);
538
+ const payload = await this.request(accessToken, "market.getSnapshot", parsedInput);
539
+ return marketSnapshotSchema.parse(this.unwrapResult(payload));
540
+ }
541
+ async getMarketSnapshotChunk(accessToken, input = {}) {
542
+ const parsedInput = marketSnapshotChunkInputSchema.parse(input);
543
+ const payload = await this.request(accessToken, "market.getSnapshotChunk", parsedInput);
544
+ return marketSnapshotChunkSchema.parse(this.unwrapResult(payload));
545
+ }
546
+ async getMarketSymbolDetail(accessToken, input) {
547
+ const parsedInput = marketSymbolDetailInputSchema.parse(input);
548
+ const payload = await this.request(accessToken, "market.getSymbolDetail", parsedInput);
549
+ return marketSymbolDetailSchema.parse(this.unwrapResult(payload));
550
+ }
551
+ async submitTradeIntent(accessToken, input) {
552
+ const parsedInput = submitTradeIntentInputSchema.parse(input);
553
+ const payload = await this.request(accessToken, "trading.submitIntent", parsedInput, "POST");
554
+ const answer = this.unwrapResult(payload) ?? {};
555
+ return submitTradeIntentResultSchema.parse({
556
+ status: "submitted",
557
+ ...answer.outcome === "placed" || answer.outcome === "replayed" ? { outcome: answer.outcome } : {},
558
+ ...typeof answer.clientOrderId === "string" ? { clientOrderId: answer.clientOrderId } : {},
559
+ ...typeof answer.orderStatus === "string" ? { orderStatus: answer.orderStatus } : {},
560
+ ...Array.isArray(answer.rejectedProtection) ? { rejectedProtection: answer.rejectedProtection } : {},
561
+ provider: parsedInput.provider,
562
+ symbol: parsedInput.symbol,
563
+ intentType: parsedInput.intentType,
564
+ direction: parsedInput.direction,
565
+ size: parsedInput.size,
566
+ execution: parsedInput.execution,
567
+ maxSlippageBps: parsedInput.maxSlippageBps,
568
+ leverageOverride: parsedInput.leverageOverride,
569
+ marginModeOverride: parsedInput.marginModeOverride,
570
+ reduceOnly: Boolean(parsedInput.reduceOnly),
571
+ hasProtection: Boolean(parsedInput.protection?.takeProfit || parsedInput.protection?.stopLoss)
572
+ });
573
+ }
574
+ async closePosition(accessToken, input) {
575
+ const parsedInput = closePositionInputSchema.parse(input);
576
+ await this.request(
577
+ accessToken,
578
+ "positions.close",
579
+ {
580
+ ...parsedInput.provider !== void 0 ? { provider: parsedInput.provider } : {},
581
+ symbol: parsedInput.symbol,
582
+ mode: "FULL",
583
+ ...parsedInput.maxSlippageBps !== void 0 ? { maxSlippageBps: parsedInput.maxSlippageBps } : {}
584
+ },
585
+ "POST"
586
+ );
587
+ return closePositionResultSchema.parse({
588
+ status: "submitted",
589
+ provider: parsedInput.provider,
590
+ symbol: parsedInput.symbol,
591
+ mode: "FULL",
592
+ maxSlippageBps: parsedInput.maxSlippageBps
593
+ });
594
+ }
595
+ async setTpSl(accessToken, input) {
596
+ const parsedInput = setTpSlInputSchema.parse(input);
597
+ await this.request(accessToken, "positions.setTpSl", parsedInput, "POST");
598
+ return setTpSlResultSchema.parse({
599
+ status: "submitted",
600
+ provider: parsedInput.provider,
601
+ symbol: parsedInput.symbol,
602
+ applyTo: parsedInput.applyTo,
603
+ quantity: parsedInput.quantity,
604
+ parentClientOrderId: parsedInput.parentClientOrderId,
605
+ hasTakeProfit: Boolean(parsedInput.takeProfit),
606
+ hasStopLoss: Boolean(parsedInput.stopLoss)
607
+ });
608
+ }
609
+ async deleteTpSl(accessToken, input) {
610
+ const parsedInput = deleteTpSlInputSchema.parse(input);
611
+ await this.request(accessToken, "positions.deleteTpSl", parsedInput, "POST");
612
+ return deleteTpSlResultSchema.parse({
613
+ status: "deleted",
614
+ provider: parsedInput.provider,
615
+ symbol: parsedInput.symbol,
616
+ orderId: parsedInput.orderId
617
+ });
618
+ }
619
+ async getOpenOrders(accessToken) {
620
+ const payload = await this.request(accessToken, "positions.getOpenOrders");
621
+ return openOrderSchema.array().parse(this.unwrapResult(payload));
622
+ }
623
+ async cancelOrder(accessToken, input) {
624
+ const parsedInput = cancelOrderInputSchema.parse(input);
625
+ await this.request(accessToken, "positions.cancelOrder", parsedInput, "POST");
626
+ return cancelOrderResultSchema.parse({
627
+ status: "cancelled",
628
+ symbol: parsedInput.symbol,
629
+ oid: parsedInput.oid
630
+ });
631
+ }
632
+ async request(accessToken, procedure, input, method = "GET") {
633
+ let response;
634
+ try {
635
+ response = await this.fetchImpl(this.buildProcedureUrl(procedure, method === "GET" ? input : void 0), {
636
+ method,
637
+ headers: {
638
+ Accept: "application/json",
639
+ ...method === "POST" ? { "Content-Type": "application/json" } : {},
640
+ Authorization: `Bearer ${accessToken}`
641
+ },
642
+ ...method === "POST" && input !== void 0 ? { body: JSON.stringify({ json: input }) } : {}
643
+ });
644
+ } catch (error) {
645
+ throw new HeliosAgentApiError({
646
+ status: 0,
647
+ code: "network_error",
648
+ message: error instanceof Error ? error.message : "Network error",
649
+ cause: error
650
+ });
651
+ }
652
+ const payload = await this.parseJson(response);
653
+ if (!response.ok) {
654
+ throw new HeliosAgentApiError({
655
+ status: response.status,
656
+ code: this.extractErrorCode(payload),
657
+ message: this.extractErrorMessage(payload, response.status),
658
+ payload
659
+ });
660
+ }
661
+ return payload;
662
+ }
663
+ buildProcedureUrl(procedure, input) {
664
+ const url = new URL(`${this.baseUrl}/api/trpc/${procedure}`);
665
+ if (input !== void 0) {
666
+ url.searchParams.set("input", JSON.stringify({ json: input }));
667
+ }
668
+ return url.toString();
669
+ }
670
+ async parseJson(response) {
671
+ const text = await response.text();
672
+ if (!text) {
673
+ return null;
674
+ }
675
+ try {
676
+ return JSON.parse(text);
677
+ } catch (error) {
678
+ throw new HeliosAgentApiError({
679
+ status: response.status,
680
+ code: "invalid_json",
681
+ message: "Received an invalid JSON response from Helios data bridge",
682
+ cause: error
683
+ });
684
+ }
685
+ }
686
+ unwrapResult(payload) {
687
+ if (!payload || typeof payload !== "object") {
688
+ throw new HeliosAgentApiError({
689
+ status: 200,
690
+ code: "invalid_response",
691
+ message: "Helios data bridge returned an invalid response payload",
692
+ payload
693
+ });
694
+ }
695
+ const result = payload.result;
696
+ if (!result) {
697
+ throw new HeliosAgentApiError({
698
+ status: 200,
699
+ code: "invalid_response",
700
+ message: "Helios data bridge response is missing a result payload",
701
+ payload
702
+ });
703
+ }
704
+ const data = result.data;
705
+ if (data && typeof data === "object" && "json" in data) {
706
+ return data.json;
707
+ }
708
+ return data;
709
+ }
710
+ extractErrorCode(payload) {
711
+ if (payload && typeof payload === "object") {
712
+ const errorShape = this.unwrapTrpcError(payload);
713
+ if (errorShape?.data?.code) {
714
+ return errorShape.data.code;
715
+ }
716
+ }
717
+ return "request_failed";
718
+ }
719
+ extractErrorMessage(payload, status) {
720
+ if (payload && typeof payload === "object") {
721
+ const errorShape = this.unwrapTrpcError(payload);
722
+ if (errorShape?.message) {
723
+ return errorShape.message;
724
+ }
725
+ }
726
+ return `Request failed with status ${status}`;
727
+ }
728
+ /**
729
+ * Unwrap a tRPC error envelope, handling the superjson `{ json: ... }` wrapper
730
+ * that the data-bridge applies via its transformer configuration.
731
+ */
732
+ unwrapTrpcError(payload) {
733
+ const envelope = payload.error;
734
+ if (!envelope || typeof envelope !== "object") {
735
+ return void 0;
736
+ }
737
+ if ("json" in envelope) {
738
+ const inner = envelope.json;
739
+ if (inner && typeof inner === "object") {
740
+ return inner;
741
+ }
742
+ }
743
+ return envelope;
744
+ }
745
+ };
746
+ var DEFAULT_AGENT_REFRESH_WINDOW_MS = 60 * 1e3;
747
+ var agentConnectionStatusSchema = z3.enum([
748
+ "disconnected",
749
+ "pending",
750
+ "connected",
751
+ "rejected",
752
+ "expired",
753
+ "failed"
754
+ ]);
755
+ var storedAgentSessionSchema = z3.object({
756
+ accessToken: z3.string(),
757
+ refreshToken: z3.string(),
758
+ tokenType: agentTokenResponseSchema.shape.tokenType,
759
+ ownerUserId: z3.string(),
760
+ agentGrantId: z3.string(),
761
+ scope: z3.array(agentScopeSchema).min(1),
762
+ accessTokenExpiresAt: z3.string().datetime(),
763
+ createdAt: z3.string().datetime(),
764
+ lastRefreshedAt: z3.string().datetime()
765
+ });
766
+ var agentSessionViewSchema = z3.object({
767
+ connected: z3.boolean(),
768
+ status: agentConnectionStatusSchema,
769
+ ownerUserId: z3.string().optional(),
770
+ agentGrantId: z3.string().optional(),
771
+ scope: z3.array(agentScopeSchema).optional(),
772
+ accessTokenExpiresAt: z3.string().datetime().optional(),
773
+ lastRefreshedAt: z3.string().datetime().optional()
774
+ });
775
+ function createStoredAgentSession(tokenResponse, now = /* @__PURE__ */ new Date()) {
776
+ const createdAt = now.toISOString();
777
+ return {
778
+ accessToken: tokenResponse.accessToken,
779
+ refreshToken: tokenResponse.refreshToken,
780
+ tokenType: tokenResponse.tokenType,
781
+ ownerUserId: tokenResponse.ownerUserId,
782
+ agentGrantId: tokenResponse.agentGrantId,
783
+ scope: tokenResponse.scope,
784
+ accessTokenExpiresAt: new Date(now.getTime() + tokenResponse.expiresInSeconds * 1e3).toISOString(),
785
+ createdAt,
786
+ lastRefreshedAt: createdAt
787
+ };
788
+ }
789
+ function sanitizeAgentSession(session, status = session ? "connected" : "disconnected") {
790
+ if (!session) {
791
+ return {
792
+ connected: false,
793
+ status: status === "connected" ? "disconnected" : status
794
+ };
795
+ }
796
+ return {
797
+ connected: true,
798
+ status,
799
+ ownerUserId: session.ownerUserId,
800
+ agentGrantId: session.agentGrantId,
801
+ scope: session.scope,
802
+ accessTokenExpiresAt: session.accessTokenExpiresAt,
803
+ lastRefreshedAt: session.lastRefreshedAt
804
+ };
805
+ }
806
+ function shouldRefreshAgentSession(session, now = /* @__PURE__ */ new Date(), refreshWindowMs = DEFAULT_AGENT_REFRESH_WINDOW_MS) {
807
+ return new Date(session.accessTokenExpiresAt).getTime() - now.getTime() <= refreshWindowMs;
808
+ }
809
+
810
+ // src/auth-service.ts
811
+ var HOSTED_RECONNECT_MESSAGE = "Helios no longer accepts this connection (it expired or was revoked). Reconnect Helios in your AI app to continue.";
812
+ var HeliosAgentMcpAuthService = class {
813
+ constructor(options) {
814
+ __publicField(this, "client");
815
+ __publicField(this, "sessionStore");
816
+ __publicField(this, "refreshWindowMs");
817
+ __publicField(this, "now");
818
+ __publicField(this, "deviceLogin");
819
+ this.client = options.client;
820
+ this.sessionStore = options.sessionStore;
821
+ this.refreshWindowMs = options.refreshWindowMs ?? 60 * 1e3;
822
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
823
+ this.deviceLogin = options.deviceLogin ?? true;
824
+ }
825
+ async startLogin(input) {
826
+ const response = await this.startDeviceLogin(input);
827
+ const result = this.buildStartLoginResult(response, input.scope);
828
+ await this.sessionStore.setPendingLogin(result);
829
+ return result;
830
+ }
831
+ async resetSessionAndStartLogin(input) {
832
+ await this.sessionStore.clearSession();
833
+ await this.sessionStore.clearPendingLogin();
834
+ const response = await this.startDeviceLogin(input);
835
+ const result = this.buildStartLoginResult(response, input.scope);
836
+ await this.sessionStore.setPendingLogin(result);
837
+ return result;
838
+ }
839
+ async startDeviceLogin(input) {
840
+ if (!this.deviceLogin) {
841
+ throw new Error(HOSTED_RECONNECT_MESSAGE);
842
+ }
843
+ return this.client.startLogin(input);
844
+ }
845
+ buildStartLoginResult(response, requestedScope) {
846
+ return {
847
+ status: "pending",
848
+ ...response,
849
+ requestedScope,
850
+ startedAt: this.now().toISOString()
851
+ };
852
+ }
853
+ async startRelogin(options = {}) {
854
+ const requestedScope = options.scope ?? [AGENT_SCOPES.ACCOUNT_READ, AGENT_SCOPES.MARKET_READ];
855
+ const started = await this.resetSessionAndStartLogin({
856
+ clientName: options.clientName ?? "Helios MCP",
857
+ scope: requestedScope,
858
+ constraints: options.constraints
859
+ });
860
+ return {
861
+ ...started,
862
+ connected: false,
863
+ message: formatHeliosLoginPrompt(started)
864
+ };
865
+ }
866
+ async clearSessionState() {
867
+ await this.sessionStore.clearSession();
868
+ await this.sessionStore.clearPendingLogin();
869
+ }
870
+ async invalidateIfUnauthorized(error, options = {}) {
871
+ if (!isHeliosAgentApiError(error) || error.status !== 401) {
872
+ return null;
873
+ }
874
+ return this.startRelogin(options);
875
+ }
876
+ async refreshSessionAfterUnauthorized(error) {
877
+ if (!isHeliosAgentApiError(error) || error.status !== 401) {
878
+ return null;
879
+ }
880
+ const session = await this.sessionStore.getSession();
881
+ if (!session) {
882
+ return null;
883
+ }
884
+ return this.refreshStoredSession(session);
885
+ }
886
+ async ensureLogin(options = {}) {
887
+ const requestedScope = options.scope ?? [AGENT_SCOPES.ACCOUNT_READ, AGENT_SCOPES.MARKET_READ];
888
+ const requestedConstraints = options.constraints ?? {};
889
+ const session = await this.getValidSession();
890
+ if (session) {
891
+ return {
892
+ ...sanitizeAgentSession(session),
893
+ connected: true,
894
+ status: "connected"
895
+ };
896
+ }
897
+ const pendingLogin = await this.getPendingLogin({
898
+ requestedScope,
899
+ requestedConstraints
900
+ });
901
+ if (pendingLogin) {
902
+ const polled = await this.pollLogin(pendingLogin.deviceCode).catch(() => null);
903
+ if (polled?.status === "connected") return polled;
904
+ if (polled?.status !== "rejected" && polled?.status !== "expired") {
905
+ return {
906
+ ...pendingLogin,
907
+ connected: false,
908
+ message: formatHeliosLoginPrompt(pendingLogin)
909
+ };
910
+ }
911
+ }
912
+ const started = await this.startLogin({
913
+ clientName: options.clientName ?? "Helios MCP",
914
+ scope: requestedScope,
915
+ constraints: options.constraints
916
+ });
917
+ return {
918
+ ...started,
919
+ connected: false,
920
+ message: formatHeliosLoginPrompt(started)
921
+ };
922
+ }
923
+ /** Polls the given login, or the stored pending one when no device code is given. */
924
+ async pollLogin(deviceCode) {
925
+ if (!deviceCode) {
926
+ const pending = await this.sessionStore.getPendingLogin();
927
+ if (!pending) {
928
+ const session = await this.getValidSession();
929
+ if (session) return { ...sanitizeAgentSession(session), connected: true, status: "connected" };
930
+ return {
931
+ status: "failed",
932
+ connected: false,
933
+ message: "No Helios login is in progress. Call helios_auth_ensure_login to start one."
934
+ };
935
+ }
936
+ deviceCode = pending.deviceCode;
937
+ } else {
938
+ const pending = await this.sessionStore.getPendingLogin();
939
+ if (pending && pending.userCode.toUpperCase() === deviceCode.trim().toUpperCase()) deviceCode = pending.deviceCode;
940
+ }
941
+ try {
942
+ const response = await this.client.exchangeDeviceCode(deviceCode);
943
+ const session = createStoredAgentSession(response, this.now());
944
+ await this.sessionStore.setSession(session);
945
+ await this.sessionStore.clearPendingLogin();
946
+ return {
947
+ ...sanitizeAgentSession(session),
948
+ connected: true,
949
+ status: "connected"
950
+ };
951
+ } catch (error) {
952
+ if (isHeliosAgentApiError(error)) {
953
+ if (error.code === "authorization_pending") {
954
+ return {
955
+ status: "pending",
956
+ connected: false,
957
+ message: error.message
958
+ };
959
+ }
960
+ if (error.code === "access_denied") {
961
+ await this.clearPendingLoginIfMatches(deviceCode);
962
+ return {
963
+ status: "rejected",
964
+ connected: false,
965
+ message: error.message
966
+ };
967
+ }
968
+ if (error.code === "expired_token") {
969
+ await this.clearPendingLoginIfMatches(deviceCode);
970
+ return {
971
+ status: "expired",
972
+ connected: false,
973
+ message: error.message
974
+ };
975
+ }
976
+ return {
977
+ status: "failed",
978
+ connected: false,
979
+ message: error.message
980
+ };
981
+ }
982
+ return {
983
+ status: "failed",
984
+ connected: false,
985
+ message: error instanceof Error ? error.message : "Unexpected Helios login error"
986
+ };
987
+ }
988
+ }
989
+ async whoami() {
990
+ const session = await this.getValidSession();
991
+ return sanitizeAgentSession(session);
992
+ }
993
+ async getAccessToken() {
994
+ const session = await this.getValidSession();
995
+ return session?.accessToken ?? null;
996
+ }
997
+ async requireSession() {
998
+ const session = await this.getValidSession();
999
+ if (!session) {
1000
+ throw new Error("No Helios delegated agent session is connected");
1001
+ }
1002
+ return session;
1003
+ }
1004
+ async getValidSession() {
1005
+ const session = await this.sessionStore.getSession();
1006
+ if (!session) {
1007
+ return null;
1008
+ }
1009
+ if (!shouldRefreshAgentSession(session, this.now(), this.refreshWindowMs)) {
1010
+ return session;
1011
+ }
1012
+ return this.refreshStoredSession(session);
1013
+ }
1014
+ async refreshStoredSession(session) {
1015
+ try {
1016
+ const refreshed = await this.client.refreshSession(session.refreshToken);
1017
+ const nextSession = createStoredAgentSession(refreshed, this.now());
1018
+ await this.sessionStore.setSession(nextSession);
1019
+ return nextSession;
1020
+ } catch (error) {
1021
+ if (isHeliosAgentApiError(error) && error.code === "invalid_grant") {
1022
+ await this.sessionStore.clearSession();
1023
+ await this.sessionStore.clearPendingLogin();
1024
+ return null;
1025
+ }
1026
+ throw error;
1027
+ }
1028
+ }
1029
+ async getPendingLogin(options) {
1030
+ const pendingLogin = await this.sessionStore.getPendingLogin();
1031
+ if (!pendingLogin) {
1032
+ return null;
1033
+ }
1034
+ const expiresAt = new Date(pendingLogin.startedAt).getTime() + pendingLogin.expiresInSeconds * 1e3;
1035
+ if (this.now().getTime() >= expiresAt) {
1036
+ await this.sessionStore.clearPendingLogin();
1037
+ return null;
1038
+ }
1039
+ if (!isPendingLoginCompatible(pendingLogin, options.requestedScope, options.requestedConstraints)) {
1040
+ return null;
1041
+ }
1042
+ return pendingLogin;
1043
+ }
1044
+ async clearPendingLoginIfMatches(deviceCode) {
1045
+ const pendingLogin = await this.sessionStore.getPendingLogin();
1046
+ if (pendingLogin?.deviceCode === deviceCode) {
1047
+ await this.sessionStore.clearPendingLogin();
1048
+ }
1049
+ }
1050
+ };
1051
+ async function retryAfterUnauthorizedRefresh(options) {
1052
+ const refreshedSession = await options.authService.refreshSessionAfterUnauthorized(options.error);
1053
+ if (!refreshedSession) {
1054
+ return options.authService.invalidateIfUnauthorized(options.error, options.loginOptions);
1055
+ }
1056
+ try {
1057
+ return await options.retry(refreshedSession.accessToken);
1058
+ } catch (retryError) {
1059
+ const relogin = await options.authService.invalidateIfUnauthorized(retryError, options.loginOptions);
1060
+ if (relogin) {
1061
+ return relogin;
1062
+ }
1063
+ throw retryError;
1064
+ }
1065
+ }
1066
+ function formatHeliosLoginPrompt(result) {
1067
+ return `Log in to Helios by opening this URL in your browser:
1068
+
1069
+ ${result.verificationUriComplete}
1070
+
1071
+ User code: ${result.userCode}
1072
+
1073
+ Requested scopes: ${result.requestedScope.join(", ")}
1074
+
1075
+ After approving access, call helios_auth_ensure_login (or helios_auth_poll_login) again to finish connecting.`;
1076
+ }
1077
+ function isPendingLoginCompatible(pendingLogin, requestedScope, requestedConstraints) {
1078
+ const pendingScope = new Set(pendingLogin.requestedScope);
1079
+ const scopeCompatible = requestedScope.every((scope) => pendingScope.has(scope));
1080
+ if (!scopeCompatible) {
1081
+ return false;
1082
+ }
1083
+ return Object.keys(requestedConstraints ?? {}).length === 0;
1084
+ }
1085
+
1086
+ // src/account-service.ts
1087
+ var HeliosAgentMcpAccountService = class {
1088
+ constructor(options) {
1089
+ __publicField(this, "authService");
1090
+ __publicField(this, "dataBridgeClient");
1091
+ __publicField(this, "providerService");
1092
+ this.authService = options.authService;
1093
+ this.dataBridgeClient = options.dataBridgeClient;
1094
+ this.providerService = options.providerService;
1095
+ }
1096
+ async getWalletState() {
1097
+ const loginOptions = this.accountReadOptions();
1098
+ const login = await this.authService.ensureLogin(loginOptions);
1099
+ if (login.status !== "connected") {
1100
+ return {
1101
+ ...login,
1102
+ status: "pending",
1103
+ connected: false
1104
+ };
1105
+ }
1106
+ const session = await this.authService.requireSession();
1107
+ try {
1108
+ const walletState = await this.dataBridgeClient.getWalletState(session.accessToken);
1109
+ return {
1110
+ status: "connected",
1111
+ connected: true,
1112
+ walletState
1113
+ };
1114
+ } catch (error) {
1115
+ const recovery = await retryAfterUnauthorizedRefresh({
1116
+ authService: this.authService,
1117
+ error,
1118
+ loginOptions,
1119
+ retry: async (accessToken) => {
1120
+ const walletState = await this.dataBridgeClient.getWalletState(accessToken);
1121
+ return {
1122
+ status: "connected",
1123
+ connected: true,
1124
+ walletState
1125
+ };
1126
+ }
1127
+ });
1128
+ if (recovery) {
1129
+ return recovery;
1130
+ }
1131
+ throw error;
1132
+ }
1133
+ }
1134
+ async getPortfolio(input = {}) {
1135
+ const loginOptions = this.accountReadOptions();
1136
+ const login = await this.authService.ensureLogin(loginOptions);
1137
+ if (login.status !== "connected") {
1138
+ return {
1139
+ ...login,
1140
+ status: "pending",
1141
+ connected: false
1142
+ };
1143
+ }
1144
+ const session = await this.authService.requireSession();
1145
+ try {
1146
+ const provider = await this.providerService.resolveProvider(input.provider);
1147
+ const portfolio = await this.dataBridgeClient.getPortfolio(session.accessToken, { provider });
1148
+ return {
1149
+ status: "connected",
1150
+ connected: true,
1151
+ portfolio
1152
+ };
1153
+ } catch (error) {
1154
+ const recovery = await retryAfterUnauthorizedRefresh({
1155
+ authService: this.authService,
1156
+ error,
1157
+ loginOptions,
1158
+ retry: async (accessToken) => {
1159
+ const provider = await this.providerService.resolveProvider(input.provider);
1160
+ const portfolio = await this.dataBridgeClient.getPortfolio(accessToken, { provider });
1161
+ return {
1162
+ status: "connected",
1163
+ connected: true,
1164
+ portfolio
1165
+ };
1166
+ }
1167
+ });
1168
+ if (recovery) {
1169
+ return recovery;
1170
+ }
1171
+ throw error;
1172
+ }
1173
+ }
1174
+ accountReadOptions() {
1175
+ return {
1176
+ clientName: "Helios MCP",
1177
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1178
+ };
1179
+ }
1180
+ };
1181
+
1182
+ // src/docs-service.ts
1183
+ import { readdirSync, readFileSync, statSync } from "fs";
1184
+ import path from "path";
1185
+ var HeliosAgentMcpDocsService = class {
1186
+ constructor(options) {
1187
+ __publicField(this, "docsRoot");
1188
+ this.docsRoot = options.docsRoot;
1189
+ }
1190
+ async getIndex() {
1191
+ const documents = listDocumentPaths(this.docsRoot).map((documentPath) => this.readDocumentMetadata(documentPath));
1192
+ return {
1193
+ root: "docs",
1194
+ documents
1195
+ };
1196
+ }
1197
+ async getDocument(input) {
1198
+ const documentPath = resolveDocumentPath(this.docsRoot, input.path);
1199
+ const body = readFileSync(documentPath, "utf8");
1200
+ const stats = statSync(documentPath);
1201
+ const relativePath = toPosixPath(path.relative(this.docsRoot, documentPath));
1202
+ return {
1203
+ path: relativePath,
1204
+ section: getDocumentSection(relativePath),
1205
+ title: extractDocumentTitle(body, relativePath),
1206
+ body,
1207
+ bytes: stats.size
1208
+ };
1209
+ }
1210
+ readDocumentMetadata(documentPath) {
1211
+ const body = readFileSync(documentPath, "utf8");
1212
+ const stats = statSync(documentPath);
1213
+ const relativePath = toPosixPath(path.relative(this.docsRoot, documentPath));
1214
+ return {
1215
+ path: relativePath,
1216
+ section: getDocumentSection(relativePath),
1217
+ title: extractDocumentTitle(body, relativePath),
1218
+ bytes: stats.size
1219
+ };
1220
+ }
1221
+ };
1222
+ function getDefaultHeliosAgentMcpDocsRoot() {
1223
+ return path.resolve(__dirname, "..", "docs");
1224
+ }
1225
+ function listDocumentPaths(root) {
1226
+ return walk(root).filter((filePath) => filePath.endsWith(".txt")).sort((left, right) => left.localeCompare(right));
1227
+ }
1228
+ function walk(currentPath) {
1229
+ const entries = readdirSync(currentPath, { withFileTypes: true });
1230
+ const files = [];
1231
+ for (const entry of entries) {
1232
+ const nextPath = path.join(currentPath, entry.name);
1233
+ if (entry.isDirectory()) {
1234
+ files.push(...walk(nextPath));
1235
+ continue;
1236
+ }
1237
+ if (entry.isFile()) {
1238
+ files.push(nextPath);
1239
+ }
1240
+ }
1241
+ return files;
1242
+ }
1243
+ function resolveDocumentPath(root, relativeDocumentPath) {
1244
+ const normalizedPath = relativeDocumentPath.replace(/\\/g, "/").replace(/^\/+/, "");
1245
+ const resolvedPath = path.resolve(root, normalizedPath);
1246
+ const relativePath = path.relative(root, resolvedPath);
1247
+ if (!normalizedPath) {
1248
+ throw new Error("Document path is required.");
1249
+ }
1250
+ if (path.isAbsolute(normalizedPath) || relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
1251
+ throw new Error(`Document path "${relativeDocumentPath}" is outside the docs root.`);
1252
+ }
1253
+ if (!resolvedPath.endsWith(".txt")) {
1254
+ throw new Error(`Document path "${relativeDocumentPath}" must point to a .txt file.`);
1255
+ }
1256
+ return resolvedPath;
1257
+ }
1258
+ function extractDocumentTitle(body, relativePath) {
1259
+ const lines = body.split(/\r?\n/);
1260
+ for (const line of lines) {
1261
+ const trimmed = line.trim();
1262
+ if (!trimmed || /^=+$/.test(trimmed)) {
1263
+ continue;
1264
+ }
1265
+ if (trimmed.startsWith("TITLE:")) {
1266
+ return trimmed.slice("TITLE:".length).trim();
1267
+ }
1268
+ return trimmed;
1269
+ }
1270
+ return path.basename(relativePath, ".txt");
1271
+ }
1272
+ function getDocumentSection(relativePath) {
1273
+ return relativePath.split("/")[0] ?? "docs";
1274
+ }
1275
+ function toPosixPath(value) {
1276
+ return value.split(path.sep).join("/");
1277
+ }
1278
+
1279
+ // src/ledger-service.ts
1280
+ var HeliosAgentMcpLedgerService = class {
1281
+ constructor(options) {
1282
+ __publicField(this, "authService");
1283
+ __publicField(this, "dataBridgeClient");
1284
+ this.authService = options.authService;
1285
+ this.dataBridgeClient = options.dataBridgeClient;
1286
+ }
1287
+ async getOpenPositions() {
1288
+ const loginOptions = this.accountReadOptions();
1289
+ const login = await this.authService.ensureLogin(loginOptions);
1290
+ if (login.status !== "connected") {
1291
+ return asPending(login);
1292
+ }
1293
+ const session = await this.authService.requireSession();
1294
+ try {
1295
+ const openPositions = await this.dataBridgeClient.getOpenPositions(session.accessToken);
1296
+ return {
1297
+ status: "connected",
1298
+ connected: true,
1299
+ openPositions
1300
+ };
1301
+ } catch (error) {
1302
+ const recovery = await retryAfterUnauthorizedRefresh({
1303
+ authService: this.authService,
1304
+ error,
1305
+ loginOptions,
1306
+ retry: async (accessToken) => {
1307
+ const openPositions = await this.dataBridgeClient.getOpenPositions(accessToken);
1308
+ return {
1309
+ status: "connected",
1310
+ connected: true,
1311
+ openPositions
1312
+ };
1313
+ }
1314
+ });
1315
+ if (recovery) {
1316
+ return recovery;
1317
+ }
1318
+ throw error;
1319
+ }
1320
+ }
1321
+ async getFills(input = {}) {
1322
+ const loginOptions = this.accountReadOptions();
1323
+ const login = await this.authService.ensureLogin(loginOptions);
1324
+ if (login.status !== "connected") {
1325
+ return asPending(login);
1326
+ }
1327
+ const session = await this.authService.requireSession();
1328
+ try {
1329
+ const fills = await this.dataBridgeClient.getLedgerFills(session.accessToken, input);
1330
+ return {
1331
+ status: "connected",
1332
+ connected: true,
1333
+ fills
1334
+ };
1335
+ } catch (error) {
1336
+ const recovery = await retryAfterUnauthorizedRefresh({
1337
+ authService: this.authService,
1338
+ error,
1339
+ loginOptions,
1340
+ retry: async (accessToken) => {
1341
+ const fills = await this.dataBridgeClient.getLedgerFills(accessToken, input);
1342
+ return {
1343
+ status: "connected",
1344
+ connected: true,
1345
+ fills
1346
+ };
1347
+ }
1348
+ });
1349
+ if (recovery) {
1350
+ return recovery;
1351
+ }
1352
+ throw error;
1353
+ }
1354
+ }
1355
+ async getSummary(input = {}) {
1356
+ const loginOptions = this.accountReadOptions();
1357
+ const login = await this.authService.ensureLogin(loginOptions);
1358
+ if (login.status !== "connected") {
1359
+ return asPending(login);
1360
+ }
1361
+ const session = await this.authService.requireSession();
1362
+ try {
1363
+ const summary = await this.dataBridgeClient.getLedgerSummary(session.accessToken, input);
1364
+ return {
1365
+ status: "connected",
1366
+ connected: true,
1367
+ summary
1368
+ };
1369
+ } catch (error) {
1370
+ const recovery = await retryAfterUnauthorizedRefresh({
1371
+ authService: this.authService,
1372
+ error,
1373
+ loginOptions,
1374
+ retry: async (accessToken) => {
1375
+ const summary = await this.dataBridgeClient.getLedgerSummary(accessToken, input);
1376
+ return {
1377
+ status: "connected",
1378
+ connected: true,
1379
+ summary
1380
+ };
1381
+ }
1382
+ });
1383
+ if (recovery) {
1384
+ return recovery;
1385
+ }
1386
+ throw error;
1387
+ }
1388
+ }
1389
+ accountReadOptions() {
1390
+ return {
1391
+ clientName: "Helios MCP",
1392
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1393
+ };
1394
+ }
1395
+ };
1396
+ function asPending(login) {
1397
+ return {
1398
+ ...login,
1399
+ status: "pending",
1400
+ connected: false
1401
+ };
1402
+ }
1403
+
1404
+ // src/market-service.ts
1405
+ var DEFAULT_SNAPSHOT_TOP = 50;
1406
+ var DEFAULT_SNAPSHOT_FIELDS = [
1407
+ // Price, size and returns.
1408
+ "rank",
1409
+ "lp",
1410
+ "qv",
1411
+ "r15m",
1412
+ "r1h",
1413
+ "r4h",
1414
+ "r24h",
1415
+ "r7d",
1416
+ // Regime and momentum turn: the one edge that held out of sample is buying a sharp turn up in a BREAKDOWN/CRASH coin.
1417
+ "reg",
1418
+ "hmi",
1419
+ "hmiv",
1420
+ "hs",
1421
+ // Stretch and location: fades beat chases in the wallet research.
1422
+ "ob",
1423
+ "obosp",
1424
+ "de",
1425
+ "ms",
1426
+ "srs",
1427
+ "srr",
1428
+ "fh24",
1429
+ "fl24",
1430
+ "fh7",
1431
+ "fl7",
1432
+ "vwz",
1433
+ "tri"
1434
+ ];
1435
+ function withSnapshotDefaults(input) {
1436
+ return {
1437
+ ...input,
1438
+ fields: input.fields ?? [...DEFAULT_SNAPSHOT_FIELDS],
1439
+ sort: input.sort ?? "rank"
1440
+ };
1441
+ }
1442
+ function topOfSnapshot(snapshot, input, top = DEFAULT_SNAPSHOT_TOP) {
1443
+ if (input.symbols?.length || snapshot.table.rows.length <= top) return snapshot;
1444
+ const baseIndex = snapshot.table.fieldIds.indexOf("base");
1445
+ const rows = snapshot.table.rows.slice(0, top);
1446
+ const returnedSymbols = baseIndex === -1 ? snapshot.returnedSymbols.slice(0, top) : rows.map((row) => String(row[baseIndex]));
1447
+ return { ...snapshot, symbolCount: rows.length, returnedSymbols, table: { ...snapshot.table, rows } };
1448
+ }
1449
+ var HeliosAgentMcpMarketService = class {
1450
+ constructor(options) {
1451
+ __publicField(this, "authService");
1452
+ __publicField(this, "dataBridgeClient");
1453
+ this.authService = options.authService;
1454
+ this.dataBridgeClient = options.dataBridgeClient;
1455
+ }
1456
+ async getSnapshot(input = {}) {
1457
+ const loginOptions = {
1458
+ clientName: "Helios MCP",
1459
+ scope: [AGENT_SCOPES.MARKET_READ]
1460
+ };
1461
+ const login = await this.authService.ensureLogin(loginOptions);
1462
+ if (login.status !== "connected") {
1463
+ return {
1464
+ ...login,
1465
+ status: "pending",
1466
+ connected: false
1467
+ };
1468
+ }
1469
+ const session = await this.authService.requireSession();
1470
+ try {
1471
+ const snapshot = topOfSnapshot(await this.dataBridgeClient.getMarketSnapshot(session.accessToken, withSnapshotDefaults(input)), input);
1472
+ return {
1473
+ status: "connected",
1474
+ connected: true,
1475
+ snapshot
1476
+ };
1477
+ } catch (error) {
1478
+ const recovery = await retryAfterUnauthorizedRefresh({
1479
+ authService: this.authService,
1480
+ error,
1481
+ loginOptions,
1482
+ retry: async (accessToken) => {
1483
+ const snapshot = topOfSnapshot(await this.dataBridgeClient.getMarketSnapshot(accessToken, withSnapshotDefaults(input)), input);
1484
+ return {
1485
+ status: "connected",
1486
+ connected: true,
1487
+ snapshot
1488
+ };
1489
+ }
1490
+ });
1491
+ if (recovery) {
1492
+ return recovery;
1493
+ }
1494
+ throw error;
1495
+ }
1496
+ }
1497
+ async getSnapshotChunk(input = {}) {
1498
+ const loginOptions = {
1499
+ clientName: "Helios MCP",
1500
+ scope: [AGENT_SCOPES.MARKET_READ]
1501
+ };
1502
+ const login = await this.authService.ensureLogin(loginOptions);
1503
+ if (login.status !== "connected") {
1504
+ return {
1505
+ ...login,
1506
+ status: "pending",
1507
+ connected: false
1508
+ };
1509
+ }
1510
+ const session = await this.authService.requireSession();
1511
+ try {
1512
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(session.accessToken, withSnapshotDefaults(input));
1513
+ return {
1514
+ status: "connected",
1515
+ connected: true,
1516
+ snapshotChunk
1517
+ };
1518
+ } catch (error) {
1519
+ const recovery = await retryAfterUnauthorizedRefresh({
1520
+ authService: this.authService,
1521
+ error,
1522
+ loginOptions,
1523
+ retry: async (accessToken) => {
1524
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(accessToken, withSnapshotDefaults(input));
1525
+ return {
1526
+ status: "connected",
1527
+ connected: true,
1528
+ snapshotChunk
1529
+ };
1530
+ }
1531
+ });
1532
+ if (recovery) {
1533
+ return recovery;
1534
+ }
1535
+ throw error;
1536
+ }
1537
+ }
1538
+ async getSymbolDetail(input) {
1539
+ const loginOptions = {
1540
+ clientName: "Helios MCP",
1541
+ scope: [AGENT_SCOPES.MARKET_READ]
1542
+ };
1543
+ const login = await this.authService.ensureLogin(loginOptions);
1544
+ if (login.status !== "connected") {
1545
+ return {
1546
+ ...login,
1547
+ status: "pending",
1548
+ connected: false
1549
+ };
1550
+ }
1551
+ const session = await this.authService.requireSession();
1552
+ try {
1553
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(session.accessToken, input);
1554
+ return {
1555
+ status: "connected",
1556
+ connected: true,
1557
+ detail
1558
+ };
1559
+ } catch (error) {
1560
+ const recovery = await retryAfterUnauthorizedRefresh({
1561
+ authService: this.authService,
1562
+ error,
1563
+ loginOptions,
1564
+ retry: async (accessToken) => {
1565
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(accessToken, input);
1566
+ return {
1567
+ status: "connected",
1568
+ connected: true,
1569
+ detail
1570
+ };
1571
+ }
1572
+ });
1573
+ if (recovery) {
1574
+ return recovery;
1575
+ }
1576
+ throw error;
1577
+ }
1578
+ }
1579
+ };
1580
+
1581
+ // src/provider-service.ts
1582
+ var HeliosAgentMcpProviderService = class {
1583
+ constructor(options) {
1584
+ __publicField(this, "sessionStore");
1585
+ this.sessionStore = options.sessionStore;
1586
+ }
1587
+ async getActiveProvider() {
1588
+ const provider = await this.sessionStore.getActiveProvider();
1589
+ if (!provider) {
1590
+ return {
1591
+ configured: false,
1592
+ provider: null
1593
+ };
1594
+ }
1595
+ return {
1596
+ configured: true,
1597
+ provider
1598
+ };
1599
+ }
1600
+ async setActiveProvider(provider) {
1601
+ await this.sessionStore.setActiveProvider(provider);
1602
+ return {
1603
+ configured: true,
1604
+ provider
1605
+ };
1606
+ }
1607
+ async resolveProvider(explicitProvider) {
1608
+ if (explicitProvider) {
1609
+ return explicitProvider;
1610
+ }
1611
+ const activeProvider = await this.sessionStore.getActiveProvider();
1612
+ if (activeProvider) {
1613
+ return activeProvider;
1614
+ }
1615
+ throw new Error("No active provider configured. Call helios_provider_set_active or pass provider explicitly.");
1616
+ }
1617
+ };
1618
+
1619
+ // src/session-store.ts
1620
+ import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
1621
+ import { homedir } from "os";
1622
+ import path2 from "path";
1623
+ import { z as z4 } from "zod";
1624
+ function getDefaultHeliosAgentMcpSessionPath() {
1625
+ return path2.join(homedir(), ".helios-agent-mcp", "session.json");
1626
+ }
1627
+ var pendingAgentLoginSchema = z4.object({
1628
+ status: z4.literal("pending"),
1629
+ deviceCode: z4.string(),
1630
+ userCode: z4.string(),
1631
+ verificationUri: z4.string().url(),
1632
+ verificationUriComplete: z4.string().url(),
1633
+ expiresInSeconds: z4.number().int().positive(),
1634
+ pollIntervalSeconds: z4.number().int().positive(),
1635
+ requestedScope: z4.array(agentScopeSchema).min(1),
1636
+ startedAt: z4.string().datetime()
1637
+ });
1638
+ var mcpSessionStateSchema = z4.object({
1639
+ session: storedAgentSessionSchema.nullish(),
1640
+ pendingLogin: pendingAgentLoginSchema.nullish(),
1641
+ // A provider pinned before Binance was retired ('binance') reads as unpinned, so the agent must pick again, rather than
1642
+ // failing the whole file (which would drop the session) or silently switching it to Hyperliquid.
1643
+ activeProvider: providerSchema.nullish().catch(null)
1644
+ });
1645
+ var FileAgentSessionStore = class {
1646
+ constructor(filePath = getDefaultHeliosAgentMcpSessionPath()) {
1647
+ this.filePath = filePath;
1648
+ }
1649
+ async getSession() {
1650
+ return (await this.readState()).session;
1651
+ }
1652
+ async getPendingLogin() {
1653
+ return (await this.readState()).pendingLogin;
1654
+ }
1655
+ async getActiveProvider() {
1656
+ return (await this.readState()).activeProvider;
1657
+ }
1658
+ async setSession(session) {
1659
+ const state = await this.readState();
1660
+ await this.writeState({
1661
+ ...state,
1662
+ session
1663
+ });
1664
+ }
1665
+ async setPendingLogin(pendingLogin) {
1666
+ const state = await this.readState();
1667
+ await this.writeState({
1668
+ ...state,
1669
+ pendingLogin
1670
+ });
1671
+ }
1672
+ async setActiveProvider(activeProvider) {
1673
+ const state = await this.readState();
1674
+ await this.writeState({
1675
+ ...state,
1676
+ activeProvider
1677
+ });
1678
+ }
1679
+ async clearSession() {
1680
+ const state = await this.readState();
1681
+ await this.writeStateOrDelete({
1682
+ ...state,
1683
+ session: null
1684
+ });
1685
+ }
1686
+ async clearPendingLogin() {
1687
+ const state = await this.readState();
1688
+ await this.writeStateOrDelete({
1689
+ ...state,
1690
+ pendingLogin: null
1691
+ });
1692
+ }
1693
+ async clearActiveProvider() {
1694
+ const state = await this.readState();
1695
+ await this.writeStateOrDelete({
1696
+ ...state,
1697
+ activeProvider: null
1698
+ });
1699
+ }
1700
+ async readState() {
1701
+ try {
1702
+ const raw = await readFile(this.filePath, "utf8");
1703
+ const parsed = JSON.parse(raw);
1704
+ if (parsed && typeof parsed === "object" && ("session" in parsed || "pendingLogin" in parsed || "activeProvider" in parsed)) {
1705
+ const envelope = mcpSessionStateSchema.safeParse(parsed);
1706
+ if (envelope.success) {
1707
+ return {
1708
+ session: envelope.data.session ?? null,
1709
+ pendingLogin: envelope.data.pendingLogin ?? null,
1710
+ activeProvider: envelope.data.activeProvider ?? null
1711
+ };
1712
+ }
1713
+ }
1714
+ const legacySession = storedAgentSessionSchema.safeParse(parsed);
1715
+ if (legacySession.success) {
1716
+ return {
1717
+ session: legacySession.data,
1718
+ pendingLogin: null,
1719
+ activeProvider: null
1720
+ };
1721
+ }
1722
+ return {
1723
+ session: null,
1724
+ pendingLogin: null,
1725
+ activeProvider: null
1726
+ };
1727
+ } catch (error) {
1728
+ if (isMissingFileError(error)) {
1729
+ return {
1730
+ session: null,
1731
+ pendingLogin: null,
1732
+ activeProvider: null
1733
+ };
1734
+ }
1735
+ if (error instanceof Error && error.name === "ZodError") {
1736
+ return {
1737
+ session: null,
1738
+ pendingLogin: null,
1739
+ activeProvider: null
1740
+ };
1741
+ }
1742
+ throw error;
1743
+ }
1744
+ }
1745
+ async writeState(state) {
1746
+ await mkdir(path2.dirname(this.filePath), { recursive: true });
1747
+ await writeFile(this.filePath, `${JSON.stringify(state, null, 2)}
1748
+ `, { encoding: "utf8", mode: 384 });
1749
+ await chmod(this.filePath, 384).catch(() => void 0);
1750
+ }
1751
+ async writeStateOrDelete(state) {
1752
+ if (!state.session && !state.pendingLogin && !state.activeProvider) {
1753
+ await this.deleteFile();
1754
+ return;
1755
+ }
1756
+ await this.writeState(state);
1757
+ }
1758
+ async deleteFile() {
1759
+ try {
1760
+ await rm(this.filePath, { force: true });
1761
+ } catch (error) {
1762
+ if (!isMissingFileError(error)) {
1763
+ throw error;
1764
+ }
1765
+ }
1766
+ }
1767
+ };
1768
+ var MemoryAgentMcpSessionStore = class {
1769
+ constructor(session = null, activeProvider = "hyperliquid") {
1770
+ this.session = session;
1771
+ this.activeProvider = activeProvider;
1772
+ __publicField(this, "pendingLogin", null);
1773
+ }
1774
+ async getSession() {
1775
+ return this.session;
1776
+ }
1777
+ async setSession(session) {
1778
+ this.session = session;
1779
+ }
1780
+ async clearSession() {
1781
+ this.session = null;
1782
+ }
1783
+ async getActiveProvider() {
1784
+ return this.activeProvider;
1785
+ }
1786
+ async setActiveProvider(provider) {
1787
+ this.activeProvider = provider;
1788
+ }
1789
+ async clearActiveProvider() {
1790
+ this.activeProvider = null;
1791
+ }
1792
+ async getPendingLogin() {
1793
+ return this.pendingLogin;
1794
+ }
1795
+ async setPendingLogin(pendingLogin) {
1796
+ this.pendingLogin = pendingLogin;
1797
+ }
1798
+ async clearPendingLogin() {
1799
+ this.pendingLogin = null;
1800
+ }
1801
+ };
1802
+ function isMissingFileError(error) {
1803
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
1804
+ }
1805
+
1806
+ // src/trading-service.ts
1807
+ import { randomUUID } from "crypto";
1808
+ var HeliosAgentMcpTradingService = class {
1809
+ constructor(options) {
1810
+ __publicField(this, "authService");
1811
+ __publicField(this, "dataBridgeClient");
1812
+ __publicField(this, "providerService");
1813
+ this.authService = options.authService;
1814
+ this.dataBridgeClient = options.dataBridgeClient;
1815
+ this.providerService = options.providerService;
1816
+ }
1817
+ async open(input) {
1818
+ return this.submitIntent("OPEN", input);
1819
+ }
1820
+ async dca(input) {
1821
+ return this.submitIntent("DCA", input);
1822
+ }
1823
+ async reverse(input) {
1824
+ return this.submitIntent("REVERSE", input);
1825
+ }
1826
+ async close(input) {
1827
+ const loginOptions = {
1828
+ clientName: "Helios MCP",
1829
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1830
+ };
1831
+ const login = await this.authService.ensureLogin(loginOptions);
1832
+ if (login.status !== "connected") {
1833
+ return asPending2(login);
1834
+ }
1835
+ const session = await this.authService.requireSession();
1836
+ try {
1837
+ const provider = await this.providerService.resolveProvider(input.provider);
1838
+ const closure = await this.dataBridgeClient.closePosition(session.accessToken, {
1839
+ ...input,
1840
+ provider
1841
+ });
1842
+ return {
1843
+ status: "connected",
1844
+ connected: true,
1845
+ closure
1846
+ };
1847
+ } catch (error) {
1848
+ const recovery = await retryAfterUnauthorizedRefresh({
1849
+ authService: this.authService,
1850
+ error,
1851
+ loginOptions,
1852
+ retry: async (accessToken) => {
1853
+ const provider = await this.providerService.resolveProvider(input.provider);
1854
+ const closure = await this.dataBridgeClient.closePosition(accessToken, {
1855
+ ...input,
1856
+ provider
1857
+ });
1858
+ return {
1859
+ status: "connected",
1860
+ connected: true,
1861
+ closure
1862
+ };
1863
+ }
1864
+ });
1865
+ if (recovery) {
1866
+ return recovery;
1867
+ }
1868
+ throw error;
1869
+ }
1870
+ }
1871
+ async setTpSl(input) {
1872
+ const loginOptions = {
1873
+ clientName: "Helios MCP",
1874
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1875
+ };
1876
+ const login = await this.authService.ensureLogin(loginOptions);
1877
+ if (login.status !== "connected") {
1878
+ return asPending2(login);
1879
+ }
1880
+ const session = await this.authService.requireSession();
1881
+ try {
1882
+ const provider = await this.providerService.resolveProvider(input.provider);
1883
+ const protection = await this.dataBridgeClient.setTpSl(session.accessToken, {
1884
+ ...input,
1885
+ provider
1886
+ });
1887
+ return {
1888
+ status: "connected",
1889
+ connected: true,
1890
+ protection
1891
+ };
1892
+ } catch (error) {
1893
+ const recovery = await retryAfterUnauthorizedRefresh({
1894
+ authService: this.authService,
1895
+ error,
1896
+ loginOptions,
1897
+ retry: async (accessToken) => {
1898
+ const provider = await this.providerService.resolveProvider(input.provider);
1899
+ const protection = await this.dataBridgeClient.setTpSl(accessToken, {
1900
+ ...input,
1901
+ provider
1902
+ });
1903
+ return {
1904
+ status: "connected",
1905
+ connected: true,
1906
+ protection
1907
+ };
1908
+ }
1909
+ });
1910
+ if (recovery) {
1911
+ return recovery;
1912
+ }
1913
+ throw error;
1914
+ }
1915
+ }
1916
+ async deleteTpSl(input) {
1917
+ const loginOptions = {
1918
+ clientName: "Helios MCP",
1919
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
1920
+ };
1921
+ const login = await this.authService.ensureLogin(loginOptions);
1922
+ if (login.status !== "connected") {
1923
+ return asPending2(login);
1924
+ }
1925
+ const session = await this.authService.requireSession();
1926
+ try {
1927
+ const provider = await this.providerService.resolveProvider(input.provider);
1928
+ const deletion = await this.dataBridgeClient.deleteTpSl(session.accessToken, {
1929
+ ...input,
1930
+ provider
1931
+ });
1932
+ return {
1933
+ status: "connected",
1934
+ connected: true,
1935
+ deletion
1936
+ };
1937
+ } catch (error) {
1938
+ const recovery = await retryAfterUnauthorizedRefresh({
1939
+ authService: this.authService,
1940
+ error,
1941
+ loginOptions,
1942
+ retry: async (accessToken) => {
1943
+ const provider = await this.providerService.resolveProvider(input.provider);
1944
+ const deletion = await this.dataBridgeClient.deleteTpSl(accessToken, {
1945
+ ...input,
1946
+ provider
1947
+ });
1948
+ return {
1949
+ status: "connected",
1950
+ connected: true,
1951
+ deletion
1952
+ };
1953
+ }
1954
+ });
1955
+ if (recovery) {
1956
+ return recovery;
1957
+ }
1958
+ throw error;
1959
+ }
1960
+ }
1961
+ async getOpenOrders() {
1962
+ const loginOptions = {
1963
+ clientName: "Helios MCP",
1964
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1965
+ };
1966
+ const login = await this.authService.ensureLogin(loginOptions);
1967
+ if (login.status !== "connected") {
1968
+ return asPending2(login);
1969
+ }
1970
+ const session = await this.authService.requireSession();
1971
+ try {
1972
+ const orders = await this.dataBridgeClient.getOpenOrders(session.accessToken);
1973
+ return {
1974
+ status: "connected",
1975
+ connected: true,
1976
+ orders
1977
+ };
1978
+ } catch (error) {
1979
+ const recovery = await retryAfterUnauthorizedRefresh({
1980
+ authService: this.authService,
1981
+ error,
1982
+ loginOptions,
1983
+ retry: async (accessToken) => {
1984
+ const orders = await this.dataBridgeClient.getOpenOrders(accessToken);
1985
+ return {
1986
+ status: "connected",
1987
+ connected: true,
1988
+ orders
1989
+ };
1990
+ }
1991
+ });
1992
+ if (recovery) {
1993
+ return recovery;
1994
+ }
1995
+ throw error;
1996
+ }
1997
+ }
1998
+ async cancelOrder(input) {
1999
+ const loginOptions = {
2000
+ clientName: "Helios MCP",
2001
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
2002
+ };
2003
+ const login = await this.authService.ensureLogin(loginOptions);
2004
+ if (login.status !== "connected") {
2005
+ return asPending2(login);
2006
+ }
2007
+ const session = await this.authService.requireSession();
2008
+ try {
2009
+ const cancellation = await this.dataBridgeClient.cancelOrder(session.accessToken, input);
2010
+ return {
2011
+ status: "connected",
2012
+ connected: true,
2013
+ cancellation
2014
+ };
2015
+ } catch (error) {
2016
+ const recovery = await retryAfterUnauthorizedRefresh({
2017
+ authService: this.authService,
2018
+ error,
2019
+ loginOptions,
2020
+ retry: async (accessToken) => {
2021
+ const cancellation = await this.dataBridgeClient.cancelOrder(accessToken, input);
2022
+ return {
2023
+ status: "connected",
2024
+ connected: true,
2025
+ cancellation
2026
+ };
2027
+ }
2028
+ });
2029
+ if (recovery) {
2030
+ return recovery;
2031
+ }
2032
+ throw error;
2033
+ }
2034
+ }
2035
+ async submitIntent(intentType, input) {
2036
+ const loginOptions = {
2037
+ clientName: "Helios MCP",
2038
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
2039
+ };
2040
+ const login = await this.authService.ensureLogin(loginOptions);
2041
+ if (login.status !== "connected") {
2042
+ return asPending2(login);
2043
+ }
2044
+ const session = await this.authService.requireSession();
2045
+ const idempotencyKey = input.idempotencyKey ?? randomUUID().replace(/-/g, "");
2046
+ try {
2047
+ const provider = await this.providerService.resolveProvider(input.provider);
2048
+ const submission = await this.dataBridgeClient.submitTradeIntent(session.accessToken, {
2049
+ ...input,
2050
+ provider,
2051
+ intentType,
2052
+ idempotencyKey
2053
+ });
2054
+ return {
2055
+ status: "connected",
2056
+ connected: true,
2057
+ submission
2058
+ };
2059
+ } catch (error) {
2060
+ const recovery = await retryAfterUnauthorizedRefresh({
2061
+ authService: this.authService,
2062
+ error,
2063
+ loginOptions,
2064
+ retry: async (accessToken) => {
2065
+ const provider = await this.providerService.resolveProvider(input.provider);
2066
+ const submission = await this.dataBridgeClient.submitTradeIntent(accessToken, {
2067
+ ...input,
2068
+ provider,
2069
+ intentType,
2070
+ idempotencyKey
2071
+ });
2072
+ return {
2073
+ status: "connected",
2074
+ connected: true,
2075
+ submission
2076
+ };
2077
+ }
2078
+ });
2079
+ if (recovery) {
2080
+ return recovery;
2081
+ }
2082
+ throw error;
2083
+ }
2084
+ }
2085
+ };
2086
+ function asPending2(login) {
2087
+ return {
2088
+ ...login,
2089
+ status: "pending",
2090
+ connected: false
2091
+ };
2092
+ }
2093
+
2094
+ // src/tools.ts
2095
+ import { z as z5 } from "zod";
2096
+ var pollLoginInputSchema = z5.object({
2097
+ /** Optional: defaults to the login started by helios_auth_ensure_login / helios_auth_start_login. */
2098
+ deviceCode: z5.string().min(1).optional()
2099
+ });
2100
+ var startLoginOutputSchema = z5.object({
2101
+ status: z5.literal("pending"),
2102
+ deviceCode: z5.string(),
2103
+ userCode: z5.string(),
2104
+ verificationUri: z5.string().url(),
2105
+ verificationUriComplete: z5.string().url(),
2106
+ expiresInSeconds: z5.number().int().positive(),
2107
+ pollIntervalSeconds: z5.number().int().positive(),
2108
+ requestedScope: z5.array(agentScopeSchema).min(1),
2109
+ startedAt: z5.string().datetime()
2110
+ });
2111
+ var ensureLoginInputSchema = z5.object({
2112
+ clientName: z5.string().min(1).max(64).optional(),
2113
+ scope: z5.array(agentScopeSchema).min(1).optional(),
2114
+ constraints: agentConstraintsSchema.optional()
2115
+ });
2116
+ var providerSelectionInputSchema = z5.object({
2117
+ provider: providerSchema.optional()
2118
+ });
2119
+ var providerSetInputSchema = z5.object({
2120
+ provider: providerSchema
2121
+ });
2122
+ var activeProviderSchema = z5.object({
2123
+ configured: z5.boolean(),
2124
+ provider: providerSchema.nullable()
2125
+ });
2126
+ var ensureLoginOutputSchema = z5.discriminatedUnion("status", [
2127
+ agentSessionViewSchema.extend({
2128
+ status: z5.literal("connected"),
2129
+ connected: z5.literal(true)
2130
+ }),
2131
+ startLoginOutputSchema.extend({
2132
+ status: z5.literal("pending"),
2133
+ connected: z5.literal(false),
2134
+ message: z5.string()
2135
+ })
2136
+ ]);
2137
+ var pollLoginOutputSchema = z5.discriminatedUnion("status", [
2138
+ agentSessionViewSchema.extend({
2139
+ status: z5.literal("connected"),
2140
+ connected: z5.literal(true)
2141
+ }),
2142
+ z5.object({
2143
+ status: z5.enum(["pending", "rejected", "expired", "failed"]),
2144
+ connected: z5.literal(false),
2145
+ message: z5.string()
2146
+ })
2147
+ ]);
2148
+ var walletStateToolOutputSchema = z5.discriminatedUnion("status", [
2149
+ z5.object({
2150
+ status: z5.literal("connected"),
2151
+ connected: z5.literal(true),
2152
+ walletState: walletStateSchema
2153
+ }),
2154
+ startLoginOutputSchema.extend({
2155
+ status: z5.literal("pending"),
2156
+ connected: z5.literal(false),
2157
+ message: z5.string()
2158
+ })
2159
+ ]);
2160
+ var portfolioToolOutputSchema = z5.discriminatedUnion("status", [
2161
+ z5.object({
2162
+ status: z5.literal("connected"),
2163
+ connected: z5.literal(true),
2164
+ portfolio: portfolioSnapshotSchema
2165
+ }),
2166
+ startLoginOutputSchema.extend({
2167
+ status: z5.literal("pending"),
2168
+ connected: z5.literal(false),
2169
+ message: z5.string()
2170
+ })
2171
+ ]);
2172
+ var openPositionsToolOutputSchema = z5.discriminatedUnion("status", [
2173
+ z5.object({
2174
+ status: z5.literal("connected"),
2175
+ connected: z5.literal(true),
2176
+ openPositions: openPositionsSnapshotSchema
2177
+ }),
2178
+ startLoginOutputSchema.extend({
2179
+ status: z5.literal("pending"),
2180
+ connected: z5.literal(false),
2181
+ message: z5.string()
2182
+ })
2183
+ ]);
2184
+ var ledgerFillsToolOutputSchema = z5.discriminatedUnion("status", [
2185
+ z5.object({
2186
+ status: z5.literal("connected"),
2187
+ connected: z5.literal(true),
2188
+ fills: ledgerFillsPageSchema
2189
+ }),
2190
+ startLoginOutputSchema.extend({
2191
+ status: z5.literal("pending"),
2192
+ connected: z5.literal(false),
2193
+ message: z5.string()
2194
+ })
2195
+ ]);
2196
+ var ledgerSummaryToolOutputSchema = z5.discriminatedUnion("status", [
2197
+ z5.object({
2198
+ status: z5.literal("connected"),
2199
+ connected: z5.literal(true),
2200
+ summary: ledgerSummarySchema
2201
+ }),
2202
+ startLoginOutputSchema.extend({
2203
+ status: z5.literal("pending"),
2204
+ connected: z5.literal(false),
2205
+ message: z5.string()
2206
+ })
2207
+ ]);
2208
+ var marketSnapshotToolOutputSchema = z5.discriminatedUnion("status", [
2209
+ z5.object({
2210
+ status: z5.literal("connected"),
2211
+ connected: z5.literal(true),
2212
+ snapshot: marketSnapshotSchema
2213
+ }),
2214
+ startLoginOutputSchema.extend({
2215
+ status: z5.literal("pending"),
2216
+ connected: z5.literal(false),
2217
+ message: z5.string()
2218
+ })
2219
+ ]);
2220
+ var marketSnapshotChunkToolOutputSchema = z5.discriminatedUnion("status", [
2221
+ z5.object({
2222
+ status: z5.literal("connected"),
2223
+ connected: z5.literal(true),
2224
+ snapshotChunk: marketSnapshotChunkSchema
2225
+ }),
2226
+ startLoginOutputSchema.extend({
2227
+ status: z5.literal("pending"),
2228
+ connected: z5.literal(false),
2229
+ message: z5.string()
2230
+ })
2231
+ ]);
2232
+ var marketSymbolDetailToolOutputSchema = z5.discriminatedUnion("status", [
2233
+ z5.object({
2234
+ status: z5.literal("connected"),
2235
+ connected: z5.literal(true),
2236
+ detail: marketSymbolDetailSchema
2237
+ }),
2238
+ startLoginOutputSchema.extend({
2239
+ status: z5.literal("pending"),
2240
+ connected: z5.literal(false),
2241
+ message: z5.string()
2242
+ })
2243
+ ]);
2244
+ var tradeActionInputSchema = submitTradeIntentInputSchema.omit({
2245
+ intentType: true
2246
+ });
2247
+ var tradeActionToolOutputSchema = z5.discriminatedUnion("status", [
2248
+ z5.object({
2249
+ status: z5.literal("connected"),
2250
+ connected: z5.literal(true),
2251
+ submission: submitTradeIntentResultSchema
2252
+ }),
2253
+ startLoginOutputSchema.extend({
2254
+ status: z5.literal("pending"),
2255
+ connected: z5.literal(false),
2256
+ message: z5.string()
2257
+ })
2258
+ ]);
2259
+ var closeTradeToolOutputSchema = z5.discriminatedUnion("status", [
2260
+ z5.object({
2261
+ status: z5.literal("connected"),
2262
+ connected: z5.literal(true),
2263
+ closure: closePositionResultSchema
2264
+ }),
2265
+ startLoginOutputSchema.extend({
2266
+ status: z5.literal("pending"),
2267
+ connected: z5.literal(false),
2268
+ message: z5.string()
2269
+ })
2270
+ ]);
2271
+ var setTpSlToolOutputSchema = z5.discriminatedUnion("status", [
2272
+ z5.object({
2273
+ status: z5.literal("connected"),
2274
+ connected: z5.literal(true),
2275
+ protection: setTpSlResultSchema
2276
+ }),
2277
+ startLoginOutputSchema.extend({
2278
+ status: z5.literal("pending"),
2279
+ connected: z5.literal(false),
2280
+ message: z5.string()
2281
+ })
2282
+ ]);
2283
+ var deleteTpSlToolOutputSchema = z5.discriminatedUnion("status", [
2284
+ z5.object({
2285
+ status: z5.literal("connected"),
2286
+ connected: z5.literal(true),
2287
+ deletion: deleteTpSlResultSchema
2288
+ }),
2289
+ startLoginOutputSchema.extend({
2290
+ status: z5.literal("pending"),
2291
+ connected: z5.literal(false),
2292
+ message: z5.string()
2293
+ })
2294
+ ]);
2295
+ var openOrdersToolOutputSchema = z5.discriminatedUnion("status", [
2296
+ z5.object({
2297
+ status: z5.literal("connected"),
2298
+ connected: z5.literal(true),
2299
+ orders: z5.array(openOrderSchema)
2300
+ }),
2301
+ startLoginOutputSchema.extend({
2302
+ status: z5.literal("pending"),
2303
+ connected: z5.literal(false),
2304
+ message: z5.string()
2305
+ })
2306
+ ]);
2307
+ var cancelOrderToolOutputSchema = z5.discriminatedUnion("status", [
2308
+ z5.object({
2309
+ status: z5.literal("connected"),
2310
+ connected: z5.literal(true),
2311
+ cancellation: cancelOrderResultSchema
2312
+ }),
2313
+ startLoginOutputSchema.extend({
2314
+ status: z5.literal("pending"),
2315
+ connected: z5.literal(false),
2316
+ message: z5.string()
2317
+ })
2318
+ ]);
2319
+ var documentPathInputSchema = z5.object({
2320
+ path: z5.string().min(1)
2321
+ });
2322
+ var docsIndexSchema = z5.object({
2323
+ root: z5.literal("docs"),
2324
+ documents: z5.array(
2325
+ z5.object({
2326
+ path: z5.string(),
2327
+ section: z5.string(),
2328
+ title: z5.string(),
2329
+ bytes: z5.number().int().nonnegative()
2330
+ })
2331
+ )
2332
+ });
2333
+ var documentSchema = z5.object({
2334
+ path: z5.string(),
2335
+ section: z5.string(),
2336
+ title: z5.string(),
2337
+ body: z5.string(),
2338
+ bytes: z5.number().int().nonnegative()
2339
+ });
2340
+ function createHeliosDocsToolDefinitions(service) {
2341
+ return [
2342
+ {
2343
+ name: "helios_docs_get_index",
2344
+ title: "Get Helios Docs Index",
2345
+ description: "Lists the package-local Helios MCP and indicator .txt documentation available to the agent.",
2346
+ inputSchema: z5.object({}),
2347
+ async execute() {
2348
+ const result = docsIndexSchema.parse(await service.getIndex());
2349
+ return {
2350
+ content: [
2351
+ {
2352
+ type: "text",
2353
+ text: `Helios docs index: ${result.documents.length} documents across ${new Set(result.documents.map((document) => document.section)).size} sections.`
2354
+ }
2355
+ ],
2356
+ structuredContent: result
2357
+ };
2358
+ }
2359
+ },
2360
+ {
2361
+ name: "helios_docs_get_document",
2362
+ title: "Get Helios Doc",
2363
+ description: "Returns one package-local Helios .txt document by relative docs path.",
2364
+ inputSchema: documentPathInputSchema,
2365
+ async execute(input) {
2366
+ const result = documentSchema.parse(await service.getDocument(input));
2367
+ return {
2368
+ content: [
2369
+ {
2370
+ type: "text",
2371
+ text: result.body
2372
+ }
2373
+ ],
2374
+ structuredContent: result
2375
+ };
2376
+ }
2377
+ }
2378
+ ];
2379
+ }
2380
+ function createHeliosAuthToolDefinitions(service) {
2381
+ return [
2382
+ {
2383
+ name: "helios_auth_start_login",
2384
+ title: "Start Helios Login",
2385
+ description: "Starts the delegated Helios login flow and returns the approval URL for the user.",
2386
+ inputSchema: agentDeviceStartInputSchema,
2387
+ async execute(input) {
2388
+ const result = startLoginOutputSchema.parse(await service.startLogin(input));
2389
+ const manualResult = {
2390
+ ...result,
2391
+ ...withManualLoginFields(result)
2392
+ };
2393
+ return {
2394
+ content: [
2395
+ {
2396
+ type: "text",
2397
+ text: buildManualLoginText(result)
2398
+ }
2399
+ ],
2400
+ structuredContent: manualResult
2401
+ };
2402
+ }
2403
+ },
2404
+ {
2405
+ name: "helios_auth_ensure_login",
2406
+ title: "Ensure Helios Login",
2407
+ description: "Ensures a delegated Helios session exists, or starts a login flow and returns a ready-to-display approval prompt. Call it again after the person approves: it finishes connecting.",
2408
+ inputSchema: ensureLoginInputSchema,
2409
+ async execute(input) {
2410
+ const result = ensureLoginOutputSchema.parse(await service.ensureLogin(input));
2411
+ const structuredContent = result.status === "connected" ? result : {
2412
+ ...result,
2413
+ ...withManualLoginFields(result)
2414
+ };
2415
+ return {
2416
+ content: [
2417
+ {
2418
+ type: "text",
2419
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : result.message
2420
+ }
2421
+ ],
2422
+ structuredContent
2423
+ };
2424
+ }
2425
+ },
2426
+ {
2427
+ name: "helios_auth_poll_login",
2428
+ title: "Poll Helios Login",
2429
+ description: "Checks whether the Helios login was approved and finishes connecting. The device code is optional; without it, the login in progress is checked.",
2430
+ inputSchema: pollLoginInputSchema,
2431
+ async execute(input) {
2432
+ const result = pollLoginOutputSchema.parse(await service.pollLogin(input.deviceCode));
2433
+ return {
2434
+ content: [
2435
+ {
2436
+ type: "text",
2437
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : `Helios login is ${result.status}: ${result.message}`
2438
+ }
2439
+ ],
2440
+ structuredContent: result
2441
+ };
2442
+ }
2443
+ },
2444
+ {
2445
+ name: "helios_auth_whoami",
2446
+ title: "Helios Login Status",
2447
+ description: "Returns the delegated Helios session state currently stored by the MCP server.",
2448
+ inputSchema: z5.object({}),
2449
+ async execute() {
2450
+ const result = agentSessionViewSchema.parse(await service.whoami());
2451
+ return {
2452
+ content: [
2453
+ {
2454
+ type: "text",
2455
+ text: result.connected ? `Connected to Helios as user ${result.ownerUserId}.` : "No delegated Helios session is connected."
2456
+ }
2457
+ ],
2458
+ structuredContent: result
2459
+ };
2460
+ }
2461
+ }
2462
+ ];
2463
+ }
2464
+ function createHeliosProviderToolDefinitions(service) {
2465
+ return [
2466
+ {
2467
+ name: "helios_provider_get_active",
2468
+ title: "Get Helios Active Provider",
2469
+ description: "Returns the provider currently pinned for this MCP session, if any.",
2470
+ inputSchema: z5.object({}),
2471
+ async execute() {
2472
+ const result = activeProviderSchema.parse(await service.getActiveProvider());
2473
+ return {
2474
+ content: [
2475
+ {
2476
+ type: "text",
2477
+ text: result.configured ? `Helios active provider is ${result.provider}.` : "No Helios active provider is configured for this session."
2478
+ }
2479
+ ],
2480
+ structuredContent: result
2481
+ };
2482
+ }
2483
+ },
2484
+ {
2485
+ name: "helios_provider_set_active",
2486
+ title: "Set Helios Active Provider",
2487
+ description: "Pins the active provider for this MCP session so portfolio and trading tools can omit provider.",
2488
+ inputSchema: providerSetInputSchema,
2489
+ async execute(input) {
2490
+ const result = activeProviderSchema.parse(await service.setActiveProvider(input.provider));
2491
+ return {
2492
+ content: [
2493
+ {
2494
+ type: "text",
2495
+ text: `Helios active provider set to ${result.provider}.`
2496
+ }
2497
+ ],
2498
+ structuredContent: result
2499
+ };
2500
+ }
2501
+ }
2502
+ ];
2503
+ }
2504
+ function createHeliosAccountToolDefinitions(service) {
2505
+ return [
2506
+ {
2507
+ name: "helios_account_get_wallet_state",
2508
+ title: "Get Helios Wallet State",
2509
+ description: "Returns the current Hyperliquid wallet snapshot for the connected Helios account.",
2510
+ inputSchema: z5.object({}),
2511
+ async execute() {
2512
+ const result = walletStateToolOutputSchema.parse(await service.getWalletState());
2513
+ const structuredContent = result.status === "connected" ? result : {
2514
+ ...result,
2515
+ ...withManualLoginFields(result)
2516
+ };
2517
+ return {
2518
+ content: [
2519
+ {
2520
+ type: "text",
2521
+ text: result.status === "connected" ? `Helios wallet state: available balance ${result.walletState.availableBalance}, account value ${result.walletState.accountValue}.` : result.message
2522
+ }
2523
+ ],
2524
+ structuredContent
2525
+ };
2526
+ }
2527
+ },
2528
+ {
2529
+ name: "helios_portfolio_get",
2530
+ title: "Get Helios Portfolio",
2531
+ description: "Returns a provider-specific portfolio snapshot. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2532
+ inputSchema: providerSelectionInputSchema,
2533
+ async execute(input) {
2534
+ const result = portfolioToolOutputSchema.parse(await service.getPortfolio(input));
2535
+ const structuredContent = result.status === "connected" ? result : {
2536
+ ...result,
2537
+ ...withManualLoginFields(result)
2538
+ };
2539
+ return {
2540
+ content: [
2541
+ {
2542
+ type: "text",
2543
+ text: result.status === "connected" ? buildPortfolioText(result.portfolio) : result.message
2544
+ }
2545
+ ],
2546
+ structuredContent
2547
+ };
2548
+ }
2549
+ }
2550
+ ];
2551
+ }
2552
+ function createHeliosLedgerToolDefinitions(service) {
2553
+ return [
2554
+ {
2555
+ name: "helios_positions_get_open",
2556
+ title: "Get Helios Open Positions",
2557
+ description: "Returns the current open Hyperliquid positions for the connected Helios account.",
2558
+ inputSchema: z5.object({}),
2559
+ async execute() {
2560
+ const result = openPositionsToolOutputSchema.parse(await service.getOpenPositions());
2561
+ const structuredContent = result.status === "connected" ? result : {
2562
+ ...result,
2563
+ ...withManualLoginFields(result)
2564
+ };
2565
+ return {
2566
+ content: [
2567
+ {
2568
+ type: "text",
2569
+ text: result.status === "connected" ? `Helios open positions: ${result.openPositions.positions.length} positions, total unrealized PnL ${result.openPositions.totalUnrealizedPnl}.` : result.message
2570
+ }
2571
+ ],
2572
+ structuredContent
2573
+ };
2574
+ }
2575
+ },
2576
+ {
2577
+ name: "helios_ledger_get_fills",
2578
+ title: "Get Helios Ledger Fills",
2579
+ description: "Returns recent Hyperliquid fills/trade history for the connected Helios account.",
2580
+ inputSchema: ledgerFillsInputSchema,
2581
+ async execute(input) {
2582
+ const result = ledgerFillsToolOutputSchema.parse(await service.getFills(input));
2583
+ const structuredContent = result.status === "connected" ? result : {
2584
+ ...result,
2585
+ ...withManualLoginFields(result)
2586
+ };
2587
+ return {
2588
+ content: [
2589
+ {
2590
+ type: "text",
2591
+ text: result.status === "connected" ? `Helios ledger fills: ${result.fills.fills.length} fills from ${result.fills.window}${result.fills.hasMore ? ", more available" : ""}.` : result.message
2592
+ }
2593
+ ],
2594
+ structuredContent
2595
+ };
2596
+ }
2597
+ },
2598
+ {
2599
+ name: "helios_ledger_get_summary",
2600
+ title: "Get Helios Ledger Summary",
2601
+ description: "Returns realized PnL, fees, and win/loss metrics over a recent Hyperliquid fill window.",
2602
+ inputSchema: ledgerSummaryInputSchema,
2603
+ async execute(input) {
2604
+ const result = ledgerSummaryToolOutputSchema.parse(await service.getSummary(input));
2605
+ const structuredContent = result.status === "connected" ? result : {
2606
+ ...result,
2607
+ ...withManualLoginFields(result)
2608
+ };
2609
+ return {
2610
+ content: [
2611
+ {
2612
+ type: "text",
2613
+ text: result.status === "connected" ? `Helios ledger summary (${result.summary.window}): realized PnL ${result.summary.realizedPnl}, fees ${result.summary.totalFees}, wins ${result.summary.winCount}, losses ${result.summary.lossCount}.` : result.message
2614
+ }
2615
+ ],
2616
+ structuredContent
2617
+ };
2618
+ }
2619
+ }
2620
+ ];
2621
+ }
2622
+ function createHeliosMarketToolDefinitions(service) {
2623
+ return [
2624
+ {
2625
+ name: "helios_market_get_snapshot",
2626
+ title: "Get Helios Market Snapshot",
2627
+ description: "Returns a compact market snapshot for the selected, all, or explicitly requested symbols. By default: the top 50 coins by market cap with the main columns; name symbols to get other coins, pass fields for other columns.",
2628
+ inputSchema: marketSnapshotInputSchema,
2629
+ async execute(input) {
2630
+ const result = marketSnapshotToolOutputSchema.parse(await service.getSnapshot(input));
2631
+ const structuredContent = result.status === "connected" ? result : {
2632
+ ...result,
2633
+ ...withManualLoginFields(result)
2634
+ };
2635
+ return {
2636
+ content: [
2637
+ {
2638
+ type: "text",
2639
+ text: result.status === "connected" ? `Helios market snapshot: ${result.snapshot.symbolCount} symbols (${result.snapshot.scope}) at ${result.snapshot.generatedAt}. Timeframe return fields are already percentages; do not multiply by 100. Null means unavailable, not zero.` : result.message
2640
+ }
2641
+ ],
2642
+ structuredContent
2643
+ };
2644
+ }
2645
+ },
2646
+ {
2647
+ name: "helios_market_get_snapshot_chunk",
2648
+ title: "Get Helios Market Snapshot Chunk",
2649
+ description: "Returns one chunk of the Helios market snapshot for batch analysis when the full snapshot is too large.",
2650
+ inputSchema: marketSnapshotChunkInputSchema,
2651
+ async execute(input) {
2652
+ const result = marketSnapshotChunkToolOutputSchema.parse(await service.getSnapshotChunk(input));
2653
+ const structuredContent = result.status === "connected" ? result : {
2654
+ ...result,
2655
+ ...withManualLoginFields(result)
2656
+ };
2657
+ return {
2658
+ content: [
2659
+ {
2660
+ type: "text",
2661
+ text: result.status === "connected" ? `Helios market snapshot chunk: ${result.snapshotChunk.chunkSymbolCount}/${result.snapshotChunk.totalSymbolCount} symbols at offset ${result.snapshotChunk.offset} (limit ${result.snapshotChunk.limit}). ${result.snapshotChunk.hasMore ? `Read next chunk at offset ${result.snapshotChunk.nextOffset}.` : "No more chunks remain."} Timeframe return fields are already percentages; do not multiply by 100. Null means unavailable, not zero.` : result.message
2662
+ }
2663
+ ],
2664
+ structuredContent
2665
+ };
2666
+ }
2667
+ },
2668
+ {
2669
+ name: "helios_market_get_symbol_detail",
2670
+ title: "Get Helios Symbol Detail",
2671
+ description: "Returns expanded market detail for one symbol from the current Helios market snapshot.",
2672
+ inputSchema: marketSymbolDetailInputSchema,
2673
+ async execute(input) {
2674
+ const result = marketSymbolDetailToolOutputSchema.parse(await service.getSymbolDetail(input));
2675
+ const structuredContent = result.status === "connected" ? result : {
2676
+ ...result,
2677
+ ...withManualLoginFields(result)
2678
+ };
2679
+ return {
2680
+ content: [
2681
+ {
2682
+ type: "text",
2683
+ text: result.status === "connected" ? `Helios symbol detail: ${result.detail.symbol} at ${result.detail.generatedAt}. Timeframe return fields are already percentages; do not multiply by 100. Null means unavailable, not zero.` : result.message
2684
+ }
2685
+ ],
2686
+ structuredContent
2687
+ };
2688
+ }
2689
+ }
2690
+ ];
2691
+ }
2692
+ function createHeliosTradingToolDefinitions(service) {
2693
+ return [
2694
+ {
2695
+ name: "helios_trading_open",
2696
+ title: "Open Helios Position",
2697
+ description: "Submits a Helios OPEN trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2698
+ inputSchema: tradeActionInputSchema,
2699
+ async execute(input) {
2700
+ const result = tradeActionToolOutputSchema.parse(await service.open(input));
2701
+ return {
2702
+ content: [
2703
+ {
2704
+ type: "text",
2705
+ text: result.status === "connected" ? `Submitted Helios OPEN intent for ${result.submission.provider ?? input.provider} ${result.submission.symbol} ${result.submission.direction} with ${result.submission.execution.style} execution.` : result.message
2706
+ }
2707
+ ],
2708
+ structuredContent: result.status === "connected" ? result : {
2709
+ ...result,
2710
+ ...withManualLoginFields(result)
2711
+ }
2712
+ };
2713
+ }
2714
+ },
2715
+ {
2716
+ name: "helios_trading_dca",
2717
+ title: "DCA Helios Position",
2718
+ description: "Submits a Helios DCA trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2719
+ inputSchema: tradeActionInputSchema,
2720
+ async execute(input) {
2721
+ const result = tradeActionToolOutputSchema.parse(await service.dca(input));
2722
+ return {
2723
+ content: [
2724
+ {
2725
+ type: "text",
2726
+ text: result.status === "connected" ? `Submitted Helios DCA intent for ${result.submission.provider ?? input.provider} ${result.submission.symbol} ${result.submission.direction} with ${result.submission.execution.style} execution.` : result.message
2727
+ }
2728
+ ],
2729
+ structuredContent: result.status === "connected" ? result : {
2730
+ ...result,
2731
+ ...withManualLoginFields(result)
2732
+ }
2733
+ };
2734
+ }
2735
+ },
2736
+ {
2737
+ name: "helios_trading_reverse",
2738
+ title: "Reverse Helios Position",
2739
+ description: "Submits a Helios REVERSE trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2740
+ inputSchema: tradeActionInputSchema,
2741
+ async execute(input) {
2742
+ const result = tradeActionToolOutputSchema.parse(await service.reverse(input));
2743
+ return {
2744
+ content: [
2745
+ {
2746
+ type: "text",
2747
+ text: result.status === "connected" ? `Submitted Helios REVERSE intent for ${result.submission.provider ?? input.provider} ${result.submission.symbol} ${result.submission.direction} with ${result.submission.execution.style} execution.` : result.message
2748
+ }
2749
+ ],
2750
+ structuredContent: result.status === "connected" ? result : {
2751
+ ...result,
2752
+ ...withManualLoginFields(result)
2753
+ }
2754
+ };
2755
+ }
2756
+ },
2757
+ {
2758
+ name: "helios_trading_close",
2759
+ title: "Close Helios Position",
2760
+ description: "Closes the full Helios position using the dedicated backend close route. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2761
+ inputSchema: closePositionInputSchema,
2762
+ async execute(input) {
2763
+ const result = closeTradeToolOutputSchema.parse(await service.close(input));
2764
+ return {
2765
+ content: [
2766
+ {
2767
+ type: "text",
2768
+ text: result.status === "connected" ? `Submitted Helios full close for ${result.closure.provider ?? input.provider} ${result.closure.symbol}.` : result.message
2769
+ }
2770
+ ],
2771
+ structuredContent: result.status === "connected" ? result : {
2772
+ ...result,
2773
+ ...withManualLoginFields(result)
2774
+ }
2775
+ };
2776
+ }
2777
+ },
2778
+ {
2779
+ name: "helios_positions_set_tp_sl",
2780
+ title: "Set Helios TP/SL",
2781
+ description: "Creates or replaces take-profit and stop-loss protection for an existing Helios position. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2782
+ inputSchema: setTpSlInputSchema,
2783
+ async execute(input) {
2784
+ const result = setTpSlToolOutputSchema.parse(await service.setTpSl(input));
2785
+ return {
2786
+ content: [
2787
+ {
2788
+ type: "text",
2789
+ text: result.status === "connected" ? `Submitted ${result.protection.provider ?? input.provider} TP/SL protection update for ${result.protection.symbol}.` : result.message
2790
+ }
2791
+ ],
2792
+ structuredContent: result.status === "connected" ? result : {
2793
+ ...result,
2794
+ ...withManualLoginFields(result)
2795
+ }
2796
+ };
2797
+ }
2798
+ },
2799
+ {
2800
+ name: "helios_positions_delete_tp_sl",
2801
+ title: "Delete Helios TP/SL",
2802
+ description: "Deletes an existing Helios take-profit or stop-loss order by order id. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2803
+ inputSchema: deleteTpSlInputSchema,
2804
+ async execute(input) {
2805
+ const result = deleteTpSlToolOutputSchema.parse(await service.deleteTpSl(input));
2806
+ return {
2807
+ content: [
2808
+ {
2809
+ type: "text",
2810
+ text: result.status === "connected" ? `Deleted ${result.deletion.provider ?? input.provider} TP/SL order ${result.deletion.orderId} for ${result.deletion.symbol}.` : result.message
2811
+ }
2812
+ ],
2813
+ structuredContent: result.status === "connected" ? result : {
2814
+ ...result,
2815
+ ...withManualLoginFields(result)
2816
+ }
2817
+ };
2818
+ }
2819
+ },
2820
+ {
2821
+ name: "helios_orders_get_open",
2822
+ title: "Get Helios Open Orders",
2823
+ description: "Lists the currently open Hyperliquid orders for the connected account.",
2824
+ inputSchema: z5.object({}),
2825
+ async execute() {
2826
+ const result = openOrdersToolOutputSchema.parse(await service.getOpenOrders());
2827
+ return {
2828
+ content: [
2829
+ {
2830
+ type: "text",
2831
+ text: result.status === "connected" ? `Retrieved ${result.orders.length} open Helios orders.` : result.message
2832
+ }
2833
+ ],
2834
+ structuredContent: result.status === "connected" ? result : {
2835
+ ...result,
2836
+ ...withManualLoginFields(result)
2837
+ }
2838
+ };
2839
+ }
2840
+ },
2841
+ {
2842
+ name: "helios_orders_cancel",
2843
+ title: "Cancel Helios Order",
2844
+ description: "Cancels an open Hyperliquid order by symbol and order id.",
2845
+ inputSchema: cancelOrderInputSchema,
2846
+ async execute(input) {
2847
+ const result = cancelOrderToolOutputSchema.parse(await service.cancelOrder(input));
2848
+ return {
2849
+ content: [
2850
+ {
2851
+ type: "text",
2852
+ text: result.status === "connected" ? `Cancelled Helios order ${result.cancellation.oid} for ${result.cancellation.symbol}.` : result.message
2853
+ }
2854
+ ],
2855
+ structuredContent: result.status === "connected" ? result : {
2856
+ ...result,
2857
+ ...withManualLoginFields(result)
2858
+ }
2859
+ };
2860
+ }
2861
+ }
2862
+ ];
2863
+ }
2864
+ function withManualLoginFields(result) {
2865
+ return {
2866
+ actionRequired: true,
2867
+ loginUrl: result.verificationUriComplete,
2868
+ nextStep: "Open the login URL in your browser, approve Helios access, then call helios_auth_ensure_login again to finish connecting."
2869
+ };
2870
+ }
2871
+ function buildPortfolioText(result) {
2872
+ return `Helios Hyperliquid portfolio: ${result.positions.length} positions, available balance ${result.availableBalance}, total balance ${result.totalBalance}.`;
2873
+ }
2874
+ function buildManualLoginText(result) {
2875
+ return `Log in to Helios by opening this URL in your browser:
2876
+
2877
+ ${result.verificationUriComplete}
2878
+
2879
+ User code: ${result.userCode}
2880
+
2881
+ After approving access, call helios_auth_ensure_login (or helios_auth_poll_login) again to finish connecting.`;
2882
+ }
2883
+
2884
+ // src/server.ts
2885
+ async function createHeliosAgentMcpServer(options) {
2886
+ if (!options.identityServiceUrl) {
2887
+ throw new Error("identityServiceUrl is required");
2888
+ }
2889
+ if (!options.dataBridgeUrl) {
2890
+ throw new Error("dataBridgeUrl is required");
2891
+ }
2892
+ const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
2893
+ const server = new McpServer({
2894
+ name: "helios",
2895
+ version: "0.2.5"
2896
+ });
2897
+ const sessionStore = options.sessionStore ?? new FileAgentSessionStore(options.sessionPath ?? getDefaultHeliosAgentMcpSessionPath());
2898
+ const client = new HeliosAgentAuthClient({
2899
+ baseUrl: options.identityServiceUrl,
2900
+ fetch: options.fetch
2901
+ });
2902
+ const dataBridgeClient = new HeliosAgentDataBridgeClient({
2903
+ baseUrl: options.dataBridgeUrl,
2904
+ fetch: options.fetch
2905
+ });
2906
+ const authService = new HeliosAgentMcpAuthService({
2907
+ client,
2908
+ sessionStore,
2909
+ refreshWindowMs: options.refreshWindowMs,
2910
+ deviceLogin: !options.hosted
2911
+ });
2912
+ const providerService = new HeliosAgentMcpProviderService({
2913
+ sessionStore
2914
+ });
2915
+ const accountService = new HeliosAgentMcpAccountService({
2916
+ authService,
2917
+ dataBridgeClient,
2918
+ providerService
2919
+ });
2920
+ const marketService = new HeliosAgentMcpMarketService({
2921
+ authService,
2922
+ dataBridgeClient
2923
+ });
2924
+ const ledgerService = new HeliosAgentMcpLedgerService({
2925
+ authService,
2926
+ dataBridgeClient
2927
+ });
2928
+ const tradingService = new HeliosAgentMcpTradingService({
2929
+ authService,
2930
+ dataBridgeClient,
2931
+ providerService
2932
+ });
2933
+ const docsService = new HeliosAgentMcpDocsService({
2934
+ docsRoot: options.docsRoot ?? getDefaultHeliosAgentMcpDocsRoot()
2935
+ });
2936
+ const docsTools = createHeliosDocsToolDefinitions(docsService);
2937
+ const authTools = createHeliosAuthToolDefinitions(authService);
2938
+ const providerTools = createHeliosProviderToolDefinitions(providerService);
2939
+ const accountTools = createHeliosAccountToolDefinitions(accountService);
2940
+ const ledgerTools = createHeliosLedgerToolDefinitions(ledgerService);
2941
+ const marketTools = createHeliosMarketToolDefinitions(marketService);
2942
+ const tradingTools = createHeliosTradingToolDefinitions(tradingService);
2943
+ registerTool(server, docsTools[0]);
2944
+ registerTool(server, docsTools[1]);
2945
+ if (!options.hosted) {
2946
+ registerTool(server, authTools[0]);
2947
+ registerTool(server, authTools[1]);
2948
+ registerTool(server, authTools[2]);
2949
+ }
2950
+ registerTool(server, authTools[3]);
2951
+ registerTool(server, providerTools[0]);
2952
+ registerTool(server, providerTools[1]);
2953
+ registerTool(server, accountTools[0]);
2954
+ registerTool(server, accountTools[1]);
2955
+ registerTool(server, ledgerTools[0]);
2956
+ registerTool(server, ledgerTools[1]);
2957
+ registerTool(server, ledgerTools[2]);
2958
+ registerTool(server, marketTools[0]);
2959
+ registerTool(server, marketTools[1]);
2960
+ registerTool(server, marketTools[2]);
2961
+ registerTool(server, tradingTools[0]);
2962
+ registerTool(server, tradingTools[1]);
2963
+ registerTool(server, tradingTools[2]);
2964
+ registerTool(server, tradingTools[3]);
2965
+ registerTool(server, tradingTools[4]);
2966
+ registerTool(server, tradingTools[5]);
2967
+ registerTool(server, tradingTools[6]);
2968
+ registerTool(server, tradingTools[7]);
2969
+ return {
2970
+ server,
2971
+ authService,
2972
+ providerService,
2973
+ accountService,
2974
+ docsService,
2975
+ ledgerService,
2976
+ marketService,
2977
+ tradingService,
2978
+ sessionStore
2979
+ };
2980
+ }
2981
+ var ACTS_ON_ACCOUNT = /^helios_(trading_|positions_set_tp_sl|positions_delete_tp_sl|orders_cancel)/;
2982
+ var CHANGES_SESSION = /^helios_(auth_start_login|auth_ensure_login|auth_poll_login|provider_set_active)$/;
2983
+ function toolAnnotations(name) {
2984
+ if (ACTS_ON_ACCOUNT.test(name)) return { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
2985
+ if (CHANGES_SESSION.test(name)) return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
2986
+ return { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
2987
+ }
2988
+ var TEXT_IS_RESULT = /* @__PURE__ */ new Set(["helios_docs_get_document"]);
2989
+ function withDataText(name, content, structuredContent) {
2990
+ if (TEXT_IS_RESULT.has(name)) return content;
2991
+ return [...content, { type: "text", text: JSON.stringify(structuredContent) }];
2992
+ }
2993
+ function registerTool(server, tool) {
2994
+ server.registerTool(
2995
+ tool.name,
2996
+ {
2997
+ title: tool.title,
2998
+ description: tool.description,
2999
+ inputSchema: tool.inputSchema,
3000
+ annotations: { title: tool.title, ...toolAnnotations(tool.name) }
3001
+ },
3002
+ async (input) => {
3003
+ const result = await tool.execute(tool.inputSchema.parse(input));
3004
+ return {
3005
+ content: withDataText(tool.name, result.content, result.structuredContent),
3006
+ structuredContent: result.structuredContent
3007
+ };
3008
+ }
3009
+ );
3010
+ }
3011
+
3012
+ export {
3013
+ HOSTED_RECONNECT_MESSAGE,
3014
+ HeliosAgentMcpAuthService,
3015
+ retryAfterUnauthorizedRefresh,
3016
+ formatHeliosLoginPrompt,
3017
+ HeliosAgentMcpAccountService,
3018
+ HeliosAgentMcpDocsService,
3019
+ getDefaultHeliosAgentMcpDocsRoot,
3020
+ HeliosAgentMcpLedgerService,
3021
+ DEFAULT_SNAPSHOT_TOP,
3022
+ DEFAULT_SNAPSHOT_FIELDS,
3023
+ withSnapshotDefaults,
3024
+ topOfSnapshot,
3025
+ HeliosAgentMcpMarketService,
3026
+ HeliosAgentMcpProviderService,
3027
+ getDefaultHeliosAgentMcpSessionPath,
3028
+ pendingAgentLoginSchema,
3029
+ FileAgentSessionStore,
3030
+ MemoryAgentMcpSessionStore,
3031
+ HeliosAgentMcpTradingService,
3032
+ createHeliosDocsToolDefinitions,
3033
+ createHeliosAuthToolDefinitions,
3034
+ createHeliosProviderToolDefinitions,
3035
+ createHeliosAccountToolDefinitions,
3036
+ createHeliosLedgerToolDefinitions,
3037
+ createHeliosMarketToolDefinitions,
3038
+ createHeliosTradingToolDefinitions,
3039
+ createHeliosAgentMcpServer,
3040
+ toolAnnotations,
3041
+ withDataText
3042
+ };