@pgnio/helios-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +44 -2
  2. package/dist/chunk-NWGWXYTS.mjs +2964 -0
  3. package/dist/cli.d.mts +1 -0
  4. package/dist/cli.d.ts +1 -0
  5. package/dist/cli.js +2946 -0
  6. package/dist/cli.mjs +24 -0
  7. package/dist/index.d.mts +2137 -0
  8. package/dist/index.d.ts +2137 -0
  9. package/dist/index.js +3021 -0
  10. package/dist/index.mjs +52 -0
  11. package/docs/ai-agent-indicators/00_index.txt +210 -0
  12. package/docs/ai-agent-indicators/activity_ratio.txt +166 -0
  13. package/docs/ai-agent-indicators/activity_zscore.txt +166 -0
  14. package/docs/ai-agent-indicators/bayesian_overbought.txt +134 -0
  15. package/docs/ai-agent-indicators/directional_efficiency.txt +134 -0
  16. package/docs/ai-agent-indicators/hfi.txt +172 -0
  17. package/docs/ai-agent-indicators/hfi_weights.txt +124 -0
  18. package/docs/ai-agent-indicators/hmi.txt +305 -0
  19. package/docs/ai-agent-indicators/hmi_velocity.txt +155 -0
  20. package/docs/ai-agent-indicators/hurst_exponent.txt +136 -0
  21. package/docs/ai-agent-indicators/macd_divergence.txt +133 -0
  22. package/docs/ai-agent-indicators/macd_histogram.txt +145 -0
  23. package/docs/ai-agent-indicators/macd_signal.txt +119 -0
  24. package/docs/ai-agent-indicators/market_structure.txt +201 -0
  25. package/docs/ai-agent-indicators/poc.txt +131 -0
  26. package/docs/ai-agent-indicators/poc_distance.txt +129 -0
  27. package/docs/ai-agent-indicators/regime.txt +225 -0
  28. package/docs/ai-agent-indicators/rsi_divergence.txt +145 -0
  29. package/docs/ai-agent-indicators/squeeze_duration.txt +115 -0
  30. package/docs/ai-agent-indicators/squeeze_energy.txt +128 -0
  31. package/docs/ai-agent-indicators/support_resistance.txt +169 -0
  32. package/docs/ai-agent-indicators/tf_alignment.txt +165 -0
  33. package/docs/ai-agent-indicators/trend_interpretation.txt +98 -0
  34. package/docs/ai-agent-indicators/trend_strength.txt +134 -0
  35. package/docs/ai-agent-indicators/value_area_position.txt +142 -0
  36. package/docs/ai-agent-indicators/volatility_clustering.txt +160 -0
  37. package/docs/ai-agent-indicators/volatility_squeeze.txt +169 -0
  38. package/docs/ai-agent-indicators/volume_change_point.txt +151 -0
  39. package/docs/ai-agent-indicators/vwap.txt +133 -0
  40. package/docs/ai-agent-indicators/vwap_zscore.txt +154 -0
  41. package/docs/ai-agent-indicators/weighted_rsi.txt +148 -0
  42. package/docs/ai-agent-mcp/00_index.txt +110 -0
  43. package/docs/ai-agent-mcp/01_auth/00_overview.txt +51 -0
  44. package/docs/ai-agent-mcp/01_auth/01_tools.txt +94 -0
  45. package/docs/ai-agent-mcp/01_auth/02_data_contracts.txt +38 -0
  46. package/docs/ai-agent-mcp/01_auth/03_decision_rules.txt +25 -0
  47. package/docs/ai-agent-mcp/01_auth/04_failures_and_recovery.txt +46 -0
  48. package/docs/ai-agent-mcp/02_account/00_overview.txt +29 -0
  49. package/docs/ai-agent-mcp/02_account/01_tools.txt +67 -0
  50. package/docs/ai-agent-mcp/02_account/02_data_contracts.txt +34 -0
  51. package/docs/ai-agent-mcp/02_account/03_decision_rules.txt +17 -0
  52. package/docs/ai-agent-mcp/02_account/04_failures_and_recovery.txt +17 -0
  53. package/docs/ai-agent-mcp/03_market/00_overview.txt +27 -0
  54. package/docs/ai-agent-mcp/03_market/01_tools.txt +102 -0
  55. package/docs/ai-agent-mcp/03_market/02_data_contracts.txt +39 -0
  56. package/docs/ai-agent-mcp/03_market/03_decision_rules.txt +22 -0
  57. package/docs/ai-agent-mcp/03_market/04_failures_and_recovery.txt +18 -0
  58. package/docs/ai-agent-mcp/04_trading/00_overview.txt +25 -0
  59. package/docs/ai-agent-mcp/04_trading/01_tools.txt +123 -0
  60. package/docs/ai-agent-mcp/04_trading/02_data_contracts.txt +42 -0
  61. package/docs/ai-agent-mcp/04_trading/03_decision_rules.txt +30 -0
  62. package/docs/ai-agent-mcp/04_trading/04_failures_and_recovery.txt +25 -0
  63. package/docs/ai-agent-mcp/05_ledger/00_overview.txt +31 -0
  64. package/docs/ai-agent-mcp/05_ledger/01_tools.txt +80 -0
  65. package/docs/ai-agent-mcp/05_ledger/02_data_contracts.txt +46 -0
  66. package/docs/ai-agent-mcp/05_ledger/03_decision_rules.txt +44 -0
  67. package/docs/ai-agent-mcp/05_ledger/04_failures_and_recovery.txt +24 -0
  68. package/package.json +66 -3
