@jinn-network/client 0.1.0 → 0.1.1-canary.4a6ed8b2

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 (269) hide show
  1. package/README.md +98 -11
  2. package/deployments/deployment-jinn-testnet-faucet-baseSepolia-fast.json +15 -0
  3. package/dist/adapters/claim-registry/abi.d.ts +127 -0
  4. package/dist/adapters/claim-registry/abi.js +93 -0
  5. package/dist/adapters/claim-registry/abi.js.map +1 -0
  6. package/dist/adapters/claim-registry/client.d.ts +89 -0
  7. package/dist/adapters/claim-registry/client.js +205 -0
  8. package/dist/adapters/claim-registry/client.js.map +1 -0
  9. package/dist/adapters/mech/adapter.d.ts +2 -0
  10. package/dist/adapters/mech/adapter.js +110 -41
  11. package/dist/adapters/mech/adapter.js.map +1 -1
  12. package/dist/adapters/mech/contracts.d.ts +2 -0
  13. package/dist/adapters/mech/contracts.js +32 -7
  14. package/dist/adapters/mech/contracts.js.map +1 -1
  15. package/dist/adapters/mech/ipfs.d.ts +8 -0
  16. package/dist/adapters/mech/ipfs.js +12 -0
  17. package/dist/adapters/mech/ipfs.js.map +1 -1
  18. package/dist/adapters/mech/types.d.ts +20 -46
  19. package/dist/adapters/mech/types.js +16 -35
  20. package/dist/adapters/mech/types.js.map +1 -1
  21. package/dist/api/gather-status.js +11 -0
  22. package/dist/api/gather-status.js.map +1 -1
  23. package/dist/api/portfolio-v0-build.d.ts +81 -0
  24. package/dist/api/portfolio-v0-build.js +141 -0
  25. package/dist/api/portfolio-v0-build.js.map +1 -0
  26. package/dist/api/portfolio-v0-doctor.d.ts +37 -0
  27. package/dist/api/portfolio-v0-doctor.js +123 -0
  28. package/dist/api/portfolio-v0-doctor.js.map +1 -0
  29. package/dist/api/server.js +12 -0
  30. package/dist/api/server.js.map +1 -1
  31. package/dist/api/status-build.d.ts +6 -0
  32. package/dist/api/status-build.js +1 -0
  33. package/dist/api/status-build.js.map +1 -1
  34. package/dist/api/status-rollup-build.d.ts +4 -0
  35. package/dist/api/status-rollup-build.js +4 -0
  36. package/dist/api/status-rollup-build.js.map +1 -1
  37. package/dist/bin/jinn-mcp.d.ts +14 -0
  38. package/dist/bin/jinn-mcp.js +19 -0
  39. package/dist/bin/jinn-mcp.js.map +1 -0
  40. package/dist/build-meta.json +1 -1
  41. package/dist/cli/commands/auth.d.ts +3 -0
  42. package/dist/cli/commands/auth.js +236 -0
  43. package/dist/cli/commands/auth.js.map +1 -0
  44. package/dist/cli/commands/bootstrap.js +1 -0
  45. package/dist/cli/commands/bootstrap.js.map +1 -1
  46. package/dist/cli/commands/doctor.js +148 -15
  47. package/dist/cli/commands/doctor.js.map +1 -1
  48. package/dist/cli/commands/fund-requirements.js +69 -1
  49. package/dist/cli/commands/fund-requirements.js.map +1 -1
  50. package/dist/cli/commands/history.js +1 -0
  51. package/dist/cli/commands/history.js.map +1 -1
  52. package/dist/cli/commands/init.js +31 -7
  53. package/dist/cli/commands/init.js.map +1 -1
  54. package/dist/cli/commands/keys-backup.js +142 -10
  55. package/dist/cli/commands/keys-backup.js.map +1 -1
  56. package/dist/cli/commands/logs.js +28 -13
  57. package/dist/cli/commands/logs.js.map +1 -1
  58. package/dist/cli/commands/plugin-install.d.ts +3 -0
  59. package/dist/cli/commands/plugin-install.js +799 -0
  60. package/dist/cli/commands/plugin-install.js.map +1 -0
  61. package/dist/cli/commands/quickstart.d.ts +3 -0
  62. package/dist/cli/commands/quickstart.js +236 -0
  63. package/dist/cli/commands/quickstart.js.map +1 -0
  64. package/dist/cli/commands/run.js +6 -0
  65. package/dist/cli/commands/run.js.map +1 -1
  66. package/dist/cli/commands/stop.js +1 -0
  67. package/dist/cli/commands/stop.js.map +1 -1
  68. package/dist/cli/commands/submit-intent.js +79 -5
  69. package/dist/cli/commands/submit-intent.js.map +1 -1
  70. package/dist/cli/commands/update.d.ts +3 -0
  71. package/dist/cli/commands/update.js +154 -0
  72. package/dist/cli/commands/update.js.map +1 -0
  73. package/dist/cli/commands/version.js +15 -1
  74. package/dist/cli/commands/version.js.map +1 -1
  75. package/dist/cli/deployment-digest.js +20 -4
  76. package/dist/cli/deployment-digest.js.map +1 -1
  77. package/dist/cli/index.js +8 -0
  78. package/dist/cli/index.js.map +1 -1
  79. package/dist/cli/password.d.ts +15 -0
  80. package/dist/cli/password.js +29 -1
  81. package/dist/cli/password.js.map +1 -1
  82. package/dist/config.d.ts +110 -7
  83. package/dist/config.js +38 -5
  84. package/dist/config.js.map +1 -1
  85. package/dist/daemon/balance-topup-loop.d.ts +40 -0
  86. package/dist/daemon/balance-topup-loop.js +96 -0
  87. package/dist/daemon/balance-topup-loop.js.map +1 -0
  88. package/dist/daemon/daemon.d.ts +37 -0
  89. package/dist/daemon/daemon.js +98 -1
  90. package/dist/daemon/daemon.js.map +1 -1
  91. package/dist/dashboard/index.html +500 -0
  92. package/dist/earning/bootstrap.d.ts +3 -1
  93. package/dist/earning/bootstrap.js +138 -17
  94. package/dist/earning/bootstrap.js.map +1 -1
  95. package/dist/earning/contracts.d.ts +24 -0
  96. package/dist/earning/contracts.js +20 -1
  97. package/dist/earning/contracts.js.map +1 -1
  98. package/dist/earning/faucet.d.ts +15 -0
  99. package/dist/earning/faucet.js +64 -0
  100. package/dist/earning/faucet.js.map +1 -0
  101. package/dist/earning/store.d.ts +5 -0
  102. package/dist/earning/store.js +7 -3
  103. package/dist/earning/store.js.map +1 -1
  104. package/dist/errors/unauthorized-account.d.ts +10 -0
  105. package/dist/errors/unauthorized-account.js +14 -0
  106. package/dist/errors/unauthorized-account.js.map +1 -0
  107. package/dist/main.js +128 -1
  108. package/dist/main.js.map +1 -1
  109. package/dist/mcp/operator-server.d.ts +34 -0
  110. package/dist/mcp/operator-server.js +219 -0
  111. package/dist/mcp/operator-server.js.map +1 -0
  112. package/dist/operator-errors.js +11 -0
  113. package/dist/operator-errors.js.map +1 -1
  114. package/dist/preflight/claude-auth.d.ts +68 -0
  115. package/dist/preflight/claude-auth.js +171 -0
  116. package/dist/preflight/claude-auth.js.map +1 -0
  117. package/dist/restorer/engine/canonical-json.d.ts +18 -0
  118. package/dist/restorer/engine/canonical-json.js +59 -0
  119. package/dist/restorer/engine/canonical-json.js.map +1 -0
  120. package/dist/restorer/engine/claim.d.ts +69 -0
  121. package/dist/restorer/engine/claim.js +104 -0
  122. package/dist/restorer/engine/claim.js.map +1 -0
  123. package/dist/restorer/engine/delivery.d.ts +52 -0
  124. package/dist/restorer/engine/delivery.js +63 -0
  125. package/dist/restorer/engine/delivery.js.map +1 -0
  126. package/dist/restorer/engine/engine.d.ts +203 -0
  127. package/dist/restorer/engine/engine.js +658 -0
  128. package/dist/restorer/engine/engine.js.map +1 -0
  129. package/dist/restorer/engine/manifest-assembly.d.ts +67 -0
  130. package/dist/restorer/engine/manifest-assembly.js +79 -0
  131. package/dist/restorer/engine/manifest-assembly.js.map +1 -0
  132. package/dist/restorer/engine/packaging.d.ts +87 -0
  133. package/dist/restorer/engine/packaging.js +350 -0
  134. package/dist/restorer/engine/packaging.js.map +1 -0
  135. package/dist/restorer/engine/persistence.d.ts +170 -0
  136. package/dist/restorer/engine/persistence.js +381 -0
  137. package/dist/restorer/engine/persistence.js.map +1 -0
  138. package/dist/restorer/engine/recovery.d.ts +22 -0
  139. package/dist/restorer/engine/recovery.js +24 -0
  140. package/dist/restorer/engine/recovery.js.map +1 -0
  141. package/dist/restorer/engine/registry.d.ts +62 -0
  142. package/dist/restorer/engine/registry.js +73 -0
  143. package/dist/restorer/engine/registry.js.map +1 -0
  144. package/dist/restorer/engine/signing.d.ts +30 -0
  145. package/dist/restorer/engine/signing.js +39 -0
  146. package/dist/restorer/engine/signing.js.map +1 -0
  147. package/dist/restorer/engine/state.d.ts +42 -0
  148. package/dist/restorer/engine/state.js +87 -0
  149. package/dist/restorer/engine/state.js.map +1 -0
  150. package/dist/restorer/impls/claude-mcp-hyperliquid/api-wallet.d.ts +64 -0
  151. package/dist/restorer/impls/claude-mcp-hyperliquid/api-wallet.js +96 -0
  152. package/dist/restorer/impls/claude-mcp-hyperliquid/api-wallet.js.map +1 -0
  153. package/dist/restorer/impls/claude-mcp-hyperliquid/index.d.ts +88 -0
  154. package/dist/restorer/impls/claude-mcp-hyperliquid/index.js +560 -0
  155. package/dist/restorer/impls/claude-mcp-hyperliquid/index.js.map +1 -0
  156. package/dist/restorer/impls/claude-mcp-hyperliquid/mcp-tools.d.ts +137 -0
  157. package/dist/restorer/impls/claude-mcp-hyperliquid/mcp-tools.js +865 -0
  158. package/dist/restorer/impls/claude-mcp-hyperliquid/mcp-tools.js.map +1 -0
  159. package/dist/restorer/impls/claude-mcp-hyperliquid/safety-rails.d.ts +74 -0
  160. package/dist/restorer/impls/claude-mcp-hyperliquid/safety-rails.js +74 -0
  161. package/dist/restorer/impls/claude-mcp-hyperliquid/safety-rails.js.map +1 -0
  162. package/dist/restorer/impls/claude-mcp-hyperliquid/session-orchestrator.d.ts +97 -0
  163. package/dist/restorer/impls/claude-mcp-hyperliquid/session-orchestrator.js +226 -0
  164. package/dist/restorer/impls/claude-mcp-hyperliquid/session-orchestrator.js.map +1 -0
  165. package/dist/restorer/impls/legacy-claude/index.d.ts +42 -0
  166. package/dist/restorer/impls/legacy-claude/index.js +60 -0
  167. package/dist/restorer/impls/legacy-claude/index.js.map +1 -0
  168. package/dist/restorer/impls/portfolio-v0-evaluator/canonical-metrics.d.ts +68 -0
  169. package/dist/restorer/impls/portfolio-v0-evaluator/canonical-metrics.js +117 -0
  170. package/dist/restorer/impls/portfolio-v0-evaluator/canonical-metrics.js.map +1 -0
  171. package/dist/restorer/impls/portfolio-v0-evaluator/checks/availability.d.ts +49 -0
  172. package/dist/restorer/impls/portfolio-v0-evaluator/checks/availability.js +91 -0
  173. package/dist/restorer/impls/portfolio-v0-evaluator/checks/availability.js.map +1 -0
  174. package/dist/restorer/impls/portfolio-v0-evaluator/checks/consistency.d.ts +78 -0
  175. package/dist/restorer/impls/portfolio-v0-evaluator/checks/consistency.js +274 -0
  176. package/dist/restorer/impls/portfolio-v0-evaluator/checks/consistency.js.map +1 -0
  177. package/dist/restorer/impls/portfolio-v0-evaluator/checks/eligibility.d.ts +23 -0
  178. package/dist/restorer/impls/portfolio-v0-evaluator/checks/eligibility.js +49 -0
  179. package/dist/restorer/impls/portfolio-v0-evaluator/checks/eligibility.js.map +1 -0
  180. package/dist/restorer/impls/portfolio-v0-evaluator/checks/integrity.d.ts +25 -0
  181. package/dist/restorer/impls/portfolio-v0-evaluator/checks/integrity.js +44 -0
  182. package/dist/restorer/impls/portfolio-v0-evaluator/checks/integrity.js.map +1 -0
  183. package/dist/restorer/impls/portfolio-v0-evaluator/checks/spec.d.ts +17 -0
  184. package/dist/restorer/impls/portfolio-v0-evaluator/checks/spec.js +43 -0
  185. package/dist/restorer/impls/portfolio-v0-evaluator/checks/spec.js.map +1 -0
  186. package/dist/restorer/impls/portfolio-v0-evaluator/index.d.ts +43 -0
  187. package/dist/restorer/impls/portfolio-v0-evaluator/index.js +431 -0
  188. package/dist/restorer/impls/portfolio-v0-evaluator/index.js.map +1 -0
  189. package/dist/restorer/impls/portfolio-v0-evaluator/score.d.ts +21 -0
  190. package/dist/restorer/impls/portfolio-v0-evaluator/score.js +32 -0
  191. package/dist/restorer/impls/portfolio-v0-evaluator/score.js.map +1 -0
  192. package/dist/restorer/impls/portfolio-v0-evaluator/types.d.ts +32 -0
  193. package/dist/restorer/impls/portfolio-v0-evaluator/types.js +8 -0
  194. package/dist/restorer/impls/portfolio-v0-evaluator/types.js.map +1 -0
  195. package/dist/restorer/impls/prediction-v0-baseline/index.d.ts +26 -0
  196. package/dist/restorer/impls/prediction-v0-baseline/index.js +82 -0
  197. package/dist/restorer/impls/prediction-v0-baseline/index.js.map +1 -0
  198. package/dist/restorer/impls/prediction-v0-baseline/strategy.d.ts +8 -0
  199. package/dist/restorer/impls/prediction-v0-baseline/strategy.js +41 -0
  200. package/dist/restorer/impls/prediction-v0-baseline/strategy.js.map +1 -0
  201. package/dist/restorer/impls/prediction-v0-baseline/types.d.ts +7 -0
  202. package/dist/restorer/impls/prediction-v0-baseline/types.js +2 -0
  203. package/dist/restorer/impls/prediction-v0-baseline/types.js.map +1 -0
  204. package/dist/restorer/impls/prediction-v0-evaluator/canonical-metrics.d.ts +20 -0
  205. package/dist/restorer/impls/prediction-v0-evaluator/canonical-metrics.js +66 -0
  206. package/dist/restorer/impls/prediction-v0-evaluator/canonical-metrics.js.map +1 -0
  207. package/dist/restorer/impls/prediction-v0-evaluator/checks/availability.d.ts +9 -0
  208. package/dist/restorer/impls/prediction-v0-evaluator/checks/availability.js +23 -0
  209. package/dist/restorer/impls/prediction-v0-evaluator/checks/availability.js.map +1 -0
  210. package/dist/restorer/impls/prediction-v0-evaluator/checks/eligibility.d.ts +3 -0
  211. package/dist/restorer/impls/prediction-v0-evaluator/checks/eligibility.js +13 -0
  212. package/dist/restorer/impls/prediction-v0-evaluator/checks/eligibility.js.map +1 -0
  213. package/dist/restorer/impls/prediction-v0-evaluator/checks/integrity.d.ts +7 -0
  214. package/dist/restorer/impls/prediction-v0-evaluator/checks/integrity.js +74 -0
  215. package/dist/restorer/impls/prediction-v0-evaluator/checks/integrity.js.map +1 -0
  216. package/dist/restorer/impls/prediction-v0-evaluator/checks/spec.d.ts +5 -0
  217. package/dist/restorer/impls/prediction-v0-evaluator/checks/spec.js +20 -0
  218. package/dist/restorer/impls/prediction-v0-evaluator/checks/spec.js.map +1 -0
  219. package/dist/restorer/impls/prediction-v0-evaluator/index.d.ts +33 -0
  220. package/dist/restorer/impls/prediction-v0-evaluator/index.js +179 -0
  221. package/dist/restorer/impls/prediction-v0-evaluator/index.js.map +1 -0
  222. package/dist/restorer/impls/prediction-v0-evaluator/score.d.ts +8 -0
  223. package/dist/restorer/impls/prediction-v0-evaluator/score.js +15 -0
  224. package/dist/restorer/impls/prediction-v0-evaluator/score.js.map +1 -0
  225. package/dist/restorer/impls/prediction-v0-evaluator/types.d.ts +7 -0
  226. package/dist/restorer/impls/prediction-v0-evaluator/types.js +2 -0
  227. package/dist/restorer/impls/prediction-v0-evaluator/types.js.map +1 -0
  228. package/dist/restorer/types.d.ts +62 -0
  229. package/dist/restorer/types.js +7 -0
  230. package/dist/restorer/types.js.map +1 -0
  231. package/dist/runner/claude.js +15 -0
  232. package/dist/runner/claude.js.map +1 -1
  233. package/dist/store/store.d.ts +3 -1
  234. package/dist/store/store.js +8 -0
  235. package/dist/store/store.js.map +1 -1
  236. package/dist/tx-retry.js +11 -1
  237. package/dist/tx-retry.js.map +1 -1
  238. package/dist/types/desired-state.d.ts +53 -0
  239. package/dist/types/desired-state.js +20 -0
  240. package/dist/types/desired-state.js.map +1 -1
  241. package/dist/types/index.d.ts +3 -1
  242. package/dist/types/index.js +3 -1
  243. package/dist/types/index.js.map +1 -1
  244. package/dist/types/portfolio.d.ts +1000 -0
  245. package/dist/types/portfolio.js +168 -0
  246. package/dist/types/portfolio.js.map +1 -0
  247. package/dist/types/prediction.d.ts +751 -0
  248. package/dist/types/prediction.js +128 -0
  249. package/dist/types/prediction.js.map +1 -0
  250. package/dist/venues/chainlink/client.d.ts +99 -0
  251. package/dist/venues/chainlink/client.js +130 -0
  252. package/dist/venues/chainlink/client.js.map +1 -0
  253. package/dist/venues/chainlink/feeds.d.ts +8 -0
  254. package/dist/venues/chainlink/feeds.js +9 -0
  255. package/dist/venues/chainlink/feeds.js.map +1 -0
  256. package/dist/venues/hyperliquid/account-value.d.ts +30 -0
  257. package/dist/venues/hyperliquid/account-value.js +30 -0
  258. package/dist/venues/hyperliquid/account-value.js.map +1 -0
  259. package/dist/venues/hyperliquid/client.d.ts +63 -0
  260. package/dist/venues/hyperliquid/client.js +135 -0
  261. package/dist/venues/hyperliquid/client.js.map +1 -0
  262. package/dist/venues/hyperliquid/grid.d.ts +36 -0
  263. package/dist/venues/hyperliquid/grid.js +61 -0
  264. package/dist/venues/hyperliquid/grid.js.map +1 -0
  265. package/dist/venues/hyperliquid/types.d.ts +81 -0
  266. package/dist/venues/hyperliquid/types.js +8 -0
  267. package/dist/venues/hyperliquid/types.js.map +1 -0
  268. package/package.json +18 -3
  269. package/skills/jinn-operator/SKILL.md +213 -0
