visionclaw 0.1.220-beta.2 → 0.1.220-beta.21

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 (239) hide show
  1. package/README.md +2 -2
  2. package/dist/agent/activity-tracker.d.ts +8 -17
  3. package/dist/agent/activity-tracker.d.ts.map +1 -1
  4. package/dist/agent/activity-tracker.js +11 -25
  5. package/dist/agent/activity-tracker.js.map +1 -1
  6. package/dist/agent/command-handlers.js +1 -1
  7. package/dist/agent/command-handlers.js.map +1 -1
  8. package/dist/agent/context.d.ts +0 -22
  9. package/dist/agent/context.d.ts.map +1 -1
  10. package/dist/agent/context.js +0 -79
  11. package/dist/agent/context.js.map +1 -1
  12. package/dist/agent/engine-switch-handler.d.ts +2 -2
  13. package/dist/agent/engine-switch-handler.js +3 -3
  14. package/dist/agent/engine-switch-handler.js.map +1 -1
  15. package/dist/agent/engine-switch-target.d.ts.map +1 -1
  16. package/dist/agent/engine-switch-target.js +5 -1
  17. package/dist/agent/engine-switch-target.js.map +1 -1
  18. package/dist/agent/engine-switch.d.ts +4 -4
  19. package/dist/agent/engine-switch.d.ts.map +1 -1
  20. package/dist/agent/engine-switch.js +9 -3
  21. package/dist/agent/engine-switch.js.map +1 -1
  22. package/dist/agent/engines/claude/session.d.ts +2 -1
  23. package/dist/agent/engines/claude/session.d.ts.map +1 -1
  24. package/dist/agent/engines/claude/session.js +5 -4
  25. package/dist/agent/engines/claude/session.js.map +1 -1
  26. package/dist/agent/engines/pi/tools.d.ts.map +1 -1
  27. package/dist/agent/engines/pi/tools.js +3 -1
  28. package/dist/agent/engines/pi/tools.js.map +1 -1
  29. package/dist/agent/engines/pi-coding/mcp-config.d.ts +10 -1
  30. package/dist/agent/engines/pi-coding/mcp-config.d.ts.map +1 -1
  31. package/dist/agent/engines/pi-coding/mcp-config.js +4 -7
  32. package/dist/agent/engines/pi-coding/mcp-config.js.map +1 -1
  33. package/dist/agent/engines/pi-coding/session.d.ts +1 -1
  34. package/dist/agent/engines/pi-coding/session.d.ts.map +1 -1
  35. package/dist/agent/engines/pi-coding/session.js +17 -22
  36. package/dist/agent/engines/pi-coding/session.js.map +1 -1
  37. package/dist/agent/engines/session-types.d.ts +2 -0
  38. package/dist/agent/engines/session-types.d.ts.map +1 -1
  39. package/dist/agent/fast-response-eligibility.d.ts +2 -2
  40. package/dist/agent/fast-response-eligibility.d.ts.map +1 -1
  41. package/dist/agent/fast-response-eligibility.js +10 -2
  42. package/dist/agent/fast-response-eligibility.js.map +1 -1
  43. package/dist/agent/interrupt-handler.d.ts +2 -2
  44. package/dist/agent/interrupt-handler.js +4 -4
  45. package/dist/agent/interrupt-handler.js.map +1 -1
  46. package/dist/agent/llm-engine-capabilities.d.ts.map +1 -1
  47. package/dist/agent/llm-engine-capabilities.js +4 -1
  48. package/dist/agent/llm-engine-capabilities.js.map +1 -1
  49. package/dist/agent/loop.d.ts +0 -2
  50. package/dist/agent/loop.d.ts.map +1 -1
  51. package/dist/agent/loop.js +12 -4
  52. package/dist/agent/loop.js.map +1 -1
  53. package/dist/agent/model-provider.d.ts +1 -7
  54. package/dist/agent/model-provider.d.ts.map +1 -1
  55. package/dist/agent/model-provider.js +2 -10
  56. package/dist/agent/model-provider.js.map +1 -1
  57. package/dist/agent/owner-initiated-eligibility.d.ts +2 -0
  58. package/dist/agent/owner-initiated-eligibility.d.ts.map +1 -1
  59. package/dist/agent/owner-initiated-eligibility.js +5 -15
  60. package/dist/agent/owner-initiated-eligibility.js.map +1 -1
  61. package/dist/agent/reply-watchdog.d.ts +1 -1
  62. package/dist/agent/reply-watchdog.js +2 -2
  63. package/dist/agent/reply-watchdog.js.map +1 -1
  64. package/dist/agent/runtime-surface.d.ts +2 -0
  65. package/dist/agent/runtime-surface.d.ts.map +1 -1
  66. package/dist/agent/runtime-surface.js +12 -2
  67. package/dist/agent/runtime-surface.js.map +1 -1
  68. package/dist/agent/status.js +1 -1
  69. package/dist/agent/status.js.map +1 -1
  70. package/dist/agent/stream-handler.d.ts.map +1 -1
  71. package/dist/agent/stream-handler.js +48 -22
  72. package/dist/agent/stream-handler.js.map +1 -1
  73. package/dist/agent/system-prompt.d.ts.map +1 -1
  74. package/dist/agent/system-prompt.js +10 -4
  75. package/dist/agent/system-prompt.js.map +1 -1
  76. package/dist/agent/wake-cycle-runner.d.ts +1 -1
  77. package/dist/agent/wake-cycle-runner.d.ts.map +1 -1
  78. package/dist/agent/wake-cycle-runner.js +2 -3
  79. package/dist/agent/wake-cycle-runner.js.map +1 -1
  80. package/dist/builtin-skills/rethinka-fund/SKILL.md +287 -28
  81. package/dist/builtin-skills/rethinka-fund/core-contract.md +30 -14
  82. package/dist/channels/interface.d.ts +0 -34
  83. package/dist/channels/interface.d.ts.map +1 -1
  84. package/dist/channels/manager.d.ts.map +1 -1
  85. package/dist/channels/manager.js +4 -0
  86. package/dist/channels/manager.js.map +1 -1
  87. package/dist/channels/qq.js +1 -1
  88. package/dist/channels/qq.js.map +1 -1
  89. package/dist/channels/rethinka-fund.d.ts +16 -3
  90. package/dist/channels/rethinka-fund.d.ts.map +1 -1
  91. package/dist/channels/rethinka-fund.js +180 -16
  92. package/dist/channels/rethinka-fund.js.map +1 -1
  93. package/dist/channels/telegram.js +1 -1
  94. package/dist/channels/telegram.js.map +1 -1
  95. package/dist/channels/tui-commands.js +1 -1
  96. package/dist/channels/tui-commands.js.map +1 -1
  97. package/dist/config/types.d.ts +4 -2
  98. package/dist/config/types.d.ts.map +1 -1
  99. package/dist/config/types.js +1 -1
  100. package/dist/config/types.js.map +1 -1
  101. package/dist/index.js.map +1 -1
  102. package/dist/obs/mini-app/status.d.ts.map +1 -1
  103. package/dist/obs/mini-app/status.js +63 -0
  104. package/dist/obs/mini-app/status.js.map +1 -1
  105. package/dist/obs/mini-app/telegram-auth.d.ts +23 -0
  106. package/dist/obs/mini-app/telegram-auth.d.ts.map +1 -0
  107. package/dist/obs/mini-app/telegram-auth.js +55 -0
  108. package/dist/obs/mini-app/telegram-auth.js.map +1 -0
  109. package/dist/obs/rdp/linux-x11-backend.d.ts +9 -0
  110. package/dist/obs/rdp/linux-x11-backend.d.ts.map +1 -1
  111. package/dist/obs/rdp/linux-x11-backend.js +69 -33
  112. package/dist/obs/rdp/linux-x11-backend.js.map +1 -1
  113. package/dist/obs/server.d.ts.map +1 -1
  114. package/dist/obs/server.js +29 -0
  115. package/dist/obs/server.js.map +1 -1
  116. package/dist/reconfigure.d.ts.map +1 -1
  117. package/dist/reconfigure.js +7 -1
  118. package/dist/reconfigure.js.map +1 -1
  119. package/dist/rethinka-fund/hyperliquid-signing.d.ts +56 -0
  120. package/dist/rethinka-fund/hyperliquid-signing.d.ts.map +1 -0
  121. package/dist/rethinka-fund/hyperliquid-signing.js +159 -0
  122. package/dist/rethinka-fund/hyperliquid-signing.js.map +1 -0
  123. package/dist/rethinka-fund/hyperliquid-trading.d.ts +154 -0
  124. package/dist/rethinka-fund/hyperliquid-trading.d.ts.map +1 -0
  125. package/dist/rethinka-fund/hyperliquid-trading.js +673 -0
  126. package/dist/rethinka-fund/hyperliquid-trading.js.map +1 -0
  127. package/dist/rethinka-fund/ibkr-flex.d.ts +49 -0
  128. package/dist/rethinka-fund/ibkr-flex.d.ts.map +1 -0
  129. package/dist/rethinka-fund/ibkr-flex.js +182 -0
  130. package/dist/rethinka-fund/ibkr-flex.js.map +1 -0
  131. package/dist/rethinka-fund/ibkr-mcp.d.ts +119 -0
  132. package/dist/rethinka-fund/ibkr-mcp.d.ts.map +1 -0
  133. package/dist/rethinka-fund/ibkr-mcp.js +418 -0
  134. package/dist/rethinka-fund/ibkr-mcp.js.map +1 -0
  135. package/dist/rethinka-fund/ibkr-sync.d.ts +30 -17
  136. package/dist/rethinka-fund/ibkr-sync.d.ts.map +1 -1
  137. package/dist/rethinka-fund/ibkr-sync.js +66 -31
  138. package/dist/rethinka-fund/ibkr-sync.js.map +1 -1
  139. package/dist/rethinka-fund/ibkr-trading.d.ts +102 -0
  140. package/dist/rethinka-fund/ibkr-trading.d.ts.map +1 -0
  141. package/dist/rethinka-fund/ibkr-trading.js +594 -0
  142. package/dist/rethinka-fund/ibkr-trading.js.map +1 -0
  143. package/dist/rethinka-fund/order-refresh.d.ts +66 -0
  144. package/dist/rethinka-fund/order-refresh.d.ts.map +1 -0
  145. package/dist/rethinka-fund/order-refresh.js +195 -0
  146. package/dist/rethinka-fund/order-refresh.js.map +1 -0
  147. package/dist/rethinka-fund/polymarket-redeem.d.ts +82 -0
  148. package/dist/rethinka-fund/polymarket-redeem.d.ts.map +1 -0
  149. package/dist/rethinka-fund/polymarket-redeem.js +353 -0
  150. package/dist/rethinka-fund/polymarket-redeem.js.map +1 -0
  151. package/dist/rethinka-fund/polymarket-trading.d.ts +61 -30
  152. package/dist/rethinka-fund/polymarket-trading.d.ts.map +1 -1
  153. package/dist/rethinka-fund/polymarket-trading.js +183 -71
  154. package/dist/rethinka-fund/polymarket-trading.js.map +1 -1
  155. package/dist/rethinka-fund/trading-common.d.ts +157 -0
  156. package/dist/rethinka-fund/trading-common.d.ts.map +1 -0
  157. package/dist/rethinka-fund/trading-common.js +237 -0
  158. package/dist/rethinka-fund/trading-common.js.map +1 -0
  159. package/dist/rethinka-fund-credentials.d.ts +2 -0
  160. package/dist/rethinka-fund-credentials.d.ts.map +1 -1
  161. package/dist/rethinka-fund-credentials.js +2 -0
  162. package/dist/rethinka-fund-credentials.js.map +1 -1
  163. package/dist/sites/manager.d.ts +50 -0
  164. package/dist/sites/manager.d.ts.map +1 -0
  165. package/dist/sites/manager.js +353 -0
  166. package/dist/sites/manager.js.map +1 -0
  167. package/dist/sites/pm2-injected-env.d.ts +49 -0
  168. package/dist/sites/pm2-injected-env.d.ts.map +1 -0
  169. package/dist/sites/pm2-injected-env.js +160 -0
  170. package/dist/sites/pm2-injected-env.js.map +1 -0
  171. package/dist/sites/process.d.ts +20 -0
  172. package/dist/sites/process.d.ts.map +1 -0
  173. package/dist/sites/process.js +122 -0
  174. package/dist/sites/process.js.map +1 -0
  175. package/dist/sites/registry.d.ts +79 -0
  176. package/dist/sites/registry.d.ts.map +1 -0
  177. package/dist/sites/registry.js +147 -0
  178. package/dist/sites/registry.js.map +1 -0
  179. package/dist/threads/execution-snapshot.d.ts +1 -0
  180. package/dist/threads/execution-snapshot.d.ts.map +1 -1
  181. package/dist/threads/foreground-task.d.ts +16 -3
  182. package/dist/threads/foreground-task.d.ts.map +1 -1
  183. package/dist/threads/foreground-task.js +57 -7
  184. package/dist/threads/foreground-task.js.map +1 -1
  185. package/dist/threads/foreman-execution.d.ts +14 -2
  186. package/dist/threads/foreman-execution.d.ts.map +1 -1
  187. package/dist/threads/foreman-execution.js +15 -3
  188. package/dist/threads/foreman-execution.js.map +1 -1
  189. package/dist/threads/foreman-host.d.ts +1 -0
  190. package/dist/threads/foreman-host.d.ts.map +1 -1
  191. package/dist/threads/foreman-host.js +27 -5
  192. package/dist/threads/foreman-host.js.map +1 -1
  193. package/dist/threads/foreman-protocol.d.ts +1 -0
  194. package/dist/threads/foreman-protocol.d.ts.map +1 -1
  195. package/dist/threads/foreman-protocol.js +2 -2
  196. package/dist/threads/foreman-protocol.js.map +1 -1
  197. package/dist/threads/foreman-write-contract.d.ts +1 -1
  198. package/dist/threads/foreman-write-contract.d.ts.map +1 -1
  199. package/dist/threads/foreman-write-contract.js +1 -1
  200. package/dist/threads/foreman-write-contract.js.map +1 -1
  201. package/dist/threads/supervisor.d.ts +2 -1
  202. package/dist/threads/supervisor.d.ts.map +1 -1
  203. package/dist/threads/supervisor.js +4 -1
  204. package/dist/threads/supervisor.js.map +1 -1
  205. package/dist/threads/thread-meta.d.ts +1 -0
  206. package/dist/threads/thread-meta.d.ts.map +1 -1
  207. package/dist/tools/delegation.d.ts.map +1 -1
  208. package/dist/tools/delegation.js +4 -1
  209. package/dist/tools/delegation.js.map +1 -1
  210. package/dist/tools/email.d.ts +1 -1
  211. package/dist/tools/event-trigger.d.ts +2 -2
  212. package/dist/tools/finish.d.ts.map +1 -1
  213. package/dist/tools/finish.js +5 -1
  214. package/dist/tools/finish.js.map +1 -1
  215. package/dist/tools/index.d.ts.map +1 -1
  216. package/dist/tools/index.js +4 -0
  217. package/dist/tools/index.js.map +1 -1
  218. package/dist/tools/rethinka-fund-trading.d.ts +137 -1
  219. package/dist/tools/rethinka-fund-trading.d.ts.map +1 -1
  220. package/dist/tools/rethinka-fund-trading.js +102 -5
  221. package/dist/tools/rethinka-fund-trading.js.map +1 -1
  222. package/dist/tools/sites.d.ts +24 -0
  223. package/dist/tools/sites.d.ts.map +1 -0
  224. package/dist/tools/sites.js +61 -0
  225. package/dist/tools/sites.js.map +1 -0
  226. package/dist/tui/index.js +1 -1
  227. package/dist-agent/bundle.cjs +2 -2
  228. package/dist-agent/image-resize-worker.js +1 -0
  229. package/dist-agent/image-resize-worker.mjs +375 -0
  230. package/dist-agent/mcp-script-worker.mjs +6 -2
  231. package/package.json +8 -8
  232. package/dist/agent/fast-responder.d.ts +0 -52
  233. package/dist/agent/fast-responder.d.ts.map +0 -1
  234. package/dist/agent/fast-responder.js +0 -213
  235. package/dist/agent/fast-responder.js.map +0 -1
  236. package/dist/rethinka-fund/ibkr-collect.d.ts +0 -70
  237. package/dist/rethinka-fund/ibkr-collect.d.ts.map +0 -1
  238. package/dist/rethinka-fund/ibkr-collect.js +0 -180
  239. package/dist/rethinka-fund/ibkr-collect.js.map +0 -1
