@pgnio/helios-mcp 0.0.0-stage → 0.2.1

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 (70) hide show
  1. package/README.md +44 -2
  2. package/dist/chunk-EIAUO3XE.mjs +2955 -0
  3. package/dist/chunk-NCF7ASJB.mjs +2986 -0
  4. package/dist/chunk-NWGWXYTS.mjs +2964 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.d.ts +1 -0
  7. package/dist/cli.js +2968 -0
  8. package/dist/cli.mjs +24 -0
  9. package/dist/index.d.mts +2138 -0
  10. package/dist/index.d.ts +2138 -0
  11. package/dist/index.js +3043 -0
  12. package/dist/index.mjs +52 -0
  13. package/docs/ai-agent-indicators/00_index.txt +210 -0
  14. package/docs/ai-agent-indicators/activity_ratio.txt +166 -0
  15. package/docs/ai-agent-indicators/activity_zscore.txt +166 -0
  16. package/docs/ai-agent-indicators/bayesian_overbought.txt +134 -0
  17. package/docs/ai-agent-indicators/directional_efficiency.txt +134 -0
  18. package/docs/ai-agent-indicators/hfi.txt +172 -0
  19. package/docs/ai-agent-indicators/hfi_weights.txt +124 -0
  20. package/docs/ai-agent-indicators/hmi.txt +305 -0
  21. package/docs/ai-agent-indicators/hmi_velocity.txt +155 -0
  22. package/docs/ai-agent-indicators/hurst_exponent.txt +136 -0
  23. package/docs/ai-agent-indicators/macd_divergence.txt +133 -0
  24. package/docs/ai-agent-indicators/macd_histogram.txt +145 -0
  25. package/docs/ai-agent-indicators/macd_signal.txt +119 -0
  26. package/docs/ai-agent-indicators/market_structure.txt +201 -0
  27. package/docs/ai-agent-indicators/poc.txt +131 -0
  28. package/docs/ai-agent-indicators/poc_distance.txt +129 -0
  29. package/docs/ai-agent-indicators/regime.txt +225 -0
  30. package/docs/ai-agent-indicators/rsi_divergence.txt +145 -0
  31. package/docs/ai-agent-indicators/squeeze_duration.txt +115 -0
  32. package/docs/ai-agent-indicators/squeeze_energy.txt +128 -0
  33. package/docs/ai-agent-indicators/support_resistance.txt +169 -0
  34. package/docs/ai-agent-indicators/tf_alignment.txt +165 -0
  35. package/docs/ai-agent-indicators/trend_interpretation.txt +98 -0
  36. package/docs/ai-agent-indicators/trend_strength.txt +134 -0
  37. package/docs/ai-agent-indicators/value_area_position.txt +142 -0
  38. package/docs/ai-agent-indicators/volatility_clustering.txt +160 -0
  39. package/docs/ai-agent-indicators/volatility_squeeze.txt +169 -0
  40. package/docs/ai-agent-indicators/volume_change_point.txt +151 -0
  41. package/docs/ai-agent-indicators/vwap.txt +133 -0
  42. package/docs/ai-agent-indicators/vwap_zscore.txt +154 -0
  43. package/docs/ai-agent-indicators/weighted_rsi.txt +148 -0
  44. package/docs/ai-agent-mcp/00_index.txt +110 -0
  45. package/docs/ai-agent-mcp/01_auth/00_overview.txt +51 -0
  46. package/docs/ai-agent-mcp/01_auth/01_tools.txt +94 -0
  47. package/docs/ai-agent-mcp/01_auth/02_data_contracts.txt +38 -0
  48. package/docs/ai-agent-mcp/01_auth/03_decision_rules.txt +25 -0
  49. package/docs/ai-agent-mcp/01_auth/04_failures_and_recovery.txt +46 -0
  50. package/docs/ai-agent-mcp/02_account/00_overview.txt +29 -0
  51. package/docs/ai-agent-mcp/02_account/01_tools.txt +67 -0
  52. package/docs/ai-agent-mcp/02_account/02_data_contracts.txt +34 -0
  53. package/docs/ai-agent-mcp/02_account/03_decision_rules.txt +17 -0
  54. package/docs/ai-agent-mcp/02_account/04_failures_and_recovery.txt +17 -0
  55. package/docs/ai-agent-mcp/03_market/00_overview.txt +27 -0
  56. package/docs/ai-agent-mcp/03_market/01_tools.txt +102 -0
  57. package/docs/ai-agent-mcp/03_market/02_data_contracts.txt +39 -0
  58. package/docs/ai-agent-mcp/03_market/03_decision_rules.txt +22 -0
  59. package/docs/ai-agent-mcp/03_market/04_failures_and_recovery.txt +18 -0
  60. package/docs/ai-agent-mcp/04_trading/00_overview.txt +25 -0
  61. package/docs/ai-agent-mcp/04_trading/01_tools.txt +123 -0
  62. package/docs/ai-agent-mcp/04_trading/02_data_contracts.txt +42 -0
  63. package/docs/ai-agent-mcp/04_trading/03_decision_rules.txt +30 -0
  64. package/docs/ai-agent-mcp/04_trading/04_failures_and_recovery.txt +25 -0
  65. package/docs/ai-agent-mcp/05_ledger/00_overview.txt +31 -0
  66. package/docs/ai-agent-mcp/05_ledger/01_tools.txt +80 -0
  67. package/docs/ai-agent-mcp/05_ledger/02_data_contracts.txt +46 -0
  68. package/docs/ai-agent-mcp/05_ledger/03_decision_rules.txt +44 -0
  69. package/docs/ai-agent-mcp/05_ledger/04_failures_and_recovery.txt +24 -0
  70. package/package.json +66 -3
