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