@@ -0,0 +1,418 @@
1
+ /**
2
+ * IBKR through Interactive Brokers' own MCP server, for the Rethinka Fund
3
+ * agent: the authorization the owner gives it, and reading the account.
4
+ *
5
+ * The owner's IBKR login never passes through here. The owner signs in on
6
+ * Interactive Brokers' page, on their own computer, and what comes back is a
7
+ * one-time code that only this agent can redeem: it holds the other half (the
8
+ * PKCE verifier). The tokens that follow stay in this agent's profile
9
+ * directory. The Rethinka Fund server never holds them, the same way it never
10
+ * holds a wallet key.
11
+ *
12
+ * What is asked for is reading (`mcp.read`) and creating order
13
+ * instructions (`mcp.orders.stage`, which Interactive Brokers grants with
14
+ * `mcp.write`). An instruction is not an order: the owner submits it in
15
+ * Interactive Brokers' own app, or it never trades. The permission to submit
16
+ * orders is never asked for, and no tool that submits,
17
+ * changes or cancels an order is ever called.
18
+ * tests/unit/rethinka-fund/ibkr-mcp.test.ts checks that it stays that way.
19
+ */
20
+ import { createHash, randomBytes } from "node:crypto";
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import { z } from "zod";
24
+ import { getSharedProfileDir } from "../config/index.js";
25
+ export const IBKR_MCP_URL = "https://api.ibkr.com/v1/api/mcp-public";
26
+ /** From https://api.ibkr.com/.well-known/oauth-authorization-server. */
27
+ const AUTHORIZE_URL = "https://api.ibkr.com/oauth2/authorize";
28
+ const TOKEN_URL = "https://api.ibkr.com/oauth2/api/v1/token";
29
+ const REGISTER_URL = "https://api.ibkr.com/oauth2/register";
30
+ const SCOPE = "mcp.read mcp.orders.stage mcp.write";
31
+ /** What an authorization needs to hold for order instructions to be created. One from before only reads. */
32
+ const ORDER_SCOPES = ["mcp.orders.stage", "mcp.write"];
33
+ /**
34
+ * Where Interactive Brokers sends the owner's browser after the login. Nothing
35
+ * listens there: the owner's computer is not this host. The browser shows a
36
+ * page that cannot be reached, with the code in its address bar, and the owner
37
+ * hands that address to the agent.
38
+ */
39
+ const REDIRECT_URI = "http://127.0.0.1:8976/callback";
40
+ /** A login link is good for this long. The code Interactive Brokers issues lasts a few minutes itself. */
41
+ const PENDING_TTL_MS = 30 * 60_000;
42
+ /** An access token is renewed this long before it runs out. */
43
+ const RENEW_BEFORE_MS = 60_000;
44
+ const REQUEST_TIMEOUT_MS = 30_000;
45
+ /** The newest trades a snapshot carries. The server takes a snapshot of two megabytes at most, and keeps each trade once however often it is sent. */
46
+ const MAX_TRADES = 2000;
47
+ export const IBKR_AUTH_FILE = "rethinka-fund-ibkr-auth.json";
48
+ export function ibkrAuthPath() {
49
+ return path.join(getSharedProfileDir(), IBKR_AUTH_FILE);
50
+ }
51
+ const AuthFileSchema = z.object({
52
+ /** A login the owner has been sent a link for and has not finished. */
53
+ pending: z.object({ client_id: z.string().min(1), verifier: z.string().min(1), state: z.string().min(1), created_at: z.number() }).optional(),
54
+ /** What the owner granted. The refresh token is replaced every time it is used. */
55
+ tokens: z.object({ client_id: z.string().min(1), access_token: z.string().min(1), refresh_token: z.string().min(1), expires_at: z.number(), scope: z.string().default("") }).optional(),
56
+ });
57
+ function readAuth(file) {
58
+ let text;
59
+ try {
60
+ text = fs.readFileSync(file, "utf8");
61
+ }
62
+ catch (err) {
63
+ if (err.code === "ENOENT")
64
+ return {};
65
+ throw err;
66
+ }
67
+ // A file that cannot be read is no authorization. The reason says nothing of what is in it: a parser's own
68
+ // message can quote the text it choked on, and this text is tokens.
69
+ let raw;
70
+ try {
71
+ raw = JSON.parse(text);
72
+ }
73
+ catch {
74
+ raw = null;
75
+ }
76
+ const parsed = AuthFileSchema.safeParse(raw);
77
+ if (!parsed.success)
78
+ throw new Error(`${file} is not an authorization this agent wrote; delete it and connect IBKR again`);
79
+ return parsed.data;
80
+ }
81
+ /** Written whole, to a file beside it first: a refresh token is good once, so a half-written file would lose the authorization. */
82
+ function writeAuth(file, value) {
83
+ const temporary = `${file}.${String(process.pid)}.tmp`;
84
+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2), { mode: 0o600 });
85
+ fs.renameSync(temporary, file);
86
+ }
87
+ const base64url = (bytes) => bytes.toString("base64url");
88
+ async function postJson(fetchImpl, url, init) {
89
+ const reply = await fetchImpl(url, { ...init, method: "POST", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
90
+ const body = (await reply.json().catch(() => ({})));
91
+ return { ok: reply.ok, status: reply.status, body };
92
+ }
93
+ /** Why Interactive Brokers refused, without anything it was sent. */
94
+ function refusal(status, body) {
95
+ const error = typeof body.error === "string" ? body.error : "";
96
+ const description = typeof body.error_description === "string" ? body.error_description : "";
97
+ return `HTTP ${String(status)}${error ? ` ${error}` : ""}${description ? `: ${description}` : ""}`;
98
+ }
99
+ /**
100
+ * Begin a login: registers this agent with Interactive Brokers and returns the
101
+ * address the owner opens. Starting again replaces a login that was not
102
+ * finished; an authorization already in place stays until the new one is.
103
+ */
104
+ export async function startIbkrAuthorization(deps = {}) {
105
+ const file = deps.authFile ?? ibkrAuthPath();
106
+ const fetchImpl = deps.fetchImpl ?? fetch;
107
+ const registered = await postJson(fetchImpl, REGISTER_URL, {
108
+ headers: { "content-type": "application/json" },
109
+ body: JSON.stringify({ client_name: "Rethinka Fund agent", redirect_uris: [REDIRECT_URI], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none", scope: SCOPE }),
110
+ });
111
+ const clientId = registered.body.client_id;
112
+ if (!registered.ok || typeof clientId !== "string" || !clientId)
113
+ throw new Error(`Interactive Brokers did not register this agent (${refusal(registered.status, registered.body)})`);
114
+ const verifier = base64url(randomBytes(48));
115
+ const state = base64url(randomBytes(16));
116
+ const url = new URL(AUTHORIZE_URL);
117
+ for (const [key, value] of Object.entries({
118
+ response_type: "code",
119
+ client_id: clientId,
120
+ redirect_uri: REDIRECT_URI,
121
+ scope: SCOPE,
122
+ state,
123
+ code_challenge: base64url(createHash("sha256").update(verifier).digest()),
124
+ code_challenge_method: "S256",
125
+ resource: IBKR_MCP_URL,
126
+ }))
127
+ url.searchParams.set(key, value);
128
+ writeAuth(file, { ...readAuth(file), pending: { client_id: clientId, verifier, state, created_at: (deps.now ?? Date.now)() } });
129
+ return { url: url.toString(), redirectUri: REDIRECT_URI, expiresInMinutes: PENDING_TTL_MS / 60_000 };
130
+ }
131
+ /**
132
+ * Finish a login with the address the owner's browser ended on. It carries a
133
+ * one-time code; the tokens it is redeemed for are written to the profile
134
+ * directory and returned to nobody.
135
+ */
136
+ export async function finishIbkrAuthorization(redirected, deps = {}) {
137
+ const file = deps.authFile ?? ibkrAuthPath();
138
+ const now = (deps.now ?? Date.now)();
139
+ const auth = readAuth(file);
140
+ const pending = auth.pending;
141
+ if (!pending)
142
+ throw new Error("no IBKR login is in progress; start one first");
143
+ if (now - pending.created_at > PENDING_TTL_MS)
144
+ throw new Error("that IBKR login link has expired; start again");
145
+ let params;
146
+ try {
147
+ params = new URL(redirected.trim()).searchParams;
148
+ }
149
+ catch {
150
+ throw new Error(`that is not the address the browser ended on: it starts with ${REDIRECT_URI}?`);
151
+ }
152
+ const failed = params.get("error");
153
+ if (failed)
154
+ throw new Error(`Interactive Brokers did not authorize it: ${failed}${params.get("error_description") ? ` (${params.get("error_description") ?? ""})` : ""}`);
155
+ const code = params.get("code");
156
+ if (!code)
157
+ throw new Error("that address carries no code; copy the whole address from the browser's address bar after the login");
158
+ if (params.get("state") !== pending.state)
159
+ throw new Error("that address belongs to another login, not the one in progress; start again and use the new link");
160
+ const exchanged = await postJson(deps.fetchImpl ?? fetch, TOKEN_URL, {
161
+ headers: { "content-type": "application/x-www-form-urlencoded" },
162
+ body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: REDIRECT_URI, client_id: pending.client_id, code_verifier: pending.verifier, resource: IBKR_MCP_URL }).toString(),
163
+ });
164
+ const tokens = readTokens(exchanged.body, pending.client_id, now);
165
+ if (!exchanged.ok || !tokens)
166
+ throw new Error(`Interactive Brokers did not issue the authorization (${refusal(exchanged.status, exchanged.body)}); the code is good once and for a few minutes, so start again`);
167
+ writeAuth(file, { tokens });
168
+ return { scope: tokens.scope };
169
+ }
170
+ function readTokens(body, clientId, now) {
171
+ const { access_token: access, refresh_token: refresh, expires_in: expiresIn, scope } = body;
172
+ if (typeof access !== "string" || !access || typeof refresh !== "string" || !refresh)
173
+ return null;
174
+ const seconds = typeof expiresIn === "number" && expiresIn > 0 ? expiresIn : 300;
175
+ return { client_id: clientId, access_token: access, refresh_token: refresh, expires_at: now + seconds * 1000, scope: typeof scope === "string" ? scope : "" };
176
+ }
177
+ /** Whether the authorization on file lets order instructions be created, or only reads the account. */
178
+ export function ibkrMayStageOrders(deps = {}) {
179
+ const scopes = new Set((readAuth(deps.authFile ?? ibkrAuthPath()).tokens?.scope ?? "").split(/\s+/));
180
+ return ORDER_SCOPES.every((scope) => scopes.has(scope));
181
+ }
182
+ /** Where the authorization stands, for the agent to tell the owner. Never the tokens. */
183
+ export function ibkrAuthorizationStatus(deps = {}) {
184
+ const auth = readAuth(deps.authFile ?? ibkrAuthPath());
185
+ if (auth.tokens)
186
+ return "authorized";
187
+ return auth.pending && (deps.now ?? Date.now)() - auth.pending.created_at <= PENDING_TTL_MS ? "login in progress" : "not authorized";
188
+ }
189
+ /** The owner has to log in again: there is no authorization, or Interactive Brokers no longer honours it. */
190
+ export class IbkrNotAuthorizedError extends Error {
191
+ constructor(reason) {
192
+ super(`IBKR is not authorized on this agent (${reason}); the owner has to log in again`);
193
+ this.name = "IbkrNotAuthorizedError";
194
+ }
195
+ }
196
+ /** A renewal that holds the lock longer than this has died with its process, and the lock is taken over. */
197
+ /** Longer than a renewal can take (its request times out at REQUEST_TIMEOUT_MS), so a lock is never broken while it is held. */
198
+ const LOCK_STALE_MS = 3 * REQUEST_TIMEOUT_MS;
199
+ const LOCK_WAIT_MS = 15_000;
200
+ /**
201
+ * Run `work` while holding the authorization file's lock, a directory beside
202
+ * it. The sync loop and the trading tools both renew the same tokens, and a
203
+ * renewal retires the refresh token it used: two at once would leave one of
204
+ * them holding a token that no longer works.
205
+ */
206
+ async function withAuthLock(file, work) {
207
+ const lock = `${file}.lock`;
208
+ const started = Date.now();
209
+ for (;;) {
210
+ try {
211
+ fs.mkdirSync(lock);
212
+ break;
213
+ }
214
+ catch (err) {
215
+ if (err.code !== "EEXIST")
216
+ throw err;
217
+ let age = 0;
218
+ try {
219
+ age = Date.now() - fs.statSync(lock).mtimeMs;
220
+ }
221
+ catch {
222
+ continue;
223
+ }
224
+ if (age > LOCK_STALE_MS) {
225
+ fs.rmSync(lock, { recursive: true, force: true });
226
+ continue;
227
+ }
228
+ if (Date.now() - started > LOCK_WAIT_MS)
229
+ throw new Error("the IBKR authorization is being renewed elsewhere; try again in a moment");
230
+ await new Promise((resolve) => setTimeout(resolve, 100));
231
+ }
232
+ }
233
+ try {
234
+ return await work();
235
+ }
236
+ finally {
237
+ fs.rmSync(lock, { recursive: true, force: true });
238
+ }
239
+ }
240
+ /**
241
+ * An access token that is good now. A refresh hands back a new refresh token
242
+ * and retires the one it used, so the new pair is on disk before it is used,
243
+ * and only one renewal runs at a time.
244
+ */
245
+ async function accessToken(deps) {
246
+ const file = deps.authFile ?? ibkrAuthPath();
247
+ const fresh = readAuth(file).tokens;
248
+ if (!fresh)
249
+ throw new IbkrNotAuthorizedError("no authorization on file");
250
+ if (fresh.expires_at - (deps.now ?? Date.now)() > RENEW_BEFORE_MS)
251
+ return fresh.access_token;
252
+ return await withAuthLock(file, () => renew(file, deps));
253
+ }
254
+ async function renew(file, deps) {
255
+ const now = (deps.now ?? Date.now)();
256
+ // Read again under the lock: whoever held it before may have renewed it already.
257
+ const auth = readAuth(file);
258
+ const held = auth.tokens;
259
+ if (!held)
260
+ throw new IbkrNotAuthorizedError("no authorization on file");
261
+ if (held.expires_at - now > RENEW_BEFORE_MS)
262
+ return held.access_token;
263
+ const renewed = await postJson(deps.fetchImpl ?? fetch, TOKEN_URL, {
264
+ headers: { "content-type": "application/x-www-form-urlencoded" },
265
+ body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: held.refresh_token, client_id: held.client_id, resource: IBKR_MCP_URL }).toString(),
266
+ });
267
+ // A renewal that names no scope keeps what was granted: it is the same grant.
268
+ const tokens = readTokens({ refresh_token: held.refresh_token, scope: held.scope, ...renewed.body }, held.client_id, now);
269
+ // The file is read again before it is written: while this was on its way the owner may have started a login, or
270
+ // finished one. A login started must keep its other half, and one finished is the newer authorization.
271
+ const current = readAuth(file);
272
+ const replaced = current.tokens !== undefined && current.tokens.refresh_token !== held.refresh_token;
273
+ if (!renewed.ok || !tokens) {
274
+ // The grant itself is gone (revoked in Client Portal, or expired): only then is it dropped. Any other refusal may
275
+ // pass, and the same token is tried again.
276
+ const gone = renewed.body.error === "invalid_grant" || renewed.body.error === "invalid_client";
277
+ if (!gone)
278
+ throw new Error(`the IBKR authorization could not be renewed just now (${refusal(renewed.status, renewed.body)})`);
279
+ if (replaced && current.tokens)
280
+ return current.tokens.access_token;
281
+ writeAuth(file, { ...(current.pending ? { pending: current.pending } : {}) });
282
+ throw new IbkrNotAuthorizedError(`Interactive Brokers refused to renew it: ${refusal(renewed.status, renewed.body)}`);
283
+ }
284
+ if (replaced && current.tokens)
285
+ return current.tokens.access_token;
286
+ writeAuth(file, { ...(current.pending ? { pending: current.pending } : {}), tokens });
287
+ return tokens.access_token;
288
+ }
289
+ /** The tools the sync loop calls on Interactive Brokers' server: the ones that read the account, and the two that find an exchange rate. */
290
+ export const IBKR_READ_TOOLS = ["get_account_summary", "get_account_balances", "get_account_positions", "get_account_trades", "search_contracts", "get_price_snapshot"];
291
+ /**
292
+ * The tools the trading tools call besides: finding options, reading orders and
293
+ * instructions, and creating and deleting an instruction. Nothing that submits,
294
+ * changes or cancels an order.
295
+ */
296
+ export const IBKR_ORDER_TOOLS = ["get_option_parameters", "get_option_data", "get_order_instructions", "get_account_orders", "create_order_instruction", "delete_order_instruction"];
297
+ /** One conversation with the MCP server: opened, a few tools called, and left. */
298
+ /** Interactive Brokers answered a tool call, and the answer was a refusal: unlike a timeout, nothing was done. */
299
+ export class IbkrToolError extends Error {
300
+ }
301
+ export class IbkrMcpSession {
302
+ deps;
303
+ session = null;
304
+ nextId = 0;
305
+ constructor(deps) {
306
+ this.deps = deps;
307
+ }
308
+ async request(method, params, notification = false) {
309
+ const headers = {
310
+ "content-type": "application/json",
311
+ accept: "application/json, text/event-stream",
312
+ authorization: `Bearer ${await accessToken(this.deps)}`,
313
+ "mcp-protocol-version": "2025-06-18",
314
+ };
315
+ if (this.session)
316
+ headers["mcp-session-id"] = this.session;
317
+ const id = notification ? undefined : ++this.nextId;
318
+ const reply = await (this.deps.fetchImpl ?? fetch)(IBKR_MCP_URL, {
319
+ method: "POST",
320
+ headers,
321
+ body: JSON.stringify({ jsonrpc: "2.0", ...(id === undefined ? {} : { id }), method, params }),
322
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
323
+ });
324
+ this.session = reply.headers.get("mcp-session-id") ?? this.session;
325
+ if (reply.status === 401)
326
+ throw new IbkrNotAuthorizedError("Interactive Brokers refused the access token");
327
+ const text = await reply.text();
328
+ if (notification)
329
+ return undefined;
330
+ if (!reply.ok)
331
+ throw new Error(`IBKR MCP ${method} returned HTTP ${String(reply.status)}`);
332
+ // The server answers either with one JSON message or with a stream of them.
333
+ const messages = (reply.headers.get("content-type") ?? "").includes("text/event-stream")
334
+ ? text.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).filter(Boolean).map((line) => JSON.parse(line))
335
+ : [JSON.parse(text)];
336
+ const answer = messages.find((message) => message.id === id);
337
+ if (!answer)
338
+ throw new Error(`IBKR MCP ${method} returned no answer`);
339
+ if (answer.error)
340
+ throw new Error(`IBKR MCP ${method} failed: ${JSON.stringify(answer.error).slice(0, 300)}`);
341
+ return answer.result;
342
+ }
343
+ async open() {
344
+ await this.request("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "rethinka-fund-agent", version: "1" } });
345
+ await this.request("notifications/initialized", {}, true);
346
+ }
347
+ /** What a tool returned, as the object it describes. */
348
+ async call(name, args = {}) {
349
+ const result = (await this.request("tools/call", { name, arguments: args }));
350
+ const text = (result.content ?? []).filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n");
351
+ if (result.isError === true)
352
+ throw new IbkrToolError(`IBKR ${name} failed: ${text.slice(0, 300)}`);
353
+ if (result.structuredContent !== undefined)
354
+ return result.structuredContent;
355
+ try {
356
+ return JSON.parse(text);
357
+ }
358
+ catch {
359
+ throw new Error(`IBKR ${name} returned something that is not JSON`);
360
+ }
361
+ }
362
+ }
363
+ function asRecord(value) {
364
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
365
+ }
366
+ /** The answer of `get_account_trades` with its newest trades only, when it holds more than a snapshot can carry. */
367
+ function newestTrades(answer) {
368
+ const list = asRecord(answer).trades;
369
+ if (!Array.isArray(list) || list.length <= MAX_TRADES)
370
+ return answer;
371
+ const time = (trade) => {
372
+ const stamp = asRecord(trade).trade_time;
373
+ const at = typeof stamp === "string" ? Date.parse(stamp) : Number.NaN;
374
+ return Number.isNaN(at) ? 0 : at;
375
+ };
376
+ return { ...asRecord(answer), trades: [...list].sort((a, b) => time(b) - time(a)).slice(0, MAX_TRADES) };
377
+ }
378
+ /** Posts to the Rethinka Fund server. Throws with the server's reason when it refuses. */
379
+ export async function pushIbkr(baseUrl, key, kind, body, fetchImpl = fetch) {
380
+ const response = await fetchImpl(`${baseUrl}/gateway/ibkr/${kind}`, {
381
+ method: "POST",
382
+ headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
383
+ body: JSON.stringify(body),
384
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
385
+ });
386
+ if (response.ok)
387
+ return;
388
+ const reply = (await response.json().catch(() => ({})));
389
+ throw new Error(`Rethinka refused the ${kind} (HTTP ${String(response.status)}): ${typeof reply.error === "string" ? reply.error : "no reason given"}`);
390
+ }
391
+ /** Read the account once. Four reads, and two more when a dollar rate is needed. */
392
+ export async function collectIbkrMcpSnapshot(options) {
393
+ const mcp = new IbkrMcpSession(options);
394
+ await mcp.open();
395
+ const summary = await mcp.call("get_account_summary");
396
+ const balances = await mcp.call("get_account_balances");
397
+ const positions = await mcp.call("get_account_positions");
398
+ const trades = newestTrades(await mcp.call("get_account_trades", { period: options.tradesPeriod }));
399
+ const payload = { source: "ibkr-mcp", account: options.account, summary, balances, positions, trades };
400
+ // The console values everything in US dollars. An account in another currency names a rate only for what it holds.
401
+ const base = asRecord(summary).currency;
402
+ const rows = asRecord(balances).balances;
403
+ const holdsDollars = Array.isArray(rows) && rows.some((row) => asRecord(row).currency === "USD");
404
+ if (typeof base === "string" && /^[A-Z]{3}$/.test(base) && base !== "USD" && !holdsDollars) {
405
+ const pair = `USD.${base}`;
406
+ const found = asRecord(await mcp.call("search_contracts", { query: pair })).results;
407
+ const contract = (Array.isArray(found) ? found : []).map(asRecord).find((row) => row.symbol === "USD" && typeof row.underlying_contract_id === "number" && typeof row.exchange === "string"
408
+ && Array.isArray(row.sections) && row.sections.some((section) => asRecord(section).security_type === "CASH"));
409
+ // Left out when there is no such contract: the server then says the account cannot be valued, rather than guessing.
410
+ if (contract) {
411
+ const contractId = contract.underlying_contract_id;
412
+ const exchange = contract.exchange;
413
+ payload.fx = { pair, contract_id: contractId, exchange, snapshot: await mcp.call("get_price_snapshot", { contract_id: contractId, exchange }) };
414
+ }
415
+ }
416
+ return payload;
417
+ }
418
+ //# sourceMappingURL=ibkr-mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ibkr-mcp.js","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAIzD,MAAM,CAAC,MAAM,YAAY,GAAG,wCAAwC,CAAC;AACrE,wEAAwE;AACxE,MAAM,aAAa,GAAG,uCAAuC,CAAC;AAC9D,MAAM,SAAS,GAAG,0CAA0C,CAAC;AAC7D,MAAM,YAAY,GAAG,sCAAsC,CAAC;AAC5D,MAAM,KAAK,GAAG,qCAAqC,CAAC;AACpD,4GAA4G;AAC5G,MAAM,YAAY,GAAG,CAAC,kBAAkB,EAAE,WAAW,CAAC,CAAC;AACvD;;;;;GAKG;AACH,MAAM,YAAY,GAAG,gCAAgC,CAAC;AACtD,0GAA0G;AAC1G,MAAM,cAAc,GAAG,EAAE,GAAG,MAAM,CAAC;AACnC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AAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,aAAa,KAAK,MAAM,CAAC,CAAC,CAAC;QAChH,oHAAoH;QACpH,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,UAAU,GAAG,QAAQ,CAAC,sBAAgC,CAAC;YAC7D,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAkB,CAAC;YAC7C,OAAO,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAClJ,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -1,33 +1,35 @@
1
1
  /**
2
2
  * IBKR sync for the Rethinka Fund agent.
3
3
  *
4
- * IB Gateway only answers on its own machine, which is this agent's host, so
5
- * the Rethinka Fund server cannot read an IBKR account itself. This loop reads
6
- * it here through the TWS API and pushes what it saw to the server
7
- * (`POST /gateway/ibkr/snapshot`, services/rethinka/docs/ibkr-sync.md).
4
+ * The Rethinka Fund server reads no account it would need a login for, so an
5
+ * IBKR account is read here, by the agent the owner authorized, and what it
6
+ * saw is pushed to the server (`POST /gateway/ibkr/snapshot`,
7
+ * services/rethinka/docs/ibkr-sync.md). The reading goes through Interactive
8
+ * Brokers' own MCP server (./ibkr-mcp.ts): nothing runs on this host besides
9
+ * the agent.
8
10
  *
9
11
  * It ships inside the agent and runs in the agent's main process, for as long
10
12
  * as the Rethinka Fund channel is up: there is nothing to download or install,
11
13
  * and it is always the version that matches the agent.
12
14
  *
13
- * It is off until the settings file exists. The agent writes that file when
14
- * the owner hands it the collector key (skill: rethinka-fund), and the loop
15
- * picks it up on its next pass, without a restart.
15
+ * It is off until the settings file exists and the owner has authorized this
16
+ * agent with Interactive Brokers. The agent writes the settings file when the
17
+ * owner hands it the collector key (skill: rethinka-fund), and the loop picks
18
+ * both up on its next pass, without a restart.
16
19
  *
17
- * This loop only reads. Orders go through the same IB Gateway on a different
18
- * client id and are not this file's business.
20
+ * This loop only reads, and is no model: the same reads, in the same order,
21
+ * every pass.
19
22
  */