package/dist/cli.js ADDED
@@ -0,0 +1,2968 @@
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
+ const polled = await this.pollLogin(pendingLogin.deviceCode).catch(() => null);
924
+ if (polled?.status === "connected") return polled;
925
+ if (polled?.status !== "rejected" && polled?.status !== "expired") {
926
+ return {
927
+ ...pendingLogin,
928
+ connected: false,
929
+ message: formatHeliosLoginPrompt(pendingLogin)
930
+ };
931
+ }
932
+ }
933
+ const started = await this.startLogin({
934
+ clientName: options.clientName ?? "Helios MCP",
935
+ scope: requestedScope,
936
+ constraints: options.constraints
937
+ });
938
+ return {
939
+ ...started,
940
+ connected: false,
941
+ message: formatHeliosLoginPrompt(started)
942
+ };
943
+ }
944
+ /** Polls the given login, or the stored pending one when no device code is given. */
945
+ async pollLogin(deviceCode) {
946
+ if (!deviceCode) {
947
+ const pending = await this.sessionStore.getPendingLogin();
948
+ if (!pending) {
949
+ const session = await this.getValidSession();
950
+ if (session) return { ...sanitizeAgentSession(session), connected: true, status: "connected" };
951
+ return {
952
+ status: "failed",
953
+ connected: false,
954
+ message: "No Helios login is in progress. Call helios_auth_ensure_login to start one."
955
+ };
956
+ }
957
+ deviceCode = pending.deviceCode;
958
+ } else {
959
+ const pending = await this.sessionStore.getPendingLogin();
960
+ if (pending && pending.userCode.toUpperCase() === deviceCode.trim().toUpperCase()) deviceCode = pending.deviceCode;
961
+ }
962
+ try {
963
+ const response = await this.client.exchangeDeviceCode(deviceCode);
964
+ const session = createStoredAgentSession(response, this.now());
965
+ await this.sessionStore.setSession(session);
966
+ await this.sessionStore.clearPendingLogin();
967
+ return {
968
+ ...sanitizeAgentSession(session),
969
+ connected: true,
970
+ status: "connected"
971
+ };
972
+ } catch (error) {
973
+ if (isHeliosAgentApiError(error)) {
974
+ if (error.code === "authorization_pending") {
975
+ return {
976
+ status: "pending",
977
+ connected: false,
978
+ message: error.message
979
+ };
980
+ }
981
+ if (error.code === "access_denied") {
982
+ await this.clearPendingLoginIfMatches(deviceCode);
983
+ return {
984
+ status: "rejected",
985
+ connected: false,
986
+ message: error.message
987
+ };
988
+ }
989
+ if (error.code === "expired_token") {
990
+ await this.clearPendingLoginIfMatches(deviceCode);
991
+ return {
992
+ status: "expired",
993
+ connected: false,
994
+ message: error.message
995
+ };
996
+ }
997
+ return {
998
+ status: "failed",
999
+ connected: false,
1000
+ message: error.message
1001
+ };
1002
+ }
1003
+ return {
1004
+ status: "failed",
1005
+ connected: false,
1006
+ message: error instanceof Error ? error.message : "Unexpected Helios login error"
1007
+ };
1008
+ }
1009
+ }
1010
+ async whoami() {
1011
+ const session = await this.getValidSession();
1012
+ return sanitizeAgentSession(session);
1013
+ }
1014
+ async getAccessToken() {
1015
+ const session = await this.getValidSession();
1016
+ return session?.accessToken ?? null;
1017
+ }
1018
+ async requireSession() {
1019
+ const session = await this.getValidSession();
1020
+ if (!session) {
1021
+ throw new Error("No Helios delegated agent session is connected");
1022
+ }
1023
+ return session;
1024
+ }
1025
+ async getValidSession() {
1026
+ const session = await this.sessionStore.getSession();
1027
+ if (!session) {
1028
+ return null;
1029
+ }
1030
+ if (!shouldRefreshAgentSession(session, this.now(), this.refreshWindowMs)) {
1031
+ return session;
1032
+ }
1033
+ return this.refreshStoredSession(session);
1034
+ }
1035
+ async refreshStoredSession(session) {
1036
+ try {
1037
+ const refreshed = await this.client.refreshSession(session.refreshToken);
1038
+ const nextSession = createStoredAgentSession(refreshed, this.now());
1039
+ await this.sessionStore.setSession(nextSession);
1040
+ return nextSession;
1041
+ } catch (error) {
1042
+ if (isHeliosAgentApiError(error) && error.code === "invalid_grant") {
1043
+ await this.sessionStore.clearSession();
1044
+ await this.sessionStore.clearPendingLogin();
1045
+ return null;
1046
+ }
1047
+ throw error;
1048
+ }
1049
+ }
1050
+ async getPendingLogin(options) {
1051
+ const pendingLogin = await this.sessionStore.getPendingLogin();
1052
+ if (!pendingLogin) {
1053
+ return null;
1054
+ }
1055
+ const expiresAt = new Date(pendingLogin.startedAt).getTime() + pendingLogin.expiresInSeconds * 1e3;
1056
+ if (this.now().getTime() >= expiresAt) {
1057
+ await this.sessionStore.clearPendingLogin();
1058
+ return null;
1059
+ }
1060
+ if (!isPendingLoginCompatible(pendingLogin, options.requestedScope, options.requestedConstraints)) {
1061
+ return null;
1062
+ }
1063
+ return pendingLogin;
1064
+ }
1065
+ async clearPendingLoginIfMatches(deviceCode) {
1066
+ const pendingLogin = await this.sessionStore.getPendingLogin();
1067
+ if (pendingLogin?.deviceCode === deviceCode) {
1068
+ await this.sessionStore.clearPendingLogin();
1069
+ }
1070
+ }
1071
+ };
1072
+ async function retryAfterUnauthorizedRefresh(options) {
1073
+ const refreshedSession = await options.authService.refreshSessionAfterUnauthorized(options.error);
1074
+ if (!refreshedSession) {
1075
+ return options.authService.invalidateIfUnauthorized(options.error, options.loginOptions);
1076
+ }
1077
+ try {
1078
+ return await options.retry(refreshedSession.accessToken);
1079
+ } catch (retryError) {
1080
+ const relogin = await options.authService.invalidateIfUnauthorized(retryError, options.loginOptions);
1081
+ if (relogin) {
1082
+ return relogin;
1083
+ }
1084
+ throw retryError;
1085
+ }
1086
+ }
1087
+ function formatHeliosLoginPrompt(result) {
1088
+ return `Log in to Helios by opening this URL in your browser:
1089
+
1090
+ ${result.verificationUriComplete}
1091
+
1092
+ User code: ${result.userCode}
1093
+
1094
+ Requested scopes: ${result.requestedScope.join(", ")}
1095
+
1096
+ After approving access, call helios_auth_ensure_login (or helios_auth_poll_login) again to finish connecting.`;
1097
+ }
1098
+ function isPendingLoginCompatible(pendingLogin, requestedScope, requestedConstraints) {
1099
+ const pendingScope = new Set(pendingLogin.requestedScope);
1100
+ const scopeCompatible = requestedScope.every((scope) => pendingScope.has(scope));
1101
+ if (!scopeCompatible) {
1102
+ return false;
1103
+ }
1104
+ return Object.keys(requestedConstraints ?? {}).length === 0;
1105
+ }
1106
+
1107
+ // src/account-service.ts
1108
+ var HeliosAgentMcpAccountService = class {
1109
+ constructor(options) {
1110
+ __publicField(this, "authService");
1111
+ __publicField(this, "dataBridgeClient");
1112
+ __publicField(this, "providerService");
1113
+ this.authService = options.authService;
1114
+ this.dataBridgeClient = options.dataBridgeClient;
1115
+ this.providerService = options.providerService;
1116
+ }
1117
+ async getWalletState() {
1118
+ const loginOptions = this.accountReadOptions();
1119
+ const login = await this.authService.ensureLogin(loginOptions);
1120
+ if (login.status !== "connected") {
1121
+ return {
1122
+ ...login,
1123
+ status: "pending",
1124
+ connected: false
1125
+ };
1126
+ }
1127
+ const session = await this.authService.requireSession();
1128
+ try {
1129
+ const walletState = await this.dataBridgeClient.getWalletState(session.accessToken);
1130
+ return {
1131
+ status: "connected",
1132
+ connected: true,
1133
+ walletState
1134
+ };
1135
+ } catch (error) {
1136
+ const recovery = await retryAfterUnauthorizedRefresh({
1137
+ authService: this.authService,
1138
+ error,
1139
+ loginOptions,
1140
+ retry: async (accessToken) => {
1141
+ const walletState = await this.dataBridgeClient.getWalletState(accessToken);
1142
+ return {
1143
+ status: "connected",
1144
+ connected: true,
1145
+ walletState
1146
+ };
1147
+ }
1148
+ });
1149
+ if (recovery) {
1150
+ return recovery;
1151
+ }
1152
+ throw error;
1153
+ }
1154
+ }
1155
+ async getPortfolio(input = {}) {
1156
+ const loginOptions = this.accountReadOptions();
1157
+ const login = await this.authService.ensureLogin(loginOptions);
1158
+ if (login.status !== "connected") {
1159
+ return {
1160
+ ...login,
1161
+ status: "pending",
1162
+ connected: false
1163
+ };
1164
+ }
1165
+ const session = await this.authService.requireSession();
1166
+ try {
1167
+ const provider = await this.providerService.resolveProvider(input.provider);
1168
+ const portfolio = await this.dataBridgeClient.getPortfolio(session.accessToken, { provider });
1169
+ return {
1170
+ status: "connected",
1171
+ connected: true,
1172
+ portfolio
1173
+ };
1174
+ } catch (error) {
1175
+ const recovery = await retryAfterUnauthorizedRefresh({
1176
+ authService: this.authService,
1177
+ error,
1178
+ loginOptions,
1179
+ retry: async (accessToken) => {
1180
+ const provider = await this.providerService.resolveProvider(input.provider);
1181
+ const portfolio = await this.dataBridgeClient.getPortfolio(accessToken, { provider });
1182
+ return {
1183
+ status: "connected",
1184
+ connected: true,
1185
+ portfolio
1186
+ };
1187
+ }
1188
+ });
1189
+ if (recovery) {
1190
+ return recovery;
1191
+ }
1192
+ throw error;
1193
+ }
1194
+ }
1195
+ accountReadOptions() {
1196
+ return {
1197
+ clientName: "Helios MCP",
1198
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1199
+ };
1200
+ }
1201
+ };
1202
+
1203
+ // src/docs-service.ts
1204
+ var import_node_fs = require("fs");
1205
+ var import_node_path = __toESM(require("path"));
1206
+ var HeliosAgentMcpDocsService = class {
1207
+ constructor(options) {
1208
+ __publicField(this, "docsRoot");
1209
+ this.docsRoot = options.docsRoot;
1210
+ }
1211
+ async getIndex() {
1212
+ const documents = listDocumentPaths(this.docsRoot).map((documentPath) => this.readDocumentMetadata(documentPath));
1213
+ return {
1214
+ root: "docs",
1215
+ documents
1216
+ };
1217
+ }
1218
+ async getDocument(input) {
1219
+ const documentPath = resolveDocumentPath(this.docsRoot, input.path);
1220
+ const body = (0, import_node_fs.readFileSync)(documentPath, "utf8");
1221
+ const stats = (0, import_node_fs.statSync)(documentPath);
1222
+ const relativePath = toPosixPath(import_node_path.default.relative(this.docsRoot, documentPath));
1223
+ return {
1224
+ path: relativePath,
1225
+ section: getDocumentSection(relativePath),
1226
+ title: extractDocumentTitle(body, relativePath),
1227
+ body,
1228
+ bytes: stats.size
1229
+ };
1230
+ }
1231
+ readDocumentMetadata(documentPath) {
1232
+ const body = (0, import_node_fs.readFileSync)(documentPath, "utf8");
1233
+ const stats = (0, import_node_fs.statSync)(documentPath);
1234
+ const relativePath = toPosixPath(import_node_path.default.relative(this.docsRoot, documentPath));
1235
+ return {
1236
+ path: relativePath,
1237
+ section: getDocumentSection(relativePath),
1238
+ title: extractDocumentTitle(body, relativePath),
1239
+ bytes: stats.size
1240
+ };
1241
+ }
1242
+ };
1243
+ function getDefaultHeliosAgentMcpDocsRoot() {
1244
+ return import_node_path.default.resolve(__dirname, "..", "docs");
1245
+ }
1246
+ function listDocumentPaths(root) {
1247
+ return walk(root).filter((filePath) => filePath.endsWith(".txt")).sort((left, right) => left.localeCompare(right));
1248
+ }
1249
+ function walk(currentPath) {
1250
+ const entries = (0, import_node_fs.readdirSync)(currentPath, { withFileTypes: true });
1251
+ const files = [];
1252
+ for (const entry of entries) {
1253
+ const nextPath = import_node_path.default.join(currentPath, entry.name);
1254
+ if (entry.isDirectory()) {
1255
+ files.push(...walk(nextPath));
1256
+ continue;
1257
+ }
1258
+ if (entry.isFile()) {
1259
+ files.push(nextPath);
1260
+ }
1261
+ }
1262
+ return files;
1263
+ }
1264
+ function resolveDocumentPath(root, relativeDocumentPath) {
1265
+ const normalizedPath = relativeDocumentPath.replace(/\\/g, "/").replace(/^\/+/, "");
1266
+ const resolvedPath = import_node_path.default.resolve(root, normalizedPath);
1267
+ const relativePath = import_node_path.default.relative(root, resolvedPath);
1268
+ if (!normalizedPath) {
1269
+ throw new Error("Document path is required.");
1270
+ }
1271
+ if (import_node_path.default.isAbsolute(normalizedPath) || relativePath.startsWith("..") || import_node_path.default.isAbsolute(relativePath)) {
1272
+ throw new Error(`Document path "${relativeDocumentPath}" is outside the docs root.`);
1273
+ }
1274
+ if (!resolvedPath.endsWith(".txt")) {
1275
+ throw new Error(`Document path "${relativeDocumentPath}" must point to a .txt file.`);
1276
+ }
1277
+ return resolvedPath;
1278
+ }
1279
+ function extractDocumentTitle(body, relativePath) {
1280
+ const lines = body.split(/\r?\n/);
1281
+ for (const line of lines) {
1282
+ const trimmed = line.trim();
1283
+ if (!trimmed || /^=+$/.test(trimmed)) {
1284
+ continue;
1285
+ }
1286
+ if (trimmed.startsWith("TITLE:")) {
1287
+ return trimmed.slice("TITLE:".length).trim();
1288
+ }
1289
+ return trimmed;
1290
+ }
1291
+ return import_node_path.default.basename(relativePath, ".txt");
1292
+ }
1293
+ function getDocumentSection(relativePath) {
1294
+ return relativePath.split("/")[0] ?? "docs";
1295
+ }
1296
+ function toPosixPath(value) {
1297
+ return value.split(import_node_path.default.sep).join("/");
1298
+ }
1299
+
1300
+ // src/ledger-service.ts
1301
+ var HeliosAgentMcpLedgerService = class {
1302
+ constructor(options) {
1303
+ __publicField(this, "authService");
1304
+ __publicField(this, "dataBridgeClient");
1305
+ this.authService = options.authService;
1306
+ this.dataBridgeClient = options.dataBridgeClient;
1307
+ }
1308
+ async getOpenPositions() {
1309
+ const loginOptions = this.accountReadOptions();
1310
+ const login = await this.authService.ensureLogin(loginOptions);
1311
+ if (login.status !== "connected") {
1312
+ return asPending(login);
1313
+ }
1314
+ const session = await this.authService.requireSession();
1315
+ try {
1316
+ const openPositions = await this.dataBridgeClient.getOpenPositions(session.accessToken);
1317
+ return {
1318
+ status: "connected",
1319
+ connected: true,
1320
+ openPositions
1321
+ };
1322
+ } catch (error) {
1323
+ const recovery = await retryAfterUnauthorizedRefresh({
1324
+ authService: this.authService,
1325
+ error,
1326
+ loginOptions,
1327
+ retry: async (accessToken) => {
1328
+ const openPositions = await this.dataBridgeClient.getOpenPositions(accessToken);
1329
+ return {
1330
+ status: "connected",
1331
+ connected: true,
1332
+ openPositions
1333
+ };
1334
+ }
1335
+ });
1336
+ if (recovery) {
1337
+ return recovery;
1338
+ }
1339
+ throw error;
1340
+ }
1341
+ }
1342
+ async getFills(input = {}) {
1343
+ const loginOptions = this.accountReadOptions();
1344
+ const login = await this.authService.ensureLogin(loginOptions);
1345
+ if (login.status !== "connected") {
1346
+ return asPending(login);
1347
+ }
1348
+ const session = await this.authService.requireSession();
1349
+ try {
1350
+ const fills = await this.dataBridgeClient.getLedgerFills(session.accessToken, input);
1351
+ return {
1352
+ status: "connected",
1353
+ connected: true,
1354
+ fills
1355
+ };
1356
+ } catch (error) {
1357
+ const recovery = await retryAfterUnauthorizedRefresh({
1358
+ authService: this.authService,
1359
+ error,
1360
+ loginOptions,
1361
+ retry: async (accessToken) => {
1362
+ const fills = await this.dataBridgeClient.getLedgerFills(accessToken, input);
1363
+ return {
1364
+ status: "connected",
1365
+ connected: true,
1366
+ fills
1367
+ };
1368
+ }
1369
+ });
1370
+ if (recovery) {
1371
+ return recovery;
1372
+ }
1373
+ throw error;
1374
+ }
1375
+ }
1376
+ async getSummary(input = {}) {
1377
+ const loginOptions = this.accountReadOptions();
1378
+ const login = await this.authService.ensureLogin(loginOptions);
1379
+ if (login.status !== "connected") {
1380
+ return asPending(login);
1381
+ }
1382
+ const session = await this.authService.requireSession();
1383
+ try {
1384
+ const summary = await this.dataBridgeClient.getLedgerSummary(session.accessToken, input);
1385
+ return {
1386
+ status: "connected",
1387
+ connected: true,
1388
+ summary
1389
+ };
1390
+ } catch (error) {
1391
+ const recovery = await retryAfterUnauthorizedRefresh({
1392
+ authService: this.authService,
1393
+ error,
1394
+ loginOptions,
1395
+ retry: async (accessToken) => {
1396
+ const summary = await this.dataBridgeClient.getLedgerSummary(accessToken, input);
1397
+ return {
1398
+ status: "connected",
1399
+ connected: true,
1400
+ summary
1401
+ };
1402
+ }
1403
+ });
1404
+ if (recovery) {
1405
+ return recovery;
1406
+ }
1407
+ throw error;
1408
+ }
1409
+ }
1410
+ accountReadOptions() {
1411
+ return {
1412
+ clientName: "Helios MCP",
1413
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1414
+ };
1415
+ }
1416
+ };
1417
+ function asPending(login) {
1418
+ return {
1419
+ ...login,
1420
+ status: "pending",
1421
+ connected: false
1422
+ };
1423
+ }
1424
+
1425
+ // src/market-service.ts
1426
+ var HeliosAgentMcpMarketService = class {
1427
+ constructor(options) {
1428
+ __publicField(this, "authService");
1429
+ __publicField(this, "dataBridgeClient");
1430
+ this.authService = options.authService;
1431
+ this.dataBridgeClient = options.dataBridgeClient;
1432
+ }
1433
+ async getSnapshot(input = {}) {
1434
+ const loginOptions = {
1435
+ clientName: "Helios MCP",
1436
+ scope: [AGENT_SCOPES.MARKET_READ]
1437
+ };
1438
+ const login = await this.authService.ensureLogin(loginOptions);
1439
+ if (login.status !== "connected") {
1440
+ return {
1441
+ ...login,
1442
+ status: "pending",
1443
+ connected: false
1444
+ };
1445
+ }
1446
+ const session = await this.authService.requireSession();
1447
+ try {
1448
+ const snapshot = await this.dataBridgeClient.getMarketSnapshot(session.accessToken, input);
1449
+ return {
1450
+ status: "connected",
1451
+ connected: true,
1452
+ snapshot
1453
+ };
1454
+ } catch (error) {
1455
+ const recovery = await retryAfterUnauthorizedRefresh({
1456
+ authService: this.authService,
1457
+ error,
1458
+ loginOptions,
1459
+ retry: async (accessToken) => {
1460
+ const snapshot = await this.dataBridgeClient.getMarketSnapshot(accessToken, input);
1461
+ return {
1462
+ status: "connected",
1463
+ connected: true,
1464
+ snapshot
1465
+ };
1466
+ }
1467
+ });
1468
+ if (recovery) {
1469
+ return recovery;
1470
+ }
1471
+ throw error;
1472
+ }
1473
+ }
1474
+ async getSnapshotChunk(input = {}) {
1475
+ const loginOptions = {
1476
+ clientName: "Helios MCP",
1477
+ scope: [AGENT_SCOPES.MARKET_READ]
1478
+ };
1479
+ const login = await this.authService.ensureLogin(loginOptions);
1480
+ if (login.status !== "connected") {
1481
+ return {
1482
+ ...login,
1483
+ status: "pending",
1484
+ connected: false
1485
+ };
1486
+ }
1487
+ const session = await this.authService.requireSession();
1488
+ try {
1489
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(session.accessToken, input);
1490
+ return {
1491
+ status: "connected",
1492
+ connected: true,
1493
+ snapshotChunk
1494
+ };
1495
+ } catch (error) {
1496
+ const recovery = await retryAfterUnauthorizedRefresh({
1497
+ authService: this.authService,
1498
+ error,
1499
+ loginOptions,
1500
+ retry: async (accessToken) => {
1501
+ const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(accessToken, input);
1502
+ return {
1503
+ status: "connected",
1504
+ connected: true,
1505
+ snapshotChunk
1506
+ };
1507
+ }
1508
+ });
1509
+ if (recovery) {
1510
+ return recovery;
1511
+ }
1512
+ throw error;
1513
+ }
1514
+ }
1515
+ async getSymbolDetail(input) {
1516
+ const loginOptions = {
1517
+ clientName: "Helios MCP",
1518
+ scope: [AGENT_SCOPES.MARKET_READ]
1519
+ };
1520
+ const login = await this.authService.ensureLogin(loginOptions);
1521
+ if (login.status !== "connected") {
1522
+ return {
1523
+ ...login,
1524
+ status: "pending",
1525
+ connected: false
1526
+ };
1527
+ }
1528
+ const session = await this.authService.requireSession();
1529
+ try {
1530
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(session.accessToken, input);
1531
+ return {
1532
+ status: "connected",
1533
+ connected: true,
1534
+ detail
1535
+ };
1536
+ } catch (error) {
1537
+ const recovery = await retryAfterUnauthorizedRefresh({
1538
+ authService: this.authService,
1539
+ error,
1540
+ loginOptions,
1541
+ retry: async (accessToken) => {
1542
+ const detail = await this.dataBridgeClient.getMarketSymbolDetail(accessToken, input);
1543
+ return {
1544
+ status: "connected",
1545
+ connected: true,
1546
+ detail
1547
+ };
1548
+ }
1549
+ });
1550
+ if (recovery) {
1551
+ return recovery;
1552
+ }
1553
+ throw error;
1554
+ }
1555
+ }
1556
+ };
1557
+
1558
+ // src/provider-service.ts
1559
+ var HeliosAgentMcpProviderService = class {
1560
+ constructor(options) {
1561
+ __publicField(this, "sessionStore");
1562
+ this.sessionStore = options.sessionStore;
1563
+ }
1564
+ async getActiveProvider() {
1565
+ const provider = await this.sessionStore.getActiveProvider();
1566
+ if (!provider) {
1567
+ return {
1568
+ configured: false,
1569
+ provider: null
1570
+ };
1571
+ }
1572
+ return {
1573
+ configured: true,
1574
+ provider
1575
+ };
1576
+ }
1577
+ async setActiveProvider(provider) {
1578
+ await this.sessionStore.setActiveProvider(provider);
1579
+ return {
1580
+ configured: true,
1581
+ provider
1582
+ };
1583
+ }
1584
+ async resolveProvider(explicitProvider) {
1585
+ if (explicitProvider) {
1586
+ return explicitProvider;
1587
+ }
1588
+ const activeProvider = await this.sessionStore.getActiveProvider();
1589
+ if (activeProvider) {
1590
+ return activeProvider;
1591
+ }
1592
+ throw new Error("No active provider configured. Call helios_provider_set_active or pass provider explicitly.");
1593
+ }
1594
+ };
1595
+
1596
+ // src/session-store.ts
1597
+ var import_promises = require("fs/promises");
1598
+ var import_node_os = require("os");
1599
+ var import_node_path2 = __toESM(require("path"));
1600
+ var import_zod4 = require("zod");
1601
+ function getDefaultHeliosAgentMcpSessionPath() {
1602
+ return import_node_path2.default.join((0, import_node_os.homedir)(), ".helios-agent-mcp", "session.json");
1603
+ }
1604
+ var pendingAgentLoginSchema = import_zod4.z.object({
1605
+ status: import_zod4.z.literal("pending"),
1606
+ deviceCode: import_zod4.z.string(),
1607
+ userCode: import_zod4.z.string(),
1608
+ verificationUri: import_zod4.z.string().url(),
1609
+ verificationUriComplete: import_zod4.z.string().url(),
1610
+ expiresInSeconds: import_zod4.z.number().int().positive(),
1611
+ pollIntervalSeconds: import_zod4.z.number().int().positive(),
1612
+ requestedScope: import_zod4.z.array(agentScopeSchema).min(1),
1613
+ startedAt: import_zod4.z.string().datetime()
1614
+ });
1615
+ var mcpSessionStateSchema = import_zod4.z.object({
1616
+ session: storedAgentSessionSchema.nullish(),
1617
+ pendingLogin: pendingAgentLoginSchema.nullish(),
1618
+ // A provider pinned before Binance was retired ('binance') reads as unpinned, so the agent must pick again, rather than
1619
+ // failing the whole file (which would drop the session) or silently switching it to Hyperliquid.
1620
+ activeProvider: providerSchema.nullish().catch(null)
1621
+ });
1622
+ var FileAgentSessionStore = class {
1623
+ constructor(filePath = getDefaultHeliosAgentMcpSessionPath()) {
1624
+ this.filePath = filePath;
1625
+ }
1626
+ async getSession() {
1627
+ return (await this.readState()).session;
1628
+ }
1629
+ async getPendingLogin() {
1630
+ return (await this.readState()).pendingLogin;
1631
+ }
1632
+ async getActiveProvider() {
1633
+ return (await this.readState()).activeProvider;
1634
+ }
1635
+ async setSession(session) {
1636
+ const state = await this.readState();
1637
+ await this.writeState({
1638
+ ...state,
1639
+ session
1640
+ });
1641
+ }
1642
+ async setPendingLogin(pendingLogin) {
1643
+ const state = await this.readState();
1644
+ await this.writeState({
1645
+ ...state,
1646
+ pendingLogin
1647
+ });
1648
+ }
1649
+ async setActiveProvider(activeProvider) {
1650
+ const state = await this.readState();
1651
+ await this.writeState({
1652
+ ...state,
1653
+ activeProvider
1654
+ });
1655
+ }
1656
+ async clearSession() {
1657
+ const state = await this.readState();
1658
+ await this.writeStateOrDelete({
1659
+ ...state,
1660
+ session: null
1661
+ });
1662
+ }
1663
+ async clearPendingLogin() {
1664
+ const state = await this.readState();
1665
+ await this.writeStateOrDelete({
1666
+ ...state,
1667
+ pendingLogin: null
1668
+ });
1669
+ }
1670
+ async clearActiveProvider() {
1671
+ const state = await this.readState();
1672
+ await this.writeStateOrDelete({
1673
+ ...state,
1674
+ activeProvider: null
1675
+ });
1676
+ }
1677
+ async readState() {
1678
+ try {
1679
+ const raw = await (0, import_promises.readFile)(this.filePath, "utf8");
1680
+ const parsed = JSON.parse(raw);
1681
+ if (parsed && typeof parsed === "object" && ("session" in parsed || "pendingLogin" in parsed || "activeProvider" in parsed)) {
1682
+ const envelope = mcpSessionStateSchema.safeParse(parsed);
1683
+ if (envelope.success) {
1684
+ return {
1685
+ session: envelope.data.session ?? null,
1686
+ pendingLogin: envelope.data.pendingLogin ?? null,
1687
+ activeProvider: envelope.data.activeProvider ?? null
1688
+ };
1689
+ }
1690
+ }
1691
+ const legacySession = storedAgentSessionSchema.safeParse(parsed);
1692
+ if (legacySession.success) {
1693
+ return {
1694
+ session: legacySession.data,
1695
+ pendingLogin: null,
1696
+ activeProvider: null
1697
+ };
1698
+ }
1699
+ return {
1700
+ session: null,
1701
+ pendingLogin: null,
1702
+ activeProvider: null
1703
+ };
1704
+ } catch (error) {
1705
+ if (isMissingFileError(error)) {
1706
+ return {
1707
+ session: null,
1708
+ pendingLogin: null,
1709
+ activeProvider: null
1710
+ };
1711
+ }
1712
+ if (error instanceof Error && error.name === "ZodError") {
1713
+ return {
1714
+ session: null,
1715
+ pendingLogin: null,
1716
+ activeProvider: null
1717
+ };
1718
+ }
1719
+ throw error;
1720
+ }
1721
+ }
1722
+ async writeState(state) {
1723
+ await (0, import_promises.mkdir)(import_node_path2.default.dirname(this.filePath), { recursive: true });
1724
+ await (0, import_promises.writeFile)(this.filePath, `${JSON.stringify(state, null, 2)}
1725
+ `, { encoding: "utf8", mode: 384 });
1726
+ await (0, import_promises.chmod)(this.filePath, 384).catch(() => void 0);
1727
+ }
1728
+ async writeStateOrDelete(state) {
1729
+ if (!state.session && !state.pendingLogin && !state.activeProvider) {
1730
+ await this.deleteFile();
1731
+ return;
1732
+ }
1733
+ await this.writeState(state);
1734
+ }
1735
+ async deleteFile() {
1736
+ try {
1737
+ await (0, import_promises.rm)(this.filePath, { force: true });
1738
+ } catch (error) {
1739
+ if (!isMissingFileError(error)) {
1740
+ throw error;
1741
+ }
1742
+ }
1743
+ }
1744
+ };
1745
+ function isMissingFileError(error) {
1746
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
1747
+ }
1748
+
1749
+ // src/trading-service.ts
1750
+ var import_node_crypto = require("crypto");
1751
+ var HeliosAgentMcpTradingService = class {
1752
+ constructor(options) {
1753
+ __publicField(this, "authService");
1754
+ __publicField(this, "dataBridgeClient");
1755
+ __publicField(this, "providerService");
1756
+ this.authService = options.authService;
1757
+ this.dataBridgeClient = options.dataBridgeClient;
1758
+ this.providerService = options.providerService;
1759
+ }
1760
+ async open(input) {
1761
+ return this.submitIntent("OPEN", input);
1762
+ }
1763
+ async dca(input) {
1764
+ return this.submitIntent("DCA", input);
1765
+ }
1766
+ async reverse(input) {
1767
+ return this.submitIntent("REVERSE", input);
1768
+ }
1769
+ async close(input) {
1770
+ const loginOptions = {
1771
+ clientName: "Helios MCP",
1772
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1773
+ };
1774
+ const login = await this.authService.ensureLogin(loginOptions);
1775
+ if (login.status !== "connected") {
1776
+ return asPending2(login);
1777
+ }
1778
+ const session = await this.authService.requireSession();
1779
+ try {
1780
+ const provider = await this.providerService.resolveProvider(input.provider);
1781
+ const closure = await this.dataBridgeClient.closePosition(session.accessToken, {
1782
+ ...input,
1783
+ provider
1784
+ });
1785
+ return {
1786
+ status: "connected",
1787
+ connected: true,
1788
+ closure
1789
+ };
1790
+ } catch (error) {
1791
+ const recovery = await retryAfterUnauthorizedRefresh({
1792
+ authService: this.authService,
1793
+ error,
1794
+ loginOptions,
1795
+ retry: async (accessToken) => {
1796
+ const provider = await this.providerService.resolveProvider(input.provider);
1797
+ const closure = await this.dataBridgeClient.closePosition(accessToken, {
1798
+ ...input,
1799
+ provider
1800
+ });
1801
+ return {
1802
+ status: "connected",
1803
+ connected: true,
1804
+ closure
1805
+ };
1806
+ }
1807
+ });
1808
+ if (recovery) {
1809
+ return recovery;
1810
+ }
1811
+ throw error;
1812
+ }
1813
+ }
1814
+ async setTpSl(input) {
1815
+ const loginOptions = {
1816
+ clientName: "Helios MCP",
1817
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1818
+ };
1819
+ const login = await this.authService.ensureLogin(loginOptions);
1820
+ if (login.status !== "connected") {
1821
+ return asPending2(login);
1822
+ }
1823
+ const session = await this.authService.requireSession();
1824
+ try {
1825
+ const provider = await this.providerService.resolveProvider(input.provider);
1826
+ const protection = await this.dataBridgeClient.setTpSl(session.accessToken, {
1827
+ ...input,
1828
+ provider
1829
+ });
1830
+ return {
1831
+ status: "connected",
1832
+ connected: true,
1833
+ protection
1834
+ };
1835
+ } catch (error) {
1836
+ const recovery = await retryAfterUnauthorizedRefresh({
1837
+ authService: this.authService,
1838
+ error,
1839
+ loginOptions,
1840
+ retry: async (accessToken) => {
1841
+ const provider = await this.providerService.resolveProvider(input.provider);
1842
+ const protection = await this.dataBridgeClient.setTpSl(accessToken, {
1843
+ ...input,
1844
+ provider
1845
+ });
1846
+ return {
1847
+ status: "connected",
1848
+ connected: true,
1849
+ protection
1850
+ };
1851
+ }
1852
+ });
1853
+ if (recovery) {
1854
+ return recovery;
1855
+ }
1856
+ throw error;
1857
+ }
1858
+ }
1859
+ async deleteTpSl(input) {
1860
+ const loginOptions = {
1861
+ clientName: "Helios MCP",
1862
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
1863
+ };
1864
+ const login = await this.authService.ensureLogin(loginOptions);
1865
+ if (login.status !== "connected") {
1866
+ return asPending2(login);
1867
+ }
1868
+ const session = await this.authService.requireSession();
1869
+ try {
1870
+ const provider = await this.providerService.resolveProvider(input.provider);
1871
+ const deletion = await this.dataBridgeClient.deleteTpSl(session.accessToken, {
1872
+ ...input,
1873
+ provider
1874
+ });
1875
+ return {
1876
+ status: "connected",
1877
+ connected: true,
1878
+ deletion
1879
+ };
1880
+ } catch (error) {
1881
+ const recovery = await retryAfterUnauthorizedRefresh({
1882
+ authService: this.authService,
1883
+ error,
1884
+ loginOptions,
1885
+ retry: async (accessToken) => {
1886
+ const provider = await this.providerService.resolveProvider(input.provider);
1887
+ const deletion = await this.dataBridgeClient.deleteTpSl(accessToken, {
1888
+ ...input,
1889
+ provider
1890
+ });
1891
+ return {
1892
+ status: "connected",
1893
+ connected: true,
1894
+ deletion
1895
+ };
1896
+ }
1897
+ });
1898
+ if (recovery) {
1899
+ return recovery;
1900
+ }
1901
+ throw error;
1902
+ }
1903
+ }
1904
+ async getOpenOrders() {
1905
+ const loginOptions = {
1906
+ clientName: "Helios MCP",
1907
+ scope: [AGENT_SCOPES.ACCOUNT_READ]
1908
+ };
1909
+ const login = await this.authService.ensureLogin(loginOptions);
1910
+ if (login.status !== "connected") {
1911
+ return asPending2(login);
1912
+ }
1913
+ const session = await this.authService.requireSession();
1914
+ try {
1915
+ const orders = await this.dataBridgeClient.getOpenOrders(session.accessToken);
1916
+ return {
1917
+ status: "connected",
1918
+ connected: true,
1919
+ orders
1920
+ };
1921
+ } catch (error) {
1922
+ const recovery = await retryAfterUnauthorizedRefresh({
1923
+ authService: this.authService,
1924
+ error,
1925
+ loginOptions,
1926
+ retry: async (accessToken) => {
1927
+ const orders = await this.dataBridgeClient.getOpenOrders(accessToken);
1928
+ return {
1929
+ status: "connected",
1930
+ connected: true,
1931
+ orders
1932
+ };
1933
+ }
1934
+ });
1935
+ if (recovery) {
1936
+ return recovery;
1937
+ }
1938
+ throw error;
1939
+ }
1940
+ }
1941
+ async cancelOrder(input) {
1942
+ const loginOptions = {
1943
+ clientName: "Helios MCP",
1944
+ scope: [AGENT_SCOPES.ORDERS_CANCEL]
1945
+ };
1946
+ const login = await this.authService.ensureLogin(loginOptions);
1947
+ if (login.status !== "connected") {
1948
+ return asPending2(login);
1949
+ }
1950
+ const session = await this.authService.requireSession();
1951
+ try {
1952
+ const cancellation = await this.dataBridgeClient.cancelOrder(session.accessToken, input);
1953
+ return {
1954
+ status: "connected",
1955
+ connected: true,
1956
+ cancellation
1957
+ };
1958
+ } catch (error) {
1959
+ const recovery = await retryAfterUnauthorizedRefresh({
1960
+ authService: this.authService,
1961
+ error,
1962
+ loginOptions,
1963
+ retry: async (accessToken) => {
1964
+ const cancellation = await this.dataBridgeClient.cancelOrder(accessToken, input);
1965
+ return {
1966
+ status: "connected",
1967
+ connected: true,
1968
+ cancellation
1969
+ };
1970
+ }
1971
+ });
1972
+ if (recovery) {
1973
+ return recovery;
1974
+ }
1975
+ throw error;
1976
+ }
1977
+ }
1978
+ async submitIntent(intentType, input) {
1979
+ const loginOptions = {
1980
+ clientName: "Helios MCP",
1981
+ scope: [AGENT_SCOPES.ORDERS_WRITE]
1982
+ };
1983
+ const login = await this.authService.ensureLogin(loginOptions);
1984
+ if (login.status !== "connected") {
1985
+ return asPending2(login);
1986
+ }
1987
+ const session = await this.authService.requireSession();
1988
+ const idempotencyKey = input.idempotencyKey ?? (0, import_node_crypto.randomUUID)().replace(/-/g, "");
1989
+ try {
1990
+ const provider = await this.providerService.resolveProvider(input.provider);
1991
+ const submission = await this.dataBridgeClient.submitTradeIntent(session.accessToken, {
1992
+ ...input,
1993
+ provider,
1994
+ intentType,
1995
+ idempotencyKey
1996
+ });
1997
+ return {
1998
+ status: "connected",
1999
+ connected: true,
2000
+ submission
2001
+ };
2002
+ } catch (error) {
2003
+ const recovery = await retryAfterUnauthorizedRefresh({
2004
+ authService: this.authService,
2005
+ error,
2006
+ loginOptions,
2007
+ retry: async (accessToken) => {
2008
+ const provider = await this.providerService.resolveProvider(input.provider);
2009
+ const submission = await this.dataBridgeClient.submitTradeIntent(accessToken, {
2010
+ ...input,
2011
+ provider,
2012
+ intentType,
2013
+ idempotencyKey
2014
+ });
2015
+ return {
2016
+ status: "connected",
2017
+ connected: true,
2018
+ submission
2019
+ };
2020
+ }
2021
+ });
2022
+ if (recovery) {
2023
+ return recovery;
2024
+ }
2025
+ throw error;
2026
+ }
2027
+ }
2028
+ };
2029
+ function asPending2(login) {
2030
+ return {
2031
+ ...login,
2032
+ status: "pending",
2033
+ connected: false
2034
+ };
2035
+ }
2036
+
2037
+ // src/tools.ts
2038
+ var import_zod5 = require("zod");
2039
+ var pollLoginInputSchema = import_zod5.z.object({
2040
+ /** Optional: defaults to the login started by helios_auth_ensure_login / helios_auth_start_login. */
2041
+ deviceCode: import_zod5.z.string().min(1).optional()
2042
+ });
2043
+ var startLoginOutputSchema = import_zod5.z.object({
2044
+ status: import_zod5.z.literal("pending"),
2045
+ deviceCode: import_zod5.z.string(),
2046
+ userCode: import_zod5.z.string(),
2047
+ verificationUri: import_zod5.z.string().url(),
2048
+ verificationUriComplete: import_zod5.z.string().url(),
2049
+ expiresInSeconds: import_zod5.z.number().int().positive(),
2050
+ pollIntervalSeconds: import_zod5.z.number().int().positive(),
2051
+ requestedScope: import_zod5.z.array(agentScopeSchema).min(1),
2052
+ startedAt: import_zod5.z.string().datetime()
2053
+ });
2054
+ var ensureLoginInputSchema = import_zod5.z.object({
2055
+ clientName: import_zod5.z.string().min(1).max(64).optional(),
2056
+ scope: import_zod5.z.array(agentScopeSchema).min(1).optional(),
2057
+ constraints: agentConstraintsSchema.optional()
2058
+ });
2059
+ var providerSelectionInputSchema = import_zod5.z.object({
2060
+ provider: providerSchema.optional()
2061
+ });
2062
+ var providerSetInputSchema = import_zod5.z.object({
2063
+ provider: providerSchema
2064
+ });
2065
+ var activeProviderSchema = import_zod5.z.object({
2066
+ configured: import_zod5.z.boolean(),
2067
+ provider: providerSchema.nullable()
2068
+ });
2069
+ var ensureLoginOutputSchema = import_zod5.z.discriminatedUnion("status", [
2070
+ agentSessionViewSchema.extend({
2071
+ status: import_zod5.z.literal("connected"),
2072
+ connected: import_zod5.z.literal(true)
2073
+ }),
2074
+ startLoginOutputSchema.extend({
2075
+ status: import_zod5.z.literal("pending"),
2076
+ connected: import_zod5.z.literal(false),
2077
+ message: import_zod5.z.string()
2078
+ })
2079
+ ]);
2080
+ var pollLoginOutputSchema = import_zod5.z.discriminatedUnion("status", [
2081
+ agentSessionViewSchema.extend({
2082
+ status: import_zod5.z.literal("connected"),
2083
+ connected: import_zod5.z.literal(true)
2084
+ }),
2085
+ import_zod5.z.object({
2086
+ status: import_zod5.z.enum(["pending", "rejected", "expired", "failed"]),
2087
+ connected: import_zod5.z.literal(false),
2088
+ message: import_zod5.z.string()
2089
+ })
2090
+ ]);
2091
+ var walletStateToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2092
+ import_zod5.z.object({
2093
+ status: import_zod5.z.literal("connected"),
2094
+ connected: import_zod5.z.literal(true),
2095
+ walletState: walletStateSchema
2096
+ }),
2097
+ startLoginOutputSchema.extend({
2098
+ status: import_zod5.z.literal("pending"),
2099
+ connected: import_zod5.z.literal(false),
2100
+ message: import_zod5.z.string()
2101
+ })
2102
+ ]);
2103
+ var portfolioToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2104
+ import_zod5.z.object({
2105
+ status: import_zod5.z.literal("connected"),
2106
+ connected: import_zod5.z.literal(true),
2107
+ portfolio: portfolioSnapshotSchema
2108
+ }),
2109
+ startLoginOutputSchema.extend({
2110
+ status: import_zod5.z.literal("pending"),
2111
+ connected: import_zod5.z.literal(false),
2112
+ message: import_zod5.z.string()
2113
+ })
2114
+ ]);
2115
+ var openPositionsToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2116
+ import_zod5.z.object({
2117
+ status: import_zod5.z.literal("connected"),
2118
+ connected: import_zod5.z.literal(true),
2119
+ openPositions: openPositionsSnapshotSchema
2120
+ }),
2121
+ startLoginOutputSchema.extend({
2122
+ status: import_zod5.z.literal("pending"),
2123
+ connected: import_zod5.z.literal(false),
2124
+ message: import_zod5.z.string()
2125
+ })
2126
+ ]);
2127
+ var ledgerFillsToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2128
+ import_zod5.z.object({
2129
+ status: import_zod5.z.literal("connected"),
2130
+ connected: import_zod5.z.literal(true),
2131
+ fills: ledgerFillsPageSchema
2132
+ }),
2133
+ startLoginOutputSchema.extend({
2134
+ status: import_zod5.z.literal("pending"),
2135
+ connected: import_zod5.z.literal(false),
2136
+ message: import_zod5.z.string()
2137
+ })
2138
+ ]);
2139
+ var ledgerSummaryToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2140
+ import_zod5.z.object({
2141
+ status: import_zod5.z.literal("connected"),
2142
+ connected: import_zod5.z.literal(true),
2143
+ summary: ledgerSummarySchema
2144
+ }),
2145
+ startLoginOutputSchema.extend({
2146
+ status: import_zod5.z.literal("pending"),
2147
+ connected: import_zod5.z.literal(false),
2148
+ message: import_zod5.z.string()
2149
+ })
2150
+ ]);
2151
+ var marketSnapshotToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2152
+ import_zod5.z.object({
2153
+ status: import_zod5.z.literal("connected"),
2154
+ connected: import_zod5.z.literal(true),
2155
+ snapshot: marketSnapshotSchema
2156
+ }),
2157
+ startLoginOutputSchema.extend({
2158
+ status: import_zod5.z.literal("pending"),
2159
+ connected: import_zod5.z.literal(false),
2160
+ message: import_zod5.z.string()
2161
+ })
2162
+ ]);
2163
+ var marketSnapshotChunkToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2164
+ import_zod5.z.object({
2165
+ status: import_zod5.z.literal("connected"),
2166
+ connected: import_zod5.z.literal(true),
2167
+ snapshotChunk: marketSnapshotChunkSchema
2168
+ }),
2169
+ startLoginOutputSchema.extend({
2170
+ status: import_zod5.z.literal("pending"),
2171
+ connected: import_zod5.z.literal(false),
2172
+ message: import_zod5.z.string()
2173
+ })
2174
+ ]);
2175
+ var marketSymbolDetailToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2176
+ import_zod5.z.object({
2177
+ status: import_zod5.z.literal("connected"),
2178
+ connected: import_zod5.z.literal(true),
2179
+ detail: marketSymbolDetailSchema
2180
+ }),
2181
+ startLoginOutputSchema.extend({
2182
+ status: import_zod5.z.literal("pending"),
2183
+ connected: import_zod5.z.literal(false),
2184
+ message: import_zod5.z.string()
2185
+ })
2186
+ ]);
2187
+ var tradeActionInputSchema = submitTradeIntentInputSchema.omit({
2188
+ intentType: true
2189
+ });
2190
+ var tradeActionToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2191
+ import_zod5.z.object({
2192
+ status: import_zod5.z.literal("connected"),
2193
+ connected: import_zod5.z.literal(true),
2194
+ submission: submitTradeIntentResultSchema
2195
+ }),
2196
+ startLoginOutputSchema.extend({
2197
+ status: import_zod5.z.literal("pending"),
2198
+ connected: import_zod5.z.literal(false),
2199
+ message: import_zod5.z.string()
2200
+ })
2201
+ ]);
2202
+ var closeTradeToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2203
+ import_zod5.z.object({
2204
+ status: import_zod5.z.literal("connected"),
2205
+ connected: import_zod5.z.literal(true),
2206
+ closure: closePositionResultSchema
2207
+ }),
2208
+ startLoginOutputSchema.extend({
2209
+ status: import_zod5.z.literal("pending"),
2210
+ connected: import_zod5.z.literal(false),
2211
+ message: import_zod5.z.string()
2212
+ })
2213
+ ]);
2214
+ var setTpSlToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2215
+ import_zod5.z.object({
2216
+ status: import_zod5.z.literal("connected"),
2217
+ connected: import_zod5.z.literal(true),
2218
+ protection: setTpSlResultSchema
2219
+ }),
2220
+ startLoginOutputSchema.extend({
2221
+ status: import_zod5.z.literal("pending"),
2222
+ connected: import_zod5.z.literal(false),
2223
+ message: import_zod5.z.string()
2224
+ })
2225
+ ]);
2226
+ var deleteTpSlToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2227
+ import_zod5.z.object({
2228
+ status: import_zod5.z.literal("connected"),
2229
+ connected: import_zod5.z.literal(true),
2230
+ deletion: deleteTpSlResultSchema
2231
+ }),
2232
+ startLoginOutputSchema.extend({
2233
+ status: import_zod5.z.literal("pending"),
2234
+ connected: import_zod5.z.literal(false),
2235
+ message: import_zod5.z.string()
2236
+ })
2237
+ ]);
2238
+ var openOrdersToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2239
+ import_zod5.z.object({
2240
+ status: import_zod5.z.literal("connected"),
2241
+ connected: import_zod5.z.literal(true),
2242
+ orders: import_zod5.z.array(openOrderSchema)
2243
+ }),
2244
+ startLoginOutputSchema.extend({
2245
+ status: import_zod5.z.literal("pending"),
2246
+ connected: import_zod5.z.literal(false),
2247
+ message: import_zod5.z.string()
2248
+ })
2249
+ ]);
2250
+ var cancelOrderToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2251
+ import_zod5.z.object({
2252
+ status: import_zod5.z.literal("connected"),
2253
+ connected: import_zod5.z.literal(true),
2254
+ cancellation: cancelOrderResultSchema
2255
+ }),
2256
+ startLoginOutputSchema.extend({
2257
+ status: import_zod5.z.literal("pending"),
2258
+ connected: import_zod5.z.literal(false),
2259
+ message: import_zod5.z.string()
2260
+ })
2261
+ ]);
2262
+ var documentPathInputSchema = import_zod5.z.object({
2263
+ path: import_zod5.z.string().min(1)
2264
+ });
2265
+ var docsIndexSchema = import_zod5.z.object({
2266
+ root: import_zod5.z.literal("docs"),
2267
+ documents: import_zod5.z.array(
2268
+ import_zod5.z.object({
2269
+ path: import_zod5.z.string(),
2270
+ section: import_zod5.z.string(),
2271
+ title: import_zod5.z.string(),
2272
+ bytes: import_zod5.z.number().int().nonnegative()
2273
+ })
2274
+ )
2275
+ });
2276
+ var documentSchema = import_zod5.z.object({
2277
+ path: import_zod5.z.string(),
2278
+ section: import_zod5.z.string(),
2279
+ title: import_zod5.z.string(),
2280
+ body: import_zod5.z.string(),
2281
+ bytes: import_zod5.z.number().int().nonnegative()
2282
+ });
2283
+ function createHeliosDocsToolDefinitions(service) {
2284
+ return [
2285
+ {
2286
+ name: "helios_docs_get_index",
2287
+ title: "Get Helios Docs Index",
2288
+ description: "Lists the package-local Helios MCP and indicator .txt documentation available to the agent.",
2289
+ inputSchema: import_zod5.z.object({}),
2290
+ async execute() {
2291
+ const result = docsIndexSchema.parse(await service.getIndex());
2292
+ return {
2293
+ content: [
2294
+ {
2295
+ type: "text",
2296
+ text: `Helios docs index: ${result.documents.length} documents across ${new Set(result.documents.map((document) => document.section)).size} sections.`
2297
+ }
2298
+ ],
2299
+ structuredContent: result
2300
+ };
2301
+ }
2302
+ },
2303
+ {
2304
+ name: "helios_docs_get_document",
2305
+ title: "Get Helios Doc",
2306
+ description: "Returns one package-local Helios .txt document by relative docs path.",
2307
+ inputSchema: documentPathInputSchema,
2308
+ async execute(input) {
2309
+ const result = documentSchema.parse(await service.getDocument(input));
2310
+ return {
2311
+ content: [
2312
+ {
2313
+ type: "text",
2314
+ text: result.body
2315
+ }
2316
+ ],
2317
+ structuredContent: result
2318
+ };
2319
+ }
2320
+ }
2321
+ ];
2322
+ }
2323
+ function createHeliosAuthToolDefinitions(service) {
2324
+ return [
2325
+ {
2326
+ name: "helios_auth_start_login",
2327
+ title: "Start Helios Login",
2328
+ description: "Starts the delegated Helios login flow and returns the approval URL for the user.",
2329
+ inputSchema: agentDeviceStartInputSchema,
2330
+ async execute(input) {
2331
+ const result = startLoginOutputSchema.parse(await service.startLogin(input));
2332
+ const manualResult = {
2333
+ ...result,
2334
+ ...withManualLoginFields(result)
2335
+ };
2336
+ return {
2337
+ content: [
2338
+ {
2339
+ type: "text",
2340
+ text: buildManualLoginText(result)
2341
+ }
2342
+ ],
2343
+ structuredContent: manualResult
2344
+ };
2345
+ }
2346
+ },
2347
+ {
2348
+ name: "helios_auth_ensure_login",
2349
+ title: "Ensure Helios Login",
2350
+ description: "Ensures a delegated Helios session exists, or starts a login flow and returns a ready-to-display approval prompt. Call it again after the person approves: it finishes connecting.",
2351
+ inputSchema: ensureLoginInputSchema,
2352
+ async execute(input) {
2353
+ const result = ensureLoginOutputSchema.parse(await service.ensureLogin(input));
2354
+ const structuredContent = result.status === "connected" ? result : {
2355
+ ...result,
2356
+ ...withManualLoginFields(result)
2357
+ };
2358
+ return {
2359
+ content: [
2360
+ {
2361
+ type: "text",
2362
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : result.message
2363
+ }
2364
+ ],
2365
+ structuredContent
2366
+ };
2367
+ }
2368
+ },
2369
+ {
2370
+ name: "helios_auth_poll_login",
2371
+ title: "Poll Helios Login",
2372
+ description: "Checks whether the Helios login was approved and finishes connecting. The device code is optional; without it, the login in progress is checked.",
2373
+ inputSchema: pollLoginInputSchema,
2374
+ async execute(input) {
2375
+ const result = pollLoginOutputSchema.parse(await service.pollLogin(input.deviceCode));
2376
+ return {
2377
+ content: [
2378
+ {
2379
+ type: "text",
2380
+ text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : `Helios login is ${result.status}: ${result.message}`
2381
+ }
2382
+ ],
2383
+ structuredContent: result
2384
+ };
2385
+ }
2386
+ },
2387
+ {
2388
+ name: "helios_auth_whoami",
2389
+ title: "Helios Login Status",
2390
+ description: "Returns the delegated Helios session state currently stored by the MCP server.",
2391
+ inputSchema: import_zod5.z.object({}),
2392
+ async execute() {
2393
+ const result = agentSessionViewSchema.parse(await service.whoami());
2394
+ return {
2395
+ content: [
2396
+ {
2397
+ type: "text",
2398
+ text: result.connected ? `Connected to Helios as user ${result.ownerUserId}.` : "No delegated Helios session is connected."
2399
+ }
2400
+ ],
2401
+ structuredContent: result
2402
+ };
2403
+ }
2404
+ }
2405
+ ];
2406
+ }
2407
+ function createHeliosProviderToolDefinitions(service) {
2408
+ return [
2409
+ {
2410
+ name: "helios_provider_get_active",
2411
+ title: "Get Helios Active Provider",
2412
+ description: "Returns the provider currently pinned for this MCP session, if any.",
2413
+ inputSchema: import_zod5.z.object({}),
2414
+ async execute() {
2415
+ const result = activeProviderSchema.parse(await service.getActiveProvider());
2416
+ return {
2417
+ content: [
2418
+ {
2419
+ type: "text",
2420
+ text: result.configured ? `Helios active provider is ${result.provider}.` : "No Helios active provider is configured for this session."
2421
+ }
2422
+ ],
2423
+ structuredContent: result
2424
+ };
2425
+ }
2426
+ },
2427
+ {
2428
+ name: "helios_provider_set_active",
2429
+ title: "Set Helios Active Provider",
2430
+ description: "Pins the active provider for this MCP session so portfolio and trading tools can omit provider.",
2431
+ inputSchema: providerSetInputSchema,
2432
+ async execute(input) {
2433
+ const result = activeProviderSchema.parse(await service.setActiveProvider(input.provider));
2434
+ return {
2435
+ content: [
2436
+ {
2437
+ type: "text",
2438
+ text: `Helios active provider set to ${result.provider}.`
2439
+ }
2440
+ ],
2441
+ structuredContent: result
2442
+ };
2443
+ }
2444
+ }
2445
+ ];
2446
+ }
2447
+ function createHeliosAccountToolDefinitions(service) {
2448
+ return [
2449
+ {
2450
+ name: "helios_account_get_wallet_state",
2451
+ title: "Get Helios Wallet State",
2452
+ description: "Returns the current Hyperliquid wallet snapshot for the connected Helios account.",
2453
+ inputSchema: import_zod5.z.object({}),
2454
+ async execute() {
2455
+ const result = walletStateToolOutputSchema.parse(await service.getWalletState());
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" ? `Helios wallet state: available balance ${result.walletState.availableBalance}, account value ${result.walletState.accountValue}.` : result.message
2465
+ }
2466
+ ],
2467
+ structuredContent
2468
+ };
2469
+ }
2470
+ },
2471
+ {
2472
+ name: "helios_portfolio_get",
2473
+ title: "Get Helios Portfolio",
2474
+ description: "Returns a provider-specific portfolio snapshot. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2475
+ inputSchema: providerSelectionInputSchema,
2476
+ async execute(input) {
2477
+ const result = portfolioToolOutputSchema.parse(await service.getPortfolio(input));
2478
+ const structuredContent = result.status === "connected" ? result : {
2479
+ ...result,
2480
+ ...withManualLoginFields(result)
2481
+ };
2482
+ return {
2483
+ content: [
2484
+ {
2485
+ type: "text",
2486
+ text: result.status === "connected" ? buildPortfolioText(result.portfolio) : result.message
2487
+ }
2488
+ ],
2489
+ structuredContent
2490
+ };
2491
+ }
2492
+ }
2493
+ ];
2494
+ }
2495
+ function createHeliosLedgerToolDefinitions(service) {
2496
+ return [
2497
+ {
2498
+ name: "helios_positions_get_open",
2499
+ title: "Get Helios Open Positions",
2500
+ description: "Returns the current open Hyperliquid positions for the connected Helios account.",
2501
+ inputSchema: import_zod5.z.object({}),
2502
+ async execute() {
2503
+ const result = openPositionsToolOutputSchema.parse(await service.getOpenPositions());
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 open positions: ${result.openPositions.positions.length} positions, total unrealized PnL ${result.openPositions.totalUnrealizedPnl}.` : result.message
2513
+ }
2514
+ ],
2515
+ structuredContent
2516
+ };
2517
+ }
2518
+ },
2519
+ {
2520
+ name: "helios_ledger_get_fills",
2521
+ title: "Get Helios Ledger Fills",
2522
+ description: "Returns recent Hyperliquid fills/trade history for the connected Helios account.",
2523
+ inputSchema: ledgerFillsInputSchema,
2524
+ async execute(input) {
2525
+ const result = ledgerFillsToolOutputSchema.parse(await service.getFills(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 fills: ${result.fills.fills.length} fills from ${result.fills.window}${result.fills.hasMore ? ", more available" : ""}.` : result.message
2535
+ }
2536
+ ],
2537
+ structuredContent
2538
+ };
2539
+ }
2540
+ },
2541
+ {
2542
+ name: "helios_ledger_get_summary",
2543
+ title: "Get Helios Ledger Summary",
2544
+ description: "Returns realized PnL, fees, and win/loss metrics over a recent Hyperliquid fill window.",
2545
+ inputSchema: ledgerSummaryInputSchema,
2546
+ async execute(input) {
2547
+ const result = ledgerSummaryToolOutputSchema.parse(await service.getSummary(input));
2548
+ const structuredContent = result.status === "connected" ? result : {
2549
+ ...result,
2550
+ ...withManualLoginFields(result)
2551
+ };
2552
+ return {
2553
+ content: [
2554
+ {
2555
+ type: "text",
2556
+ 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
2557
+ }
2558
+ ],
2559
+ structuredContent
2560
+ };
2561
+ }
2562
+ }
2563
+ ];
2564
+ }
2565
+ function createHeliosMarketToolDefinitions(service) {
2566
+ return [
2567
+ {
2568
+ name: "helios_market_get_snapshot",
2569
+ title: "Get Helios Market Snapshot",
2570
+ description: "Returns a compact market snapshot for the selected, all, or explicitly requested symbols.",
2571
+ inputSchema: marketSnapshotInputSchema,
2572
+ async execute(input) {
2573
+ const result = marketSnapshotToolOutputSchema.parse(await service.getSnapshot(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: ${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
2583
+ }
2584
+ ],
2585
+ structuredContent
2586
+ };
2587
+ }
2588
+ },
2589
+ {
2590
+ name: "helios_market_get_snapshot_chunk",
2591
+ title: "Get Helios Market Snapshot Chunk",
2592
+ description: "Returns one chunk of the Helios market snapshot for batch analysis when the full snapshot is too large.",
2593
+ inputSchema: marketSnapshotChunkInputSchema,
2594
+ async execute(input) {
2595
+ const result = marketSnapshotChunkToolOutputSchema.parse(await service.getSnapshotChunk(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 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
2605
+ }
2606
+ ],
2607
+ structuredContent
2608
+ };
2609
+ }
2610
+ },
2611
+ {
2612
+ name: "helios_market_get_symbol_detail",
2613
+ title: "Get Helios Symbol Detail",
2614
+ description: "Returns expanded market detail for one symbol from the current Helios market snapshot.",
2615
+ inputSchema: marketSymbolDetailInputSchema,
2616
+ async execute(input) {
2617
+ const result = marketSymbolDetailToolOutputSchema.parse(await service.getSymbolDetail(input));
2618
+ const structuredContent = result.status === "connected" ? result : {
2619
+ ...result,
2620
+ ...withManualLoginFields(result)
2621
+ };
2622
+ return {
2623
+ content: [
2624
+ {
2625
+ type: "text",
2626
+ 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
2627
+ }
2628
+ ],
2629
+ structuredContent
2630
+ };
2631
+ }
2632
+ }
2633
+ ];
2634
+ }
2635
+ function createHeliosTradingToolDefinitions(service) {
2636
+ return [
2637
+ {
2638
+ name: "helios_trading_open",
2639
+ title: "Open Helios Position",
2640
+ description: "Submits a Helios OPEN trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2641
+ inputSchema: tradeActionInputSchema,
2642
+ async execute(input) {
2643
+ const result = tradeActionToolOutputSchema.parse(await service.open(input));
2644
+ return {
2645
+ content: [
2646
+ {
2647
+ type: "text",
2648
+ 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
2649
+ }
2650
+ ],
2651
+ structuredContent: result.status === "connected" ? result : {
2652
+ ...result,
2653
+ ...withManualLoginFields(result)
2654
+ }
2655
+ };
2656
+ }
2657
+ },
2658
+ {
2659
+ name: "helios_trading_dca",
2660
+ title: "DCA Helios Position",
2661
+ description: "Submits a Helios DCA trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2662
+ inputSchema: tradeActionInputSchema,
2663
+ async execute(input) {
2664
+ const result = tradeActionToolOutputSchema.parse(await service.dca(input));
2665
+ return {
2666
+ content: [
2667
+ {
2668
+ type: "text",
2669
+ 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
2670
+ }
2671
+ ],
2672
+ structuredContent: result.status === "connected" ? result : {
2673
+ ...result,
2674
+ ...withManualLoginFields(result)
2675
+ }
2676
+ };
2677
+ }
2678
+ },
2679
+ {
2680
+ name: "helios_trading_reverse",
2681
+ title: "Reverse Helios Position",
2682
+ description: "Submits a Helios REVERSE trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2683
+ inputSchema: tradeActionInputSchema,
2684
+ async execute(input) {
2685
+ const result = tradeActionToolOutputSchema.parse(await service.reverse(input));
2686
+ return {
2687
+ content: [
2688
+ {
2689
+ type: "text",
2690
+ 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
2691
+ }
2692
+ ],
2693
+ structuredContent: result.status === "connected" ? result : {
2694
+ ...result,
2695
+ ...withManualLoginFields(result)
2696
+ }
2697
+ };
2698
+ }
2699
+ },
2700
+ {
2701
+ name: "helios_trading_close",
2702
+ title: "Close Helios Position",
2703
+ 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.",
2704
+ inputSchema: closePositionInputSchema,
2705
+ async execute(input) {
2706
+ const result = closeTradeToolOutputSchema.parse(await service.close(input));
2707
+ return {
2708
+ content: [
2709
+ {
2710
+ type: "text",
2711
+ text: result.status === "connected" ? `Submitted Helios full close for ${result.closure.provider ?? input.provider} ${result.closure.symbol}.` : result.message
2712
+ }
2713
+ ],
2714
+ structuredContent: result.status === "connected" ? result : {
2715
+ ...result,
2716
+ ...withManualLoginFields(result)
2717
+ }
2718
+ };
2719
+ }
2720
+ },
2721
+ {
2722
+ name: "helios_positions_set_tp_sl",
2723
+ title: "Set Helios TP/SL",
2724
+ 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.",
2725
+ inputSchema: setTpSlInputSchema,
2726
+ async execute(input) {
2727
+ const result = setTpSlToolOutputSchema.parse(await service.setTpSl(input));
2728
+ return {
2729
+ content: [
2730
+ {
2731
+ type: "text",
2732
+ text: result.status === "connected" ? `Submitted ${result.protection.provider ?? input.provider} TP/SL protection update for ${result.protection.symbol}.` : result.message
2733
+ }
2734
+ ],
2735
+ structuredContent: result.status === "connected" ? result : {
2736
+ ...result,
2737
+ ...withManualLoginFields(result)
2738
+ }
2739
+ };
2740
+ }
2741
+ },
2742
+ {
2743
+ name: "helios_positions_delete_tp_sl",
2744
+ title: "Delete Helios TP/SL",
2745
+ 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.",
2746
+ inputSchema: deleteTpSlInputSchema,
2747
+ async execute(input) {
2748
+ const result = deleteTpSlToolOutputSchema.parse(await service.deleteTpSl(input));
2749
+ return {
2750
+ content: [
2751
+ {
2752
+ type: "text",
2753
+ text: result.status === "connected" ? `Deleted ${result.deletion.provider ?? input.provider} TP/SL order ${result.deletion.orderId} for ${result.deletion.symbol}.` : result.message
2754
+ }
2755
+ ],
2756
+ structuredContent: result.status === "connected" ? result : {
2757
+ ...result,
2758
+ ...withManualLoginFields(result)
2759
+ }
2760
+ };
2761
+ }
2762
+ },
2763
+ {
2764
+ name: "helios_orders_get_open",
2765
+ title: "Get Helios Open Orders",
2766
+ description: "Lists the currently open Hyperliquid orders for the connected account.",
2767
+ inputSchema: import_zod5.z.object({}),
2768
+ async execute() {
2769
+ const result = openOrdersToolOutputSchema.parse(await service.getOpenOrders());
2770
+ return {
2771
+ content: [
2772
+ {
2773
+ type: "text",
2774
+ text: result.status === "connected" ? `Retrieved ${result.orders.length} open Helios orders.` : result.message
2775
+ }
2776
+ ],
2777
+ structuredContent: result.status === "connected" ? result : {
2778
+ ...result,
2779
+ ...withManualLoginFields(result)
2780
+ }
2781
+ };
2782
+ }
2783
+ },
2784
+ {
2785
+ name: "helios_orders_cancel",
2786
+ title: "Cancel Helios Order",
2787
+ description: "Cancels an open Hyperliquid order by symbol and order id.",
2788
+ inputSchema: cancelOrderInputSchema,
2789
+ async execute(input) {
2790
+ const result = cancelOrderToolOutputSchema.parse(await service.cancelOrder(input));
2791
+ return {
2792
+ content: [
2793
+ {
2794
+ type: "text",
2795
+ text: result.status === "connected" ? `Cancelled Helios order ${result.cancellation.oid} for ${result.cancellation.symbol}.` : result.message
2796
+ }
2797
+ ],
2798
+ structuredContent: result.status === "connected" ? result : {
2799
+ ...result,
2800
+ ...withManualLoginFields(result)
2801
+ }
2802
+ };
2803
+ }
2804
+ }
2805
+ ];
2806
+ }
2807
+ function withManualLoginFields(result) {
2808
+ return {
2809
+ actionRequired: true,
2810
+ loginUrl: result.verificationUriComplete,
2811
+ nextStep: "Open the login URL in your browser, approve Helios access, then call helios_auth_ensure_login again to finish connecting."
2812
+ };
2813
+ }
2814
+ function buildPortfolioText(result) {
2815
+ return `Helios Hyperliquid portfolio: ${result.positions.length} positions, available balance ${result.availableBalance}, total balance ${result.totalBalance}.`;
2816
+ }
2817
+ function buildManualLoginText(result) {
2818
+ return `Log in to Helios by opening this URL in your browser:
2819
+
2820
+ ${result.verificationUriComplete}
2821
+
2822
+ User code: ${result.userCode}
2823
+
2824
+ After approving access, call helios_auth_ensure_login (or helios_auth_poll_login) again to finish connecting.`;
2825
+ }
2826
+
2827
+ // src/server.ts
2828
+ async function createHeliosAgentMcpServer(options) {
2829
+ if (!options.identityServiceUrl) {
2830
+ throw new Error("identityServiceUrl is required");
2831
+ }
2832
+ if (!options.dataBridgeUrl) {
2833
+ throw new Error("dataBridgeUrl is required");
2834
+ }
2835
+ const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
2836
+ const server = new McpServer({
2837
+ name: "helios",
2838
+ version: "0.2.1"
2839
+ });
2840
+ const sessionStore = options.sessionStore ?? new FileAgentSessionStore(options.sessionPath ?? getDefaultHeliosAgentMcpSessionPath());
2841
+ const client = new HeliosAgentAuthClient({
2842
+ baseUrl: options.identityServiceUrl,
2843
+ fetch: options.fetch
2844
+ });
2845
+ const dataBridgeClient = new HeliosAgentDataBridgeClient({
2846
+ baseUrl: options.dataBridgeUrl,
2847
+ fetch: options.fetch
2848
+ });
2849
+ const authService = new HeliosAgentMcpAuthService({
2850
+ client,
2851
+ sessionStore,
2852
+ refreshWindowMs: options.refreshWindowMs,
2853
+ deviceLogin: !options.hosted
2854
+ });
2855
+ const providerService = new HeliosAgentMcpProviderService({
2856
+ sessionStore
2857
+ });
2858
+ const accountService = new HeliosAgentMcpAccountService({
2859
+ authService,
2860
+ dataBridgeClient,
2861
+ providerService
2862
+ });
2863
+ const marketService = new HeliosAgentMcpMarketService({
2864
+ authService,
2865
+ dataBridgeClient
2866
+ });
2867
+ const ledgerService = new HeliosAgentMcpLedgerService({
2868
+ authService,
2869
+ dataBridgeClient
2870
+ });
2871
+ const tradingService = new HeliosAgentMcpTradingService({
2872
+ authService,
2873
+ dataBridgeClient,
2874
+ providerService
2875
+ });
2876
+ const docsService = new HeliosAgentMcpDocsService({
2877
+ docsRoot: options.docsRoot ?? getDefaultHeliosAgentMcpDocsRoot()
2878
+ });
2879
+ const docsTools = createHeliosDocsToolDefinitions(docsService);
2880
+ const authTools = createHeliosAuthToolDefinitions(authService);
2881
+ const providerTools = createHeliosProviderToolDefinitions(providerService);
2882
+ const accountTools = createHeliosAccountToolDefinitions(accountService);
2883
+ const ledgerTools = createHeliosLedgerToolDefinitions(ledgerService);
2884
+ const marketTools = createHeliosMarketToolDefinitions(marketService);
2885
+ const tradingTools = createHeliosTradingToolDefinitions(tradingService);
2886
+ registerTool(server, docsTools[0]);
2887
+ registerTool(server, docsTools[1]);
2888
+ if (!options.hosted) {
2889
+ registerTool(server, authTools[0]);
2890
+ registerTool(server, authTools[1]);
2891
+ registerTool(server, authTools[2]);
2892
+ }
2893
+ registerTool(server, authTools[3]);
2894
+ registerTool(server, providerTools[0]);
2895
+ registerTool(server, providerTools[1]);
2896
+ registerTool(server, accountTools[0]);
2897
+ registerTool(server, accountTools[1]);
2898
+ registerTool(server, ledgerTools[0]);
2899
+ registerTool(server, ledgerTools[1]);
2900
+ registerTool(server, ledgerTools[2]);
2901
+ registerTool(server, marketTools[0]);
2902
+ registerTool(server, marketTools[1]);
2903
+ registerTool(server, marketTools[2]);
2904
+ registerTool(server, tradingTools[0]);
2905
+ registerTool(server, tradingTools[1]);
2906
+ registerTool(server, tradingTools[2]);
2907
+ registerTool(server, tradingTools[3]);
2908
+ registerTool(server, tradingTools[4]);
2909
+ registerTool(server, tradingTools[5]);
2910
+ registerTool(server, tradingTools[6]);
2911
+ registerTool(server, tradingTools[7]);
2912
+ return {
2913
+ server,
2914
+ authService,
2915
+ providerService,
2916
+ accountService,
2917
+ docsService,
2918
+ ledgerService,
2919
+ marketService,
2920
+ tradingService,
2921
+ sessionStore
2922
+ };
2923
+ }
2924
+ var ACTS_ON_ACCOUNT = /^helios_(trading_|positions_set_tp_sl|positions_delete_tp_sl|orders_cancel)/;
2925
+ var CHANGES_SESSION = /^helios_(auth_start_login|auth_ensure_login|auth_poll_login|provider_set_active)$/;
2926
+ function toolAnnotations(name) {
2927
+ if (ACTS_ON_ACCOUNT.test(name)) return { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
2928
+ if (CHANGES_SESSION.test(name)) return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
2929
+ return { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
2930
+ }
2931
+ function registerTool(server, tool) {
2932
+ server.registerTool(
2933
+ tool.name,
2934
+ {
2935
+ title: tool.title,
2936
+ description: tool.description,
2937
+ inputSchema: tool.inputSchema,
2938
+ annotations: { title: tool.title, ...toolAnnotations(tool.name) }
2939
+ },
2940
+ async (input) => {
2941
+ const result = await tool.execute(tool.inputSchema.parse(input));
2942
+ return {
2943
+ ...result,
2944
+ structuredContent: result.structuredContent
2945
+ };
2946
+ }
2947
+ );
2948
+ }
2949
+
2950
+ // src/cli.ts
2951
+ async function main() {
2952
+ const identityServiceUrl = process.env.HELIOS_IDENTITY_SERVICE_URL || "https://helios.pgn.io";
2953
+ const dataBridgeUrl = process.env.HELIOS_DATA_BRIDGE_URL || "https://helios.pgn.io";
2954
+ const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
2955
+ const { server } = await createHeliosAgentMcpServer({
2956
+ identityServiceUrl,
2957
+ dataBridgeUrl,
2958
+ sessionPath: process.env.HELIOS_AGENT_MCP_SESSION_PATH
2959
+ });
2960
+ const transport = new StdioServerTransport();
2961
+ await server.connect(transport);
2962
+ }
2963
+ main().catch((error) => {
2964
+ const message = error instanceof Error ? error.stack ?? error.message : String(error);
2965
+ process.stderr.write(`${message}
2966
+ `);
2967
+ process.exitCode = 1;
2968
+ });