@@ -0,0 +1,560 @@
1
+ /**
2
+ * claude-mcp-hyperliquid — Reference RestorerImpl for portfolio.v0 — §8.
3
+ *
4
+ * Spawns Claude Code session(s) with HL-specific MCP tools (§8.2).
5
+ * Safety rails enforced at the tool boundary (§8.3).
6
+ * Sequential session cadence per §8.4.
7
+ * API wallet managed in implStateDir (§8.1).
8
+ *
9
+ * OPERATOR PREREQUISITE (v0):
10
+ * Before this impl can place trades, the operator must:
11
+ * 1. Let the daemon boot once (or call canAttempt()) to generate the API wallet.
12
+ * 2. Approve the generated API wallet address on their HL master account
13
+ * (Settings → API Wallets → Add in the HL UI).
14
+ * 3. Set approved:true in <implStateDir>/api-wallet.json
15
+ *
16
+ * The impl will surface the wallet address and instructions in canAttempt()
17
+ * if the wallet is not yet approved.
18
+ *
19
+ * Programmatic approval is a §8.5 future item.
20
+ */
21
+ import { writeFileSync, mkdirSync, chmodSync } from 'node:fs';
22
+ import { join } from 'node:path';
23
+ import { HyperliquidClient, HL_MAINNET_BASE_URL, HL_TESTNET_BASE_URL } from '../../../venues/hyperliquid/client.js';
24
+ import { getUnifiedAccountValue } from '../../../venues/hyperliquid/account-value.js';
25
+ import { PortfolioV0IntentSchema, PortfolioV0EligibilitySchema, } from '../../../types/portfolio.js';
26
+ import { equityCurve, equityReturnPct, maxDrawdownPct, closedTradesCount, tradedNotionalMultiple, } from '../portfolio-v0-evaluator/canonical-metrics.js';
27
+ import { provisionApiWallet } from './api-wallet.js';
28
+ import { buildHlTools } from './mcp-tools.js';
29
+ import { createRateLimitState, DEFAULT_SAFETY_CONFIG as DEFAULT_SAFETY_CONFIG_IMPORTED } from './safety-rails.js';
30
+ import { runSessionLoop } from './session-orchestrator.js';
31
+ // ── Impl ───────────────────────────────────────────────────────────────────────
32
+ export class ClaudeMcpHyperliquidImpl {
33
+ name = 'claude-mcp-hyperliquid';
34
+ version = '1.0.0';
35
+ config;
36
+ constructor(config = {}) {
37
+ this.config = config;
38
+ }
39
+ supports(ctx) {
40
+ return ctx.kind === 'portfolio.v0' && ctx.type !== 'evaluation';
41
+ }
42
+ async canAttempt(intent) {
43
+ if (!intent.spec || intent.spec['kind'] !== 'portfolio.v0') {
44
+ return { ok: false, reason: 'spec.kind is not portfolio.v0' };
45
+ }
46
+ // Validate the intent shape
47
+ const parseResult = PortfolioV0IntentSchema.safeParse(intent);
48
+ if (!parseResult.success) {
49
+ return {
50
+ ok: false,
51
+ reason: `Invalid portfolio.v0 intent: ${parseResult.error.message}`,
52
+ };
53
+ }
54
+ // implStateDir is not available in canAttempt — we can only check
55
+ // if the intent is structurally valid. API wallet check is done at run() time.
56
+ return { ok: true };
57
+ }
58
+ async run(ctx) {
59
+ const { intent, implStateDir, workingDir, log, abort, msUntilEndTs } = ctx;
60
+ const testDeps = this.config._testDeps;
61
+ log({ level: 'info', msg: 'claude-mcp-hyperliquid: starting', data: { implStateDir, workingDir } });
62
+ // ── Parse intent ──────────────────────────────────────────────────────────
63
+ const portfolioIntent = PortfolioV0IntentSchema.parse(intent);
64
+ const { masterAddress, venue } = portfolioIntent.spec.account;
65
+ const eligibility = PortfolioV0EligibilitySchema.parse(portfolioIntent.eligibility ?? {});
66
+ const window = portfolioIntent.window;
67
+ // ── Select HL client ──────────────────────────────────────────────────────
68
+ const hlBaseUrl = venue === 'hyperliquid-mainnet' ? HL_MAINNET_BASE_URL : HL_TESTNET_BASE_URL;
69
+ const hlClient = testDeps?.hlClient ?? new HyperliquidClient(hlBaseUrl);
70
+ // ── Provision API wallet ──────────────────────────────────────────────────
71
+ const walletState = provisionApiWallet(implStateDir);
72
+ if (!walletState.approved && !testDeps) {
73
+ log({
74
+ level: 'warn',
75
+ msg: 'claude-mcp-hyperliquid: API wallet not approved — write tools will fail. Operator action required.',
76
+ data: {
77
+ apiWalletAddress: walletState.address,
78
+ instructions: [
79
+ '1. Go to Hyperliquid Settings → API Wallets → Add',
80
+ `2. Approve address: ${walletState.address}`,
81
+ '3. Set approved:true in <implStateDir>/api-wallet.json',
82
+ ],
83
+ },
84
+ });
85
+ // Continue anyway — read-only sessions still work; write tools will fail at the HL exchange layer
86
+ }
87
+ // Sanity check: the agent key stored in api-wallet.json was approved by a
88
+ // specific master. HL routes trades to THAT master, regardless of what the
89
+ // intent's spec says. If the operator switched masters (new wallet, new
90
+ // approval) without updating the intent, every trade would silently land
91
+ // on the wrong account and pre/post snapshots would read the wrong equity.
92
+ // Fail fast with a clear remedy.
93
+ if (!testDeps
94
+ && walletState.masterAddress !== undefined
95
+ && walletState.masterAddress.toLowerCase() !== masterAddress.toLowerCase()) {
96
+ throw new Error(`E_MASTER_MISMATCH: api-wallet.json says the agent ${walletState.address} is approved by ` +
97
+ `${walletState.masterAddress}, but the intent's spec.account.masterAddress is ${masterAddress}. ` +
98
+ `HL would route trades to the agent's approver (${walletState.masterAddress}) while pre/post ` +
99
+ `snapshots would read from the intent's master (${masterAddress}) — silent fund-on-the-wrong-account bug. ` +
100
+ `Remedy: either (a) update ~/.jinn-client/portfolio-v0-intent.json to use masterAddress=${walletState.masterAddress}, ` +
101
+ `or (b) approve the agent on the intent's master (${masterAddress}) via the HL UI and update ${implStateDir}/api-wallet.json.`);
102
+ }
103
+ // ── Take pre-snapshot ─────────────────────────────────────────────────────
104
+ //
105
+ // Pre/post snapshots source equity from HL's unified view: perps
106
+ // `marginSummary.accountValue` + spot USDC balance. This matches the
107
+ // `portfolio` endpoint's `accountValueHistory` (which reports the unified
108
+ // figure too), so restorer-claimed equity and evaluator-rederived grid
109
+ // points compare cleanly — and accounts parked on spot are not ignored.
110
+ log({ level: 'info', msg: 'claude-mcp-hyperliquid: taking pre-snapshot' });
111
+ const preUnified = await getUnifiedAccountValue(hlClient, masterAddress);
112
+ const preSnapshot = {
113
+ capturedAt: Date.now(),
114
+ hlTime: preUnified.clearinghouseState.time,
115
+ payload: buildSnapshotPayload(preUnified),
116
+ };
117
+ log({
118
+ level: 'info',
119
+ msg: 'claude-mcp-hyperliquid: pre-snapshot captured',
120
+ data: {
121
+ accountValue: preUnified.accountValue,
122
+ perpsAccountValue: preUnified.perpsAccountValue,
123
+ spotUsdc: preUnified.spotUsdc,
124
+ },
125
+ });
126
+ // ── Set up session infrastructure ─────────────────────────────────────────
127
+ const writeOps = [];
128
+ const rateLimitState = createRateLimitState();
129
+ // Build HL tools (shared across sessions via closure)
130
+ const hlTools = buildHlTools({
131
+ hlClient,
132
+ hlBaseUrl,
133
+ apiWalletPrivateKey: walletState.privateKey,
134
+ apiWalletAddress: walletState.address,
135
+ masterAddress,
136
+ safetyConfig: this.config.safetyConfig
137
+ ? { ...DEFAULT_SAFETY_CONFIG_IMPORTED, ...this.config.safetyConfig }
138
+ : undefined,
139
+ rateLimitState,
140
+ onWriteOp: (op) => writeOps.push(op),
141
+ });
142
+ // ── MCP config for Claude sessions ────────────────────────────────────────
143
+ // The HL tools are served via an in-process MCP server written to a temp script.
144
+ // We create a per-run MCP config that includes both:
145
+ // 1. The existing jinn-client MCP server (tool: submit_restoration_result etc)
146
+ // 2. A new HL-specific MCP server (tool: hl_*)
147
+ //
148
+ // The HL server is an inline node script that creates a McpServer with the tools.
149
+ // We write it to workingDir/mcp/hl-server.ts and reference it in the config.
150
+ const hlMcpServerPath = join(workingDir, 'mcp', 'hl-server.mjs');
151
+ // Config file path — written by _writeHlMcpServerScript alongside the script
152
+ const hlMcpConfigPath = join(workingDir, 'mcp', 'hl-server-config.json');
153
+ mkdirSync(join(workingDir, 'mcp'), { recursive: true });
154
+ _writeHlMcpServerScript(hlMcpServerPath, {
155
+ hlBaseUrl,
156
+ apiWalletPrivateKey: walletState.privateKey,
157
+ apiWalletAddress: walletState.address,
158
+ masterAddress,
159
+ safetyConfig: this.config.safetyConfig,
160
+ });
161
+ const { command: jinnMcpCommand, args: jinnMcpArgs } = _resolveJinnMcpLauncher();
162
+ const mcpConfigPath = join(workingDir, 'mcp', 'mcp-config.json');
163
+ writeFileSync(mcpConfigPath, JSON.stringify({
164
+ mcpServers: {
165
+ 'jinn-client': {
166
+ command: jinnMcpCommand,
167
+ args: jinnMcpArgs,
168
+ env: {
169
+ DESIRED_STATE_ID: intent.id,
170
+ DESIRED_STATE_DESCRIPTION: intent.description,
171
+ DESIRED_STATE_CONTEXT: intent.context ? JSON.stringify(intent.context) : '',
172
+ DESIRED_STATE_TYPE: intent.type ?? '',
173
+ RESTORATION_REQUEST_ID: intent.restorationRequestId ?? '',
174
+ REQUEST_ID: intent.restorationRequestId ?? '',
175
+ },
176
+ },
177
+ 'jinn-hl': {
178
+ command: process.execPath,
179
+ // Pass config file path as argv[2] — private key is in config file, not script body
180
+ args: [hlMcpServerPath, hlMcpConfigPath],
181
+ },
182
+ },
183
+ }));
184
+ // ── Session loop ──────────────────────────────────────────────────────────
185
+ const rationale = [];
186
+ let allSessions = [];
187
+ if (testDeps?.runSession) {
188
+ // Test mode: use injected runner instead of spawning Claude
189
+ allSessions = await _runTestSessions(testDeps.runSession, intent, portfolioIntent, workingDir, abort, msUntilEndTs, log, this.config);
190
+ }
191
+ else {
192
+ // Production mode: spawn Claude with MCP config
193
+ const preAccountValue = parseFloat(preUnified.accountValue);
194
+ const loopResult = await runSessionLoop((sessionNum, sessionId) => buildSessionPrompt({
195
+ sessionNum,
196
+ sessionId,
197
+ intent: portfolioIntent,
198
+ preAccountValue,
199
+ msUntilEndTs: msUntilEndTs(),
200
+ }), {
201
+ claudePath: this.config.claudePath ?? 'claude',
202
+ claudeModel: this.config.claudeModel,
203
+ mcpConfigPath,
204
+ workingDir,
205
+ abort,
206
+ msUntilEndTs,
207
+ log,
208
+ getMids: () => hlClient.allMids(),
209
+ // Write a per-session outcome.json as soon as each Claude subprocess
210
+ // exits. Consumed by gather-status.ts / portfolio-v0-build.ts to
211
+ // surface `recentClaudeOutcomes` in /v1/status — operators can see
212
+ // trading activity before the 24h window closes.
213
+ //
214
+ // NOTE: the daemon-side `writeOps` closure was initially used for
215
+ // tool-call counts, but the actual MCP tool invocations happen in
216
+ // Claude's hl-server.mjs SUBPROCESS — the daemon's callback is never
217
+ // wired to that server. So the authoritative counter for real trading
218
+ // is HL's own userFillsByTime: ask HL what filled between the
219
+ // session's start/end (±5s padding for clock skew) and report that.
220
+ onSessionEnd: async (sr) => {
221
+ try {
222
+ const outcomePath = join(workingDir, 'sessions', sr.sessionId, 'outcome.json');
223
+ let fillsInWindow = [];
224
+ let fillsQueryError = null;
225
+ try {
226
+ // Give HL a moment to propagate fills before we query.
227
+ await new Promise(r => setTimeout(r, 2000));
228
+ const { fills } = await hlClient.userFillsByTime(masterAddress, sr.startedAt - 5_000, sr.endedAt + 5_000);
229
+ fillsInWindow = fills.map(f => ({ coin: f.coin, dir: f.dir, oid: f.oid }));
230
+ }
231
+ catch (err) {
232
+ fillsQueryError = err instanceof Error ? err.message : String(err);
233
+ }
234
+ const coinCounts = {};
235
+ for (const f of fillsInWindow) {
236
+ coinCounts[f.coin] = (coinCounts[f.coin] ?? 0) + 1;
237
+ }
238
+ const outcome = {
239
+ schemaVersion: 2,
240
+ requestId: ctx.intent.restorationRequestId ?? ctx.intent.id,
241
+ sessionId: sr.sessionId,
242
+ startedAt: sr.startedAt,
243
+ endedAt: sr.endedAt,
244
+ durationMs: sr.endedAt - sr.startedAt,
245
+ aborted: sr.aborted,
246
+ fillsInSessionWindow: fillsInWindow.length,
247
+ coinCounts,
248
+ ...(fillsQueryError !== null ? { fillsQueryError } : {}),
249
+ };
250
+ writeFileSync(outcomePath, JSON.stringify(outcome, null, 2), { encoding: 'utf-8' });
251
+ }
252
+ catch (err) {
253
+ log({
254
+ level: 'warn',
255
+ msg: 'claude-mcp-hyperliquid: failed to write session outcome.json',
256
+ data: { sessionId: sr.sessionId, err: err instanceof Error ? err.message : String(err) },
257
+ });
258
+ }
259
+ },
260
+ config: {
261
+ cadenceMs: this.config.cadenceMs,
262
+ sessionMaxMs: this.config.sessionMaxMs,
263
+ trackedCoins: [], // could be populated from intent context
264
+ },
265
+ });
266
+ allSessions = loopResult.sessions;
267
+ }
268
+ // ── Post-session: match fills to sessions ─────────────────────────────────
269
+ log({ level: 'info', msg: 'claude-mcp-hyperliquid: matching fills to sessions' });
270
+ let windowFills = [];
271
+ try {
272
+ const fillsResult = await hlClient.userFillsByTime(masterAddress, window.startTs, window.endTs);
273
+ windowFills = fillsResult.fills;
274
+ }
275
+ catch (e) {
276
+ log({ level: 'warn', msg: 'claude-mcp-hyperliquid: failed to fetch window fills', data: { err: e instanceof Error ? e.message : String(e) } });
277
+ }
278
+ // Match fills to sessions by timestamp
279
+ for (const session of allSessions) {
280
+ const sessionFillTids = windowFills
281
+ .filter((f) => f.time >= session.startedAt - 5000 && f.time <= session.endedAt + 5000)
282
+ .map((f) => f.tid);
283
+ session.initiatedFillTids = sessionFillTids;
284
+ if (sessionFillTids.length > 0) {
285
+ rationale.push({
286
+ ts: session.startedAt,
287
+ sessionId: session.sessionId,
288
+ note: `Session completed with ${sessionFillTids.length} fills`,
289
+ relatedFillTids: sessionFillTids,
290
+ });
291
+ }
292
+ }
293
+ // ── Take post-snapshot ────────────────────────────────────────────────────
294
+ log({ level: 'info', msg: 'claude-mcp-hyperliquid: taking post-snapshot' });
295
+ let postUnified;
296
+ try {
297
+ postUnified = await getUnifiedAccountValue(hlClient, masterAddress);
298
+ }
299
+ catch (e) {
300
+ log({ level: 'error', msg: 'claude-mcp-hyperliquid: failed to take post-snapshot', data: { err: e instanceof Error ? e.message : String(e) } });
301
+ // Use pre-snapshot as fallback
302
+ postUnified = preUnified;
303
+ }
304
+ const postSnapshot = {
305
+ capturedAt: Date.now(),
306
+ hlTime: postUnified.clearinghouseState.time,
307
+ payload: buildSnapshotPayload(postUnified),
308
+ };
309
+ // ── Compute canonical metrics (import from evaluator — §8 task discipline) ─
310
+ const preValue = parseFloat(preUnified.accountValue);
311
+ const postValue = parseFloat(postUnified.accountValue);
312
+ const fillTimes = windowFills.map((f) => f.time);
313
+ const curve = equityCurve(preSnapshot.capturedAt, preValue, postSnapshot.capturedAt, postValue, fillTimes);
314
+ const equityReturn = equityReturnPct(preValue, postValue);
315
+ const drawdown = maxDrawdownPct(curve);
316
+ const closedTrades = closedTradesCount(windowFills);
317
+ const notional = tradedNotionalMultiple(windowFills, preValue);
318
+ log({
319
+ level: 'info',
320
+ msg: 'claude-mcp-hyperliquid: metrics computed',
321
+ data: { equityReturn, drawdown, closedTrades, notional },
322
+ });
323
+ // ── Build artifacts list (transcripts) ────────────────────────────────────
324
+ const artifacts = allSessions.map((session) => ({
325
+ path: `sessions/${session.sessionId}/transcript.txt`,
326
+ role: 'session_transcript',
327
+ metadata: {
328
+ sessionId: session.sessionId,
329
+ startedAt: session.startedAt,
330
+ endedAt: session.endedAt,
331
+ modelId: this.config.claudeModel ?? 'unknown',
332
+ initiatedFillTids: session.initiatedFillTids,
333
+ },
334
+ tags: ['transcript', 'session'],
335
+ access: { kind: 'open' },
336
+ }));
337
+ // ── Return RestorationOutput ──────────────────────────────────────────────
338
+ return {
339
+ venueRef: { name: venue === 'hyperliquid-mainnet' ? 'hyperliquid-mainnet' : 'hyperliquid-testnet' },
340
+ preSnapshot,
341
+ postSnapshot,
342
+ fills: windowFills,
343
+ gating: {
344
+ equityReturnPct: String(equityReturn),
345
+ maxDrawdownPct: String(drawdown),
346
+ closedTradesCount: closedTrades,
347
+ tradedNotionalMultiple: String(notional),
348
+ },
349
+ informational: {
350
+ sessionCount: allSessions.length,
351
+ totalWriteOps: writeOps.length,
352
+ preAccountValue: String(preValue),
353
+ postAccountValue: String(postValue),
354
+ windowFillCount: windowFills.length,
355
+ minReturnPct: portfolioIntent.spec.target.minReturnPct,
356
+ maxDrawdownConstraint: portfolioIntent.spec.constraint.maxDrawdownPct,
357
+ minClosedTrades: eligibility.minClosedTrades,
358
+ minTradedNotionalMultiple: eligibility.minTradedNotionalMultiple,
359
+ },
360
+ artifacts,
361
+ rationale,
362
+ };
363
+ }
364
+ }
365
+ // ── Snapshot payload ──────────────────────────────────────────────────────────
366
+ /**
367
+ * Build the on-manifest snapshot payload from a unified account-value result.
368
+ *
369
+ * The top-level `accountValue` is the canonical figure used for metrics and
370
+ * consistency checks (matches HL's `portfolio` endpoint unified equity).
371
+ * The raw perps and spot payloads are included verbatim for auditability.
372
+ */
373
+ function buildSnapshotPayload(unified) {
374
+ return {
375
+ accountValue: unified.accountValue,
376
+ perpsAccountValue: unified.perpsAccountValue,
377
+ spotUsdc: unified.spotUsdc,
378
+ clearinghouseState: unified.clearinghouseState,
379
+ spotClearinghouseState: unified.spotClearinghouseState,
380
+ };
381
+ }
382
+ function buildSessionPrompt(params) {
383
+ const { sessionNum, sessionId, intent, preAccountValue, msUntilEndTs } = params;
384
+ const minsRemaining = Math.round(msUntilEndTs / 60_000);
385
+ const { minReturnPct } = intent.spec.target;
386
+ const { maxDrawdownPct } = intent.spec.constraint;
387
+ const { masterAddress } = intent.spec.account;
388
+ return `EXECUTE IMMEDIATELY. DO NOT WRITE TEXT BEFORE YOUR FIRST TOOL CALL. DO NOT ASK QUESTIONS.
389
+
390
+ Your first action this turn MUST be a tool call to \`hl_account_unified\`. Begin now.
391
+
392
+ You are an autonomous trader managing a Hyperliquid perpetuals portfolio. Every turn, you call tools, observe results, and decide the next action. You never defer to a human — there is no human in the loop. The only way to satisfy the intent is to open positions, close them, and repeat enough times to hit the targets below.
393
+
394
+ ## Verdict criteria (ALL four must pass for a PASS verdict)
395
+ - Equity return ≥ ${minReturnPct}% over the 24h window
396
+ - Max drawdown ≤ ${maxDrawdownPct}% peak-to-trough
397
+ - At least 20 closed trades
398
+ - Traded notional ≥ 5× starting equity (~$${(preAccountValue * 5).toFixed(2)})
399
+
400
+ Missing any one → REJECTED → zero rewards. Inaction = REJECTED.
401
+
402
+ ## Context
403
+ - Intent: ${intent.description}
404
+ - Master account: ${masterAddress}
405
+ - Starting equity: $${preAccountValue.toFixed(2)}
406
+ - Session ${sessionNum} (${sessionId})
407
+ - Time remaining in window: ${minsRemaining} min
408
+ - You run again in ~30 minutes, or sooner on ≥2% mid-move. Use this session fully.
409
+
410
+ ## Tools you will call (all are MCP tools — call them by name)
411
+ Read (prefer these):
412
+ - \`hl_account_unified\` — PREFERRED single-call read: unified equity (perps+spot), positions, open orders
413
+ - \`hl_all_mids\` — current mid prices for all assets
414
+ - \`hl_user_fills\` — recent fills (check turnover + trade count)
415
+ - \`hl_meta\` — asset metadata (max leverage, size decimals)
416
+ Read (niche):
417
+ - \`hl_clearinghouse_state\` — perps-only snapshot; DO NOT use for decisions (hides spot USDC)
418
+ - \`hl_portfolio\` — historical equity curve
419
+ Write: \`hl_open_position\`, \`hl_close_position\`, \`hl_modify_position\`, \`hl_cancel_orders\`
420
+
421
+ ## Risk rails (tool-enforced — not suggestions)
422
+ - Max 25% of account value per position
423
+ - Max 10× leverage
424
+ - Max 50 bps slippage
425
+ - **Every \`hl_open_position\` MUST include both \`tp\` (take-profit) and \`sl\` (stop-loss)**. The tool rejects bare opens with \`TPSL_REQUIRED\` unless you pass \`bypassRiskRails=true\`. Only bypass for a scalp you will close THIS turn. Between turns you're unprotected — ~30 min of tail risk is enough to break the ${maxDrawdownPct}% drawdown on a 5–10× move.
426
+ - Sensible starting ranges: sl at 1–2% adverse from mid; tp at 1–3% favorable. Example long at mid $2300: \`sl=2265\` (−1.5%), \`tp=2345\` (+2%).
427
+ - The tool validates tp/sl are on the correct sides of mid. A long with sl≥mid or tp≤mid returns \`SL_INVALID\`/\`TP_INVALID\`.
428
+
429
+ ## Your turn (do this sequence in tool calls, not prose)
430
+ 1. \`hl_account_unified\` — one call, gives you unified equity + positions + open orders
431
+ 2. \`hl_all_mids\` — current prices for majors (BTC, ETH, SOL, at minimum)
432
+ 3. \`hl_user_fills\` — recent fills so you know your turnover + trade count so far
433
+ 4. Based on the read tool outputs, open/adjust/close positions with the write tools. Aim for at least 2–3 position actions in this session. You have 20+ trades to hit across the window — aggressive, disciplined turnover is required, not careful inaction.
434
+ 5. Emit a ONE-PARAGRAPH rationale as your final text message after the tool calls. Not before.
435
+
436
+ Begin with \`hl_account_unified\` now. No preamble.`;
437
+ }
438
+ // ── Test session runner ────────────────────────────────────────────────────────
439
+ async function _runTestSessions(runSession, intent, portfolioIntent, workingDir, abort, msUntilEndTs, log, config) {
440
+ const sessions = [];
441
+ let sessionNum = 0;
442
+ // Run a single test session (tests don't need full cadence)
443
+ if (!abort.aborted && msUntilEndTs() > 0) {
444
+ sessionNum++;
445
+ const sessionId = `test-session-${sessionNum}`;
446
+ const startedAt = Date.now();
447
+ const sessionDir = join(workingDir, 'sessions', sessionId);
448
+ mkdirSync(sessionDir, { recursive: true });
449
+ const transcriptPath = join(sessionDir, 'transcript.txt');
450
+ let stdout = '';
451
+ try {
452
+ const result = await runSession(sessionId, `Session ${sessionNum} for ${intent.id}`);
453
+ stdout = result.stdout;
454
+ }
455
+ catch (e) {
456
+ log({ level: 'warn', msg: 'claude-mcp-hyperliquid: test session threw', data: { err: e instanceof Error ? e.message : String(e) } });
457
+ }
458
+ writeFileSync(transcriptPath, stdout || '(test session — no output)');
459
+ sessions.push({
460
+ sessionId,
461
+ startedAt,
462
+ endedAt: Date.now(),
463
+ transcriptPath,
464
+ aborted: abort.aborted,
465
+ stdout,
466
+ initiatedFillTids: [],
467
+ });
468
+ }
469
+ return sessions;
470
+ }
471
+ /**
472
+ * Write a thin ESM wrapper script to disk that delegates to the compiled
473
+ * startMcpServer() from this package. This is spawned as a subprocess by
474
+ * Claude's --mcp-config.
475
+ *
476
+ * Security: the config (including apiWalletPrivateKey) is written to a
477
+ * SEPARATE file (hl-server-config.json) with mode 0o600. The script body
478
+ * receives only the config file path via process.argv[2] — no private key
479
+ * or secret data appears in the script source.
480
+ *
481
+ * The import path is resolved at write-time from __dirname (this module's
482
+ * location) so it always points to the compiled mcp-tools.js alongside this
483
+ * file. The daemon MUST run from a compiled build (dist/) — `yarn build`
484
+ * produces `dist/restorer/impls/claude-mcp-hyperliquid/mcp-tools.js`, which
485
+ * this wrapper imports by absolute path from plain Node. Running from tsx
486
+ * against src/ would leave mcp-tools.js non-existent and cause Claude to
487
+ * silently spawn with no HL tools loaded — hence the explicit existence
488
+ * check and `E_DAEMON_MUST_RUN_FROM_DIST` error below.
489
+ */
490
+ export function _writeHlMcpServerScript(outPath, hlConfig) {
491
+ // Absolute path to the compiled mcp-tools module, alongside this file.
492
+ const mcpToolsPath = join(__dirname, 'mcp-tools.js');
493
+ // Production guardrail: the generated wrapper is loaded by plain Node (the
494
+ // Claude subprocess's --mcp-config launches `node hl-server.mjs`), which
495
+ // can only import `.js`. Running the daemon via tsx against src/ leaves
496
+ // mcp-tools.js non-existent and Claude spawns with zero HL tools — a
497
+ // silent failure that looks like "Claude refused to trade." Skipped under
498
+ // NODE_ENV=test so vitest runs don't need a preceding `yarn build`.
499
+ if (process.env['NODE_ENV'] !== 'test' && !existsSync(mcpToolsPath)) {
500
+ throw new Error(`E_DAEMON_MUST_RUN_FROM_DIST: ${mcpToolsPath} does not exist. ` +
501
+ `The Jinn daemon must run from a compiled build (e.g. \`node dist/bin/jinn.js run\`), ` +
502
+ `not directly via tsx/ts-node against src/. ` +
503
+ `If you're developing, run \`yarn dev\` (build + run alias) instead of \`yarn jinn run\`. ` +
504
+ `If you installed via npm, the compiled artifact ships in the package — reinstall with ` +
505
+ `\`npm install -g @jinn-network/client@latest\` and use the \`jinn\` binary directly.`);
506
+ }
507
+ // Write config (including private key) to a separate file alongside the script,
508
+ // with restricted permissions — private key must not be world-readable.
509
+ const scriptDir = join(outPath, '..');
510
+ const configPath = join(scriptDir, 'hl-server-config.json');
511
+ // Write config with restricted permissions — private key must not be world-readable
512
+ writeFileSync(configPath, JSON.stringify(hlConfig), { encoding: 'utf-8', mode: 0o600 });
513
+ // Explicitly chmod in case the umask relaxed the mode
514
+ chmodSync(configPath, 0o600);
515
+ const script = `#!/usr/bin/env node
516
+ // Auto-generated HL MCP server wrapper — do not edit.
517
+ // Delegates to the compiled mcp-tools module so the real EIP-712 signing path
518
+ // is always active. See: ${mcpToolsPath}
519
+ //
520
+ // The private key is NOT embedded here — it is read from the config file
521
+ // passed as process.argv[2]. The config file is created at mode 0o600.
522
+ //
523
+ // We deliberately do NOT unlink the config file on exit. Each Claude session
524
+ // spawns a fresh hl-server.mjs child (via --mcp-config); deleting the config
525
+ // when session N exits means session N+1 starts with no HL tools and hangs
526
+ // until sessionMaxMs. The working directory is ephemeral — it gets cleared
527
+ // on next attempt — so leaving the mode-0o600 config in place is safe.
528
+ import { readFileSync } from 'node:fs';
529
+ import { startMcpServer } from ${JSON.stringify(mcpToolsPath)};
530
+
531
+ const configPath = process.argv[2];
532
+ if (!configPath) {
533
+ process.stderr.write('Usage: hl-server.mjs <config-file-path>\\n');
534
+ process.exit(1);
535
+ }
536
+
537
+ const config = JSON.parse(readFileSync(configPath, 'utf-8'));
538
+ await startMcpServer(config);
539
+ `.trim();
540
+ writeFileSync(outPath, script, { encoding: 'utf-8', mode: 0o600 });
541
+ }
542
+ // ── Jinn MCP launcher resolution ──────────────────────────────────────────────
543
+ import { existsSync } from 'node:fs';
544
+ import { dirname } from 'node:path';
545
+ import { fileURLToPath } from 'node:url';
546
+ const __dirname = dirname(fileURLToPath(import.meta.url));
547
+ function _resolveJinnMcpLauncher() {
548
+ const mcpDir = join(__dirname, '..', '..', '..', 'mcp');
549
+ const js = join(mcpDir, 'server.js');
550
+ const ts = join(mcpDir, 'server.ts');
551
+ if (existsSync(js)) {
552
+ return { command: process.execPath, args: [js] };
553
+ }
554
+ if (existsSync(ts)) {
555
+ return { command: process.execPath, args: ['--import', 'tsx', ts] };
556
+ }
557
+ return { command: process.execPath, args: [js] };
558
+ }
559
+ export default ClaudeMcpHyperliquidImpl;
560
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/restorer/impls/claude-mcp-hyperliquid/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,SAAS,C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