20
23
  import { z } from "zod";
21
- import type { FetchLike, IbClient } from "./ibkr-collect.js";
24
+ import type { FlexCashFlows, FlexDeps, FlexSettings } from "./ibkr-flex.js";
25
+ import { type FetchLike, type IbkrCollectOptions, type IbkrMcpSnapshotPayload } from "./ibkr-mcp.js";
22
26
  export declare const IBKR_SYNC_SETTINGS_FILE = "rethinka-fund-ibkr.json";
23
27
  export declare const IbkrSyncSettingsSchema: z.ZodObject<{
24
28
  account: z.ZodString;
25
29
  key: z.ZodString;
26
- host: z.ZodDefault<z.ZodString>;
27
- port: z.ZodDefault<z.ZodNumber>;
28
- clientId: z.ZodDefault<z.ZodNumber>;
29
30
  intervalSeconds: z.ZodDefault<z.ZodNumber>;
30
- timezone: z.ZodOptional<z.ZodString>;
31
+ flexToken: z.ZodOptional<z.ZodString>;
32
+ flexQueryId: z.ZodOptional<z.ZodString>;
31
33
  }, z.core.$strip>;
32
34
  export type IbkrSyncSettings = z.infer<typeof IbkrSyncSettingsSchema>;
33
35
  export declare function ibkrSyncSettingsPath(): string;
