@pgnio/helios-mcp 0.2.3 → 0.2.4

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,3038 @@
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, 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
+ "vwz",
1429
+ "tri"
1430
+ ];
1431
+ function withSnapshotDefaults(input) {
1432
+ return {
1433
+ ...input,
1434
+ fields: input.fields ?? [...DEFAULT_SNAPSHOT_FIELDS],
1435
+ sort: input.sort ?? "rank"
1436
+ };
1437
+ }
1438
+ function topOfSnapshot(snapshot, input, top = DEFAULT_SNAPSHOT_TOP) {
1439
+ if (input.symbols?.length || snapshot.table.rows.length <= top) return snapshot;
1440
+ const baseIndex = snapshot.table.fieldIds.indexOf("base");
1441
+ const rows = snapshot.table.rows.slice(0, top);
1442
+ const returnedSymbols = baseIndex === -1 ? snapshot.returnedSymbols.slice(0, top) : rows.map((row) => String(row[baseIndex]));
1443
+ return { ...snapshot, symbolCount: rows.length, returnedSymbols, table: { ...snapshot.table, rows } };
1444
+ }
1445
+ var HeliosAgentMcpMarketService = class {
1446
+ constructor(options) {
1447
+ __publicField(this, "authService");
1448
+ __publicField(this, "dataBridgeClient");
1449
+ this.authService = options.authService;
1450
+ this.dataBridgeClient = options.dataBridgeClient;
1451
+ }
1452
+ async getSnapshot(input = {}) {
1453
+ const loginOptions = {
1454
+ clientName: "Helios MCP",
1455
+ scope: [AGENT_SCOPES.MARKET_READ]
1456
+ };
1457
+ const login = await this.authService.ensureLogin(loginOptions);
1458
+ if (login.status !== "connected") {
1459
+ return {
1460
+ ...login,
1461
+ status: "pending",
1462
+ connected: false
1463
+ };
1464
+ }
1465
+ const session = await this.authService.requireSession();
1466
+ try {
1467
+ const snapshot = topOfSnapshot(await this.dataBridgeClient.getMarketSnapshot(session.accessToken, withSnapshotDefaults(input)), input);
1468
+ return {
1469
+ status: "connected",
1470
+ connected: true,
1471
+ snapshot
1472
+ };
1473
+ } catch (error) {
1474
+ const recovery = await retryAfterUnauthorizedRefresh({
1475
+ authService: this.authService,
1476
+ error,
1477
+ loginOptions,
1478
+ retry: async (accessToken) => {
1479
+ const snapshot = topOfSnapshot(await this.dataBridgeClient.getMarketSnapshot(accessToken, withSnapshotDefaults(input)), input);
1480
+ return {
1481
+ status: "connected",
1482
+ connected: true,
1483
+ snapshot
1484
+ };
1485
+ }
1486
+ });
1487
+ if (recovery) {
1488
+ return recovery;
1489
+ }
1490
+ throw error;
1491
+ }
1492
+ }
1493
+ async getSnapshotChunk(input = {}) {
1494
+ const loginOptions = {
1495
+ clientName: "Helios MCP",
1496
+ scope: [AGENT_SCOPES.MARKET_READ]
1497
+ };
1498
+ const login = await this.authService.ensureLogin(loginOptions);
1499
+ if (login.status !== "connected") {
1500
+ return {
1501
+ ...login,
1502
+ status: "pending",
1503
+ connected: false
1504
+ };
1505
+ }
1506
+ const session = await this.authService.requireSession();
1507
+ try {
1508
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(session.accessToken, withSnapshotDefaults(input));
1509
+ return {
1510
+ status: "connected",
1511
+ connected: true,
1512
+ snapshotChunk
1513
+ };
1514
+ } catch (error) {
1515
+ const recovery = await retryAfterUnauthorizedRefresh({
1516
+ authService: this.authService,
1517
+ error,
1518
+ loginOptions,
1519
+ retry: async (accessToken) => {
1520
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(accessToken, withSnapshotDefaults(input));
1521
+ return {
1522
+ status: "connected",
1523
+ connected: true,
1524
+ snapshotChunk
1525
+ };
1526
+ }
1527
+ });
1528
+ if (recovery) {
1529
+ return recovery;
1530
+ }
1531
+ throw error;
1532
+ }
1533
+ }
1534
+ async getSymbolDetail(input) {
1535
+ const loginOptions = {
1536
+ clientName: "Helios MCP",
1537
+ scope: [AGENT_SCOPES.MARKET_READ]
1538
+ };
1539
+ const login = await this.authService.ensureLogin(loginOptions);
1540
+ if (login.status !== "connected") {
1541
+ return {
1542
+ ...login,
1543
+ status: "pending",
1544
+ connected: false
1545
+ };
1546
+ }
1547
+ const session = await this.authService.requireSession();
1548
+ try {
1549
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(session.accessToken, input);
1550
+ return {
1551
+ status: "connected",
1552
+ connected: true,
1553
+ detail
1554
+ };
1555
+ } catch (error) {
1556
+ const recovery = await retryAfterUnauthorizedRefresh({
1557
+ authService: this.authService,
1558
+ error,
1559
+ loginOptions,
1560
+ retry: async (accessToken) => {
1561
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(accessToken, input);
1562
+ return {
1563
+ status: "connected",
1564
+ connected: true,
1565
+ detail
1566
+ };
1567
+ }
1568
+ });
1569
+ if (recovery) {
1570
+ return recovery;
1571
+ }
1572
+ throw error;
1573
+ }
1574
+ }
1575
+ };
1576
+
1577
+ // src/provider-service.ts
1578
+ var HeliosAgentMcpProviderService = class {
1579
+ constructor(options) {
1580
+ __publicField(this, "sessionStore");
1581
+ this.sessionStore = options.sessionStore;
1582
+ }
1583
+ async getActiveProvider() {
1584
+ const provider = await this.sessionStore.getActiveProvider();
1585
+ if (!provider) {
1586
+ return {
1587
+ configured: false,
1588
+ provider: null
1589
+ };
1590
+ }
1591
+ return {
1592
+ configured: true,
1593
+ provider
1594
+ };
1595
+ }
1596
+ async setActiveProvider(provider) {
1597
+ await this.sessionStore.setActiveProvider(provider);
1598
+ return {
1599
+ configured: true,
1600
+ provider
1601
+ };
1602
+ }
1603
+ async resolveProvider(explicitProvider) {
1604
+ if (explicitProvider) {
1605
+ return explicitProvider;
1606
+ }
1607
+ const activeProvider = await this.sessionStore.getActiveProvider();
1608
+ if (activeProvider) {
1609
+ return activeProvider;
1610
+ }
1611
+ throw new Error("No active provider configured. Call helios_provider_set_active or pass provider explicitly.");
1612
+ }
1613
+ };
1614
+
1615
+ // src/session-store.ts
1616
+ import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
1617
+ import { homedir } from "os";
1618
+ import path2 from "path";
1619
+ import { z as z4 } from "zod";
1620
+ function getDefaultHeliosAgentMcpSessionPath() {
1621
+ return path2.join(homedir(), ".helios-agent-mcp", "session.json");
1622
+ }
1623
+ var pendingAgentLoginSchema = z4.object({
1624
+ status: z4.literal("pending"),
1625
+ deviceCode: z4.string(),
1626
+ userCode: z4.string(),
1627
+ verificationUri: z4.string().url(),
1628
+ verificationUriComplete: z4.string().url(),
1629
+ expiresInSeconds: z4.number().int().positive(),
1630
+ pollIntervalSeconds: z4.number().int().positive(),
1631
+ requestedScope: z4.array(agentScopeSchema).min(1),
1632
+ startedAt: z4.string().datetime()
1633
+ });
1634
+ var mcpSessionStateSchema = z4.object({
1635
+ session: storedAgentSessionSchema.nullish(),
1636
+ pendingLogin: pendingAgentLoginSchema.nullish(),
1637
+ // A provider pinned before Binance was retired ('binance') reads as unpinned, so the agent must pick again, rather than
1638
+ // failing the whole file (which would drop the session) or silently switching it to Hyperliquid.
1639
+ activeProvider: providerSchema.nullish().catch(null)
1640
+ });
1641
+ var FileAgentSessionStore = class {
1642
+ constructor(filePath = getDefaultHeliosAgentMcpSessionPath()) {
1643
+ this.filePath = filePath;
1644
+ }
1645
+ async getSession() {
1646
+ return (await this.readState()).session;
1647
+ }
1648
+ async getPendingLogin() {
1649
+ return (await this.readState()).pendingLogin;
1650
+ }
1651
+ async getActiveProvider() {
1652
+ return (await this.readState()).activeProvider;
1653
+ }
1654
+ async setSession(session) {
1655
+ const state = await this.readState();
1656
+ await this.writeState({
1657
+ ...state,
1658
+ session
1659
+ });
1660
+ }
1661
+ async setPendingLogin(pendingLogin) {
1662
+ const state = await this.readState();
1663
+ await this.writeState({
1664
+ ...state,
1665
+ pendingLogin
1666
+ });
1667
+ }
1668
+ async setActiveProvider(activeProvider) {
1669
+ const state = await this.readState();
1670
+ await this.writeState({
1671
+ ...state,
1672
+ activeProvider
1673
+ });
1674
+ }
1675
+ async clearSession() {
1676
+ const state = await this.readState();
1677
+ await this.writeStateOrDelete({
1678
+ ...state,
1679
+ session: null
1680
+ });
1681
+ }
1682
+ async clearPendingLogin() {
1683
+ const state = await this.readState();
1684
+ await this.writeStateOrDelete({
1685
+ ...state,
1686
+ pendingLogin: null
1687
+ });
1688
+ }
1689
+ async clearActiveProvider() {
1690
+ const state = await this.readState();
1691
+ await this.writeStateOrDelete({
1692
+ ...state,
1693
+ activeProvider: null
1694
+ });
1695
+ }
1696
+ async readState() {
1697
+ try {
1698
+ const raw = await readFile(this.filePath, "utf8");
1699
+ const parsed = JSON.parse(raw);
1700
+ if (parsed && typeof parsed === "object" && ("session" in parsed || "pendingLogin" in parsed || "activeProvider" in parsed)) {
1701
+ const envelope = mcpSessionStateSchema.safeParse(parsed);
1702
+ if (envelope.success) {
1703
+ return {
1704
+ session: envelope.data.session ?? null,
1705
+ pendingLogin: envelope.data.pendingLogin ?? null,
1706
+ activeProvider: envelope.data.activeProvider ?? null
1707
+ };
1708
+ }
1709
+ }
1710
+ const legacySession = storedAgentSessionSchema.safeParse(parsed);
1711
+ if (legacySession.success) {
1712
+ return {
1713
+ session: legacySession.data,
1714
+ pendingLogin: null,
1715
+ activeProvider: null
1716
+ };
1717
+ }
1718
+ return {
1719
+ session: null,
1720
+ pendingLogin: null,
1721
+ activeProvider: null
1722
+ };
1723
+ } catch (error) {
1724
+ if (isMissingFileError(error)) {
1725
+ return {
1726
+ session: null,
1727
+ pendingLogin: null,
1728
+ activeProvider: null
1729
+ };
1730
+ }
1731
+ if (error instanceof Error && error.name === "ZodError") {
1732
+ return {
1733
+ session: null,
1734
+ pendingLogin: null,
1735
+ activeProvider: null
1736
+ };
1737
+ }
1738
+ throw error;
1739
+ }
1740
+ }
1741
+ async writeState(state) {
1742
+ await mkdir(path2.dirname(this.filePath), { recursive: true });
1743
+ await writeFile(this.filePath, `${JSON.stringify(state, null, 2)}
1744
+ `, { encoding: "utf8", mode: 384 });
1745
+ await chmod(this.filePath, 384).catch(() => void 0);
1746
+ }
1747
+ async writeStateOrDelete(state) {
1748
+ if (!state.session && !state.pendingLogin && !state.activeProvider) {
1749
+ await this.deleteFile();
1750
+ return;
1751
+ }
1752
+ await this.writeState(state);
1753
+ }
1754
+ async deleteFile() {
1755
+ try {
1756
+ await rm(this.filePath, { force: true });
1757
+ } catch (error) {
1758
+ if (!isMissingFileError(error)) {
1759
+ throw error;
1760
+ }
1761
+ }
1762
+ }
1763
+ };
1764
+ var MemoryAgentMcpSessionStore = class {
1765
+ constructor(session = null, activeProvider = "hyperliquid") {
1766
+ this.session = session;
1767
+ this.activeProvider = activeProvider;
1768
+ __publicField(this, "pendingLogin", null);
1769
+ }
1770
+ async getSession() {
1771
+ return this.session;
1772
+ }
1773
+ async setSession(session) {
1774
+ this.session = session;
1775
+ }
1776
+ async clearSession() {
1777
+ this.session = null;
1778
+ }
1779
+ async getActiveProvider() {
1780
+ return this.activeProvider;
1781
+ }
1782
+ async setActiveProvider(provider) {
1783
+ this.activeProvider = provider;
1784
+ }
1785
+ async clearActiveProvider() {
1786
+ this.activeProvider = null;
1787
+ }
1788
+ async getPendingLogin() {
1789
+ return this.pendingLogin;
1790
+ }
1791
+ async setPendingLogin(pendingLogin) {
1792
+ this.pendingLogin = pendingLogin;
1793
+ }
1794
+ async clearPendingLogin() {
1795
+ this.pendingLogin = null;
1796
+ }
1797
+ };
1798
+ function isMissingFileError(error) {
1799
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
1800
+ }
1801
+
1802
+ // src/trading-service.ts
1803
+ import { randomUUID } from "crypto";
1804
+ var HeliosAgentMcpTradingService = class {
1805
+ constructor(options) {
1806
+ __publicField(this, "authService");
1807
+ __publicField(this, "dataBridgeClient");
1808
+ __publicField(this, "providerService");
1809
+ this.authService = options.authService;
1810
+ this.dataBridgeClient = options.dataBridgeClient;
1811
+ this.providerService = options.providerService;
1812
+ }
1813
+ async open(input) {
1814
+ return this.submitIntent("OPEN", input);
1815
+ }
1816
+ async dca(input) {
1817
+ return this.submitIntent("DCA", input);
1818
+ }
1819
+ async reverse(input) {
1820
+ return this.submitIntent("REVERSE", input);
1821
+ }
1822
+ async close(input) {
1823
+ const loginOptions = {
1824
+ clientName: "Helios MCP",
1825
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1826
+ };
1827
+ const login = await this.authService.ensureLogin(loginOptions);
1828
+ if (login.status !== "connected") {
1829
+ return asPending2(login);
1830
+ }
1831
+ const session = await this.authService.requireSession();
1832
+ try {
1833
+ const provider = await this.providerService.resolveProvider(input.provider);
1834
+ const closure = await this.dataBridgeClient.closePosition(session.accessToken, {
1835
+ ...input,
1836
+ provider
1837
+ });
1838
+ return {
1839
+ status: "connected",
1840
+ connected: true,
1841
+ closure
1842
+ };
1843
+ } catch (error) {
1844
+ const recovery = await retryAfterUnauthorizedRefresh({
1845
+ authService: this.authService,
1846
+ error,
1847
+ loginOptions,
1848
+ retry: async (accessToken) => {
1849
+ const provider = await this.providerService.resolveProvider(input.provider);
1850
+ const closure = await this.dataBridgeClient.closePosition(accessToken, {
1851
+ ...input,
1852
+ provider
1853
+ });
1854
+ return {
1855
+ status: "connected",
1856
+ connected: true,
1857
+ closure
1858
+ };
1859
+ }
1860
+ });
1861
+ if (recovery) {
1862
+ return recovery;
1863
+ }
1864
+ throw error;
1865
+ }
1866
+ }
1867
+ async setTpSl(input) {
1868
+ const loginOptions = {
1869
+ clientName: "Helios MCP",
1870
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1871
+ };
1872
+ const login = await this.authService.ensureLogin(loginOptions);
1873
+ if (login.status !== "connected") {
1874
+ return asPending2(login);
1875
+ }
1876
+ const session = await this.authService.requireSession();
1877
+ try {
1878
+ const provider = await this.providerService.resolveProvider(input.provider);
1879
+ const protection = await this.dataBridgeClient.setTpSl(session.accessToken, {
1880
+ ...input,
1881
+ provider
1882
+ });
1883
+ return {
1884
+ status: "connected",
1885
+ connected: true,
1886
+ protection
1887
+ };
1888
+ } catch (error) {
1889
+ const recovery = await retryAfterUnauthorizedRefresh({
1890
+ authService: this.authService,
1891
+ error,
1892
+ loginOptions,
1893
+ retry: async (accessToken) => {
1894
+ const provider = await this.providerService.resolveProvider(input.provider);
1895
+ const protection = await this.dataBridgeClient.setTpSl(accessToken, {
1896
+ ...input,
1897
+ provider
1898
+ });
1899
+ return {
1900
+ status: "connected",
1901
+ connected: true,
1902
+ protection
1903
+ };
1904
+ }
1905
+ });
1906
+ if (recovery) {
1907
+ return recovery;
1908
+ }
1909
+ throw error;
1910
+ }
1911
+ }
1912
+ async deleteTpSl(input) {
1913
+ const loginOptions = {
1914
+ clientName: "Helios MCP",
1915
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
1916
+ };
1917
+ const login = await this.authService.ensureLogin(loginOptions);
1918
+ if (login.status !== "connected") {
1919
+ return asPending2(login);
1920
+ }
1921
+ const session = await this.authService.requireSession();
1922
+ try {
1923
+ const provider = await this.providerService.resolveProvider(input.provider);
1924
+ const deletion = await this.dataBridgeClient.deleteTpSl(session.accessToken, {
1925
+ ...input,
1926
+ provider
1927
+ });
1928
+ return {
1929
+ status: "connected",
1930
+ connected: true,
1931
+ deletion
1932
+ };
1933
+ } catch (error) {
1934
+ const recovery = await retryAfterUnauthorizedRefresh({
1935
+ authService: this.authService,
1936
+ error,
1937
+ loginOptions,
1938
+ retry: async (accessToken) => {
1939
+ const provider = await this.providerService.resolveProvider(input.provider);
1940
+ const deletion = await this.dataBridgeClient.deleteTpSl(accessToken, {
1941
+ ...input,
1942
+ provider
1943
+ });
1944
+ return {
1945
+ status: "connected",
1946
+ connected: true,
1947
+ deletion
1948
+ };
1949
+ }
1950
+ });
1951
+ if (recovery) {
1952
+ return recovery;
1953
+ }
1954
+ throw error;
1955
+ }
1956
+ }
1957
+ async getOpenOrders() {
1958
+ const loginOptions = {
1959
+ clientName: "Helios MCP",
1960
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1961
+ };
1962
+ const login = await this.authService.ensureLogin(loginOptions);
1963
+ if (login.status !== "connected") {
1964
+ return asPending2(login);
1965
+ }
1966
+ const session = await this.authService.requireSession();
1967
+ try {
1968
+ const orders = await this.dataBridgeClient.getOpenOrders(session.accessToken);
1969
+ return {
1970
+ status: "connected",
1971
+ connected: true,
1972
+ orders
1973
+ };
1974
+ } catch (error) {
1975
+ const recovery = await retryAfterUnauthorizedRefresh({
1976
+ authService: this.authService,
1977
+ error,
1978
+ loginOptions,
1979
+ retry: async (accessToken) => {
1980
+ const orders = await this.dataBridgeClient.getOpenOrders(accessToken);
1981
+ return {
1982
+ status: "connected",
1983
+ connected: true,
1984
+ orders
1985
+ };
1986
+ }
1987
+ });
1988
+ if (recovery) {
1989
+ return recovery;
1990
+ }
1991
+ throw error;
1992
+ }
1993
+ }
1994
+ async cancelOrder(input) {
1995
+ const loginOptions = {
1996
+ clientName: "Helios MCP",
1997
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
1998
+ };
1999
+ const login = await this.authService.ensureLogin(loginOptions);
2000
+ if (login.status !== "connected") {
2001
+ return asPending2(login);
2002
+ }
2003
+ const session = await this.authService.requireSession();
2004
+ try {
2005
+ const cancellation = await this.dataBridgeClient.cancelOrder(session.accessToken, input);
2006
+ return {
2007
+ status: "connected",
2008
+ connected: true,
2009
+ cancellation
2010
+ };
2011
+ } catch (error) {
2012
+ const recovery = await retryAfterUnauthorizedRefresh({
2013
+ authService: this.authService,
2014
+ error,
2015
+ loginOptions,
2016
+ retry: async (accessToken) => {
2017
+ const cancellation = await this.dataBridgeClient.cancelOrder(accessToken, input);
2018
+ return {
2019
+ status: "connected",
2020
+ connected: true,
2021
+ cancellation
2022
+ };
2023
+ }
2024
+ });
2025
+ if (recovery) {
2026
+ return recovery;
2027
+ }
2028
+ throw error;
2029
+ }
2030
+ }
2031
+ async submitIntent(intentType, input) {
2032
+ const loginOptions = {
2033
+ clientName: "Helios MCP",
2034
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
2035
+ };
2036
+ const login = await this.authService.ensureLogin(loginOptions);
2037
+ if (login.status !== "connected") {
2038
+ return asPending2(login);
2039
+ }
2040
+ const session = await this.authService.requireSession();
2041
+ const idempotencyKey = input.idempotencyKey ?? randomUUID().replace(/-/g, "");
2042
+ try {
2043
+ const provider = await this.providerService.resolveProvider(input.provider);
2044
+ const submission = await this.dataBridgeClient.submitTradeIntent(session.accessToken, {
2045
+ ...input,
2046
+ provider,
2047
+ intentType,
2048
+ idempotencyKey
2049
+ });
2050
+ return {
2051
+ status: "connected",
2052
+ connected: true,
2053
+ submission
2054
+ };
2055
+ } catch (error) {
2056
+ const recovery = await retryAfterUnauthorizedRefresh({
2057
+ authService: this.authService,
2058
+ error,
2059
+ loginOptions,
2060
+ retry: async (accessToken) => {
2061
+ const provider = await this.providerService.resolveProvider(input.provider);
2062
+ const submission = await this.dataBridgeClient.submitTradeIntent(accessToken, {
2063
+ ...input,
2064
+ provider,
2065
+ intentType,
2066
+ idempotencyKey
2067
+ });
2068
+ return {
2069
+ status: "connected",
2070
+ connected: true,
2071
+ submission
2072
+ };
2073
+ }
2074
+ });
2075
+ if (recovery) {
2076
+ return recovery;
2077
+ }
2078
+ throw error;
2079
+ }
2080
+ }
2081
+ };
2082
+ function asPending2(login) {
2083
+ return {
2084
+ ...login,
2085
+ status: "pending",
2086
+ connected: false
2087
+ };
2088
+ }
2089
+
2090
+ // src/tools.ts
2091
+ import { z as z5 } from "zod";
2092
+ var pollLoginInputSchema = z5.object({
2093
+ /** Optional: defaults to the login started by helios_auth_ensure_login / helios_auth_start_login. */
2094
+ deviceCode: z5.string().min(1).optional()
2095
+ });
2096
+ var startLoginOutputSchema = z5.object({
2097
+ status: z5.literal("pending"),
2098
+ deviceCode: z5.string(),
2099
+ userCode: z5.string(),
2100
+ verificationUri: z5.string().url(),
2101
+ verificationUriComplete: z5.string().url(),
2102
+ expiresInSeconds: z5.number().int().positive(),
2103
+ pollIntervalSeconds: z5.number().int().positive(),
2104
+ requestedScope: z5.array(agentScopeSchema).min(1),
2105
+ startedAt: z5.string().datetime()
2106
+ });
2107
+ var ensureLoginInputSchema = z5.object({
2108
+ clientName: z5.string().min(1).max(64).optional(),
2109
+ scope: z5.array(agentScopeSchema).min(1).optional(),
2110
+ constraints: agentConstraintsSchema.optional()
2111
+ });
2112
+ var providerSelectionInputSchema = z5.object({
2113
+ provider: providerSchema.optional()
2114
+ });
2115
+ var providerSetInputSchema = z5.object({
2116
+ provider: providerSchema
2117
+ });
2118
+ var activeProviderSchema = z5.object({
2119
+ configured: z5.boolean(),
2120
+ provider: providerSchema.nullable()
2121
+ });
2122
+ var ensureLoginOutputSchema = z5.discriminatedUnion("status", [
2123
+ agentSessionViewSchema.extend({
2124
+ status: z5.literal("connected"),
2125
+ connected: z5.literal(true)
2126
+ }),
2127
+ startLoginOutputSchema.extend({
2128
+ status: z5.literal("pending"),
2129
+ connected: z5.literal(false),
2130
+ message: z5.string()
2131
+ })
2132
+ ]);
2133
+ var pollLoginOutputSchema = z5.discriminatedUnion("status", [
2134
+ agentSessionViewSchema.extend({
2135
+ status: z5.literal("connected"),
2136
+ connected: z5.literal(true)
2137
+ }),
2138
+ z5.object({
2139
+ status: z5.enum(["pending", "rejected", "expired", "failed"]),
2140
+ connected: z5.literal(false),
2141
+ message: z5.string()
2142
+ })
2143
+ ]);
2144
+ var walletStateToolOutputSchema = z5.discriminatedUnion("status", [
2145
+ z5.object({
2146
+ status: z5.literal("connected"),
2147
+ connected: z5.literal(true),
2148
+ walletState: walletStateSchema
2149
+ }),
2150
+ startLoginOutputSchema.extend({
2151
+ status: z5.literal("pending"),
2152
+ connected: z5.literal(false),
2153
+ message: z5.string()
2154
+ })
2155
+ ]);
2156
+ var portfolioToolOutputSchema = z5.discriminatedUnion("status", [
2157
+ z5.object({
2158
+ status: z5.literal("connected"),
2159
+ connected: z5.literal(true),
2160
+ portfolio: portfolioSnapshotSchema
2161
+ }),
2162
+ startLoginOutputSchema.extend({
2163
+ status: z5.literal("pending"),
2164
+ connected: z5.literal(false),
2165
+ message: z5.string()
2166
+ })
2167
+ ]);
2168
+ var openPositionsToolOutputSchema = z5.discriminatedUnion("status", [
2169
+ z5.object({
2170
+ status: z5.literal("connected"),
2171
+ connected: z5.literal(true),
2172
+ openPositions: openPositionsSnapshotSchema
2173
+ }),
2174
+ startLoginOutputSchema.extend({
2175
+ status: z5.literal("pending"),
2176
+ connected: z5.literal(false),
2177
+ message: z5.string()
2178
+ })
2179
+ ]);
2180
+ var ledgerFillsToolOutputSchema = z5.discriminatedUnion("status", [
2181
+ z5.object({
2182
+ status: z5.literal("connected"),
2183
+ connected: z5.literal(true),
2184
+ fills: ledgerFillsPageSchema
2185
+ }),
2186
+ startLoginOutputSchema.extend({
2187
+ status: z5.literal("pending"),
2188
+ connected: z5.literal(false),
2189
+ message: z5.string()
2190
+ })
2191
+ ]);
2192
+ var ledgerSummaryToolOutputSchema = z5.discriminatedUnion("status", [
2193
+ z5.object({
2194
+ status: z5.literal("connected"),
2195
+ connected: z5.literal(true),
2196
+ summary: ledgerSummarySchema
2197
+ }),
2198
+ startLoginOutputSchema.extend({
2199
+ status: z5.literal("pending"),
2200
+ connected: z5.literal(false),
2201
+ message: z5.string()
2202
+ })
2203
+ ]);
2204
+ var marketSnapshotToolOutputSchema = z5.discriminatedUnion("status", [
2205
+ z5.object({
2206
+ status: z5.literal("connected"),
2207
+ connected: z5.literal(true),
2208
+ snapshot: marketSnapshotSchema
2209
+ }),
2210
+ startLoginOutputSchema.extend({
2211
+ status: z5.literal("pending"),
2212
+ connected: z5.literal(false),
2213
+ message: z5.string()
2214
+ })
2215
+ ]);
2216
+ var marketSnapshotChunkToolOutputSchema = z5.discriminatedUnion("status", [
2217
+ z5.object({
2218
+ status: z5.literal("connected"),
2219
+ connected: z5.literal(true),
2220
+ snapshotChunk: marketSnapshotChunkSchema
2221
+ }),
2222
+ startLoginOutputSchema.extend({
2223
+ status: z5.literal("pending"),
2224
+ connected: z5.literal(false),
2225
+ message: z5.string()
2226
+ })
2227
+ ]);
2228
+ var marketSymbolDetailToolOutputSchema = z5.discriminatedUnion("status", [
2229
+ z5.object({
2230
+ status: z5.literal("connected"),
2231
+ connected: z5.literal(true),
2232
+ detail: marketSymbolDetailSchema
2233
+ }),
2234
+ startLoginOutputSchema.extend({
2235
+ status: z5.literal("pending"),
2236
+ connected: z5.literal(false),
2237
+ message: z5.string()
2238
+ })
2239
+ ]);
2240
+ var tradeActionInputSchema = submitTradeIntentInputSchema.omit({
2241
+ intentType: true
2242
+ });
2243
+ var tradeActionToolOutputSchema = z5.discriminatedUnion("status", [
2244
+ z5.object({
2245
+ status: z5.literal("connected"),
2246
+ connected: z5.literal(true),
2247
+ submission: submitTradeIntentResultSchema
2248
+ }),
2249
+ startLoginOutputSchema.extend({
2250
+ status: z5.literal("pending"),
2251
+ connected: z5.literal(false),
2252
+ message: z5.string()
2253
+ })
2254
+ ]);
2255
+ var closeTradeToolOutputSchema = z5.discriminatedUnion("status", [
2256
+ z5.object({
2257
+ status: z5.literal("connected"),
2258
+ connected: z5.literal(true),
2259
+ closure: closePositionResultSchema
2260
+ }),
2261
+ startLoginOutputSchema.extend({
2262
+ status: z5.literal("pending"),
2263
+ connected: z5.literal(false),
2264
+ message: z5.string()
2265
+ })
2266
+ ]);
2267
+ var setTpSlToolOutputSchema = z5.discriminatedUnion("status", [
2268
+ z5.object({
2269
+ status: z5.literal("connected"),
2270
+ connected: z5.literal(true),
2271
+ protection: setTpSlResultSchema
2272
+ }),
2273
+ startLoginOutputSchema.extend({
2274
+ status: z5.literal("pending"),
2275
+ connected: z5.literal(false),
2276
+ message: z5.string()
2277
+ })
2278
+ ]);
2279
+ var deleteTpSlToolOutputSchema = z5.discriminatedUnion("status", [
2280
+ z5.object({
2281
+ status: z5.literal("connected"),
2282
+ connected: z5.literal(true),
2283
+ deletion: deleteTpSlResultSchema
2284
+ }),
2285
+ startLoginOutputSchema.extend({
2286
+ status: z5.literal("pending"),
2287
+ connected: z5.literal(false),
2288
+ message: z5.string()
2289
+ })
2290
+ ]);
2291
+ var openOrdersToolOutputSchema = z5.discriminatedUnion("status", [
2292
+ z5.object({
2293
+ status: z5.literal("connected"),
2294
+ connected: z5.literal(true),
2295
+ orders: z5.array(openOrderSchema)
2296
+ }),
2297
+ startLoginOutputSchema.extend({
2298
+ status: z5.literal("pending"),
2299
+ connected: z5.literal(false),
2300
+ message: z5.string()
2301
+ })
2302
+ ]);
2303
+ var cancelOrderToolOutputSchema = z5.discriminatedUnion("status", [
2304
+ z5.object({
2305
+ status: z5.literal("connected"),
2306
+ connected: z5.literal(true),
2307
+ cancellation: cancelOrderResultSchema
2308
+ }),
2309
+ startLoginOutputSchema.extend({
2310
+ status: z5.literal("pending"),
2311
+ connected: z5.literal(false),
2312
+ message: z5.string()
2313
+ })
2314
+ ]);
2315
+ var documentPathInputSchema = z5.object({
2316
+ path: z5.string().min(1)
2317
+ });
2318
+ var docsIndexSchema = z5.object({
2319
+ root: z5.literal("docs"),
2320
+ documents: z5.array(
2321
+ z5.object({
2322
+ path: z5.string(),
2323
+ section: z5.string(),
2324
+ title: z5.string(),
2325
+ bytes: z5.number().int().nonnegative()
2326
+ })
2327
+ )
2328
+ });
2329
+ var documentSchema = z5.object({
2330
+ path: z5.string(),
2331
+ section: z5.string(),
2332
+ title: z5.string(),
2333
+ body: z5.string(),
2334
+ bytes: z5.number().int().nonnegative()
2335
+ });
2336
+ function createHeliosDocsToolDefinitions(service) {
2337
+ return [
2338
+ {
2339
+ name: "helios_docs_get_index",
2340
+ title: "Get Helios Docs Index",
2341
+ description: "Lists the package-local Helios MCP and indicator .txt documentation available to the agent.",
2342
+ inputSchema: z5.object({}),
2343
+ async execute() {
2344
+ const result = docsIndexSchema.parse(await service.getIndex());
2345
+ return {
2346
+ content: [
2347
+ {
2348
+ type: "text",
2349
+ text: `Helios docs index: ${result.documents.length} documents across ${new Set(result.documents.map((document) => document.section)).size} sections.`
2350
+ }
2351
+ ],
2352
+ structuredContent: result
2353
+ };
2354
+ }
2355
+ },
2356
+ {
2357
+ name: "helios_docs_get_document",
2358
+ title: "Get Helios Doc",
2359
+ description: "Returns one package-local Helios .txt document by relative docs path.",
2360
+ inputSchema: documentPathInputSchema,
2361
+ async execute(input) {
2362
+ const result = documentSchema.parse(await service.getDocument(input));
2363
+ return {
2364
+ content: [
2365
+ {
2366
+ type: "text",
2367
+ text: result.body
2368
+ }
2369
+ ],
2370
+ structuredContent: result
2371
+ };
2372
+ }
2373
+ }
2374
+ ];
2375
+ }
2376
+ function createHeliosAuthToolDefinitions(service) {
2377
+ return [
2378
+ {
2379
+ name: "helios_auth_start_login",
2380
+ title: "Start Helios Login",
2381
+ description: "Starts the delegated Helios login flow and returns the approval URL for the user.",
2382
+ inputSchema: agentDeviceStartInputSchema,
2383
+ async execute(input) {
2384
+ const result = startLoginOutputSchema.parse(await service.startLogin(input));
2385
+ const manualResult = {
2386
+ ...result,
2387
+ ...withManualLoginFields(result)
2388
+ };
2389
+ return {
2390
+ content: [
2391
+ {
2392
+ type: "text",
2393
+ text: buildManualLoginText(result)
2394
+ }
2395
+ ],
2396
+ structuredContent: manualResult
2397
+ };
2398
+ }
2399
+ },
2400
+ {
2401
+ name: "helios_auth_ensure_login",
2402
+ title: "Ensure Helios Login",
2403
+ 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.",
2404
+ inputSchema: ensureLoginInputSchema,
2405
+ async execute(input) {
2406
+ const result = ensureLoginOutputSchema.parse(await service.ensureLogin(input));
2407
+ const structuredContent = result.status === "connected" ? result : {
2408
+ ...result,
2409
+ ...withManualLoginFields(result)
2410
+ };
2411
+ return {
2412
+ content: [
2413
+ {
2414
+ type: "text",
2415
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : result.message
2416
+ }
2417
+ ],
2418
+ structuredContent
2419
+ };
2420
+ }
2421
+ },
2422
+ {
2423
+ name: "helios_auth_poll_login",
2424
+ title: "Poll Helios Login",
2425
+ description: "Checks whether the Helios login was approved and finishes connecting. The device code is optional; without it, the login in progress is checked.",
2426
+ inputSchema: pollLoginInputSchema,
2427
+ async execute(input) {
2428
+ const result = pollLoginOutputSchema.parse(await service.pollLogin(input.deviceCode));
2429
+ return {
2430
+ content: [
2431
+ {
2432
+ type: "text",
2433
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : `Helios login is ${result.status}: ${result.message}`
2434
+ }
2435
+ ],
2436
+ structuredContent: result
2437
+ };
2438
+ }
2439
+ },
2440
+ {
2441
+ name: "helios_auth_whoami",
2442
+ title: "Helios Login Status",
2443
+ description: "Returns the delegated Helios session state currently stored by the MCP server.",
2444
+ inputSchema: z5.object({}),
2445
+ async execute() {
2446
+ const result = agentSessionViewSchema.parse(await service.whoami());
2447
+ return {
2448
+ content: [
2449
+ {
2450
+ type: "text",
2451
+ text: result.connected ? `Connected to Helios as user ${result.ownerUserId}.` : "No delegated Helios session is connected."
2452
+ }
2453
+ ],
2454
+ structuredContent: result
2455
+ };
2456
+ }
2457
+ }
2458
+ ];
2459
+ }
2460
+ function createHeliosProviderToolDefinitions(service) {
2461
+ return [
2462
+ {
2463
+ name: "helios_provider_get_active",
2464
+ title: "Get Helios Active Provider",
2465
+ description: "Returns the provider currently pinned for this MCP session, if any.",
2466
+ inputSchema: z5.object({}),
2467
+ async execute() {
2468
+ const result = activeProviderSchema.parse(await service.getActiveProvider());
2469
+ return {
2470
+ content: [
2471
+ {
2472
+ type: "text",
2473
+ text: result.configured ? `Helios active provider is ${result.provider}.` : "No Helios active provider is configured for this session."
2474
+ }
2475
+ ],
2476
+ structuredContent: result
2477
+ };
2478
+ }
2479
+ },
2480
+ {
2481
+ name: "helios_provider_set_active",
2482
+ title: "Set Helios Active Provider",
2483
+ description: "Pins the active provider for this MCP session so portfolio and trading tools can omit provider.",
2484
+ inputSchema: providerSetInputSchema,
2485
+ async execute(input) {
2486
+ const result = activeProviderSchema.parse(await service.setActiveProvider(input.provider));
2487
+ return {
2488
+ content: [
2489
+ {
2490
+ type: "text",
2491
+ text: `Helios active provider set to ${result.provider}.`
2492
+ }
2493
+ ],
2494
+ structuredContent: result
2495
+ };
2496
+ }
2497
+ }
2498
+ ];
2499
+ }
2500
+ function createHeliosAccountToolDefinitions(service) {
2501
+ return [
2502
+ {
2503
+ name: "helios_account_get_wallet_state",
2504
+ title: "Get Helios Wallet State",
2505
+ description: "Returns the current Hyperliquid wallet snapshot for the connected Helios account.",
2506
+ inputSchema: z5.object({}),
2507
+ async execute() {
2508
+ const result = walletStateToolOutputSchema.parse(await service.getWalletState());
2509
+ const structuredContent = result.status === "connected" ? result : {
2510
+ ...result,
2511
+ ...withManualLoginFields(result)
2512
+ };
2513
+ return {
2514
+ content: [
2515
+ {
2516
+ type: "text",
2517
+ text: result.status === "connected" ? `Helios wallet state: available balance ${result.walletState.availableBalance}, account value ${result.walletState.accountValue}.` : result.message
2518
+ }
2519
+ ],
2520
+ structuredContent
2521
+ };
2522
+ }
2523
+ },
2524
+ {
2525
+ name: "helios_portfolio_get",
2526
+ title: "Get Helios Portfolio",
2527
+ description: "Returns a provider-specific portfolio snapshot. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2528
+ inputSchema: providerSelectionInputSchema,
2529
+ async execute(input) {
2530
+ const result = portfolioToolOutputSchema.parse(await service.getPortfolio(input));
2531
+ const structuredContent = result.status === "connected" ? result : {
2532
+ ...result,
2533
+ ...withManualLoginFields(result)
2534
+ };
2535
+ return {
2536
+ content: [
2537
+ {
2538
+ type: "text",
2539
+ text: result.status === "connected" ? buildPortfolioText(result.portfolio) : result.message
2540
+ }
2541
+ ],
2542
+ structuredContent
2543
+ };
2544
+ }
2545
+ }
2546
+ ];
2547
+ }
2548
+ function createHeliosLedgerToolDefinitions(service) {
2549
+ return [
2550
+ {
2551
+ name: "helios_positions_get_open",
2552
+ title: "Get Helios Open Positions",
2553
+ description: "Returns the current open Hyperliquid positions for the connected Helios account.",
2554
+ inputSchema: z5.object({}),
2555
+ async execute() {
2556
+ const result = openPositionsToolOutputSchema.parse(await service.getOpenPositions());
2557
+ const structuredContent = result.status === "connected" ? result : {
2558
+ ...result,
2559
+ ...withManualLoginFields(result)
2560
+ };
2561
+ return {
2562
+ content: [
2563
+ {
2564
+ type: "text",
2565
+ text: result.status === "connected" ? `Helios open positions: ${result.openPositions.positions.length} positions, total unrealized PnL ${result.openPositions.totalUnrealizedPnl}.` : result.message
2566
+ }
2567
+ ],
2568
+ structuredContent
2569
+ };
2570
+ }
2571
+ },
2572
+ {
2573
+ name: "helios_ledger_get_fills",
2574
+ title: "Get Helios Ledger Fills",
2575
+ description: "Returns recent Hyperliquid fills/trade history for the connected Helios account.",
2576
+ inputSchema: ledgerFillsInputSchema,
2577
+ async execute(input) {
2578
+ const result = ledgerFillsToolOutputSchema.parse(await service.getFills(input));
2579
+ const structuredContent = result.status === "connected" ? result : {
2580
+ ...result,
2581
+ ...withManualLoginFields(result)
2582
+ };
2583
+ return {
2584
+ content: [
2585
+ {
2586
+ type: "text",
2587
+ text: result.status === "connected" ? `Helios ledger fills: ${result.fills.fills.length} fills from ${result.fills.window}${result.fills.hasMore ? ", more available" : ""}.` : result.message
2588
+ }
2589
+ ],
2590
+ structuredContent
2591
+ };
2592
+ }
2593
+ },
2594
+ {
2595
+ name: "helios_ledger_get_summary",
2596
+ title: "Get Helios Ledger Summary",
2597
+ description: "Returns realized PnL, fees, and win/loss metrics over a recent Hyperliquid fill window.",
2598
+ inputSchema: ledgerSummaryInputSchema,
2599
+ async execute(input) {
2600
+ const result = ledgerSummaryToolOutputSchema.parse(await service.getSummary(input));
2601
+ const structuredContent = result.status === "connected" ? result : {
2602
+ ...result,
2603
+ ...withManualLoginFields(result)
2604
+ };
2605
+ return {
2606
+ content: [
2607
+ {
2608
+ type: "text",
2609
+ 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
2610
+ }
2611
+ ],
2612
+ structuredContent
2613
+ };
2614
+ }
2615
+ }
2616
+ ];
2617
+ }
2618
+ function createHeliosMarketToolDefinitions(service) {
2619
+ return [
2620
+ {
2621
+ name: "helios_market_get_snapshot",
2622
+ title: "Get Helios Market Snapshot",
2623
+ 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.",
2624
+ inputSchema: marketSnapshotInputSchema,
2625
+ async execute(input) {
2626
+ const result = marketSnapshotToolOutputSchema.parse(await service.getSnapshot(input));
2627
+ const structuredContent = result.status === "connected" ? result : {
2628
+ ...result,
2629
+ ...withManualLoginFields(result)
2630
+ };
2631
+ return {
2632
+ content: [
2633
+ {
2634
+ type: "text",
2635
+ 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
2636
+ }
2637
+ ],
2638
+ structuredContent
2639
+ };
2640
+ }
2641
+ },
2642
+ {
2643
+ name: "helios_market_get_snapshot_chunk",
2644
+ title: "Get Helios Market Snapshot Chunk",
2645
+ description: "Returns one chunk of the Helios market snapshot for batch analysis when the full snapshot is too large.",
2646
+ inputSchema: marketSnapshotChunkInputSchema,
2647
+ async execute(input) {
2648
+ const result = marketSnapshotChunkToolOutputSchema.parse(await service.getSnapshotChunk(input));
2649
+ const structuredContent = result.status === "connected" ? result : {
2650
+ ...result,
2651
+ ...withManualLoginFields(result)
2652
+ };
2653
+ return {
2654
+ content: [
2655
+ {
2656
+ type: "text",
2657
+ 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
2658
+ }
2659
+ ],
2660
+ structuredContent
2661
+ };
2662
+ }
2663
+ },
2664
+ {
2665
+ name: "helios_market_get_symbol_detail",
2666
+ title: "Get Helios Symbol Detail",
2667
+ description: "Returns expanded market detail for one symbol from the current Helios market snapshot.",
2668
+ inputSchema: marketSymbolDetailInputSchema,
2669
+ async execute(input) {
2670
+ const result = marketSymbolDetailToolOutputSchema.parse(await service.getSymbolDetail(input));
2671
+ const structuredContent = result.status === "connected" ? result : {
2672
+ ...result,
2673
+ ...withManualLoginFields(result)
2674
+ };
2675
+ return {
2676
+ content: [
2677
+ {
2678
+ type: "text",
2679
+ 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
2680
+ }
2681
+ ],
2682
+ structuredContent
2683
+ };
2684
+ }
2685
+ }
2686
+ ];
2687
+ }
2688
+ function createHeliosTradingToolDefinitions(service) {
2689
+ return [
2690
+ {
2691
+ name: "helios_trading_open",
2692
+ title: "Open Helios Position",
2693
+ description: "Submits a Helios OPEN trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2694
+ inputSchema: tradeActionInputSchema,
2695
+ async execute(input) {
2696
+ const result = tradeActionToolOutputSchema.parse(await service.open(input));
2697
+ return {
2698
+ content: [
2699
+ {
2700
+ type: "text",
2701
+ 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
2702
+ }
2703
+ ],
2704
+ structuredContent: result.status === "connected" ? result : {
2705
+ ...result,
2706
+ ...withManualLoginFields(result)
2707
+ }
2708
+ };
2709
+ }
2710
+ },
2711
+ {
2712
+ name: "helios_trading_dca",
2713
+ title: "DCA Helios Position",
2714
+ description: "Submits a Helios DCA trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2715
+ inputSchema: tradeActionInputSchema,
2716
+ async execute(input) {
2717
+ const result = tradeActionToolOutputSchema.parse(await service.dca(input));
2718
+ return {
2719
+ content: [
2720
+ {
2721
+ type: "text",
2722
+ 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
2723
+ }
2724
+ ],
2725
+ structuredContent: result.status === "connected" ? result : {
2726
+ ...result,
2727
+ ...withManualLoginFields(result)
2728
+ }
2729
+ };
2730
+ }
2731
+ },
2732
+ {
2733
+ name: "helios_trading_reverse",
2734
+ title: "Reverse Helios Position",
2735
+ description: "Submits a Helios REVERSE trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2736
+ inputSchema: tradeActionInputSchema,
2737
+ async execute(input) {
2738
+ const result = tradeActionToolOutputSchema.parse(await service.reverse(input));
2739
+ return {
2740
+ content: [
2741
+ {
2742
+ type: "text",
2743
+ 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
2744
+ }
2745
+ ],
2746
+ structuredContent: result.status === "connected" ? result : {
2747
+ ...result,
2748
+ ...withManualLoginFields(result)
2749
+ }
2750
+ };
2751
+ }
2752
+ },
2753
+ {
2754
+ name: "helios_trading_close",
2755
+ title: "Close Helios Position",
2756
+ 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.",
2757
+ inputSchema: closePositionInputSchema,
2758
+ async execute(input) {
2759
+ const result = closeTradeToolOutputSchema.parse(await service.close(input));
2760
+ return {
2761
+ content: [
2762
+ {
2763
+ type: "text",
2764
+ text: result.status === "connected" ? `Submitted Helios full close for ${result.closure.provider ?? input.provider} ${result.closure.symbol}.` : result.message
2765
+ }
2766
+ ],
2767
+ structuredContent: result.status === "connected" ? result : {
2768
+ ...result,
2769
+ ...withManualLoginFields(result)
2770
+ }
2771
+ };
2772
+ }
2773
+ },
2774
+ {
2775
+ name: "helios_positions_set_tp_sl",
2776
+ title: "Set Helios TP/SL",
2777
+ 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.",
2778
+ inputSchema: setTpSlInputSchema,
2779
+ async execute(input) {
2780
+ const result = setTpSlToolOutputSchema.parse(await service.setTpSl(input));
2781
+ return {
2782
+ content: [
2783
+ {
2784
+ type: "text",
2785
+ text: result.status === "connected" ? `Submitted ${result.protection.provider ?? input.provider} TP/SL protection update for ${result.protection.symbol}.` : result.message
2786
+ }
2787
+ ],
2788
+ structuredContent: result.status === "connected" ? result : {
2789
+ ...result,
2790
+ ...withManualLoginFields(result)
2791
+ }
2792
+ };
2793
+ }
2794
+ },
2795
+ {
2796
+ name: "helios_positions_delete_tp_sl",
2797
+ title: "Delete Helios TP/SL",
2798
+ 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.",
2799
+ inputSchema: deleteTpSlInputSchema,
2800
+ async execute(input) {
2801
+ const result = deleteTpSlToolOutputSchema.parse(await service.deleteTpSl(input));
2802
+ return {
2803
+ content: [
2804
+ {
2805
+ type: "text",
2806
+ text: result.status === "connected" ? `Deleted ${result.deletion.provider ?? input.provider} TP/SL order ${result.deletion.orderId} for ${result.deletion.symbol}.` : result.message
2807
+ }
2808
+ ],
2809
+ structuredContent: result.status === "connected" ? result : {
2810
+ ...result,
2811
+ ...withManualLoginFields(result)
2812
+ }
2813
+ };
2814
+ }
2815
+ },
2816
+ {
2817
+ name: "helios_orders_get_open",
2818
+ title: "Get Helios Open Orders",
2819
+ description: "Lists the currently open Hyperliquid orders for the connected account.",
2820
+ inputSchema: z5.object({}),
2821
+ async execute() {
2822
+ const result = openOrdersToolOutputSchema.parse(await service.getOpenOrders());
2823
+ return {
2824
+ content: [
2825
+ {
2826
+ type: "text",
2827
+ text: result.status === "connected" ? `Retrieved ${result.orders.length} open Helios orders.` : result.message
2828
+ }
2829
+ ],
2830
+ structuredContent: result.status === "connected" ? result : {
2831
+ ...result,
2832
+ ...withManualLoginFields(result)
2833
+ }
2834
+ };
2835
+ }
2836
+ },
2837
+ {
2838
+ name: "helios_orders_cancel",
2839
+ title: "Cancel Helios Order",
2840
+ description: "Cancels an open Hyperliquid order by symbol and order id.",
2841
+ inputSchema: cancelOrderInputSchema,
2842
+ async execute(input) {
2843
+ const result = cancelOrderToolOutputSchema.parse(await service.cancelOrder(input));
2844
+ return {
2845
+ content: [
2846
+ {
2847
+ type: "text",
2848
+ text: result.status === "connected" ? `Cancelled Helios order ${result.cancellation.oid} for ${result.cancellation.symbol}.` : result.message
2849
+ }
2850
+ ],
2851
+ structuredContent: result.status === "connected" ? result : {
2852
+ ...result,
2853
+ ...withManualLoginFields(result)
2854
+ }
2855
+ };
2856
+ }
2857
+ }
2858
+ ];
2859
+ }
2860
+ function withManualLoginFields(result) {
2861
+ return {
2862
+ actionRequired: true,
2863
+ loginUrl: result.verificationUriComplete,
2864
+ nextStep: "Open the login URL in your browser, approve Helios access, then call helios_auth_ensure_login again to finish connecting."
2865
+ };
2866
+ }
2867
+ function buildPortfolioText(result) {
2868
+ return `Helios Hyperliquid portfolio: ${result.positions.length} positions, available balance ${result.availableBalance}, total balance ${result.totalBalance}.`;
2869
+ }
2870
+ function buildManualLoginText(result) {
2871
+ return `Log in to Helios by opening this URL in your browser:
2872
+
2873
+ ${result.verificationUriComplete}
2874
+
2875
+ User code: ${result.userCode}
2876
+
2877
+ After approving access, call helios_auth_ensure_login (or helios_auth_poll_login) again to finish connecting.`;
2878
+ }
2879
+
2880
+ // src/server.ts
2881
+ async function createHeliosAgentMcpServer(options) {
2882
+ if (!options.identityServiceUrl) {
2883
+ throw new Error("identityServiceUrl is required");
2884
+ }
2885
+ if (!options.dataBridgeUrl) {
2886
+ throw new Error("dataBridgeUrl is required");
2887
+ }
2888
+ const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
2889
+ const server = new McpServer({
2890
+ name: "helios",
2891
+ version: "0.2.4"
2892
+ });
2893
+ const sessionStore = options.sessionStore ?? new FileAgentSessionStore(options.sessionPath ?? getDefaultHeliosAgentMcpSessionPath());
2894
+ const client = new HeliosAgentAuthClient({
2895
+ baseUrl: options.identityServiceUrl,
2896
+ fetch: options.fetch
2897
+ });
2898
+ const dataBridgeClient = new HeliosAgentDataBridgeClient({
2899
+ baseUrl: options.dataBridgeUrl,
2900
+ fetch: options.fetch
2901
+ });
2902
+ const authService = new HeliosAgentMcpAuthService({
2903
+ client,
2904
+ sessionStore,
2905
+ refreshWindowMs: options.refreshWindowMs,
2906
+ deviceLogin: !options.hosted
2907
+ });
2908
+ const providerService = new HeliosAgentMcpProviderService({
2909
+ sessionStore
2910
+ });
2911
+ const accountService = new HeliosAgentMcpAccountService({
2912
+ authService,
2913
+ dataBridgeClient,
2914
+ providerService
2915
+ });
2916
+ const marketService = new HeliosAgentMcpMarketService({
2917
+ authService,
2918
+ dataBridgeClient
2919
+ });
2920
+ const ledgerService = new HeliosAgentMcpLedgerService({
2921
+ authService,
2922
+ dataBridgeClient
2923
+ });
2924
+ const tradingService = new HeliosAgentMcpTradingService({
2925
+ authService,
2926
+ dataBridgeClient,
2927
+ providerService
2928
+ });
2929
+ const docsService = new HeliosAgentMcpDocsService({
2930
+ docsRoot: options.docsRoot ?? getDefaultHeliosAgentMcpDocsRoot()
2931
+ });
2932
+ const docsTools = createHeliosDocsToolDefinitions(docsService);
2933
+ const authTools = createHeliosAuthToolDefinitions(authService);
2934
+ const providerTools = createHeliosProviderToolDefinitions(providerService);
2935
+ const accountTools = createHeliosAccountToolDefinitions(accountService);
2936
+ const ledgerTools = createHeliosLedgerToolDefinitions(ledgerService);
2937
+ const marketTools = createHeliosMarketToolDefinitions(marketService);
2938
+ const tradingTools = createHeliosTradingToolDefinitions(tradingService);
2939
+ registerTool(server, docsTools[0]);
2940
+ registerTool(server, docsTools[1]);
2941
+ if (!options.hosted) {
2942
+ registerTool(server, authTools[0]);
2943
+ registerTool(server, authTools[1]);
2944
+ registerTool(server, authTools[2]);
2945
+ }
2946
+ registerTool(server, authTools[3]);
2947
+ registerTool(server, providerTools[0]);
2948
+ registerTool(server, providerTools[1]);
2949
+ registerTool(server, accountTools[0]);
2950
+ registerTool(server, accountTools[1]);
2951
+ registerTool(server, ledgerTools[0]);
2952
+ registerTool(server, ledgerTools[1]);
2953
+ registerTool(server, ledgerTools[2]);
2954
+ registerTool(server, marketTools[0]);
2955
+ registerTool(server, marketTools[1]);
2956
+ registerTool(server, marketTools[2]);
2957
+ registerTool(server, tradingTools[0]);
2958
+ registerTool(server, tradingTools[1]);
2959
+ registerTool(server, tradingTools[2]);
2960
+ registerTool(server, tradingTools[3]);
2961
+ registerTool(server, tradingTools[4]);
2962
+ registerTool(server, tradingTools[5]);
2963
+ registerTool(server, tradingTools[6]);
2964
+ registerTool(server, tradingTools[7]);
2965
+ return {
2966
+ server,
2967
+ authService,
2968
+ providerService,
2969
+ accountService,
2970
+ docsService,
2971
+ ledgerService,
2972
+ marketService,
2973
+ tradingService,
2974
+ sessionStore
2975
+ };
2976
+ }
2977
+ var ACTS_ON_ACCOUNT = /^helios_(trading_|positions_set_tp_sl|positions_delete_tp_sl|orders_cancel)/;
2978
+ var CHANGES_SESSION = /^helios_(auth_start_login|auth_ensure_login|auth_poll_login|provider_set_active)$/;
2979
+ function toolAnnotations(name) {
2980
+ if (ACTS_ON_ACCOUNT.test(name)) return { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
2981
+ if (CHANGES_SESSION.test(name)) return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
2982
+ return { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
2983
+ }
2984
+ var TEXT_IS_RESULT = /* @__PURE__ */ new Set(["helios_docs_get_document"]);
2985
+ function withDataText(name, content, structuredContent) {
2986
+ if (TEXT_IS_RESULT.has(name)) return content;
2987
+ return [...content, { type: "text", text: JSON.stringify(structuredContent) }];
2988
+ }
2989
+ function registerTool(server, tool) {
2990
+ server.registerTool(
2991
+ tool.name,
2992
+ {
2993
+ title: tool.title,
2994
+ description: tool.description,
2995
+ inputSchema: tool.inputSchema,
2996
+ annotations: { title: tool.title, ...toolAnnotations(tool.name) }
2997
+ },
2998
+ async (input) => {
2999
+ const result = await tool.execute(tool.inputSchema.parse(input));
3000
+ return {
3001
+ content: withDataText(tool.name, result.content, result.structuredContent),
3002
+ structuredContent: result.structuredContent
3003
+ };
3004
+ }
3005
+ );
3006
+ }
3007
+
3008
+ export {
3009
+ HOSTED_RECONNECT_MESSAGE,
3010
+ HeliosAgentMcpAuthService,
3011
+ retryAfterUnauthorizedRefresh,
3012
+ formatHeliosLoginPrompt,
3013
+ HeliosAgentMcpAccountService,
3014
+ HeliosAgentMcpDocsService,
3015
+ getDefaultHeliosAgentMcpDocsRoot,
3016
+ HeliosAgentMcpLedgerService,
3017
+ DEFAULT_SNAPSHOT_TOP,
3018
+ DEFAULT_SNAPSHOT_FIELDS,
3019
+ withSnapshotDefaults,
3020
+ topOfSnapshot,
3021
+ HeliosAgentMcpMarketService,
3022
+ HeliosAgentMcpProviderService,
3023
+ getDefaultHeliosAgentMcpSessionPath,
3024
+ pendingAgentLoginSchema,
3025
+ FileAgentSessionStore,
3026
+ MemoryAgentMcpSessionStore,
3027
+ HeliosAgentMcpTradingService,
3028
+ createHeliosDocsToolDefinitions,
3029
+ createHeliosAuthToolDefinitions,
3030
+ createHeliosProviderToolDefinitions,
3031
+ createHeliosAccountToolDefinitions,
3032
+ createHeliosLedgerToolDefinitions,
3033
+ createHeliosMarketToolDefinitions,
3034
+ createHeliosTradingToolDefinitions,
3035
+ createHeliosAgentMcpServer,
3036
+ toolAnnotations,
3037
+ withDataText
3038
+ };