package/dist/cli.js ADDED
@@ -0,0 +1,2946 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
27
+
28
+ // ../agent/dist/index.mjs
29
+ var import_zod = require("zod");
30
+ var import_zod2 = require("zod");
31
+ var import_zod3 = require("zod");
32
+ var __defProp2 = Object.defineProperty;
33
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
34
+ var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
35
+ var AGENT_SCOPES = {
36
+ ACCOUNT_READ: "account:read",
37
+ MARKET_READ: "market:read",
38
+ ORDERS_WRITE: "orders:write",
39
+ ORDERS_CANCEL: "orders:cancel"
40
+ };
41
+ var AGENT_SCOPE_VALUES = [
42
+ AGENT_SCOPES.ACCOUNT_READ,
43
+ AGENT_SCOPES.MARKET_READ,
44
+ AGENT_SCOPES.ORDERS_WRITE,
45
+ AGENT_SCOPES.ORDERS_CANCEL
46
+ ];
47
+ var agentScopeSchema = import_zod.z.enum(AGENT_SCOPE_VALUES);
48
+ var agentGrantStatusSchema = import_zod.z.enum(["active", "revoked"]);
49
+ var agentDeviceRequestStatusSchema = import_zod.z.enum(["pending", "approved", "rejected", "exchanged", "expired"]);
50
+ var agentConstraintsSchema = import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({});
51
+ var agentGrantMetadataSchema = import_zod.z.object({
52
+ id: import_zod.z.string(),
53
+ userId: import_zod.z.string(),
54
+ clientName: import_zod.z.string(),
55
+ status: agentGrantStatusSchema,
56
+ scope: import_zod.z.array(agentScopeSchema).min(1),
57
+ constraints: agentConstraintsSchema,
58
+ tokenVersion: import_zod.z.number().int().nonnegative(),
59
+ createdAt: import_zod.z.string(),
60
+ approvedAt: import_zod.z.string().optional(),
61
+ lastUsedAt: import_zod.z.string().optional(),
62
+ revokedAt: import_zod.z.string().optional()
63
+ });
64
+ var agentDeviceStartInputSchema = import_zod.z.object({
65
+ clientName: import_zod.z.string().min(1).max(64),
66
+ scope: import_zod.z.array(agentScopeSchema).min(1),
67
+ constraints: agentConstraintsSchema.optional()
68
+ });
69
+ var agentDeviceStartOutputSchema = import_zod.z.object({
70
+ deviceCode: import_zod.z.string(),
71
+ userCode: import_zod.z.string(),
72
+ verificationUri: import_zod.z.string().url(),
73
+ verificationUriComplete: import_zod.z.string().url(),
74
+ expiresInSeconds: import_zod.z.number().int().positive(),
75
+ pollIntervalSeconds: import_zod.z.number().int().positive()
76
+ });
77
+ var agentDeviceTokenInputSchema = import_zod.z.object({
78
+ deviceCode: import_zod.z.string().min(1)
79
+ });
80
+ var agentDeviceRequestViewSchema = import_zod.z.object({
81
+ userCode: import_zod.z.string(),
82
+ clientName: import_zod.z.string(),
83
+ scope: import_zod.z.array(agentScopeSchema).min(1),
84
+ constraints: agentConstraintsSchema,
85
+ status: agentDeviceRequestStatusSchema,
86
+ expiresAt: import_zod.z.string()
87
+ });
88
+ var agentTokenResponseSchema = import_zod.z.object({
89
+ accessToken: import_zod.z.string(),
90
+ refreshToken: import_zod.z.string(),
91
+ tokenType: import_zod.z.literal("Bearer"),
92
+ expiresInSeconds: import_zod.z.number().int().positive(),
93
+ scope: import_zod.z.array(agentScopeSchema).min(1),
94
+ ownerUserId: import_zod.z.string(),
95
+ agentGrantId: import_zod.z.string()
96
+ });
97
+ var agentRefreshInputSchema = import_zod.z.object({
98
+ refreshToken: import_zod.z.string().min(1)
99
+ });
100
+ var agentApprovalResponseSchema = import_zod.z.object({
101
+ request: agentDeviceRequestViewSchema,
102
+ grant: agentGrantMetadataSchema
103
+ });
104
+ var agentSessionStateSchema = import_zod.z.object({
105
+ status: import_zod.z.enum(["pending", "authorized", "rejected", "revoked"]),
106
+ request: agentDeviceRequestViewSchema.optional(),
107
+ grant: agentGrantMetadataSchema.optional()
108
+ });
109
+ var providerSchema = import_zod.z.enum(["hyperliquid"]);
110
+ var walletStateSchema = import_zod.z.object({
111
+ provider: import_zod.z.literal("hyperliquid"),
112
+ accountValue: import_zod.z.number(),
113
+ availableBalance: import_zod.z.number(),
114
+ withdrawable: import_zod.z.number(),
115
+ totalMarginUsed: import_zod.z.number(),
116
+ totalNotionalPosition: import_zod.z.number(),
117
+ crossMarginAccountValue: import_zod.z.number(),
118
+ isActivated: import_zod.z.boolean(),
119
+ fetchedAt: import_zod.z.string().datetime()
120
+ });
121
+ var openPositionSchema = import_zod.z.object({
122
+ symbol: import_zod.z.string(),
123
+ side: import_zod.z.enum(["LONG", "SHORT"]),
124
+ size: import_zod.z.number(),
125
+ entryPrice: import_zod.z.number(),
126
+ markPrice: import_zod.z.number(),
127
+ unrealizedPnl: import_zod.z.number(),
128
+ margin: import_zod.z.number(),
129
+ leverage: import_zod.z.number(),
130
+ liquidationPrice: import_zod.z.number().optional()
131
+ });
132
+ var openPositionsSnapshotSchema = import_zod.z.object({
133
+ provider: import_zod.z.literal("hyperliquid"),
134
+ fetchedAt: import_zod.z.string().datetime(),
135
+ totalUnrealizedPnl: import_zod.z.number(),
136
+ positions: import_zod.z.array(openPositionSchema)
137
+ });
138
+ var protectiveOrderKindSchema = import_zod.z.enum(["STOP_LOSS", "TAKE_PROFIT"]);
139
+ var protectiveOrderSideSchema = import_zod.z.enum(["BUY", "SELL"]);
140
+ var protectiveOrderPositionSideSchema = import_zod.z.enum(["BOTH", "LONG", "SHORT"]);
141
+ var protectiveOrderSchema = import_zod.z.object({
142
+ id: import_zod.z.string(),
143
+ binanceOrderId: import_zod.z.number().int().nonnegative().optional(),
144
+ clientOrderId: import_zod.z.string().optional(),
145
+ symbol: import_zod.z.string(),
146
+ side: protectiveOrderSideSchema,
147
+ positionSide: protectiveOrderPositionSideSchema,
148
+ status: import_zod.z.string(),
149
+ kind: protectiveOrderKindSchema,
150
+ groupId: import_zod.z.string(),
151
+ stopPrice: import_zod.z.string().optional(),
152
+ parentClientOrderId: import_zod.z.string().optional(),
153
+ assetId: import_zod.z.number().int().nonnegative().optional(),
154
+ createdAt: import_zod.z.string().datetime()
155
+ });
156
+ var hyperliquidPortfolioSnapshotSchema = import_zod.z.object({
157
+ provider: import_zod.z.literal("hyperliquid"),
158
+ totalBalance: import_zod.z.number(),
159
+ availableBalance: import_zod.z.number(),
160
+ totalMargin: import_zod.z.number(),
161
+ unrealizedPnl: import_zod.z.number(),
162
+ positions: import_zod.z.array(openPositionSchema),
163
+ protectiveOrders: import_zod.z.array(protectiveOrderSchema)
164
+ });
165
+ var portfolioInputSchema = import_zod.z.object({
166
+ provider: providerSchema
167
+ });
168
+ var portfolioSnapshotSchema = hyperliquidPortfolioSnapshotSchema;
169
+ var ledgerWindowSchema = import_zod.z.enum(["24h", "7d", "30d"]);
170
+ var ledgerFillsInputSchema = import_zod.z.object({
171
+ window: ledgerWindowSchema.optional(),
172
+ limit: import_zod.z.number().int().positive().max(200).optional(),
173
+ before: import_zod.z.number().int().nonnegative().optional()
174
+ });
175
+ var ledgerFillSchema = import_zod.z.object({
176
+ coin: import_zod.z.string(),
177
+ px: import_zod.z.number(),
178
+ sz: import_zod.z.number(),
179
+ side: import_zod.z.enum(["B", "A"]),
180
+ time: import_zod.z.number().int().nonnegative(),
181
+ dir: import_zod.z.string(),
182
+ closedPnl: import_zod.z.number(),
183
+ fee: import_zod.z.number(),
184
+ crossed: import_zod.z.boolean(),
185
+ oid: import_zod.z.number().int().nonnegative(),
186
+ tid: import_zod.z.number().int().nonnegative()
187
+ });
188
+ var ledgerFillsPageSchema = import_zod.z.object({
189
+ window: ledgerWindowSchema,
190
+ limit: import_zod.z.number().int().positive(),
191
+ before: import_zod.z.number().int().nonnegative().optional(),
192
+ hasMore: import_zod.z.boolean(),
193
+ nextBefore: import_zod.z.number().int().nonnegative().optional(),
194
+ fetchedAt: import_zod.z.string().datetime(),
195
+ fills: import_zod.z.array(ledgerFillSchema)
196
+ });
197
+ var ledgerPeriodSummarySchema = import_zod.z.object({
198
+ realizedPnl: import_zod.z.number(),
199
+ totalFees: import_zod.z.number(),
200
+ fillCount: import_zod.z.number().int().nonnegative(),
201
+ closeCount: import_zod.z.number().int().nonnegative(),
202
+ winCount: import_zod.z.number().int().nonnegative(),
203
+ lossCount: import_zod.z.number().int().nonnegative(),
204
+ averageWin: import_zod.z.number(),
205
+ averageLoss: import_zod.z.number()
206
+ });
207
+ var ledgerSummaryInputSchema = import_zod.z.object({
208
+ window: ledgerWindowSchema.optional()
209
+ });
210
+ var ledgerSummarySchema = ledgerPeriodSummarySchema.extend({
211
+ window: ledgerWindowSchema,
212
+ generatedAt: import_zod.z.string().datetime(),
213
+ periods: import_zod.z.object({
214
+ "24h": ledgerPeriodSummarySchema,
215
+ "7d": ledgerPeriodSummarySchema
216
+ })
217
+ });
218
+ var marketSnapshotScopeSchema = import_zod.z.enum(["selected", "all"]);
219
+ var marketSnapshotResolvedScopeSchema = import_zod.z.enum(["selected", "all", "explicit"]);
220
+ var marketSnapshotValueSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean(), import_zod.z.null()]);
221
+ var marketSnapshotInputSchema = import_zod.z.object({
222
+ scope: marketSnapshotScopeSchema.optional(),
223
+ symbols: import_zod.z.array(import_zod.z.string().min(1)).min(1).optional()
224
+ });
225
+ var marketSnapshotChunkInputSchema = marketSnapshotInputSchema.extend({
226
+ offset: import_zod.z.number().int().nonnegative().optional(),
227
+ limit: import_zod.z.number().int().positive().max(100).optional()
228
+ });
229
+ var marketFieldBlockSchema = import_zod.z.object({
230
+ fieldIds: import_zod.z.array(import_zod.z.string()).min(1),
231
+ values: import_zod.z.array(marketSnapshotValueSchema),
232
+ symbolLists: import_zod.z.record(import_zod.z.string(), import_zod.z.array(import_zod.z.string())).optional()
233
+ });
234
+ var marketMatrixSchema = import_zod.z.object({
235
+ fieldIds: import_zod.z.array(import_zod.z.string()).min(1),
236
+ rows: import_zod.z.array(import_zod.z.array(marketSnapshotValueSchema))
237
+ });
238
+ var marketFieldSemanticsSchema = import_zod.z.object({
239
+ nullMeans: import_zod.z.literal("unavailable"),
240
+ percentScale: import_zod.z.literal("already_percent"),
241
+ percentFields: import_zod.z.array(import_zod.z.string()).min(1),
242
+ changeMapPercentKeys: import_zod.z.array(import_zod.z.string()).min(1)
243
+ });
244
+ var marketSnapshotSchema = import_zod.z.object({
245
+ schema: import_zod.z.literal("helios.market_snapshot.v1"),
246
+ view: import_zod.z.literal("market_overview"),
247
+ scope: marketSnapshotResolvedScopeSchema,
248
+ symbolCount: import_zod.z.number().int().nonnegative(),
249
+ generatedAt: import_zod.z.string().datetime(),
250
+ returnedSymbols: import_zod.z.array(import_zod.z.string()),
251
+ semantics: marketFieldSemanticsSchema,
252
+ market: marketFieldBlockSchema,
253
+ table: marketMatrixSchema,
254
+ legend: import_zod.z.record(import_zod.z.string(), import_zod.z.union([import_zod.z.string(), import_zod.z.array(import_zod.z.string())]))
255
+ });
256
+ var marketSnapshotChunkSchema = import_zod.z.object({
257
+ schema: import_zod.z.literal("helios.market_snapshot_chunk.v1"),
258
+ view: import_zod.z.literal("market_overview_chunk"),
259
+ scope: marketSnapshotResolvedScopeSchema,
260
+ totalSymbolCount: import_zod.z.number().int().nonnegative(),
261
+ generatedAt: import_zod.z.string().datetime(),
262
+ offset: import_zod.z.number().int().nonnegative(),
263
+ limit: import_zod.z.number().int().positive(),
264
+ chunkSymbolCount: import_zod.z.number().int().nonnegative(),
265
+ hasMore: import_zod.z.boolean(),
266
+ nextOffset: import_zod.z.number().int().nonnegative().optional(),
267
+ returnedSymbols: import_zod.z.array(import_zod.z.string()),
268
+ semantics: marketFieldSemanticsSchema,
269
+ market: marketFieldBlockSchema,
270
+ table: marketMatrixSchema,
271
+ legend: import_zod.z.record(import_zod.z.string(), import_zod.z.union([import_zod.z.string(), import_zod.z.array(import_zod.z.string())]))
272
+ });
273
+ var marketSymbolDetailInputSchema = import_zod.z.object({
274
+ symbol: import_zod.z.string().min(1)
275
+ });
276
+ var marketSymbolDetailSchema = import_zod.z.object({
277
+ schema: import_zod.z.literal("helios.market_symbol_detail.v1"),
278
+ generatedAt: import_zod.z.string().datetime(),
279
+ symbol: import_zod.z.string(),
280
+ semantics: marketFieldSemanticsSchema,
281
+ market: marketFieldBlockSchema,
282
+ row: import_zod.z.record(import_zod.z.string(), marketSnapshotValueSchema),
283
+ symbolCtx: import_zod.z.record(import_zod.z.string(), marketSnapshotValueSchema),
284
+ changeMap: import_zod.z.record(import_zod.z.string(), import_zod.z.number().nullable()),
285
+ metrics: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable(),
286
+ legend: import_zod.z.record(import_zod.z.string(), import_zod.z.union([import_zod.z.string(), import_zod.z.array(import_zod.z.string())]))
287
+ });
288
+ var tradingDirectionSchema = import_zod.z.enum(["LONG", "SHORT"]);
289
+ var tradingExecutionStyleSchema = import_zod.z.enum(["MARKET", "LIMIT_TAKER", "LIMIT_MAKER", "LIMIT_GTC"]);
290
+ var tradingSizeSchema = import_zod.z.object({
291
+ mode: import_zod.z.enum(["MARGIN_USD", "BASE_QUANTITY"]),
292
+ value: import_zod.z.number().positive()
293
+ });
294
+ var tradingProtectionLegSchema = import_zod.z.object({
295
+ kind: import_zod.z.enum(["LIMIT", "MARKET"]),
296
+ triggerPrice: import_zod.z.number().positive(),
297
+ limitPrice: import_zod.z.number().positive().optional()
298
+ });
299
+ var tradingProtectionSchema = import_zod.z.object({
300
+ takeProfit: tradingProtectionLegSchema.optional(),
301
+ stopLoss: tradingProtectionLegSchema.optional()
302
+ });
303
+ var tradeIntentTypeSchema = import_zod.z.enum(["OPEN", "DCA", "REVERSE", "CLOSE"]);
304
+ var submitTradeIntentInputSchema = import_zod.z.object({
305
+ provider: providerSchema.optional(),
306
+ symbol: import_zod.z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
307
+ intentType: tradeIntentTypeSchema,
308
+ direction: tradingDirectionSchema,
309
+ size: tradingSizeSchema,
310
+ execution: import_zod.z.object({
311
+ style: tradingExecutionStyleSchema,
312
+ timeInForce: import_zod.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
313
+ limitPrice: import_zod.z.number().positive().optional()
314
+ }),
315
+ maxSlippageBps: import_zod.z.number().int().nonnegative().max(1e3).optional(),
316
+ leverageOverride: import_zod.z.number().positive().optional(),
317
+ marginModeOverride: import_zod.z.enum(["ISOLATED", "CROSS"]).optional(),
318
+ reduceOnly: import_zod.z.boolean().optional(),
319
+ protection: tradingProtectionSchema.optional(),
320
+ /** One per user action, reused on retries: the data-bridge never places a second order for the same key. */
321
+ idempotencyKey: import_zod.z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional()
322
+ });
323
+ var submitTradeIntentResultSchema = import_zod.z.object({
324
+ status: import_zod.z.literal("submitted"),
325
+ /** `replayed`: an earlier attempt of this action already placed the order; nothing new was sent. */
326
+ outcome: import_zod.z.enum(["placed", "replayed"]).optional(),
327
+ clientOrderId: import_zod.z.string().optional(),
328
+ orderStatus: import_zod.z.string().optional(),
329
+ /** TP/SL legs Hyperliquid refused while the entry went through: the position is open without them. */
330
+ rejectedProtection: import_zod.z.array(import_zod.z.object({ kind: import_zod.z.string(), reason: import_zod.z.string() })).optional(),
331
+ provider: providerSchema.optional(),
332
+ symbol: import_zod.z.string(),
333
+ intentType: tradeIntentTypeSchema,
334
+ direction: tradingDirectionSchema,
335
+ size: tradingSizeSchema,
336
+ execution: import_zod.z.object({
337
+ style: tradingExecutionStyleSchema,
338
+ timeInForce: import_zod.z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
339
+ limitPrice: import_zod.z.number().positive().optional()
340
+ }),
341
+ maxSlippageBps: import_zod.z.number().int().nonnegative().max(1e3).optional(),
342
+ leverageOverride: import_zod.z.number().positive().optional(),
343
+ marginModeOverride: import_zod.z.enum(["ISOLATED", "CROSS"]).optional(),
344
+ reduceOnly: import_zod.z.boolean(),
345
+ hasProtection: import_zod.z.boolean()
346
+ });
347
+ var closePositionInputSchema = import_zod.z.object({
348
+ provider: providerSchema.optional(),
349
+ symbol: import_zod.z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
350
+ maxSlippageBps: import_zod.z.number().int().nonnegative().max(1e3).optional()
351
+ });
352
+ var closePositionResultSchema = import_zod.z.object({
353
+ status: import_zod.z.literal("submitted"),
354
+ provider: providerSchema.optional(),
355
+ symbol: import_zod.z.string(),
356
+ mode: import_zod.z.literal("FULL"),
357
+ maxSlippageBps: import_zod.z.number().int().nonnegative().max(1e3).optional()
358
+ });
359
+ var setTpSlInputSchema = import_zod.z.object({
360
+ provider: providerSchema.optional(),
361
+ symbol: import_zod.z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
362
+ applyTo: import_zod.z.enum(["FULL_POSITION", "CUSTOM_QUANTITY"]),
363
+ quantity: import_zod.z.number().positive().optional(),
364
+ parentClientOrderId: import_zod.z.string(),
365
+ takeProfit: tradingProtectionLegSchema.optional(),
366
+ stopLoss: tradingProtectionLegSchema.optional()
367
+ });
368
+ var setTpSlResultSchema = import_zod.z.object({
369
+ status: import_zod.z.literal("submitted"),
370
+ provider: providerSchema.optional(),
371
+ symbol: import_zod.z.string(),
372
+ applyTo: import_zod.z.enum(["FULL_POSITION", "CUSTOM_QUANTITY"]),
373
+ quantity: import_zod.z.number().positive().optional(),
374
+ parentClientOrderId: import_zod.z.string(),
375
+ hasTakeProfit: import_zod.z.boolean(),
376
+ hasStopLoss: import_zod.z.boolean()
377
+ });
378
+ var deleteTpSlInputSchema = import_zod.z.object({
379
+ provider: providerSchema.optional(),
380
+ symbol: import_zod.z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
381
+ orderId: import_zod.z.string()
382
+ });
383
+ var deleteTpSlResultSchema = import_zod.z.object({
384
+ status: import_zod.z.literal("deleted"),
385
+ provider: providerSchema.optional(),
386
+ symbol: import_zod.z.string(),
387
+ orderId: import_zod.z.string()
388
+ });
389
+ var openOrderSchema = import_zod.z.object({
390
+ coin: import_zod.z.string(),
391
+ side: import_zod.z.enum(["B", "A"]),
392
+ limitPx: import_zod.z.string(),
393
+ sz: import_zod.z.string(),
394
+ oid: import_zod.z.number().int().nonnegative(),
395
+ timestamp: import_zod.z.number().int().nonnegative(),
396
+ origSz: import_zod.z.string(),
397
+ orderType: import_zod.z.string(),
398
+ tif: import_zod.z.string().nullable(),
399
+ reduceOnly: import_zod.z.boolean(),
400
+ isTrigger: import_zod.z.boolean(),
401
+ triggerPx: import_zod.z.string(),
402
+ cloid: import_zod.z.string().nullable(),
403
+ assetId: import_zod.z.number().int().nonnegative().optional()
404
+ });
405
+ var cancelOrderInputSchema = import_zod.z.object({
406
+ symbol: import_zod.z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
407
+ oid: import_zod.z.number().int().nonnegative()
408
+ });
409
+ var cancelOrderResultSchema = import_zod.z.object({
410
+ status: import_zod.z.literal("cancelled"),
411
+ symbol: import_zod.z.string(),
412
+ oid: import_zod.z.number().int().nonnegative()
413
+ });
414
+ var heliosAgentErrorResponseSchema = import_zod2.z.object({
415
+ error: import_zod2.z.string().optional(),
416
+ errorDescription: import_zod2.z.string().optional(),
417
+ message: import_zod2.z.string().optional()
418
+ });
419
+ var HeliosAgentApiError = class extends Error {
420
+ constructor(options) {
421
+ super(options.message);
422
+ __publicField2(this, "status");
423
+ __publicField2(this, "code");
424
+ __publicField2(this, "errorDescription");
425
+ __publicField2(this, "payload");
426
+ this.name = "HeliosAgentApiError";
427
+ this.status = options.status;
428
+ this.code = options.code;
429
+ this.errorDescription = options.errorDescription;
430
+ this.payload = options.payload;
431
+ if (options.cause !== void 0) {
432
+ Object.defineProperty(this, "cause", {
433
+ configurable: true,
434
+ enumerable: false,
435
+ value: options.cause,
436
+ writable: true
437
+ });
438
+ }
439
+ }
440
+ };
441
+ function isHeliosAgentApiError(error) {
442
+ return error instanceof HeliosAgentApiError;
443
+ }
444
+ var HeliosAgentAuthClient = class {
445
+ constructor(options) {
446
+ __publicField2(this, "baseUrl");
447
+ __publicField2(this, "fetchImpl");
448
+ __publicField2(this, "headers");
449
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
450
+ this.fetchImpl = options.fetch ?? fetch;
451
+ this.headers = options.headers ?? {};
452
+ }
453
+ async startLogin(input) {
454
+ const parsed = agentDeviceStartInputSchema.parse(input);
455
+ return this.post("/api/agents/device/start", parsed, agentDeviceStartOutputSchema);
456
+ }
457
+ async exchangeDeviceCode(deviceCode) {
458
+ const parsed = agentDeviceStartOutputSchema.shape.deviceCode.parse(deviceCode);
459
+ return this.post("/api/agents/device/token", { deviceCode: parsed }, agentTokenResponseSchema);
460
+ }
461
+ async refreshSession(refreshToken) {
462
+ const parsed = agentRefreshInputSchema.parse({ refreshToken });
463
+ return this.post("/api/agents/auth/refresh", parsed, agentTokenResponseSchema);
464
+ }
465
+ async post(path3, body, schema) {
466
+ let response;
467
+ try {
468
+ response = await this.fetchImpl(`${this.baseUrl}${path3}`, {
469
+ method: "POST",
470
+ headers: {
471
+ Accept: "application/json",
472
+ "Content-Type": "application/json",
473
+ ...this.headers
474
+ },
475
+ body: JSON.stringify(body)
476
+ });
477
+ } catch (error) {
478
+ throw new HeliosAgentApiError({
479
+ status: 0,
480
+ code: "network_error",
481
+ message: error instanceof Error ? error.message : "Network error",
482
+ cause: error
483
+ });
484
+ }
485
+ const payload = await this.parseJson(response);
486
+ if (!response.ok) {
487
+ const parsed = heliosAgentErrorResponseSchema.safeParse(payload);
488
+ throw new HeliosAgentApiError({
489
+ status: response.status,
490
+ code: parsed.success ? parsed.data.error ?? "request_failed" : "request_failed",
491
+ message: parsed.success ? parsed.data.errorDescription ?? parsed.data.message ?? `Request failed with status ${response.status}` : `Request failed with status ${response.status}`,
492
+ errorDescription: parsed.success ? parsed.data.errorDescription : void 0,
493
+ payload
494
+ });
495
+ }
496
+ return schema.parse(payload);
497
+ }
498
+ async parseJson(response) {
499
+ const text = await response.text();
500
+ if (!text) {
501
+ return null;
502
+ }
503
+ try {
504
+ return JSON.parse(text);
505
+ } catch (error) {
506
+ throw new HeliosAgentApiError({
507
+ status: response.status,
508
+ code: "invalid_json",
509
+ message: "Received an invalid JSON response from Helios",
510
+ cause: error
511
+ });
512
+ }
513
+ }
514
+ };
515
+ var HeliosAgentDataBridgeClient = class {
516
+ constructor(options) {
517
+ __publicField2(this, "baseUrl");
518
+ __publicField2(this, "fetchImpl");
519
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
520
+ this.fetchImpl = options.fetch ?? fetch;
521
+ }
522
+ async getWalletState(accessToken) {
523
+ const payload = await this.request(accessToken, "account.getWalletState");
524
+ return walletStateSchema.parse(this.unwrapResult(payload));
525
+ }
526
+ async getOpenPositions(accessToken) {
527
+ const payload = await this.request(accessToken, "positions.getOpen");
528
+ return openPositionsSnapshotSchema.parse(this.unwrapResult(payload));
529
+ }
530
+ async getPortfolio(accessToken, input) {
531
+ const parsedInput = portfolioInputSchema.parse(input);
532
+ const payload = await this.request(accessToken, "positions.getPortfolio", parsedInput);
533
+ const result = this.unwrapResult(payload);
534
+ if (!result || typeof result !== "object" || Array.isArray(result)) {
535
+ throw new HeliosAgentApiError({
536
+ status: 200,
537
+ code: "invalid_response",
538
+ message: "Helios data bridge returned an invalid portfolio payload",
539
+ payload
540
+ });
541
+ }
542
+ return portfolioSnapshotSchema.parse({
543
+ ...result,
544
+ provider: parsedInput.provider
545
+ });
546
+ }
547
+ async getLedgerFills(accessToken, input = {}) {
548
+ const parsedInput = ledgerFillsInputSchema.parse(input);
549
+ const payload = await this.request(accessToken, "ledger.getFills", parsedInput);
550
+ return ledgerFillsPageSchema.parse(this.unwrapResult(payload));
551
+ }
552
+ async getLedgerSummary(accessToken, input = {}) {
553
+ const parsedInput = ledgerSummaryInputSchema.parse(input);
554
+ const payload = await this.request(accessToken, "ledger.getSummary", parsedInput);
555
+ return ledgerSummarySchema.parse(this.unwrapResult(payload));
556
+ }
557
+ async getMarketSnapshot(accessToken, input = {}) {
558
+ const parsedInput = marketSnapshotInputSchema.parse(input);
559
+ const payload = await this.request(accessToken, "market.getSnapshot", parsedInput);
560
+ return marketSnapshotSchema.parse(this.unwrapResult(payload));
561
+ }
562
+ async getMarketSnapshotChunk(accessToken, input = {}) {
563
+ const parsedInput = marketSnapshotChunkInputSchema.parse(input);
564
+ const payload = await this.request(accessToken, "market.getSnapshotChunk", parsedInput);
565
+ return marketSnapshotChunkSchema.parse(this.unwrapResult(payload));
566
+ }
567
+ async getMarketSymbolDetail(accessToken, input) {
568
+ const parsedInput = marketSymbolDetailInputSchema.parse(input);
569
+ const payload = await this.request(accessToken, "market.getSymbolDetail", parsedInput);
570
+ return marketSymbolDetailSchema.parse(this.unwrapResult(payload));
571
+ }
572
+ async submitTradeIntent(accessToken, input) {
573
+ const parsedInput = submitTradeIntentInputSchema.parse(input);
574
+ const payload = await this.request(accessToken, "trading.submitIntent", parsedInput, "POST");
575
+ const answer = this.unwrapResult(payload) ?? {};
576
+ return submitTradeIntentResultSchema.parse({
577
+ status: "submitted",
578
+ ...answer.outcome === "placed" || answer.outcome === "replayed" ? { outcome: answer.outcome } : {},
579
+ ...typeof answer.clientOrderId === "string" ? { clientOrderId: answer.clientOrderId } : {},
580
+ ...typeof answer.orderStatus === "string" ? { orderStatus: answer.orderStatus } : {},
581
+ ...Array.isArray(answer.rejectedProtection) ? { rejectedProtection: answer.rejectedProtection } : {},
582
+ provider: parsedInput.provider,
583
+ symbol: parsedInput.symbol,
584
+ intentType: parsedInput.intentType,
585
+ direction: parsedInput.direction,
586
+ size: parsedInput.size,
587
+ execution: parsedInput.execution,
588
+ maxSlippageBps: parsedInput.maxSlippageBps,
589
+ leverageOverride: parsedInput.leverageOverride,
590
+ marginModeOverride: parsedInput.marginModeOverride,
591
+ reduceOnly: Boolean(parsedInput.reduceOnly),
592
+ hasProtection: Boolean(parsedInput.protection?.takeProfit || parsedInput.protection?.stopLoss)
593
+ });
594
+ }
595
+ async closePosition(accessToken, input) {
596
+ const parsedInput = closePositionInputSchema.parse(input);
597
+ await this.request(
598
+ accessToken,
599
+ "positions.close",
600
+ {
601
+ ...parsedInput.provider !== void 0 ? { provider: parsedInput.provider } : {},
602
+ symbol: parsedInput.symbol,
603
+ mode: "FULL",
604
+ ...parsedInput.maxSlippageBps !== void 0 ? { maxSlippageBps: parsedInput.maxSlippageBps } : {}
605
+ },
606
+ "POST"
607
+ );
608
+ return closePositionResultSchema.parse({
609
+ status: "submitted",
610
+ provider: parsedInput.provider,
611
+ symbol: parsedInput.symbol,
612
+ mode: "FULL",
613
+ maxSlippageBps: parsedInput.maxSlippageBps
614
+ });
615
+ }
616
+ async setTpSl(accessToken, input) {
617
+ const parsedInput = setTpSlInputSchema.parse(input);
618
+ await this.request(accessToken, "positions.setTpSl", parsedInput, "POST");
619
+ return setTpSlResultSchema.parse({
620
+ status: "submitted",
621
+ provider: parsedInput.provider,
622
+ symbol: parsedInput.symbol,
623
+ applyTo: parsedInput.applyTo,
624
+ quantity: parsedInput.quantity,
625
+ parentClientOrderId: parsedInput.parentClientOrderId,
626
+ hasTakeProfit: Boolean(parsedInput.takeProfit),
627
+ hasStopLoss: Boolean(parsedInput.stopLoss)
628
+ });
629
+ }
630
+ async deleteTpSl(accessToken, input) {
631
+ const parsedInput = deleteTpSlInputSchema.parse(input);
632
+ await this.request(accessToken, "positions.deleteTpSl", parsedInput, "POST");
633
+ return deleteTpSlResultSchema.parse({
634
+ status: "deleted",
635
+ provider: parsedInput.provider,
636
+ symbol: parsedInput.symbol,
637
+ orderId: parsedInput.orderId
638
+ });
639
+ }
640
+ async getOpenOrders(accessToken) {
641
+ const payload = await this.request(accessToken, "positions.getOpenOrders");
642
+ return openOrderSchema.array().parse(this.unwrapResult(payload));
643
+ }
644
+ async cancelOrder(accessToken, input) {
645
+ const parsedInput = cancelOrderInputSchema.parse(input);
646
+ await this.request(accessToken, "positions.cancelOrder", parsedInput, "POST");
647
+ return cancelOrderResultSchema.parse({
648
+ status: "cancelled",
649
+ symbol: parsedInput.symbol,
650
+ oid: parsedInput.oid
651
+ });
652
+ }
653
+ async request(accessToken, procedure, input, method = "GET") {
654
+ let response;
655
+ try {
656
+ response = await this.fetchImpl(this.buildProcedureUrl(procedure, method === "GET" ? input : void 0), {
657
+ method,
658
+ headers: {
659
+ Accept: "application/json",
660
+ ...method === "POST" ? { "Content-Type": "application/json" } : {},
661
+ Authorization: `Bearer ${accessToken}`
662
+ },
663
+ ...method === "POST" && input !== void 0 ? { body: JSON.stringify({ json: input }) } : {}
664
+ });
665
+ } catch (error) {
666
+ throw new HeliosAgentApiError({
667
+ status: 0,
668
+ code: "network_error",
669
+ message: error instanceof Error ? error.message : "Network error",
670
+ cause: error
671
+ });
672
+ }
673
+ const payload = await this.parseJson(response);
674
+ if (!response.ok) {
675
+ throw new HeliosAgentApiError({
676
+ status: response.status,
677
+ code: this.extractErrorCode(payload),
678
+ message: this.extractErrorMessage(payload, response.status),
679
+ payload
680
+ });
681
+ }
682
+ return payload;
683
+ }
684
+ buildProcedureUrl(procedure, input) {
685
+ const url = new URL(`${this.baseUrl}/api/trpc/${procedure}`);
686
+ if (input !== void 0) {
687
+ url.searchParams.set("input", JSON.stringify({ json: input }));
688
+ }
689
+ return url.toString();
690
+ }
691
+ async parseJson(response) {
692
+ const text = await response.text();
693
+ if (!text) {
694
+ return null;
695
+ }
696
+ try {
697
+ return JSON.parse(text);
698
+ } catch (error) {
699
+ throw new HeliosAgentApiError({
700
+ status: response.status,
701
+ code: "invalid_json",
702
+ message: "Received an invalid JSON response from Helios data bridge",
703
+ cause: error
704
+ });
705
+ }
706
+ }
707
+ unwrapResult(payload) {
708
+ if (!payload || typeof payload !== "object") {
709
+ throw new HeliosAgentApiError({
710
+ status: 200,
711
+ code: "invalid_response",
712
+ message: "Helios data bridge returned an invalid response payload",
713
+ payload
714
+ });
715
+ }
716
+ const result = payload.result;
717
+ if (!result) {
718
+ throw new HeliosAgentApiError({
719
+ status: 200,
720
+ code: "invalid_response",
721
+ message: "Helios data bridge response is missing a result payload",
722
+ payload
723
+ });
724
+ }
725
+ const data = result.data;
726
+ if (data && typeof data === "object" && "json" in data) {
727
+ return data.json;
728
+ }
729
+ return data;
730
+ }
731
+ extractErrorCode(payload) {
732
+ if (payload && typeof payload === "object") {
733
+ const errorShape = this.unwrapTrpcError(payload);
734
+ if (errorShape?.data?.code) {
735
+ return errorShape.data.code;
736
+ }
737
+ }
738
+ return "request_failed";
739
+ }
740
+ extractErrorMessage(payload, status) {
741
+ if (payload && typeof payload === "object") {
742
+ const errorShape = this.unwrapTrpcError(payload);
743
+ if (errorShape?.message) {
744
+ return errorShape.message;
745
+ }
746
+ }
747
+ return `Request failed with status ${status}`;
748
+ }
749
+ /**
750
+ * Unwrap a tRPC error envelope, handling the superjson `{ json: ... }` wrapper
751
+ * that the data-bridge applies via its transformer configuration.
752
+ */
753
+ unwrapTrpcError(payload) {
754
+ const envelope = payload.error;
755
+ if (!envelope || typeof envelope !== "object") {
756
+ return void 0;
757
+ }
758
+ if ("json" in envelope) {
759
+ const inner = envelope.json;
760
+ if (inner && typeof inner === "object") {
761
+ return inner;
762
+ }
763
+ }
764
+ return envelope;
765
+ }
766
+ };
767
+ var DEFAULT_AGENT_REFRESH_WINDOW_MS = 60 * 1e3;
768
+ var agentConnectionStatusSchema = import_zod3.z.enum([
769
+ "disconnected",
770
+ "pending",
771
+ "connected",
772
+ "rejected",
773
+ "expired",
774
+ "failed"
775
+ ]);
776
+ var storedAgentSessionSchema = import_zod3.z.object({
777
+ accessToken: import_zod3.z.string(),
778
+ refreshToken: import_zod3.z.string(),
779
+ tokenType: agentTokenResponseSchema.shape.tokenType,
780
+ ownerUserId: import_zod3.z.string(),
781
+ agentGrantId: import_zod3.z.string(),
782
+ scope: import_zod3.z.array(agentScopeSchema).min(1),
783
+ accessTokenExpiresAt: import_zod3.z.string().datetime(),
784
+ createdAt: import_zod3.z.string().datetime(),
785
+ lastRefreshedAt: import_zod3.z.string().datetime()
786
+ });
787
+ var agentSessionViewSchema = import_zod3.z.object({
788
+ connected: import_zod3.z.boolean(),
789
+ status: agentConnectionStatusSchema,
790
+ ownerUserId: import_zod3.z.string().optional(),
791
+ agentGrantId: import_zod3.z.string().optional(),
792
+ scope: import_zod3.z.array(agentScopeSchema).optional(),
793
+ accessTokenExpiresAt: import_zod3.z.string().datetime().optional(),
794
+ lastRefreshedAt: import_zod3.z.string().datetime().optional()
795
+ });
796
+ function createStoredAgentSession(tokenResponse, now = /* @__PURE__ */ new Date()) {
797
+ const createdAt = now.toISOString();
798
+ return {
799
+ accessToken: tokenResponse.accessToken,
800
+ refreshToken: tokenResponse.refreshToken,
801
+ tokenType: tokenResponse.tokenType,
802
+ ownerUserId: tokenResponse.ownerUserId,
803
+ agentGrantId: tokenResponse.agentGrantId,
804
+ scope: tokenResponse.scope,
805
+ accessTokenExpiresAt: new Date(now.getTime() + tokenResponse.expiresInSeconds * 1e3).toISOString(),
806
+ createdAt,
807
+ lastRefreshedAt: createdAt
808
+ };
809
+ }
810
+ function sanitizeAgentSession(session, status = session ? "connected" : "disconnected") {
811
+ if (!session) {
812
+ return {
813
+ connected: false,
814
+ status: status === "connected" ? "disconnected" : status
815
+ };
816
+ }
817
+ return {
818
+ connected: true,
819
+ status,
820
+ ownerUserId: session.ownerUserId,
821
+ agentGrantId: session.agentGrantId,
822
+ scope: session.scope,
823
+ accessTokenExpiresAt: session.accessTokenExpiresAt,
824
+ lastRefreshedAt: session.lastRefreshedAt
825
+ };
826
+ }
827
+ function shouldRefreshAgentSession(session, now = /* @__PURE__ */ new Date(), refreshWindowMs = DEFAULT_AGENT_REFRESH_WINDOW_MS) {
828
+ return new Date(session.accessTokenExpiresAt).getTime() - now.getTime() <= refreshWindowMs;
829
+ }
830
+
831
+ // src/auth-service.ts
832
+ var HOSTED_RECONNECT_MESSAGE = "Helios no longer accepts this connection (it expired or was revoked). Reconnect Helios in your AI app to continue.";
833
+ var HeliosAgentMcpAuthService = class {
834
+ constructor(options) {
835
+ __publicField(this, "client");
836
+ __publicField(this, "sessionStore");
837
+ __publicField(this, "refreshWindowMs");
838
+ __publicField(this, "now");
839
+ __publicField(this, "deviceLogin");
840
+ this.client = options.client;
841
+ this.sessionStore = options.sessionStore;
842
+ this.refreshWindowMs = options.refreshWindowMs ?? 60 * 1e3;
843
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
844
+ this.deviceLogin = options.deviceLogin ?? true;
845
+ }
846
+ async startLogin(input) {
847
+ const response = await this.startDeviceLogin(input);
848
+ const result = this.buildStartLoginResult(response, input.scope);
849
+ await this.sessionStore.setPendingLogin(result);
850
+ return result;
851
+ }
852
+ async resetSessionAndStartLogin(input) {
853
+ await this.sessionStore.clearSession();
854
+ await this.sessionStore.clearPendingLogin();
855
+ const response = await this.startDeviceLogin(input);
856
+ const result = this.buildStartLoginResult(response, input.scope);
857
+ await this.sessionStore.setPendingLogin(result);
858
+ return result;
859
+ }
860
+ async startDeviceLogin(input) {
861
+ if (!this.deviceLogin) {
862
+ throw new Error(HOSTED_RECONNECT_MESSAGE);
863
+ }
864
+ return this.client.startLogin(input);
865
+ }
866
+ buildStartLoginResult(response, requestedScope) {
867
+ return {
868
+ status: "pending",
869
+ ...response,
870
+ requestedScope,
871
+ startedAt: this.now().toISOString()
872
+ };
873
+ }
874
+ async startRelogin(options = {}) {
875
+ const requestedScope = options.scope ?? [AGENT_SCOPES.ACCOUNT_READ, AGENT_SCOPES.MARKET_READ];
876
+ const started = await this.resetSessionAndStartLogin({
877
+ clientName: options.clientName ?? "Helios MCP",
878
+ scope: requestedScope,
879
+ constraints: options.constraints
880
+ });
881
+ return {
882
+ ...started,
883
+ connected: false,
884
+ message: formatHeliosLoginPrompt(started)
885
+ };
886
+ }
887
+ async clearSessionState() {
888
+ await this.sessionStore.clearSession();
889
+ await this.sessionStore.clearPendingLogin();
890
+ }
891
+ async invalidateIfUnauthorized(error, options = {}) {
892
+ if (!isHeliosAgentApiError(error) || error.status !== 401) {
893
+ return null;
894
+ }
895
+ return this.startRelogin(options);
896
+ }
897
+ async refreshSessionAfterUnauthorized(error) {
898
+ if (!isHeliosAgentApiError(error) || error.status !== 401) {
899
+ return null;
900
+ }
901
+ const session = await this.sessionStore.getSession();
902
+ if (!session) {
903
+ return null;
904
+ }
905
+ return this.refreshStoredSession(session);
906
+ }
907
+ async ensureLogin(options = {}) {
908
+ const requestedScope = options.scope ?? [AGENT_SCOPES.ACCOUNT_READ, AGENT_SCOPES.MARKET_READ];
909
+ const requestedConstraints = options.constraints ?? {};
910
+ const session = await this.getValidSession();
911
+ if (session) {
912
+ return {
913
+ ...sanitizeAgentSession(session),
914
+ connected: true,
915
+ status: "connected"
916
+ };
917
+ }
918
+ const pendingLogin = await this.getPendingLogin({
919
+ requestedScope,
920
+ requestedConstraints
921
+ });
922
+ if (pendingLogin) {
923
+ return {
924
+ ...pendingLogin,
925
+ connected: false,
926
+ message: formatHeliosLoginPrompt(pendingLogin)
927
+ };
928
+ }
929
+ const started = await this.startLogin({
930
+ clientName: options.clientName ?? "Helios MCP",
931
+ scope: requestedScope,
932
+ constraints: options.constraints
933
+ });
934
+ return {
935
+ ...started,
936
+ connected: false,
937
+ message: formatHeliosLoginPrompt(started)
938
+ };
939
+ }
940
+ async pollLogin(deviceCode) {
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, ask me to continue and I will 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
+ var import_node_fs = require("fs");
1184
+ var import_node_path = __toESM(require("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 = (0, import_node_fs.readFileSync)(documentPath, "utf8");
1200
+ const stats = (0, import_node_fs.statSync)(documentPath);
1201
+ const relativePath = toPosixPath(import_node_path.default.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 = (0, import_node_fs.readFileSync)(documentPath, "utf8");
1212
+ const stats = (0, import_node_fs.statSync)(documentPath);
1213
+ const relativePath = toPosixPath(import_node_path.default.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 import_node_path.default.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 = (0, import_node_fs.readdirSync)(currentPath, { withFileTypes: true });
1230
+ const files = [];
1231
+ for (const entry of entries) {
1232
+ const nextPath = import_node_path.default.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 = import_node_path.default.resolve(root, normalizedPath);
1246
+ const relativePath = import_node_path.default.relative(root, resolvedPath);
1247
+ if (!normalizedPath) {
1248
+ throw new Error("Document path is required.");
1249
+ }
1250
+ if (import_node_path.default.isAbsolute(normalizedPath) || relativePath.startsWith("..") || import_node_path.default.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 import_node_path.default.basename(relativePath, ".txt");
1271
+ }
1272
+ function getDocumentSection(relativePath) {
1273
+ return relativePath.split("/")[0] ?? "docs";
1274
+ }
1275
+ function toPosixPath(value) {
1276
+ return value.split(import_node_path.default.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 HeliosAgentMcpMarketService = class {
1406
+ constructor(options) {
1407
+ __publicField(this, "authService");
1408
+ __publicField(this, "dataBridgeClient");
1409
+ this.authService = options.authService;
1410
+ this.dataBridgeClient = options.dataBridgeClient;
1411
+ }
1412
+ async getSnapshot(input = {}) {
1413
+ const loginOptions = {
1414
+ clientName: "Helios MCP",
1415
+ scope: [AGENT_SCOPES.MARKET_READ]
1416
+ };
1417
+ const login = await this.authService.ensureLogin(loginOptions);
1418
+ if (login.status !== "connected") {
1419
+ return {
1420
+ ...login,
1421
+ status: "pending",
1422
+ connected: false
1423
+ };
1424
+ }
1425
+ const session = await this.authService.requireSession();
1426
+ try {
1427
+ const snapshot = await this.dataBridgeClient.getMarketSnapshot(session.accessToken, input);
1428
+ return {
1429
+ status: "connected",
1430
+ connected: true,
1431
+ snapshot
1432
+ };
1433
+ } catch (error) {
1434
+ const recovery = await retryAfterUnauthorizedRefresh({
1435
+ authService: this.authService,
1436
+ error,
1437
+ loginOptions,
1438
+ retry: async (accessToken) => {
1439
+ const snapshot = await this.dataBridgeClient.getMarketSnapshot(accessToken, input);
1440
+ return {
1441
+ status: "connected",
1442
+ connected: true,
1443
+ snapshot
1444
+ };
1445
+ }
1446
+ });
1447
+ if (recovery) {
1448
+ return recovery;
1449
+ }
1450
+ throw error;
1451
+ }
1452
+ }
1453
+ async getSnapshotChunk(input = {}) {
1454
+ const loginOptions = {
1455
+ clientName: "Helios MCP",
1456
+ scope: [AGENT_SCOPES.MARKET_READ]
1457
+ };
1458
+ const login = await this.authService.ensureLogin(loginOptions);
1459
+ if (login.status !== "connected") {
1460
+ return {
1461
+ ...login,
1462
+ status: "pending",
1463
+ connected: false
1464
+ };
1465
+ }
1466
+ const session = await this.authService.requireSession();
1467
+ try {
1468
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(session.accessToken, input);
1469
+ return {
1470
+ status: "connected",
1471
+ connected: true,
1472
+ snapshotChunk
1473
+ };
1474
+ } catch (error) {
1475
+ const recovery = await retryAfterUnauthorizedRefresh({
1476
+ authService: this.authService,
1477
+ error,
1478
+ loginOptions,
1479
+ retry: async (accessToken) => {
1480
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(accessToken, input);
1481
+ return {
1482
+ status: "connected",
1483
+ connected: true,
1484
+ snapshotChunk
1485
+ };
1486
+ }
1487
+ });
1488
+ if (recovery) {
1489
+ return recovery;
1490
+ }
1491
+ throw error;
1492
+ }
1493
+ }
1494
+ async getSymbolDetail(input) {
1495
+ const loginOptions = {
1496
+ clientName: "Helios MCP",
1497
+ scope: [AGENT_SCOPES.MARKET_READ]
1498
+ };
1499
+ const login = await this.authService.ensureLogin(loginOptions);
1500
+ if (login.status !== "connected") {
1501
+ return {
1502
+ ...login,
1503
+ status: "pending",
1504
+ connected: false
1505
+ };
1506
+ }
1507
+ const session = await this.authService.requireSession();
1508
+ try {
1509
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(session.accessToken, input);
1510
+ return {
1511
+ status: "connected",
1512
+ connected: true,
1513
+ detail
1514
+ };
1515
+ } catch (error) {
1516
+ const recovery = await retryAfterUnauthorizedRefresh({
1517
+ authService: this.authService,
1518
+ error,
1519
+ loginOptions,
1520
+ retry: async (accessToken) => {
1521
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(accessToken, input);
1522
+ return {
1523
+ status: "connected",
1524
+ connected: true,
1525
+ detail
1526
+ };
1527
+ }
1528
+ });
1529
+ if (recovery) {
1530
+ return recovery;
1531
+ }
1532
+ throw error;
1533
+ }
1534
+ }
1535
+ };
1536
+
1537
+ // src/provider-service.ts
1538
+ var HeliosAgentMcpProviderService = class {
1539
+ constructor(options) {
1540
+ __publicField(this, "sessionStore");
1541
+ this.sessionStore = options.sessionStore;
1542
+ }
1543
+ async getActiveProvider() {
1544
+ const provider = await this.sessionStore.getActiveProvider();
1545
+ if (!provider) {
1546
+ return {
1547
+ configured: false,
1548
+ provider: null
1549
+ };
1550
+ }
1551
+ return {
1552
+ configured: true,
1553
+ provider
1554
+ };
1555
+ }
1556
+ async setActiveProvider(provider) {
1557
+ await this.sessionStore.setActiveProvider(provider);
1558
+ return {
1559
+ configured: true,
1560
+ provider
1561
+ };
1562
+ }
1563
+ async resolveProvider(explicitProvider) {
1564
+ if (explicitProvider) {
1565
+ return explicitProvider;
1566
+ }
1567
+ const activeProvider = await this.sessionStore.getActiveProvider();
1568
+ if (activeProvider) {
1569
+ return activeProvider;
1570
+ }
1571
+ throw new Error("No active provider configured. Call helios_provider_set_active or pass provider explicitly.");
1572
+ }
1573
+ };
1574
+
1575
+ // src/session-store.ts
1576
+ var import_promises = require("fs/promises");
1577
+ var import_node_os = require("os");
1578
+ var import_node_path2 = __toESM(require("path"));
1579
+ var import_zod4 = require("zod");
1580
+ function getDefaultHeliosAgentMcpSessionPath() {
1581
+ return import_node_path2.default.join((0, import_node_os.homedir)(), ".helios-agent-mcp", "session.json");
1582
+ }
1583
+ var pendingAgentLoginSchema = import_zod4.z.object({
1584
+ status: import_zod4.z.literal("pending"),
1585
+ deviceCode: import_zod4.z.string(),
1586
+ userCode: import_zod4.z.string(),
1587
+ verificationUri: import_zod4.z.string().url(),
1588
+ verificationUriComplete: import_zod4.z.string().url(),
1589
+ expiresInSeconds: import_zod4.z.number().int().positive(),
1590
+ pollIntervalSeconds: import_zod4.z.number().int().positive(),
1591
+ requestedScope: import_zod4.z.array(agentScopeSchema).min(1),
1592
+ startedAt: import_zod4.z.string().datetime()
1593
+ });
1594
+ var mcpSessionStateSchema = import_zod4.z.object({
1595
+ session: storedAgentSessionSchema.nullish(),
1596
+ pendingLogin: pendingAgentLoginSchema.nullish(),
1597
+ // A provider pinned before Binance was retired ('binance') reads as unpinned, so the agent must pick again, rather than
1598
+ // failing the whole file (which would drop the session) or silently switching it to Hyperliquid.
1599
+ activeProvider: providerSchema.nullish().catch(null)
1600
+ });
1601
+ var FileAgentSessionStore = class {
1602
+ constructor(filePath = getDefaultHeliosAgentMcpSessionPath()) {
1603
+ this.filePath = filePath;
1604
+ }
1605
+ async getSession() {
1606
+ return (await this.readState()).session;
1607
+ }
1608
+ async getPendingLogin() {
1609
+ return (await this.readState()).pendingLogin;
1610
+ }
1611
+ async getActiveProvider() {
1612
+ return (await this.readState()).activeProvider;
1613
+ }
1614
+ async setSession(session) {
1615
+ const state = await this.readState();
1616
+ await this.writeState({
1617
+ ...state,
1618
+ session
1619
+ });
1620
+ }
1621
+ async setPendingLogin(pendingLogin) {
1622
+ const state = await this.readState();
1623
+ await this.writeState({
1624
+ ...state,
1625
+ pendingLogin
1626
+ });
1627
+ }
1628
+ async setActiveProvider(activeProvider) {
1629
+ const state = await this.readState();
1630
+ await this.writeState({
1631
+ ...state,
1632
+ activeProvider
1633
+ });
1634
+ }
1635
+ async clearSession() {
1636
+ const state = await this.readState();
1637
+ await this.writeStateOrDelete({
1638
+ ...state,
1639
+ session: null
1640
+ });
1641
+ }
1642
+ async clearPendingLogin() {
1643
+ const state = await this.readState();
1644
+ await this.writeStateOrDelete({
1645
+ ...state,
1646
+ pendingLogin: null
1647
+ });
1648
+ }
1649
+ async clearActiveProvider() {
1650
+ const state = await this.readState();
1651
+ await this.writeStateOrDelete({
1652
+ ...state,
1653
+ activeProvider: null
1654
+ });
1655
+ }
1656
+ async readState() {
1657
+ try {
1658
+ const raw = await (0, import_promises.readFile)(this.filePath, "utf8");
1659
+ const parsed = JSON.parse(raw);
1660
+ if (parsed && typeof parsed === "object" && ("session" in parsed || "pendingLogin" in parsed || "activeProvider" in parsed)) {
1661
+ const envelope = mcpSessionStateSchema.safeParse(parsed);
1662
+ if (envelope.success) {
1663
+ return {
1664
+ session: envelope.data.session ?? null,
1665
+ pendingLogin: envelope.data.pendingLogin ?? null,
1666
+ activeProvider: envelope.data.activeProvider ?? null
1667
+ };
1668
+ }
1669
+ }
1670
+ const legacySession = storedAgentSessionSchema.safeParse(parsed);
1671
+ if (legacySession.success) {
1672
+ return {
1673
+ session: legacySession.data,
1674
+ pendingLogin: null,
1675
+ activeProvider: null
1676
+ };
1677
+ }
1678
+ return {
1679
+ session: null,
1680
+ pendingLogin: null,
1681
+ activeProvider: null
1682
+ };
1683
+ } catch (error) {
1684
+ if (isMissingFileError(error)) {
1685
+ return {
1686
+ session: null,
1687
+ pendingLogin: null,
1688
+ activeProvider: null
1689
+ };
1690
+ }
1691
+ if (error instanceof Error && error.name === "ZodError") {
1692
+ return {
1693
+ session: null,
1694
+ pendingLogin: null,
1695
+ activeProvider: null
1696
+ };
1697
+ }
1698
+ throw error;
1699
+ }
1700
+ }
1701
+ async writeState(state) {
1702
+ await (0, import_promises.mkdir)(import_node_path2.default.dirname(this.filePath), { recursive: true });
1703
+ await (0, import_promises.writeFile)(this.filePath, `${JSON.stringify(state, null, 2)}
1704
+ `, { encoding: "utf8", mode: 384 });
1705
+ await (0, import_promises.chmod)(this.filePath, 384).catch(() => void 0);
1706
+ }
1707
+ async writeStateOrDelete(state) {
1708
+ if (!state.session && !state.pendingLogin && !state.activeProvider) {
1709
+ await this.deleteFile();
1710
+ return;
1711
+ }
1712
+ await this.writeState(state);
1713
+ }
1714
+ async deleteFile() {
1715
+ try {
1716
+ await (0, import_promises.rm)(this.filePath, { force: true });
1717
+ } catch (error) {
1718
+ if (!isMissingFileError(error)) {
1719
+ throw error;
1720
+ }
1721
+ }
1722
+ }
1723
+ };
1724
+ function isMissingFileError(error) {
1725
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
1726
+ }
1727
+
1728
+ // src/trading-service.ts
1729
+ var import_node_crypto = require("crypto");
1730
+ var HeliosAgentMcpTradingService = class {
1731
+ constructor(options) {
1732
+ __publicField(this, "authService");
1733
+ __publicField(this, "dataBridgeClient");
1734
+ __publicField(this, "providerService");
1735
+ this.authService = options.authService;
1736
+ this.dataBridgeClient = options.dataBridgeClient;
1737
+ this.providerService = options.providerService;
1738
+ }
1739
+ async open(input) {
1740
+ return this.submitIntent("OPEN", input);
1741
+ }
1742
+ async dca(input) {
1743
+ return this.submitIntent("DCA", input);
1744
+ }
1745
+ async reverse(input) {
1746
+ return this.submitIntent("REVERSE", input);
1747
+ }
1748
+ async close(input) {
1749
+ const loginOptions = {
1750
+ clientName: "Helios MCP",
1751
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1752
+ };
1753
+ const login = await this.authService.ensureLogin(loginOptions);
1754
+ if (login.status !== "connected") {
1755
+ return asPending2(login);
1756
+ }
1757
+ const session = await this.authService.requireSession();
1758
+ try {
1759
+ const provider = await this.providerService.resolveProvider(input.provider);
1760
+ const closure = await this.dataBridgeClient.closePosition(session.accessToken, {
1761
+ ...input,
1762
+ provider
1763
+ });
1764
+ return {
1765
+ status: "connected",
1766
+ connected: true,
1767
+ closure
1768
+ };
1769
+ } catch (error) {
1770
+ const recovery = await retryAfterUnauthorizedRefresh({
1771
+ authService: this.authService,
1772
+ error,
1773
+ loginOptions,
1774
+ retry: async (accessToken) => {
1775
+ const provider = await this.providerService.resolveProvider(input.provider);
1776
+ const closure = await this.dataBridgeClient.closePosition(accessToken, {
1777
+ ...input,
1778
+ provider
1779
+ });
1780
+ return {
1781
+ status: "connected",
1782
+ connected: true,
1783
+ closure
1784
+ };
1785
+ }
1786
+ });
1787
+ if (recovery) {
1788
+ return recovery;
1789
+ }
1790
+ throw error;
1791
+ }
1792
+ }
1793
+ async setTpSl(input) {
1794
+ const loginOptions = {
1795
+ clientName: "Helios MCP",
1796
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1797
+ };
1798
+ const login = await this.authService.ensureLogin(loginOptions);
1799
+ if (login.status !== "connected") {
1800
+ return asPending2(login);
1801
+ }
1802
+ const session = await this.authService.requireSession();
1803
+ try {
1804
+ const provider = await this.providerService.resolveProvider(input.provider);
1805
+ const protection = await this.dataBridgeClient.setTpSl(session.accessToken, {
1806
+ ...input,
1807
+ provider
1808
+ });
1809
+ return {
1810
+ status: "connected",
1811
+ connected: true,
1812
+ protection
1813
+ };
1814
+ } catch (error) {
1815
+ const recovery = await retryAfterUnauthorizedRefresh({
1816
+ authService: this.authService,
1817
+ error,
1818
+ loginOptions,
1819
+ retry: async (accessToken) => {
1820
+ const provider = await this.providerService.resolveProvider(input.provider);
1821
+ const protection = await this.dataBridgeClient.setTpSl(accessToken, {
1822
+ ...input,
1823
+ provider
1824
+ });
1825
+ return {
1826
+ status: "connected",
1827
+ connected: true,
1828
+ protection
1829
+ };
1830
+ }
1831
+ });
1832
+ if (recovery) {
1833
+ return recovery;
1834
+ }
1835
+ throw error;
1836
+ }
1837
+ }
1838
+ async deleteTpSl(input) {
1839
+ const loginOptions = {
1840
+ clientName: "Helios MCP",
1841
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
1842
+ };
1843
+ const login = await this.authService.ensureLogin(loginOptions);
1844
+ if (login.status !== "connected") {
1845
+ return asPending2(login);
1846
+ }
1847
+ const session = await this.authService.requireSession();
1848
+ try {
1849
+ const provider = await this.providerService.resolveProvider(input.provider);
1850
+ const deletion = await this.dataBridgeClient.deleteTpSl(session.accessToken, {
1851
+ ...input,
1852
+ provider
1853
+ });
1854
+ return {
1855
+ status: "connected",
1856
+ connected: true,
1857
+ deletion
1858
+ };
1859
+ } catch (error) {
1860
+ const recovery = await retryAfterUnauthorizedRefresh({
1861
+ authService: this.authService,
1862
+ error,
1863
+ loginOptions,
1864
+ retry: async (accessToken) => {
1865
+ const provider = await this.providerService.resolveProvider(input.provider);
1866
+ const deletion = await this.dataBridgeClient.deleteTpSl(accessToken, {
1867
+ ...input,
1868
+ provider
1869
+ });
1870
+ return {
1871
+ status: "connected",
1872
+ connected: true,
1873
+ deletion
1874
+ };
1875
+ }
1876
+ });
1877
+ if (recovery) {
1878
+ return recovery;
1879
+ }
1880
+ throw error;
1881
+ }
1882
+ }
1883
+ async getOpenOrders() {
1884
+ const loginOptions = {
1885
+ clientName: "Helios MCP",
1886
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1887
+ };
1888
+ const login = await this.authService.ensureLogin(loginOptions);
1889
+ if (login.status !== "connected") {
1890
+ return asPending2(login);
1891
+ }
1892
+ const session = await this.authService.requireSession();
1893
+ try {
1894
+ const orders = await this.dataBridgeClient.getOpenOrders(session.accessToken);
1895
+ return {
1896
+ status: "connected",
1897
+ connected: true,
1898
+ orders
1899
+ };
1900
+ } catch (error) {
1901
+ const recovery = await retryAfterUnauthorizedRefresh({
1902
+ authService: this.authService,
1903
+ error,
1904
+ loginOptions,
1905
+ retry: async (accessToken) => {
1906
+ const orders = await this.dataBridgeClient.getOpenOrders(accessToken);
1907
+ return {
1908
+ status: "connected",
1909
+ connected: true,
1910
+ orders
1911
+ };
1912
+ }
1913
+ });
1914
+ if (recovery) {
1915
+ return recovery;
1916
+ }
1917
+ throw error;
1918
+ }
1919
+ }
1920
+ async cancelOrder(input) {
1921
+ const loginOptions = {
1922
+ clientName: "Helios MCP",
1923
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
1924
+ };
1925
+ const login = await this.authService.ensureLogin(loginOptions);
1926
+ if (login.status !== "connected") {
1927
+ return asPending2(login);
1928
+ }
1929
+ const session = await this.authService.requireSession();
1930
+ try {
1931
+ const cancellation = await this.dataBridgeClient.cancelOrder(session.accessToken, input);
1932
+ return {
1933
+ status: "connected",
1934
+ connected: true,
1935
+ cancellation
1936
+ };
1937
+ } catch (error) {
1938
+ const recovery = await retryAfterUnauthorizedRefresh({
1939
+ authService: this.authService,
1940
+ error,
1941
+ loginOptions,
1942
+ retry: async (accessToken) => {
1943
+ const cancellation = await this.dataBridgeClient.cancelOrder(accessToken, input);
1944
+ return {
1945
+ status: "connected",
1946
+ connected: true,
1947
+ cancellation
1948
+ };
1949
+ }
1950
+ });
1951
+ if (recovery) {
1952
+ return recovery;
1953
+ }
1954
+ throw error;
1955
+ }
1956
+ }
1957
+ async submitIntent(intentType, input) {
1958
+ const loginOptions = {
1959
+ clientName: "Helios MCP",
1960
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
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
+ const idempotencyKey = input.idempotencyKey ?? (0, import_node_crypto.randomUUID)().replace(/-/g, "");
1968
+ try {
1969
+ const provider = await this.providerService.resolveProvider(input.provider);
1970
+ const submission = await this.dataBridgeClient.submitTradeIntent(session.accessToken, {
1971
+ ...input,
1972
+ provider,
1973
+ intentType,
1974
+ idempotencyKey
1975
+ });
1976
+ return {
1977
+ status: "connected",
1978
+ connected: true,
1979
+ submission
1980
+ };
1981
+ } catch (error) {
1982
+ const recovery = await retryAfterUnauthorizedRefresh({
1983
+ authService: this.authService,
1984
+ error,
1985
+ loginOptions,
1986
+ retry: async (accessToken) => {
1987
+ const provider = await this.providerService.resolveProvider(input.provider);
1988
+ const submission = await this.dataBridgeClient.submitTradeIntent(accessToken, {
1989
+ ...input,
1990
+ provider,
1991
+ intentType,
1992
+ idempotencyKey
1993
+ });
1994
+ return {
1995
+ status: "connected",
1996
+ connected: true,
1997
+ submission
1998
+ };
1999
+ }
2000
+ });
2001
+ if (recovery) {
2002
+ return recovery;
2003
+ }
2004
+ throw error;
2005
+ }
2006
+ }
2007
+ };
2008
+ function asPending2(login) {
2009
+ return {
2010
+ ...login,
2011
+ status: "pending",
2012
+ connected: false
2013
+ };
2014
+ }
2015
+
2016
+ // src/tools.ts
2017
+ var import_zod5 = require("zod");
2018
+ var pollLoginInputSchema = import_zod5.z.object({
2019
+ deviceCode: import_zod5.z.string().min(1)
2020
+ });
2021
+ var startLoginOutputSchema = import_zod5.z.object({
2022
+ status: import_zod5.z.literal("pending"),
2023
+ deviceCode: import_zod5.z.string(),
2024
+ userCode: import_zod5.z.string(),
2025
+ verificationUri: import_zod5.z.string().url(),
2026
+ verificationUriComplete: import_zod5.z.string().url(),
2027
+ expiresInSeconds: import_zod5.z.number().int().positive(),
2028
+ pollIntervalSeconds: import_zod5.z.number().int().positive(),
2029
+ requestedScope: import_zod5.z.array(agentScopeSchema).min(1),
2030
+ startedAt: import_zod5.z.string().datetime()
2031
+ });
2032
+ var ensureLoginInputSchema = import_zod5.z.object({
2033
+ clientName: import_zod5.z.string().min(1).max(64).optional(),
2034
+ scope: import_zod5.z.array(agentScopeSchema).min(1).optional(),
2035
+ constraints: agentConstraintsSchema.optional()
2036
+ });
2037
+ var providerSelectionInputSchema = import_zod5.z.object({
2038
+ provider: providerSchema.optional()
2039
+ });
2040
+ var providerSetInputSchema = import_zod5.z.object({
2041
+ provider: providerSchema
2042
+ });
2043
+ var activeProviderSchema = import_zod5.z.object({
2044
+ configured: import_zod5.z.boolean(),
2045
+ provider: providerSchema.nullable()
2046
+ });
2047
+ var ensureLoginOutputSchema = import_zod5.z.discriminatedUnion("status", [
2048
+ agentSessionViewSchema.extend({
2049
+ status: import_zod5.z.literal("connected"),
2050
+ connected: import_zod5.z.literal(true)
2051
+ }),
2052
+ startLoginOutputSchema.extend({
2053
+ status: import_zod5.z.literal("pending"),
2054
+ connected: import_zod5.z.literal(false),
2055
+ message: import_zod5.z.string()
2056
+ })
2057
+ ]);
2058
+ var pollLoginOutputSchema = import_zod5.z.discriminatedUnion("status", [
2059
+ agentSessionViewSchema.extend({
2060
+ status: import_zod5.z.literal("connected"),
2061
+ connected: import_zod5.z.literal(true)
2062
+ }),
2063
+ import_zod5.z.object({
2064
+ status: import_zod5.z.enum(["pending", "rejected", "expired", "failed"]),
2065
+ connected: import_zod5.z.literal(false),
2066
+ message: import_zod5.z.string()
2067
+ })
2068
+ ]);
2069
+ var walletStateToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2070
+ import_zod5.z.object({
2071
+ status: import_zod5.z.literal("connected"),
2072
+ connected: import_zod5.z.literal(true),
2073
+ walletState: walletStateSchema
2074
+ }),
2075
+ startLoginOutputSchema.extend({
2076
+ status: import_zod5.z.literal("pending"),
2077
+ connected: import_zod5.z.literal(false),
2078
+ message: import_zod5.z.string()
2079
+ })
2080
+ ]);
2081
+ var portfolioToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2082
+ import_zod5.z.object({
2083
+ status: import_zod5.z.literal("connected"),
2084
+ connected: import_zod5.z.literal(true),
2085
+ portfolio: portfolioSnapshotSchema
2086
+ }),
2087
+ startLoginOutputSchema.extend({
2088
+ status: import_zod5.z.literal("pending"),
2089
+ connected: import_zod5.z.literal(false),
2090
+ message: import_zod5.z.string()
2091
+ })
2092
+ ]);
2093
+ var openPositionsToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2094
+ import_zod5.z.object({
2095
+ status: import_zod5.z.literal("connected"),
2096
+ connected: import_zod5.z.literal(true),
2097
+ openPositions: openPositionsSnapshotSchema
2098
+ }),
2099
+ startLoginOutputSchema.extend({
2100
+ status: import_zod5.z.literal("pending"),
2101
+ connected: import_zod5.z.literal(false),
2102
+ message: import_zod5.z.string()
2103
+ })
2104
+ ]);
2105
+ var ledgerFillsToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2106
+ import_zod5.z.object({
2107
+ status: import_zod5.z.literal("connected"),
2108
+ connected: import_zod5.z.literal(true),
2109
+ fills: ledgerFillsPageSchema
2110
+ }),
2111
+ startLoginOutputSchema.extend({
2112
+ status: import_zod5.z.literal("pending"),
2113
+ connected: import_zod5.z.literal(false),
2114
+ message: import_zod5.z.string()
2115
+ })
2116
+ ]);
2117
+ var ledgerSummaryToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2118
+ import_zod5.z.object({
2119
+ status: import_zod5.z.literal("connected"),
2120
+ connected: import_zod5.z.literal(true),
2121
+ summary: ledgerSummarySchema
2122
+ }),
2123
+ startLoginOutputSchema.extend({
2124
+ status: import_zod5.z.literal("pending"),
2125
+ connected: import_zod5.z.literal(false),
2126
+ message: import_zod5.z.string()
2127
+ })
2128
+ ]);
2129
+ var marketSnapshotToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2130
+ import_zod5.z.object({
2131
+ status: import_zod5.z.literal("connected"),
2132
+ connected: import_zod5.z.literal(true),
2133
+ snapshot: marketSnapshotSchema
2134
+ }),
2135
+ startLoginOutputSchema.extend({
2136
+ status: import_zod5.z.literal("pending"),
2137
+ connected: import_zod5.z.literal(false),
2138
+ message: import_zod5.z.string()
2139
+ })
2140
+ ]);
2141
+ var marketSnapshotChunkToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2142
+ import_zod5.z.object({
2143
+ status: import_zod5.z.literal("connected"),
2144
+ connected: import_zod5.z.literal(true),
2145
+ snapshotChunk: marketSnapshotChunkSchema
2146
+ }),
2147
+ startLoginOutputSchema.extend({
2148
+ status: import_zod5.z.literal("pending"),
2149
+ connected: import_zod5.z.literal(false),
2150
+ message: import_zod5.z.string()
2151
+ })
2152
+ ]);
2153
+ var marketSymbolDetailToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2154
+ import_zod5.z.object({
2155
+ status: import_zod5.z.literal("connected"),
2156
+ connected: import_zod5.z.literal(true),
2157
+ detail: marketSymbolDetailSchema
2158
+ }),
2159
+ startLoginOutputSchema.extend({
2160
+ status: import_zod5.z.literal("pending"),
2161
+ connected: import_zod5.z.literal(false),
2162
+ message: import_zod5.z.string()
2163
+ })
2164
+ ]);
2165
+ var tradeActionInputSchema = submitTradeIntentInputSchema.omit({
2166
+ intentType: true
2167
+ });
2168
+ var tradeActionToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2169
+ import_zod5.z.object({
2170
+ status: import_zod5.z.literal("connected"),
2171
+ connected: import_zod5.z.literal(true),
2172
+ submission: submitTradeIntentResultSchema
2173
+ }),
2174
+ startLoginOutputSchema.extend({
2175
+ status: import_zod5.z.literal("pending"),
2176
+ connected: import_zod5.z.literal(false),
2177
+ message: import_zod5.z.string()
2178
+ })
2179
+ ]);
2180
+ var closeTradeToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2181
+ import_zod5.z.object({
2182
+ status: import_zod5.z.literal("connected"),
2183
+ connected: import_zod5.z.literal(true),
2184
+ closure: closePositionResultSchema
2185
+ }),
2186
+ startLoginOutputSchema.extend({
2187
+ status: import_zod5.z.literal("pending"),
2188
+ connected: import_zod5.z.literal(false),
2189
+ message: import_zod5.z.string()
2190
+ })
2191
+ ]);
2192
+ var setTpSlToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2193
+ import_zod5.z.object({
2194
+ status: import_zod5.z.literal("connected"),
2195
+ connected: import_zod5.z.literal(true),
2196
+ protection: setTpSlResultSchema
2197
+ }),
2198
+ startLoginOutputSchema.extend({
2199
+ status: import_zod5.z.literal("pending"),
2200
+ connected: import_zod5.z.literal(false),
2201
+ message: import_zod5.z.string()
2202
+ })
2203
+ ]);
2204
+ var deleteTpSlToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2205
+ import_zod5.z.object({
2206
+ status: import_zod5.z.literal("connected"),
2207
+ connected: import_zod5.z.literal(true),
2208
+ deletion: deleteTpSlResultSchema
2209
+ }),
2210
+ startLoginOutputSchema.extend({
2211
+ status: import_zod5.z.literal("pending"),
2212
+ connected: import_zod5.z.literal(false),
2213
+ message: import_zod5.z.string()
2214
+ })
2215
+ ]);
2216
+ var openOrdersToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2217
+ import_zod5.z.object({
2218
+ status: import_zod5.z.literal("connected"),
2219
+ connected: import_zod5.z.literal(true),
2220
+ orders: import_zod5.z.array(openOrderSchema)
2221
+ }),
2222
+ startLoginOutputSchema.extend({
2223
+ status: import_zod5.z.literal("pending"),
2224
+ connected: import_zod5.z.literal(false),
2225
+ message: import_zod5.z.string()
2226
+ })
2227
+ ]);
2228
+ var cancelOrderToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2229
+ import_zod5.z.object({
2230
+ status: import_zod5.z.literal("connected"),
2231
+ connected: import_zod5.z.literal(true),
2232
+ cancellation: cancelOrderResultSchema
2233
+ }),
2234
+ startLoginOutputSchema.extend({
2235
+ status: import_zod5.z.literal("pending"),
2236
+ connected: import_zod5.z.literal(false),
2237
+ message: import_zod5.z.string()
2238
+ })
2239
+ ]);
2240
+ var documentPathInputSchema = import_zod5.z.object({
2241
+ path: import_zod5.z.string().min(1)
2242
+ });
2243
+ var docsIndexSchema = import_zod5.z.object({
2244
+ root: import_zod5.z.literal("docs"),
2245
+ documents: import_zod5.z.array(
2246
+ import_zod5.z.object({
2247
+ path: import_zod5.z.string(),
2248
+ section: import_zod5.z.string(),
2249
+ title: import_zod5.z.string(),
2250
+ bytes: import_zod5.z.number().int().nonnegative()
2251
+ })
2252
+ )
2253
+ });
2254
+ var documentSchema = import_zod5.z.object({
2255
+ path: import_zod5.z.string(),
2256
+ section: import_zod5.z.string(),
2257
+ title: import_zod5.z.string(),
2258
+ body: import_zod5.z.string(),
2259
+ bytes: import_zod5.z.number().int().nonnegative()
2260
+ });
2261
+ function createHeliosDocsToolDefinitions(service) {
2262
+ return [
2263
+ {
2264
+ name: "helios_docs_get_index",
2265
+ title: "Get Helios Docs Index",
2266
+ description: "Lists the package-local Helios MCP and indicator .txt documentation available to the agent.",
2267
+ inputSchema: import_zod5.z.object({}),
2268
+ async execute() {
2269
+ const result = docsIndexSchema.parse(await service.getIndex());
2270
+ return {
2271
+ content: [
2272
+ {
2273
+ type: "text",
2274
+ text: `Helios docs index: ${result.documents.length} documents across ${new Set(result.documents.map((document) => document.section)).size} sections.`
2275
+ }
2276
+ ],
2277
+ structuredContent: result
2278
+ };
2279
+ }
2280
+ },
2281
+ {
2282
+ name: "helios_docs_get_document",
2283
+ title: "Get Helios Doc",
2284
+ description: "Returns one package-local Helios .txt document by relative docs path.",
2285
+ inputSchema: documentPathInputSchema,
2286
+ async execute(input) {
2287
+ const result = documentSchema.parse(await service.getDocument(input));
2288
+ return {
2289
+ content: [
2290
+ {
2291
+ type: "text",
2292
+ text: result.body
2293
+ }
2294
+ ],
2295
+ structuredContent: result
2296
+ };
2297
+ }
2298
+ }
2299
+ ];
2300
+ }
2301
+ function createHeliosAuthToolDefinitions(service) {
2302
+ return [
2303
+ {
2304
+ name: "helios_auth_start_login",
2305
+ title: "Start Helios Login",
2306
+ description: "Starts the delegated Helios login flow and returns the approval URL for the user.",
2307
+ inputSchema: agentDeviceStartInputSchema,
2308
+ async execute(input) {
2309
+ const result = startLoginOutputSchema.parse(await service.startLogin(input));
2310
+ const manualResult = {
2311
+ ...result,
2312
+ ...withManualLoginFields(result)
2313
+ };
2314
+ return {
2315
+ content: [
2316
+ {
2317
+ type: "text",
2318
+ text: buildManualLoginText(result)
2319
+ }
2320
+ ],
2321
+ structuredContent: manualResult
2322
+ };
2323
+ }
2324
+ },
2325
+ {
2326
+ name: "helios_auth_ensure_login",
2327
+ title: "Ensure Helios Login",
2328
+ description: "Ensures a delegated Helios session exists, or starts a login flow and returns a ready-to-display approval prompt.",
2329
+ inputSchema: ensureLoginInputSchema,
2330
+ async execute(input) {
2331
+ const result = ensureLoginOutputSchema.parse(await service.ensureLogin(input));
2332
+ const structuredContent = result.status === "connected" ? result : {
2333
+ ...result,
2334
+ ...withManualLoginFields(result)
2335
+ };
2336
+ return {
2337
+ content: [
2338
+ {
2339
+ type: "text",
2340
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : result.message
2341
+ }
2342
+ ],
2343
+ structuredContent
2344
+ };
2345
+ }
2346
+ },
2347
+ {
2348
+ name: "helios_auth_poll_login",
2349
+ title: "Poll Helios Login",
2350
+ description: "Polls the device flow until the delegated Helios login is approved or rejected.",
2351
+ inputSchema: pollLoginInputSchema,
2352
+ async execute(input) {
2353
+ const result = pollLoginOutputSchema.parse(await service.pollLogin(input.deviceCode));
2354
+ return {
2355
+ content: [
2356
+ {
2357
+ type: "text",
2358
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : `Helios login is ${result.status}: ${result.message}`
2359
+ }
2360
+ ],
2361
+ structuredContent: result
2362
+ };
2363
+ }
2364
+ },
2365
+ {
2366
+ name: "helios_auth_whoami",
2367
+ title: "Helios Login Status",
2368
+ description: "Returns the delegated Helios session state currently stored by the MCP server.",
2369
+ inputSchema: import_zod5.z.object({}),
2370
+ async execute() {
2371
+ const result = agentSessionViewSchema.parse(await service.whoami());
2372
+ return {
2373
+ content: [
2374
+ {
2375
+ type: "text",
2376
+ text: result.connected ? `Connected to Helios as user ${result.ownerUserId}.` : "No delegated Helios session is connected."
2377
+ }
2378
+ ],
2379
+ structuredContent: result
2380
+ };
2381
+ }
2382
+ }
2383
+ ];
2384
+ }
2385
+ function createHeliosProviderToolDefinitions(service) {
2386
+ return [
2387
+ {
2388
+ name: "helios_provider_get_active",
2389
+ title: "Get Helios Active Provider",
2390
+ description: "Returns the provider currently pinned for this MCP session, if any.",
2391
+ inputSchema: import_zod5.z.object({}),
2392
+ async execute() {
2393
+ const result = activeProviderSchema.parse(await service.getActiveProvider());
2394
+ return {
2395
+ content: [
2396
+ {
2397
+ type: "text",
2398
+ text: result.configured ? `Helios active provider is ${result.provider}.` : "No Helios active provider is configured for this session."
2399
+ }
2400
+ ],
2401
+ structuredContent: result
2402
+ };
2403
+ }
2404
+ },
2405
+ {
2406
+ name: "helios_provider_set_active",
2407
+ title: "Set Helios Active Provider",
2408
+ description: "Pins the active provider for this MCP session so portfolio and trading tools can omit provider.",
2409
+ inputSchema: providerSetInputSchema,
2410
+ async execute(input) {
2411
+ const result = activeProviderSchema.parse(await service.setActiveProvider(input.provider));
2412
+ return {
2413
+ content: [
2414
+ {
2415
+ type: "text",
2416
+ text: `Helios active provider set to ${result.provider}.`
2417
+ }
2418
+ ],
2419
+ structuredContent: result
2420
+ };
2421
+ }
2422
+ }
2423
+ ];
2424
+ }
2425
+ function createHeliosAccountToolDefinitions(service) {
2426
+ return [
2427
+ {
2428
+ name: "helios_account_get_wallet_state",
2429
+ title: "Get Helios Wallet State",
2430
+ description: "Returns the current Hyperliquid wallet snapshot for the connected Helios account.",
2431
+ inputSchema: import_zod5.z.object({}),
2432
+ async execute() {
2433
+ const result = walletStateToolOutputSchema.parse(await service.getWalletState());
2434
+ const structuredContent = result.status === "connected" ? result : {
2435
+ ...result,
2436
+ ...withManualLoginFields(result)
2437
+ };
2438
+ return {
2439
+ content: [
2440
+ {
2441
+ type: "text",
2442
+ text: result.status === "connected" ? `Helios wallet state: available balance ${result.walletState.availableBalance}, account value ${result.walletState.accountValue}.` : result.message
2443
+ }
2444
+ ],
2445
+ structuredContent
2446
+ };
2447
+ }
2448
+ },
2449
+ {
2450
+ name: "helios_portfolio_get",
2451
+ title: "Get Helios Portfolio",
2452
+ description: "Returns a provider-specific portfolio snapshot. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2453
+ inputSchema: providerSelectionInputSchema,
2454
+ async execute(input) {
2455
+ const result = portfolioToolOutputSchema.parse(await service.getPortfolio(input));
2456
+ const structuredContent = result.status === "connected" ? result : {
2457
+ ...result,
2458
+ ...withManualLoginFields(result)
2459
+ };
2460
+ return {
2461
+ content: [
2462
+ {
2463
+ type: "text",
2464
+ text: result.status === "connected" ? buildPortfolioText(result.portfolio) : result.message
2465
+ }
2466
+ ],
2467
+ structuredContent
2468
+ };
2469
+ }
2470
+ }
2471
+ ];
2472
+ }
2473
+ function createHeliosLedgerToolDefinitions(service) {
2474
+ return [
2475
+ {
2476
+ name: "helios_positions_get_open",
2477
+ title: "Get Helios Open Positions",
2478
+ description: "Returns the current open Hyperliquid positions for the connected Helios account.",
2479
+ inputSchema: import_zod5.z.object({}),
2480
+ async execute() {
2481
+ const result = openPositionsToolOutputSchema.parse(await service.getOpenPositions());
2482
+ const structuredContent = result.status === "connected" ? result : {
2483
+ ...result,
2484
+ ...withManualLoginFields(result)
2485
+ };
2486
+ return {
2487
+ content: [
2488
+ {
2489
+ type: "text",
2490
+ text: result.status === "connected" ? `Helios open positions: ${result.openPositions.positions.length} positions, total unrealized PnL ${result.openPositions.totalUnrealizedPnl}.` : result.message
2491
+ }
2492
+ ],
2493
+ structuredContent
2494
+ };
2495
+ }
2496
+ },
2497
+ {
2498
+ name: "helios_ledger_get_fills",
2499
+ title: "Get Helios Ledger Fills",
2500
+ description: "Returns recent Hyperliquid fills/trade history for the connected Helios account.",
2501
+ inputSchema: ledgerFillsInputSchema,
2502
+ async execute(input) {
2503
+ const result = ledgerFillsToolOutputSchema.parse(await service.getFills(input));
2504
+ const structuredContent = result.status === "connected" ? result : {
2505
+ ...result,
2506
+ ...withManualLoginFields(result)
2507
+ };
2508
+ return {
2509
+ content: [
2510
+ {
2511
+ type: "text",
2512
+ text: result.status === "connected" ? `Helios ledger fills: ${result.fills.fills.length} fills from ${result.fills.window}${result.fills.hasMore ? ", more available" : ""}.` : result.message
2513
+ }
2514
+ ],
2515
+ structuredContent
2516
+ };
2517
+ }
2518
+ },
2519
+ {
2520
+ name: "helios_ledger_get_summary",
2521
+ title: "Get Helios Ledger Summary",
2522
+ description: "Returns realized PnL, fees, and win/loss metrics over a recent Hyperliquid fill window.",
2523
+ inputSchema: ledgerSummaryInputSchema,
2524
+ async execute(input) {
2525
+ const result = ledgerSummaryToolOutputSchema.parse(await service.getSummary(input));
2526
+ const structuredContent = result.status === "connected" ? result : {
2527
+ ...result,
2528
+ ...withManualLoginFields(result)
2529
+ };
2530
+ return {
2531
+ content: [
2532
+ {
2533
+ type: "text",
2534
+ 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
2535
+ }
2536
+ ],
2537
+ structuredContent
2538
+ };
2539
+ }
2540
+ }
2541
+ ];
2542
+ }
2543
+ function createHeliosMarketToolDefinitions(service) {
2544
+ return [
2545
+ {
2546
+ name: "helios_market_get_snapshot",
2547
+ title: "Get Helios Market Snapshot",
2548
+ description: "Returns a compact market snapshot for the selected, all, or explicitly requested symbols.",
2549
+ inputSchema: marketSnapshotInputSchema,
2550
+ async execute(input) {
2551
+ const result = marketSnapshotToolOutputSchema.parse(await service.getSnapshot(input));
2552
+ const structuredContent = result.status === "connected" ? result : {
2553
+ ...result,
2554
+ ...withManualLoginFields(result)
2555
+ };
2556
+ return {
2557
+ content: [
2558
+ {
2559
+ type: "text",
2560
+ 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
2561
+ }
2562
+ ],
2563
+ structuredContent
2564
+ };
2565
+ }
2566
+ },
2567
+ {
2568
+ name: "helios_market_get_snapshot_chunk",
2569
+ title: "Get Helios Market Snapshot Chunk",
2570
+ description: "Returns one chunk of the Helios market snapshot for batch analysis when the full snapshot is too large.",
2571
+ inputSchema: marketSnapshotChunkInputSchema,
2572
+ async execute(input) {
2573
+ const result = marketSnapshotChunkToolOutputSchema.parse(await service.getSnapshotChunk(input));
2574
+ const structuredContent = result.status === "connected" ? result : {
2575
+ ...result,
2576
+ ...withManualLoginFields(result)
2577
+ };
2578
+ return {
2579
+ content: [
2580
+ {
2581
+ type: "text",
2582
+ 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
2583
+ }
2584
+ ],
2585
+ structuredContent
2586
+ };
2587
+ }
2588
+ },
2589
+ {
2590
+ name: "helios_market_get_symbol_detail",
2591
+ title: "Get Helios Symbol Detail",
2592
+ description: "Returns expanded market detail for one symbol from the current Helios market snapshot.",
2593
+ inputSchema: marketSymbolDetailInputSchema,
2594
+ async execute(input) {
2595
+ const result = marketSymbolDetailToolOutputSchema.parse(await service.getSymbolDetail(input));
2596
+ const structuredContent = result.status === "connected" ? result : {
2597
+ ...result,
2598
+ ...withManualLoginFields(result)
2599
+ };
2600
+ return {
2601
+ content: [
2602
+ {
2603
+ type: "text",
2604
+ 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
2605
+ }
2606
+ ],
2607
+ structuredContent
2608
+ };
2609
+ }
2610
+ }
2611
+ ];
2612
+ }
2613
+ function createHeliosTradingToolDefinitions(service) {
2614
+ return [
2615
+ {
2616
+ name: "helios_trading_open",
2617
+ title: "Open Helios Position",
2618
+ description: "Submits a Helios OPEN trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2619
+ inputSchema: tradeActionInputSchema,
2620
+ async execute(input) {
2621
+ const result = tradeActionToolOutputSchema.parse(await service.open(input));
2622
+ return {
2623
+ content: [
2624
+ {
2625
+ type: "text",
2626
+ 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
2627
+ }
2628
+ ],
2629
+ structuredContent: result.status === "connected" ? result : {
2630
+ ...result,
2631
+ ...withManualLoginFields(result)
2632
+ }
2633
+ };
2634
+ }
2635
+ },
2636
+ {
2637
+ name: "helios_trading_dca",
2638
+ title: "DCA Helios Position",
2639
+ description: "Submits a Helios DCA trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2640
+ inputSchema: tradeActionInputSchema,
2641
+ async execute(input) {
2642
+ const result = tradeActionToolOutputSchema.parse(await service.dca(input));
2643
+ return {
2644
+ content: [
2645
+ {
2646
+ type: "text",
2647
+ 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
2648
+ }
2649
+ ],
2650
+ structuredContent: result.status === "connected" ? result : {
2651
+ ...result,
2652
+ ...withManualLoginFields(result)
2653
+ }
2654
+ };
2655
+ }
2656
+ },
2657
+ {
2658
+ name: "helios_trading_reverse",
2659
+ title: "Reverse Helios Position",
2660
+ description: "Submits a Helios REVERSE trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2661
+ inputSchema: tradeActionInputSchema,
2662
+ async execute(input) {
2663
+ const result = tradeActionToolOutputSchema.parse(await service.reverse(input));
2664
+ return {
2665
+ content: [
2666
+ {
2667
+ type: "text",
2668
+ 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
2669
+ }
2670
+ ],
2671
+ structuredContent: result.status === "connected" ? result : {
2672
+ ...result,
2673
+ ...withManualLoginFields(result)
2674
+ }
2675
+ };
2676
+ }
2677
+ },
2678
+ {
2679
+ name: "helios_trading_close",
2680
+ title: "Close Helios Position",
2681
+ 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.",
2682
+ inputSchema: closePositionInputSchema,
2683
+ async execute(input) {
2684
+ const result = closeTradeToolOutputSchema.parse(await service.close(input));
2685
+ return {
2686
+ content: [
2687
+ {
2688
+ type: "text",
2689
+ text: result.status === "connected" ? `Submitted Helios full close for ${result.closure.provider ?? input.provider} ${result.closure.symbol}.` : result.message
2690
+ }
2691
+ ],
2692
+ structuredContent: result.status === "connected" ? result : {
2693
+ ...result,
2694
+ ...withManualLoginFields(result)
2695
+ }
2696
+ };
2697
+ }
2698
+ },
2699
+ {
2700
+ name: "helios_positions_set_tp_sl",
2701
+ title: "Set Helios TP/SL",
2702
+ 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.",
2703
+ inputSchema: setTpSlInputSchema,
2704
+ async execute(input) {
2705
+ const result = setTpSlToolOutputSchema.parse(await service.setTpSl(input));
2706
+ return {
2707
+ content: [
2708
+ {
2709
+ type: "text",
2710
+ text: result.status === "connected" ? `Submitted ${result.protection.provider ?? input.provider} TP/SL protection update for ${result.protection.symbol}.` : result.message
2711
+ }
2712
+ ],
2713
+ structuredContent: result.status === "connected" ? result : {
2714
+ ...result,
2715
+ ...withManualLoginFields(result)
2716
+ }
2717
+ };
2718
+ }
2719
+ },
2720
+ {
2721
+ name: "helios_positions_delete_tp_sl",
2722
+ title: "Delete Helios TP/SL",
2723
+ 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.",
2724
+ inputSchema: deleteTpSlInputSchema,
2725
+ async execute(input) {
2726
+ const result = deleteTpSlToolOutputSchema.parse(await service.deleteTpSl(input));
2727
+ return {
2728
+ content: [
2729
+ {
2730
+ type: "text",
2731
+ text: result.status === "connected" ? `Deleted ${result.deletion.provider ?? input.provider} TP/SL order ${result.deletion.orderId} for ${result.deletion.symbol}.` : result.message
2732
+ }
2733
+ ],
2734
+ structuredContent: result.status === "connected" ? result : {
2735
+ ...result,
2736
+ ...withManualLoginFields(result)
2737
+ }
2738
+ };
2739
+ }
2740
+ },
2741
+ {
2742
+ name: "helios_orders_get_open",
2743
+ title: "Get Helios Open Orders",
2744
+ description: "Lists the currently open Hyperliquid orders for the connected account.",
2745
+ inputSchema: import_zod5.z.object({}),
2746
+ async execute() {
2747
+ const result = openOrdersToolOutputSchema.parse(await service.getOpenOrders());
2748
+ return {
2749
+ content: [
2750
+ {
2751
+ type: "text",
2752
+ text: result.status === "connected" ? `Retrieved ${result.orders.length} open Helios orders.` : result.message
2753
+ }
2754
+ ],
2755
+ structuredContent: result.status === "connected" ? result : {
2756
+ ...result,
2757
+ ...withManualLoginFields(result)
2758
+ }
2759
+ };
2760
+ }
2761
+ },
2762
+ {
2763
+ name: "helios_orders_cancel",
2764
+ title: "Cancel Helios Order",
2765
+ description: "Cancels an open Hyperliquid order by symbol and order id.",
2766
+ inputSchema: cancelOrderInputSchema,
2767
+ async execute(input) {
2768
+ const result = cancelOrderToolOutputSchema.parse(await service.cancelOrder(input));
2769
+ return {
2770
+ content: [
2771
+ {
2772
+ type: "text",
2773
+ text: result.status === "connected" ? `Cancelled Helios order ${result.cancellation.oid} for ${result.cancellation.symbol}.` : result.message
2774
+ }
2775
+ ],
2776
+ structuredContent: result.status === "connected" ? result : {
2777
+ ...result,
2778
+ ...withManualLoginFields(result)
2779
+ }
2780
+ };
2781
+ }
2782
+ }
2783
+ ];
2784
+ }
2785
+ function withManualLoginFields(result) {
2786
+ return {
2787
+ actionRequired: true,
2788
+ loginUrl: result.verificationUriComplete,
2789
+ nextStep: "Open the login URL in your browser, approve Helios access, then ask me to continue."
2790
+ };
2791
+ }
2792
+ function buildPortfolioText(result) {
2793
+ return `Helios Hyperliquid portfolio: ${result.positions.length} positions, available balance ${result.availableBalance}, total balance ${result.totalBalance}.`;
2794
+ }
2795
+ function buildManualLoginText(result) {
2796
+ return `Log in to Helios by opening this URL in your browser:
2797
+
2798
+ ${result.verificationUriComplete}
2799
+
2800
+ User code: ${result.userCode}
2801
+
2802
+ After approving access, ask me to continue and I will finish connecting.`;
2803
+ }
2804
+
2805
+ // src/server.ts
2806
+ async function createHeliosAgentMcpServer(options) {
2807
+ if (!options.identityServiceUrl) {
2808
+ throw new Error("identityServiceUrl is required");
2809
+ }
2810
+ if (!options.dataBridgeUrl) {
2811
+ throw new Error("dataBridgeUrl is required");
2812
+ }
2813
+ const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
2814
+ const server = new McpServer({
2815
+ name: "helios",
2816
+ version: "0.1.0"
2817
+ });
2818
+ const sessionStore = options.sessionStore ?? new FileAgentSessionStore(options.sessionPath ?? getDefaultHeliosAgentMcpSessionPath());
2819
+ const client = new HeliosAgentAuthClient({
2820
+ baseUrl: options.identityServiceUrl,
2821
+ fetch: options.fetch
2822
+ });
2823
+ const dataBridgeClient = new HeliosAgentDataBridgeClient({
2824
+ baseUrl: options.dataBridgeUrl,
2825
+ fetch: options.fetch
2826
+ });
2827
+ const authService = new HeliosAgentMcpAuthService({
2828
+ client,
2829
+ sessionStore,
2830
+ refreshWindowMs: options.refreshWindowMs,
2831
+ deviceLogin: !options.hosted
2832
+ });
2833
+ const providerService = new HeliosAgentMcpProviderService({
2834
+ sessionStore
2835
+ });
2836
+ const accountService = new HeliosAgentMcpAccountService({
2837
+ authService,
2838
+ dataBridgeClient,
2839
+ providerService
2840
+ });
2841
+ const marketService = new HeliosAgentMcpMarketService({
2842
+ authService,
2843
+ dataBridgeClient
2844
+ });
2845
+ const ledgerService = new HeliosAgentMcpLedgerService({
2846
+ authService,
2847
+ dataBridgeClient
2848
+ });
2849
+ const tradingService = new HeliosAgentMcpTradingService({
2850
+ authService,
2851
+ dataBridgeClient,
2852
+ providerService
2853
+ });
2854
+ const docsService = new HeliosAgentMcpDocsService({
2855
+ docsRoot: options.docsRoot ?? getDefaultHeliosAgentMcpDocsRoot()
2856
+ });
2857
+ const docsTools = createHeliosDocsToolDefinitions(docsService);
2858
+ const authTools = createHeliosAuthToolDefinitions(authService);
2859
+ const providerTools = createHeliosProviderToolDefinitions(providerService);
2860
+ const accountTools = createHeliosAccountToolDefinitions(accountService);
2861
+ const ledgerTools = createHeliosLedgerToolDefinitions(ledgerService);
2862
+ const marketTools = createHeliosMarketToolDefinitions(marketService);
2863
+ const tradingTools = createHeliosTradingToolDefinitions(tradingService);
2864
+ registerTool(server, docsTools[0]);
2865
+ registerTool(server, docsTools[1]);
2866
+ if (!options.hosted) {
2867
+ registerTool(server, authTools[0]);
2868
+ registerTool(server, authTools[1]);
2869
+ registerTool(server, authTools[2]);
2870
+ }
2871
+ registerTool(server, authTools[3]);
2872
+ registerTool(server, providerTools[0]);
2873
+ registerTool(server, providerTools[1]);
2874
+ registerTool(server, accountTools[0]);
2875
+ registerTool(server, accountTools[1]);
2876
+ registerTool(server, ledgerTools[0]);
2877
+ registerTool(server, ledgerTools[1]);
2878
+ registerTool(server, ledgerTools[2]);
2879
+ registerTool(server, marketTools[0]);
2880
+ registerTool(server, marketTools[1]);
2881
+ registerTool(server, marketTools[2]);
2882
+ registerTool(server, tradingTools[0]);
2883
+ registerTool(server, tradingTools[1]);
2884
+ registerTool(server, tradingTools[2]);
2885
+ registerTool(server, tradingTools[3]);
2886
+ registerTool(server, tradingTools[4]);
2887
+ registerTool(server, tradingTools[5]);
2888
+ registerTool(server, tradingTools[6]);
2889
+ registerTool(server, tradingTools[7]);
2890
+ return {
2891
+ server,
2892
+ authService,
2893
+ providerService,
2894
+ accountService,
2895
+ docsService,
2896
+ ledgerService,
2897
+ marketService,
2898
+ tradingService,
2899
+ sessionStore
2900
+ };
2901
+ }
2902
+ var ACTS_ON_ACCOUNT = /^helios_(trading_|positions_set_tp_sl|positions_delete_tp_sl|orders_cancel)/;
2903
+ var CHANGES_SESSION = /^helios_(auth_start_login|auth_ensure_login|auth_poll_login|provider_set_active)$/;
2904
+ function toolAnnotations(name) {
2905
+ if (ACTS_ON_ACCOUNT.test(name)) return { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
2906
+ if (CHANGES_SESSION.test(name)) return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
2907
+ return { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
2908
+ }
2909
+ function registerTool(server, tool) {
2910
+ server.registerTool(
2911
+ tool.name,
2912
+ {
2913
+ title: tool.title,
2914
+ description: tool.description,
2915
+ inputSchema: tool.inputSchema,
2916
+ annotations: { title: tool.title, ...toolAnnotations(tool.name) }
2917
+ },
2918
+ async (input) => {
2919
+ const result = await tool.execute(tool.inputSchema.parse(input));
2920
+ return {
2921
+ ...result,
2922
+ structuredContent: result.structuredContent
2923
+ };
2924
+ }
2925
+ );
2926
+ }
2927
+
2928
+ // src/cli.ts
2929
+ async function main() {
2930
+ const identityServiceUrl = process.env.HELIOS_IDENTITY_SERVICE_URL || "https://helios.pgn.io";
2931
+ const dataBridgeUrl = process.env.HELIOS_DATA_BRIDGE_URL || "https://helios.pgn.io";
2932
+ const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
2933
+ const { server } = await createHeliosAgentMcpServer({
2934
+ identityServiceUrl,
2935
+ dataBridgeUrl,
2936
+ sessionPath: process.env.HELIOS_AGENT_MCP_SESSION_PATH
2937
+ });
2938
+ const transport = new StdioServerTransport();
2939
+ await server.connect(transport);
2940
+ }
2941
+ main().catch((error) => {
2942
+ const message = error instanceof Error ? error.stack ?? error.message : String(error);
2943
+ process.stderr.write(`${message}
2944
+ `);
2945
+ process.exitCode = 1;
2946
+ });