@@ -45,10 +47,14 @@ export interface IbkrSyncDeps {
45
47
  /** The Rethinka Fund server, or null while the agent has no credential for it. */
46
48
  baseUrl: () => string | null;
47
49
  settingsFile?: string;
48
- createClient?: (settings: IbkrSyncSettings) => Promise<IbClient>;
50
+ /** Reads the account. Tests put their own here. */
51
+ collect?: (options: IbkrCollectOptions) => Promise<IbkrMcpSnapshotPayload>;
52
+ /** Reads the Flex statement. Tests put their own here. */
53
+ readFlex?: (settings: FlexSettings, span: "history" | "recent", deps: FlexDeps) => Promise<FlexCashFlows>;
54
+ now?: () => number;
55
+ /** Where this agent keeps its IBKR authorization. */
56
+ authFile?: string;
49
57
  fetchImpl?: FetchLike;
50
- timeoutMs?: number;
51
- commissionWaitMs?: number;
52
58
  }
53
59
  export declare class IbkrSyncService {
54
60
  private readonly deps;
@@ -56,6 +62,13 @@ export declare class IbkrSyncService {
56
62
  private stopped;
57
63
  /** Last thing logged, so a steady state is one line and not one per minute. */
58
64
  private lastStatus;
65
+ /** The first pass that reads the account asks for the year's trades, so the ones from before this agent was running are there too. */
66
+ private caughtUp;
67
+ /** When the deposits and withdrawals last went through, and whether the whole history has since this process started. */
68
+ private flexSentAt;
69
+ private flexHistorySent;
70
+ /** When a statement was last asked for and did not get through, for FLEX_RETRY_MS. */
71
+ private flexFailedAt;
59
72
  constructor(deps: IbkrSyncDeps);
60
73
  start(): void;
61
74
  stop(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"ibkr-sync.d.ts","sourceRoot":"","sources":["../../src/rethinka-fund/ibkr-sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAIH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAuB,MAAM,mBAAmB,CAAC;AAElF,eAAO,MAAM,uBAAuB,4BAA4B,CAAC;AAOjE,eAAO,MAAM,sBAAsB;;;;;;;;iBAajC,CAAC;AAEH,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE,wBAAgB,oBAAoB,IAAI,MAAM,CAE7C;AAED,MAAM,MAAM,gBAAgB,GACxB;IAAE,MAAM,EAAE,QAAQ,CAAA;CAAE,GACpB;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACrC;IAAE,MAAM,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAC;AAEjD,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,CAmBnE;AAED,MAA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