felix-mcp 2.0.133 → 2.0.136

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.
package/dist/index.js CHANGED
@@ -15,8 +15,8 @@
15
15
  import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID, } from "node:crypto";
16
16
  import { constants as fsConstants, chmodSync, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
17
17
  import * as nodeNet from "node:net";
18
- import { homedir, userInfo } from "node:os";
19
- import { dirname, join, resolve } from "node:path";
18
+ import { homedir } from "node:os";
19
+ import { dirname, join } from "node:path";
20
20
  import { setTimeout as sleep } from "node:timers/promises";
21
21
  import { spawn, spawnSync } from "node:child_process";
22
22
  import { fileURLToPath } from "node:url";
@@ -27,6 +27,8 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
27
27
  import { CallToolRequestSchema, ErrorCode, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
28
28
  import { getLocalOpenOrderReservation, localOwnerAddress, placePreparedOrder, signAgentFundingContext, signApprovalContext, signRedemptionContext, signReturnContext, } from "./polymarket.js";
29
29
  import { FELIX_LEGAL_BUNDLE_VERSION, legalAcceptanceFields, } from "./legal.js";
30
+ import { credentialStoreDescription, credentialStoreKind, credentialStoreLabel, deleteCredential, hasPrivateMode, openReadNoFollow, readCredential, readCredentialOrEmpty, writeCredential, } from "./credential-store.js";
31
+ import { humanConfirmationAvailable } from "./human-prompt.js";
30
32
  import { acceptedCryptoWithdrawalAmount, assertDeriveDepositReady, assertGasSponsorshipReady, assertSubscriptionPaymentIntent, awaitFundingFeeProof, retryPendingFundingFee, prepaidFeeSpentFromFundingSource, confirmFundingFeeTransfer, executeCryptoReturnBridge, executeRelayCryptoReturn, executeCryptoWithdrawal, executeDeriveChainWithdrawal, deriveFundingNonceUnchanged, executeFeeSettlement, executeNativeUsdcSwap, executeOwnerEoaWithdrawal,
31
33
  // executeOwnerEoaCancellation is deliberately NOT imported: see
32
34
  // capitalOperationsUnavailable. This client no longer signs a nonce-replacing
@@ -126,7 +128,84 @@ export function validatedApiBase(raw = process.env.FELIX_API_URL || `https://${O
126
128
  return parsed.origin;
127
129
  }
128
130
  const API = validatedApiBase();
129
- const MCP_VERSION = "2.0.133";
131
+ const MCP_VERSION = "2.0.136";
132
+ // MCP_UPDATE_NOTICE_20261123: a user on an old build hears about it (with the exact command) before a retired
133
+ // route fails mid-workflow. Only the public npm "latest" record is read; nothing about the user is sent.
134
+ // Loopback and custom API hosts (tests, staging) stay offline unless FELIX_MCP_UPDATE_URL is set.
135
+ const MCP_UPDATE_COMMAND = "npm install --global felix-mcp@latest";
136
+ const MCP_UPDATE_CHECK_TTL_MS = 6 * 60 * 60_000;
137
+ let mcpLatestPublished;
138
+ let mcpLatestFlight;
139
+ let mcpLatestFailedAt = 0;
140
+ function mcpUpdateCheckUrl() {
141
+ const flag = String(process.env.FELIX_MCP_UPDATE_CHECK ?? "").trim().toLowerCase();
142
+ if (["0", "false", "off", "no"].includes(flag))
143
+ return undefined;
144
+ const override = String(process.env.FELIX_MCP_UPDATE_URL ?? "").trim();
145
+ if (override) {
146
+ try {
147
+ const url = new URL(override);
148
+ if (url.protocol === "https:" || LOOPBACK_API_HOSTS.has(url.hostname.toLowerCase()))
149
+ return url.toString();
150
+ }
151
+ catch { /* invalid override: stay offline */ }
152
+ return undefined;
153
+ }
154
+ return API === `https://${OFFICIAL_API_HOST}` ? "https://registry.npmjs.org/felix-mcp/latest" : undefined;
155
+ }
156
+ async function latestPublishedMcpVersion() {
157
+ if (mcpLatestPublished && Date.now() - mcpLatestPublished.checked_at < MCP_UPDATE_CHECK_TTL_MS) {
158
+ return mcpLatestPublished.version;
159
+ }
160
+ const url = mcpUpdateCheckUrl();
161
+ if (!url)
162
+ return undefined;
163
+ if (Date.now() - mcpLatestFailedAt < 10 * 60_000)
164
+ return mcpLatestPublished?.version;
165
+ if (!mcpLatestFlight) {
166
+ mcpLatestFlight = (async () => {
167
+ try {
168
+ const response = await fetch(url, {
169
+ headers: { Accept: "application/json", "User-Agent": `felix-mcp/${MCP_VERSION}` },
170
+ signal: AbortSignal.timeout(4_000),
171
+ redirect: "error",
172
+ });
173
+ if (!response.ok) {
174
+ mcpLatestFailedAt = Date.now();
175
+ return mcpLatestPublished?.version;
176
+ }
177
+ const body = await response.json();
178
+ const version = body && typeof body === "object" && typeof body.version === "string"
179
+ && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(body.version)
180
+ ? body.version : undefined;
181
+ if (version)
182
+ mcpLatestPublished = { version, checked_at: Date.now() };
183
+ else
184
+ mcpLatestFailedAt = Date.now();
185
+ return version ?? mcpLatestPublished?.version;
186
+ }
187
+ catch {
188
+ mcpLatestFailedAt = Date.now();
189
+ return mcpLatestPublished?.version;
190
+ }
191
+ finally {
192
+ mcpLatestFlight = undefined;
193
+ }
194
+ })();
195
+ }
196
+ return mcpLatestFlight;
197
+ }
198
+ function mcpUpdateNotice(latest = mcpLatestPublished?.version) {
199
+ if (!latest || versionAtLeast(MCP_VERSION, latest))
200
+ return undefined;
201
+ return {
202
+ update_available: true,
203
+ current_version: MCP_VERSION,
204
+ latest_version: latest,
205
+ how_to_update: `Run \`${MCP_UPDATE_COMMAND}\` in a terminal, then restart or reconnect your MCP client. `
206
+ + "If your client starts Felix with npx, use `npx -y felix-mcp@latest`. Updating never changes your keys, accounts or money.",
207
+ };
208
+ }
130
209
  const AES_GCM_IV_BYTES = 12;
131
210
  const AES_GCM_TAG_BYTES = 16;
132
211
  const MAX_MONEY_JOURNAL_BYTES = 16 * 1024 * 1024;
@@ -174,17 +253,14 @@ const KEYCHAIN_ACTIVE_ACCOUNT_SERVICE = activeAccountBindingService({
174
253
  const ACTIVE_ACCOUNT_BINDING_SCOPE = EXPLICIT_BINDING_PROFILE
175
254
  ? "explicit_profile"
176
255
  : "client_process";
256
+ // CROSS_PLATFORM_KEYS_20261123: macOS Keychain, Windows protected storage, or the Linux keyring / sealed file.
177
257
  function localKeychainCredential(service) {
178
- if (process.platform !== "darwin" || process.env.FELIX_MCP_TRANSPORT === "http")
258
+ if (process.env.FELIX_MCP_TRANSPORT === "http")
179
259
  return "";
180
- const result = spawnSync("/usr/bin/security", [
181
- "find-generic-password", "-a", userInfo().username, "-s", service, "-w",
182
- ], {
183
- encoding: "utf8",
184
- maxBuffer: 16 * 1024,
185
- stdio: ["ignore", "pipe", "ignore"],
186
- });
187
- return result.status === 0 ? String(result.stdout || "").replace(/\r?\n$/, "") : "";
260
+ return readCredentialOrEmpty(service);
261
+ }
262
+ function localCredentialStoreUsable() {
263
+ return process.env.FELIX_MCP_TRANSPORT !== "http";
188
264
  }
189
265
  function configuredCredential(envName, keychainService) {
190
266
  if (Object.prototype.hasOwnProperty.call(process.env, envName)) {
@@ -195,7 +271,7 @@ function configuredCredential(envName, keychainService) {
195
271
  // Per-account child live key cache. use_child_account reuses a cached key while
196
272
  // it is still active instead of minting a new one every call, which otherwise
197
273
  // churns the 20-live-key cap and rebinds order intents to a fresh key (breaking
198
- // later reconciliation). macOS keychain only; a no-op elsewhere so those hosts
274
+ // later reconciliation). Stored in the local credential store (credential-store.ts) on every OS; hosted
199
275
  // simply fall back to minting.
200
276
  function childKeyService(accountId) {
201
277
  return `trade.felix.child-key.${accountId}`;
@@ -211,34 +287,29 @@ function readCachedChildKey(accountId) {
211
287
  function cacheChildKey(accountId, apiKey) {
212
288
  if (EPHEMERAL_SESSION)
213
289
  return true;
214
- if (process.platform !== "darwin" || process.env.FELIX_MCP_TRANSPORT === "http")
290
+ if (!localCredentialStoreUsable())
215
291
  return false;
216
292
  if (!/^[0-9a-f-]{36}$/i.test(accountId) || !/^fk_[0-9a-f]{32}$/.test(apiKey))
217
293
  return false;
218
- const helper = resolve(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "keychain-write.exp");
219
- const result = spawnSync("/usr/bin/expect", [
220
- helper,
221
- userInfo().username,
222
- childKeyService(accountId),
223
- "Felix child account API key",
224
- ], {
225
- encoding: "utf8",
226
- input: apiKey,
227
- stdio: ["pipe", "ignore", "ignore"],
228
- maxBuffer: 16 * 1024,
229
- });
230
- return result.status === 0 && readCachedChildKey(accountId) === apiKey;
294
+ try {
295
+ writeCredential(childKeyService(accountId), "Felix child account API key", apiKey);
296
+ }
297
+ catch {
298
+ return false;
299
+ }
300
+ return readCachedChildKey(accountId) === apiKey;
231
301
  }
232
302
  function forgetCachedChildKey(accountId) {
233
303
  if (EPHEMERAL_SESSION)
234
304
  return;
235
- if (process.platform !== "darwin" || process.env.FELIX_MCP_TRANSPORT === "http")
305
+ if (!localCredentialStoreUsable())
236
306
  return;
237
307
  if (!/^[0-9a-f-]{36}$/i.test(accountId))
238
308
  return;
239
- spawnSync("/usr/bin/security", [
240
- "delete-generic-password", "-a", userInfo().username, "-s", childKeyService(accountId),
241
- ], { stdio: ["ignore", "ignore", "ignore"] });
309
+ try {
310
+ deleteCredential(childKeyService(accountId));
311
+ }
312
+ catch { /* a stale cache entry is re-verified before use */ }
242
313
  }
243
314
  function readActiveChildAccount() {
244
315
  if (!PERSIST_ACTIVE_ACCOUNT_SELECTION)
@@ -251,39 +322,30 @@ function readActiveChildAccount() {
251
322
  function persistActiveChildAccount(accountId) {
252
323
  if (!PERSIST_ACTIVE_ACCOUNT_SELECTION)
253
324
  return true;
254
- if (process.platform !== "darwin" || process.env.FELIX_MCP_TRANSPORT === "http")
325
+ if (!localCredentialStoreUsable())
255
326
  return false;
256
327
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(accountId))
257
328
  return false;
258
329
  if (readActiveChildAccount() === accountId)
259
330
  return true;
260
- const helper = resolve(dirname(fileURLToPath(import.meta.url)), "..", "scripts", "keychain-write.exp");
261
- const result = spawnSync("/usr/bin/expect", [
262
- helper,
263
- userInfo().username,
264
- KEYCHAIN_ACTIVE_ACCOUNT_SERVICE,
265
- "Felix active child account",
266
- ], {
267
- encoding: "utf8",
268
- input: accountId,
269
- stdio: ["pipe", "ignore", "ignore"],
270
- maxBuffer: 16 * 1024,
271
- });
331
+ try {
332
+ writeCredential(KEYCHAIN_ACTIVE_ACCOUNT_SERVICE, "Felix active child account", accountId);
333
+ }
334
+ catch { /* the read below is authoritative */ }
272
335
  // Another local MCP may have completed the same write while this helper was
273
336
  // waiting on Keychain. The authoritative final value matters, not which
274
337
  // process won add-generic-password.
275
338
  return readActiveChildAccount() === accountId;
276
339
  }
277
340
  async function acquireChildSessionLock() {
278
- if (EPHEMERAL_SESSION || process.platform !== "darwin"
279
- || process.env.FELIX_MCP_TRANSPORT === "http") {
341
+ if (EPHEMERAL_SESSION || !localCredentialStoreUsable()) {
280
342
  return { path: "", token: "ephemeral" };
281
343
  }
282
344
  const directory = join(homedir(), ".felix-mcp");
283
345
  mkdirSync(directory, { recursive: true, mode: 0o700 });
284
346
  const directoryStatus = lstatSync(directory);
285
347
  if (!directoryStatus.isDirectory() || directoryStatus.isSymbolicLink()
286
- || (directoryStatus.mode & 0o077) !== 0
348
+ || !hasPrivateMode(directoryStatus.mode)
287
349
  || (typeof process.geteuid === "function" && directoryStatus.uid !== process.geteuid())) {
288
350
  throw new Error("The Felix local state directory is not private.");
289
351
  }
@@ -340,15 +402,15 @@ function releaseChildSessionLock(lock) {
340
402
  function forgetActiveChildAccount() {
341
403
  if (!PERSIST_ACTIVE_ACCOUNT_SELECTION)
342
404
  return;
343
- if (process.platform !== "darwin" || process.env.FELIX_MCP_TRANSPORT === "http")
405
+ if (!localCredentialStoreUsable())
344
406
  return;
345
- spawnSync("/usr/bin/security", [
346
- "delete-generic-password", "-a", userInfo().username,
347
- "-s", KEYCHAIN_ACTIVE_ACCOUNT_SERVICE,
348
- ], { stdio: ["ignore", "ignore", "ignore"] });
407
+ try {
408
+ deleteCredential(KEYCHAIN_ACTIVE_ACCOUNT_SERVICE);
409
+ }
410
+ catch { /* re-verified on next read */ }
349
411
  }
350
412
  function persistActiveChildSession(accountId, apiKey) {
351
- if (process.platform !== "darwin" || process.env.FELIX_MCP_TRANSPORT === "http")
413
+ if (!localCredentialStoreUsable())
352
414
  return false;
353
415
  const keyPersisted = readCachedChildKey(accountId) === apiKey
354
416
  || cacheChildKey(accountId, apiKey);
@@ -582,7 +644,7 @@ function ensurePrivateMoneyWorkflowDirectory(directory) {
582
644
  mkdirSync(directory, { recursive: true, mode: 0o700 });
583
645
  const status = lstatSync(directory);
584
646
  if (!status.isDirectory() || status.isSymbolicLink()
585
- || (status.mode & 0o077) !== 0
647
+ || !hasPrivateMode(status.mode)
586
648
  || (typeof process.geteuid === "function" && status.uid !== process.geteuid())) {
587
649
  throw new Error("The money-workflow journal directory is not private; refusing to move funds.");
588
650
  }
@@ -590,11 +652,11 @@ function ensurePrivateMoneyWorkflowDirectory(directory) {
590
652
  function readPrivateLockFile(path) {
591
653
  let descriptor;
592
654
  try {
593
- descriptor = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
655
+ descriptor = openReadNoFollow(path);
594
656
  const status = fstatSync(descriptor);
595
657
  if (!status.isFile() || status.isSymbolicLink()
596
658
  || status.size <= 0 || status.size > 4096
597
- || (status.mode & 0o077) !== 0
659
+ || !hasPrivateMode(status.mode)
598
660
  || (typeof process.geteuid === "function" && status.uid !== process.geteuid())) {
599
661
  throw new Error("unsafe lock file");
600
662
  }
@@ -609,11 +671,11 @@ function readMoneyWorkflowJournalAtPath(path, encryptionKey) {
609
671
  let encoded;
610
672
  let descriptor;
611
673
  try {
612
- descriptor = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
674
+ descriptor = openReadNoFollow(path);
613
675
  const status = fstatSync(descriptor);
614
676
  if (!status.isFile() || status.isSymbolicLink()
615
677
  || status.size <= 0 || status.size > MAX_MONEY_JOURNAL_BYTES
616
- || (status.mode & 0o077) !== 0
678
+ || !hasPrivateMode(status.mode)
617
679
  || (typeof process.geteuid === "function" && status.uid !== process.geteuid())) {
618
680
  throw new Error("unsafe journal file");
619
681
  }
@@ -934,7 +996,7 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
934
996
  const existing = journal.entries[entryKey];
935
997
  if (existing) {
936
998
  if (existing.request_hash !== requestHash) {
937
- return clientError("idempotency_conflict", "This money-workflow key was already used for a different request.", "Reuse the original request or choose a fresh workflow key.");
999
+ return clientError("idempotency_conflict", "This idempotency_key was already used for a different request (other arguments). Nothing was sent.", "Use a new idempotency_key for this request. To finish the earlier one, repeat it with its original arguments; list_recent_operations shows it.", { money_moved: false, operation_started: false });
938
1000
  }
939
1001
  if ((existing.account_id || "launcher") !== workflowAccountId) {
940
1002
  return clientError("workflow_account_mismatch", "This saved money workflow belongs to a different Felix account.", "Restore the original child account with use_child_account before resuming. Never use a new workflow key.", { workflow_account_id: existing.account_id, active_account_id: workflowAccountId || null });
@@ -969,6 +1031,8 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
969
1031
  }
970
1032
  journal.entries[entryKey] = {
971
1033
  ...existing,
1034
+ operation: existing.operation || operation,
1035
+ workflow_key: existing.workflow_key || workflowKey,
972
1036
  ...(options.persistRequestPayload && existing.request_payload === undefined
973
1037
  ? { request_payload: structuredClone(payload) }
974
1038
  : {}),
@@ -983,6 +1047,8 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
983
1047
  const startedAt = new Date().toISOString();
984
1048
  journal.entries[entryKey] = {
985
1049
  request_hash: requestHash,
1050
+ operation,
1051
+ workflow_key: workflowKey,
986
1052
  ...(options.persistRequestPayload ? { request_payload: structuredClone(payload) } : {}),
987
1053
  ...(workflowAccountId ? { account_id: workflowAccountId } : {}),
988
1054
  status: "in_progress",
@@ -1098,6 +1164,8 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
1098
1164
  }
1099
1165
  journal.entries[entryKey] = {
1100
1166
  request_hash: requestHash,
1167
+ operation,
1168
+ workflow_key: workflowKey,
1101
1169
  ...(journal.entries[entryKey]?.request_payload
1102
1170
  ? { request_payload: journal.entries[entryKey].request_payload }
1103
1171
  : {}),
@@ -1181,6 +1249,63 @@ function readAsyncMoneyOperation(operationId) {
1181
1249
  return undefined;
1182
1250
  return entry;
1183
1251
  }
1252
+ // RECENT_OPERATIONS_20261123: multi-step money workflows (create_account, withdraw, Arc home moves...) were
1253
+ // journaled but invisible, so a half-finished one looked like nothing happened. Internal sub-steps (fxwf- keys)
1254
+ // are listed as steps of the call the user made; legacy entries from before this build show operation "unknown".
1255
+ const WORKFLOW_RECOVERY_TOOLS = {
1256
+ create_live_account: "create_account",
1257
+ withdrawal: "withdraw",
1258
+ arc_transfer: "submit_arc_transfer",
1259
+ arc_home_hl_return: "start_arc_home_hl_return",
1260
+ fee_credit_top_up: "top_up_fee_balance",
1261
+ };
1262
+ function listMoneyWorkflowOperations(journal, accountId) {
1263
+ const liveMutationOps = new Set(["place_order", "place_batch_orders", "deploy_agent", "place_manual_order"]);
1264
+ return Object.values(journal.entries)
1265
+ .filter((entry) => (entry.account_id || "launcher") === accountId
1266
+ && !liveMutationOps.has(String(entry.request_payload?.operation))
1267
+ && (!(entry.workflow_key || "").startsWith("fxwf-") || entry.status !== "completed")
1268
+ && (entry.operation !== undefined || entry.status !== "completed"))
1269
+ .map((entry) => {
1270
+ const progress = workflowProgress(entry);
1271
+ const stale = entry.status === "in_progress" && !(entry.process_id === process.pid);
1272
+ const status = stale ? "interrupted" : entry.status;
1273
+ const toolName = entry.operation
1274
+ ? (WORKFLOW_RECOVERY_TOOLS[entry.operation] || entry.operation) : undefined;
1275
+ const recoveryTool = toolName && TOOLS.some((tool) => tool.name === toolName) ? toolName : null;
1276
+ const moved = progress.money_moved;
1277
+ const response = isRecord(entry.response) ? entry.response : undefined;
1278
+ const finished = status === "completed";
1279
+ const subStep = (entry.workflow_key || "").startsWith("fxwf-");
1280
+ const toolText = recoveryTool || "the tool you originally called";
1281
+ const nextStep = subStep
1282
+ ? `This step ran inside another call (for example place_order with auto_fund, or a funding or return). ${moved === false ? "Nothing moved yet." : "Money may have moved: check get_money_map first."} Then repeat that original call with its own idempotency_key and the same arguments. Never use a new key for it.`
1283
+ : status === "interrupted" && moved === false
1284
+ ? `Nothing moved yet. Call ${toolText} again with this idempotency_key and the same arguments to resume.`
1285
+ : moved === false
1286
+ ? `Nothing moved yet. Call ${toolText} again with this idempotency_key and the same arguments. If Felix answers workflow_reconciliation_required, open a support ticket quoting this idempotency_key; never use a new key for it.`
1287
+ : `Money may have moved in step ${String(progress.last_completed_step)}. Check get_money_map and get_money_operation first. Then call ${toolText} again with this idempotency_key and the same arguments: Felix resumes only when it can prove where the money is and never repeats a finished step. If it answers workflow_reconciliation_required, open a support ticket quoting this idempotency_key. Never use a new key for it.`;
1288
+ return {
1289
+ operation_id: null,
1290
+ kind: subStep ? "money_workflow_step" : "money_workflow",
1291
+ operation: entry.operation || "unknown",
1292
+ idempotency_key: subStep ? null : (entry.workflow_key || null),
1293
+ account_id: accountId === "launcher" ? null : accountId,
1294
+ status: finished && response?.ok === false ? "stopped" : status,
1295
+ started_at: entry.started_at || null,
1296
+ updated_at: entry.updated_at,
1297
+ workflow: progress,
1298
+ ...(response && response.ok === false && isRecord(response.error) ? { error: response.error } : {}),
1299
+ ...(finished ? {} : {
1300
+ recovery_tool: subStep ? null : recoveryTool,
1301
+ next_step: nextStep,
1302
+ ...(entry.workflow_key ? {} : {
1303
+ note: "This workflow started before felix-mcp 2.0.136, so its key was not recorded. Repeat the original call with the key you used.",
1304
+ }),
1305
+ }),
1306
+ };
1307
+ });
1308
+ }
1184
1309
  function listAsyncMoneyOperations(limit = 20) {
1185
1310
  const activeAccountId = runtimeManagedAccountId || "launcher";
1186
1311
  const journal = readMoneyWorkflowJournal();
@@ -2840,7 +2965,13 @@ async function arcHomeOwnerKeyFor(accountId) {
2840
2965
  async function arcHomeCall(method, path, body, opts = {}) {
2841
2966
  // A child session's Arc home money calls go out on the launcher credential for that child (Astra mcploop r2:
2842
2967
  // the child's read/trade key got 403 'transfer' on an implicit arc_home_withdraw).
2843
- const accountId = opts.accountId || activeChildAccountId();
2968
+ // Opus QA r15: that launcher credential could act on ANY owned account, so an explicit account_id for a different
2969
+ // account than the session's is refused here exactly like call()'s child-management guard, never retargeted.
2970
+ const selected = activeChildAccountId();
2971
+ if (selected && opts.accountId && opts.accountId.toLowerCase() !== selected.toLowerCase()) {
2972
+ return clientError("account_mismatch", "This session is working on a different account than the account_id you passed. Nothing was sent.", "Omit account_id to act on the selected account, or call use_child_account with the other account first.", { selected_account_id: selected, money_moved: false });
2973
+ }
2974
+ const accountId = opts.accountId || selected;
2844
2975
  const targetPath = accountId && method === "GET" ? withTargetAccountQuery(path, accountId) : path;
2845
2976
  const targetBody = accountId && method === "POST" ? { ...(body || {}), account_id: accountId } : body;
2846
2977
  return call(method, targetPath, targetBody, {
@@ -3685,6 +3816,11 @@ async function withWorkflowBinding(name, args, action) {
3685
3816
  }
3686
3817
  }
3687
3818
  function toolOutput(out) {
3819
+ if (out.ok === false && out.mcp_update === undefined) {
3820
+ const notice = mcpUpdateNotice();
3821
+ if (notice)
3822
+ out = { ...out, mcp_update: notice };
3823
+ }
3688
3824
  return {
3689
3825
  isError: out.ok === false,
3690
3826
  content: [
@@ -3785,6 +3921,139 @@ export function withNewAccountNextStep(name, out, args = {}) {
3785
3921
  }
3786
3922
  return out;
3787
3923
  }
3924
+ // VENUE_TRANSFERS_2026_11_18: venue-to-venue transfers (engine services/agent_capital/venue_transfers.py).
3925
+ const VENUE_TRANSFER_VENUE_INPUTS = ["hyperliquid", "polymarket", "lighter", "prediction_market"];
3926
+ // Opus QA r16 F7: no "crypto" alias; Lighter is a crypto venue too. prediction_market is the engine's own alias.
3927
+ const VENUE_TRANSFER_ALIASES = {
3928
+ hyperliquid: "hyperliquid", polymarket: "polymarket", prediction_market: "polymarket", lighter: "lighter",
3929
+ };
3930
+ const VENUE_TRANSFER_NAMES = { hyperliquid: "Hyperliquid", polymarket: "Polymarket", lighter: "Lighter" };
3931
+ const VENUE_TRANSFER_FINAL = new Set(["completed", "partial", "failed", "needs_review"]);
3932
+ const VENUE_TRANSFER_STATES = new Set(["sending", ...VENUE_TRANSFER_FINAL]);
3933
+ const VENUE_TRANSFER_POLL_MS = 2_000;
3934
+ export function venueTransferVenue(value) {
3935
+ const key = typeof value === "string" ? value.trim().toLowerCase() : "";
3936
+ return Object.hasOwn(VENUE_TRANSFER_ALIASES, key) ? VENUE_TRANSFER_ALIASES[key] : undefined;
3937
+ }
3938
+ /** money_moved for a transfer record, from the engine's own state machine (venue_transfers.advance). */
3939
+ export function venueTransferMoneyMoved(state) {
3940
+ if (state === "completed" || state === "partial")
3941
+ return true;
3942
+ if (state === "failed")
3943
+ return false;
3944
+ return "unknown";
3945
+ }
3946
+ /** Adds the outcome fields an agent needs to a parsed transfer; never invents engine state. */
3947
+ export function describeVenueTransfer(transfer) {
3948
+ const state = String(transfer.state);
3949
+ const from = VENUE_TRANSFER_NAMES[String(transfer.from_venue)] ?? String(transfer.from_venue);
3950
+ const to = VENUE_TRANSFER_NAMES[String(transfer.to_venue)] ?? String(transfer.to_venue);
3951
+ const next = state === "sending"
3952
+ ? `Still moving. Poll get_venue_transfer with this transfer_id; do not start another transfer from ${from}.`
3953
+ : state === "completed"
3954
+ ? `Done: the cash is on ${to}.`
3955
+ : state === "partial"
3956
+ ? "Part of this transfer finished; message says where the cash is. It is safe in the owner's own accounts; "
3957
+ + "see get_money_map before moving it again."
3958
+ : state === "needs_review"
3959
+ ? "Felix is confirming a step. The money is safe and nothing will move twice. Do not retry; check "
3960
+ + "get_venue_transfer later."
3961
+ : "Nothing moved. A new transfer needs a new idempotency_key.";
3962
+ return { transfer, state, final: VENUE_TRANSFER_FINAL.has(state), money_moved: venueTransferMoneyMoved(state),
3963
+ next_action: next };
3964
+ }
3965
+ /** Validated venue-transfer arguments and the engine body, or the local refusal (nothing sent). */
3966
+ function venueTransferArgs(a) {
3967
+ const from = venueTransferVenue(a.from_venue);
3968
+ const to = venueTransferVenue(a.to_venue);
3969
+ const hasAmount = a.amount_usd !== undefined && a.amount_usd !== null;
3970
+ const amount = hasAmount ? arcHomeUnits(a.amount_usd, "amount_usd") : undefined;
3971
+ const bad = validateOptionalAccountId(a)
3972
+ || (!from ? clientError("invalid_argument", "from_venue must be hyperliquid, polymarket or lighter.") : undefined)
3973
+ || (!to ? clientError("invalid_argument", "to_venue must be hyperliquid, polymarket or lighter.") : undefined)
3974
+ || (from && from === to ? clientError("same_venue", "Pick two different venues.") : undefined)
3975
+ || (amount !== undefined && typeof amount !== "bigint" ? amount : undefined)
3976
+ || (typeof amount === "bigint" && amount <= 0n
3977
+ ? clientError("invalid_argument", "amount_usd must be greater than 0.") : undefined)
3978
+ || (a.all_free_cash !== undefined && typeof a.all_free_cash !== "boolean"
3979
+ ? clientError("invalid_argument", "all_free_cash must be true or false.") : undefined)
3980
+ || (hasAmount && a.all_free_cash === true
3981
+ ? clientError("invalid_argument", "Give amount_usd or all_free_cash:true, not both.") : undefined);
3982
+ if (bad || !from || !to)
3983
+ return { bad: { ...(bad ?? {}), money_moved: false } };
3984
+ return { from, to, hasAmount, requestBody: {
3985
+ ...(a.account_id ? { account_id: a.account_id } : {}),
3986
+ from_venue: from, to_venue: to,
3987
+ ...(hasAmount ? { amount_usd: Number(a.amount_usd) } : {}),
3988
+ } };
3989
+ }
3990
+ /** A transfer record shaped like the engine's public_transfer, or undefined (app parseVenueTransfer). */
3991
+ export function parseVenueTransferRecord(value) {
3992
+ if (!isRecord(value))
3993
+ return undefined;
3994
+ if (typeof value.transfer_id !== "string" || !UUID_RE.test(value.transfer_id))
3995
+ return undefined;
3996
+ if (!venueTransferVenue(value.from_venue) || !venueTransferVenue(value.to_venue))
3997
+ return undefined;
3998
+ if (typeof value.state !== "string" || !VENUE_TRANSFER_STATES.has(value.state))
3999
+ return undefined;
4000
+ return value;
4001
+ }
4002
+ const VENUE_TRANSFER_REFUSAL_HINTS = {
4003
+ insufficient_free_cash: "Pass a smaller amount_usd, or all_free_cash:true to move what is free. Open orders, "
4004
+ + "positions and running agents keep their cash.",
4005
+ below_transfer_minimum: "Transfers start at minimum_usd. Move at least that much, or add cash to the source venue first.",
4006
+ transfer_in_progress: "Another transfer from this venue is still moving. Wait for it: list_venue_transfers with open_only:true.",
4007
+ venue_cash_unreadable: "The venue balance is updating. Retry in a moment with the same idempotency_key.",
4008
+ polymarket_return_not_ready: "Polymarket cash cannot move out yet. Retry later with the same idempotency_key.",
4009
+ idempotency_conflict: "This idempotency_key already belongs to another transfer: read it first with "
4010
+ + "get_venue_transfer(existing_transfer_id); it may still be moving. Use a new idempotency_key only for a "
4011
+ + "genuinely different transfer.",
4012
+ agent_capital_not_enabled: "Transfers between venues are not available on this account yet. Fund a venue from the "
4013
+ + "Arc home with fund_hypercore_from_arc or fund_polymarket_from_arc instead.",
4014
+ unsupported_venue: "Transfers move between hyperliquid, polymarket and lighter.",
4015
+ same_venue: "Pick two different venues.",
4016
+ invalid_amount: "amount_usd must be a positive USDC amount.",
4017
+ };
4018
+ /** A refused preview/start (engine 400/409 TransferRefused): keep the engine's words, add the next step. */
4019
+ export function withVenueTransferRefusalHint(out) {
4020
+ if (out.ok !== false || !isRecord(out.error))
4021
+ return out;
4022
+ const error = out.error;
4023
+ const code = String(error.reason ?? error.code ?? "");
4024
+ const message = String(error.message ?? "");
4025
+ if (/lacks the '(?:transfer|read)' scope/.test(message)) {
4026
+ return { ...out, error: { ...error, hint: "This key cannot move money between venues. Use the owner's local "
4027
+ + "launcher session (use_child_account selects the account), or Transfer in the Felix app. This request moved no money." },
4028
+ money_moved: false };
4029
+ }
4030
+ const hint = VENUE_TRANSFER_REFUSAL_HINTS[code]
4031
+ ?? (/_order_in_flight$/.test(code)
4032
+ ? "An order on the source venue is still settling. Retry in a moment with the same idempotency_key." : undefined);
4033
+ if (!hint)
4034
+ return out;
4035
+ return { ...out, error: { ...error, hint: `${hint} This request moved no money.` }, money_moved: false };
4036
+ }
4037
+ /** Opus QA r16 F1/F3: a failed start that is not a definite engine refusal never claims nothing moved. */
4038
+ export function withVenueTransferFailureOutcome(out) {
4039
+ if (out.ok !== false || !isRecord(out.error))
4040
+ return out;
4041
+ const error = out.error;
4042
+ const code = String(error.reason ?? error.code ?? "");
4043
+ // Arc admission paused for a release: the engine refused before admission. Keep its own words and retry advice.
4044
+ if (code === "arc_admission_frozen")
4045
+ return { ...out, money_moved: false };
4046
+ const meta = isRecord(out._meta) ? out._meta : {};
4047
+ const status = finiteNumber(meta.http_status);
4048
+ const definite = status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 429
4049
+ && code !== "idempotency_in_progress";
4050
+ return {
4051
+ ...out,
4052
+ error: { ...error, hint: "Retry with the same idempotency_key: it never starts a second transfer. Check "
4053
+ + "list_venue_transfers before using a new key." },
4054
+ ...(definite ? {} : { money_moved: "unknown", outcome_unknown: true }),
4055
+ };
4056
+ }
3788
4057
  function isChildManagementRequest(method, path) {
3789
4058
  const pathname = path.split("?", 1)[0];
3790
4059
  if (method === "GET" || method === "DELETE") {
@@ -3805,6 +4074,9 @@ function isChildManagementRequest(method, path) {
3805
4074
  return pathname === "/v1/referrals"
3806
4075
  // Owner-signed venue bootstrap (routes_agent_capital.py: require("manage"), money_context(account_id)).
3807
4076
  || pathname.startsWith("/v1/agent-capital/venue-bootstrap/")
4077
+ // Venue-to-venue transfer start needs "transfer" (routes_agent_capital.py create_transfer, money_context), which
4078
+ // the account's read/trade key lacks. Preview and reads need only "read" and stay on the account's key.
4079
+ || pathname === "/v1/agent-capital/transfers"
3808
4080
  || pathname === "/v1/fund"
3809
4081
  || pathname === "/v1/bring-home"
3810
4082
  || pathname === "/v1/withdraw"
@@ -4280,6 +4552,12 @@ async function fundMarketPrecheck(venue, amountUsd, resuming, autoSwapNativeUsdc
4280
4552
  const error = isRecord(balances.error) ? balances.error : {};
4281
4553
  const status = finiteNumber(isRecord(balances._meta) ? balances._meta.http_status : undefined);
4282
4554
  if (status === 409 && ["onboarding_required", "wallet_onboarding_required"].includes(String(error.code))) {
4555
+ // FUZZ_FIXES_20261123: only say the money is in the Arc home when there is one. An unfunded account
4556
+ // (often a simulation-only one) has neither source.
4557
+ const home = await arcHomeGet("/v1/arc-home/account");
4558
+ if (home.ok !== false && home.registered !== true) {
4559
+ return markMoneyNotStarted(clientError("no_funding_source", "This account has no funding source yet: no Arc home and no Polygon owner wallet, so there is nothing to move.", "Simulation orders need no funding. For live trading, finish create_account (it sets up the Arc home), then deposit with create_deposit. Nothing was reserved or moved.", { venue, money_moved: false }));
4560
+ }
4283
4561
  // ARC_TRADE_KEY_FUNDING_20261117: an Arc-home account has no Polygon owner wallet to fund from. Its money
4284
4562
  // is in the Arc home, and the app funds a venue from there as part of the order.
4285
4563
  return markMoneyNotStarted(clientError("arc_home_funding_required", "This account's money is in its Arc home, not a Polygon owner wallet, so fund_market cannot move it.", "Move money from the Arc home with fund_hypercore_from_arc (Hyperliquid) or fund_polymarket_from_arc (Polymarket), then trade. Nothing was reserved or moved.", { venue, money_moved: false }));
@@ -4434,9 +4712,36 @@ function accountStatementNullableNonnegative(value) {
4434
4712
  function accountStatementCloseEnough(actual, expected) {
4435
4713
  return Math.abs(actual - expected) <= Math.max(1e-8, Math.abs(expected) * 1e-9);
4436
4714
  }
4715
+ // STATEMENT_SIMULATION_ROWS_20261123 (engine include_paper=true, Felix Infra shape): simulation rows are labelled
4716
+ // mode "paper" and checked for what they carry. They never count as money activity, and live rows keep the
4717
+ // strict ledger contract below.
4718
+ function validSimulationStatementTrade(value) {
4719
+ const nullableNumber = (field) => field === null || field === undefined || exactFiniteNumber(field);
4720
+ const nullableNonnegative = (field) => field === null || field === undefined
4721
+ || (exactFiniteNumber(field) && field >= 0);
4722
+ const closedAt = value.closed_at;
4723
+ return boundedStatementText(value.trade_id, 64) && UUID_RE.test(value.trade_id)
4724
+ && (value.agent_id === null || value.agent_id === undefined
4725
+ || (boundedStatementText(value.agent_id, 64) && UUID_RE.test(value.agent_id)))
4726
+ && boundedStatementText(value.instrument, 160)
4727
+ && (value.market === undefined || value.market === null || boundedStatementText(value.market, 160))
4728
+ && (value.venue === undefined || value.venue === null || boundedStatementText(value.venue, 64))
4729
+ && ACCOUNT_STATEMENT_SIDES.has(String(value.side))
4730
+ && ["open", "closed"].includes(String(value.status))
4731
+ && exactFiniteNumber(value.size_usd) && value.size_usd >= 0
4732
+ && nullableNonnegative(value.entry_price) && nullableNonnegative(value.exit_price)
4733
+ && nullableNumber(value.realized_pnl_usd)
4734
+ && nullableNonnegative(value.fee_open_usd) && nullableNonnegative(value.fee_close_usd)
4735
+ && accountStatementTimestamp(value.opened_at)
4736
+ && (closedAt === null || closedAt === undefined || closedAt === "" || accountStatementTimestamp(closedAt));
4737
+ }
4437
4738
  function validAccountStatementTrade(value) {
4438
4739
  if (!isRecord(value))
4439
4740
  return false;
4741
+ // Simulation-agent rows from the main ledger carry the full contract (pnl_status etc.) and are checked strictly;
4742
+ // standalone simulation orders (include_paper) carry the lighter shape.
4743
+ if (value.mode === "paper" && value.pnl_status === undefined)
4744
+ return validSimulationStatementTrade(value);
4440
4745
  const closed = value.status === "closed";
4441
4746
  if (!boundedStatementText(value.trade_id, 64) || !UUID_RE.test(value.trade_id)
4442
4747
  || !(value.agent_id === null
@@ -4552,9 +4857,14 @@ function guardAccountStatementResponse(out, requestedLimit) {
4552
4857
  // server's own derivation rather than against an assumption that nothing
4553
4858
  // was ever excluded.
4554
4859
  && out.page_complete === (excludedCount === 0)
4555
- && out.records_complete === (trades.every((trade) => trade.complete)
4860
+ // Live rows keep the exact derivation. Simulation rows carry no completeness contract, so a page that
4861
+ // includes them may also answer the cautious false.
4862
+ && (out.records_complete === (trades.every((trade) => trade.mode === "paper"
4863
+ || trade.complete === true)
4556
4864
  && excludedCount === 0
4557
4865
  && unpageableCount === 0)
4866
+ || (out.records_complete === false
4867
+ && trades.some((trade) => trade.mode === "paper")))
4558
4868
  && out.has_more === (out.next_cursor !== null);
4559
4869
  for (let index = 1; internallyConsistent && index < trades.length; index += 1) {
4560
4870
  const previous = trades[index - 1];
@@ -6271,7 +6581,14 @@ export function normalizeMarketSearchPayload(out) {
6271
6581
  return item;
6272
6582
  }
6273
6583
  });
6274
- return { ...out, returned_count: instruments.length, instruments };
6584
+ // FUZZ_FIXES_20261123: the engine's count is every match; say so next to what was returned.
6585
+ const totalMatches = finiteNumber(out.count);
6586
+ return {
6587
+ ...out,
6588
+ returned_count: instruments.length,
6589
+ ...(totalMatches !== undefined ? { total_matches: totalMatches } : {}),
6590
+ instruments,
6591
+ };
6275
6592
  }
6276
6593
  function canonicalTokenAddress(chain, value) {
6277
6594
  const address = nonEmptyString(value);
@@ -7325,6 +7642,274 @@ function closeAmountError(a) {
7325
7642
  }
7326
7643
  return undefined;
7327
7644
  }
7645
+ // TWAP_20261123 (Felix Infra 2 spec, engine kit algo1): Felix-run TWAP on the manual-trading key.
7646
+ const TWAP_STATUS_TEXT = {
7647
+ running: "Slices are being sent on schedule. Read get_twap for progress; cancel_twap stops future slices.",
7648
+ completed: "All slices finished.",
7649
+ cancelled: "Stopped. A slice that was already being sent at cancel time still counts; read get_twap again in a few seconds for the final filled_usd.",
7650
+ failed: "Stopped after three refusals in a row; last_error says why. Nothing more will be sent.",
7651
+ expired: "The time window passed (for example price_limit was never met). Nothing more will be sent.",
7652
+ reconcile_required: "A slice could not be confirmed. Check get_positions and get_fills before any new order; never restart the TWAP blind.",
7653
+ };
7654
+ function validateTwapArgs(a) {
7655
+ const instrument = nonEmptyString(a.instrument);
7656
+ const size = finiteNumber(a.size_usd);
7657
+ const minutes = finiteNumber(a.duration_minutes);
7658
+ const slices = a.slices === undefined ? undefined : finiteNumber(a.slices);
7659
+ const leverage = a.leverage === undefined ? undefined : finiteNumber(a.leverage);
7660
+ const limit = a.price_limit === undefined ? undefined : finiteNumber(a.price_limit);
7661
+ const key = nonEmptyString(a.idempotency_key);
7662
+ const fail = (message) => clientError("invalid_argument", message, "Nothing was sent.", { money_moved: false, order_sent: false });
7663
+ if (!instrument || !/^(perp|lighter):[A-Za-z0-9._-]{1,40}$/i.test(instrument))
7664
+ return fail("instrument must be perp:SYM or lighter:SYM.");
7665
+ if (!["buy", "sell"].includes(String(a.side || "").toLowerCase()))
7666
+ return fail("side must be buy or sell.");
7667
+ if (size === undefined || size < 10 || size > PRACTICAL_NO_CAP_USD)
7668
+ return fail("size_usd must be at least 10.");
7669
+ if (minutes === undefined || !Number.isInteger(minutes) || minutes < 5 || minutes > 1440)
7670
+ return fail("duration_minutes must be a whole number from 5 to 1440.");
7671
+ const sliceCount = slices ?? minutes;
7672
+ if (a.slices !== undefined && (slices === undefined || !Number.isInteger(slices) || slices < 1))
7673
+ return fail("slices must be a whole number of at least 1.");
7674
+ if (size / sliceCount < 10)
7675
+ return fail(`Each slice must be at least $10: ${sliceCount} slices of $${(size / sliceCount).toFixed(2)} is too small. Use fewer slices or a larger size_usd.`);
7676
+ if ((minutes * 60) / sliceCount < 30)
7677
+ return fail("Slices must be at least 30 seconds apart: use fewer slices or a longer duration.");
7678
+ if (a.leverage !== undefined && (leverage === undefined || !Number.isInteger(leverage) || leverage < 1))
7679
+ return fail("leverage must be a whole number of at least 1.");
7680
+ if (a.reduce_only !== undefined && typeof a.reduce_only !== "boolean")
7681
+ return fail("reduce_only must be true or false.");
7682
+ if (a.price_limit !== undefined && (limit === undefined || limit <= 0))
7683
+ return fail("price_limit must be a positive price.");
7684
+ if (!key || key.length < 8 || key.length > 128 || /[^\x21-\x7e]/.test(key)) {
7685
+ return clientError("missing_argument", "idempotency_key is required (8-128 printable characters).", "Choose one key per TWAP and reuse it only to retry the exact same request. Nothing was sent.", { money_moved: false, order_sent: false });
7686
+ }
7687
+ if (a.reduce_only !== true && size > maxLocalLiveOrderUsd()) {
7688
+ return clientError("local_safety_cap", "This TWAP's total exceeds the local FELIX_MAX_LIVE_ORDER_USD safety cap.", "Raise the local cap only after reviewing the key's server-side limits. Nothing was sent.", { money_moved: false, order_sent: false });
7689
+ }
7690
+ return undefined;
7691
+ }
7692
+ function describeTwap(record) {
7693
+ const status = nonEmptyString(record.status)?.toLowerCase() || "unknown";
7694
+ const filled = finiteNumber(record.filled_usd);
7695
+ return {
7696
+ ...record,
7697
+ algo_id: record.algo_id ?? record.id ?? null,
7698
+ status,
7699
+ final: ["completed", "cancelled", "failed", "expired"].includes(status),
7700
+ // An unconfirmed slice may have filled even when filled_usd does not show it yet.
7701
+ // Review r1: "nothing moved" only when the TWAP can no longer send a slice. A running or just-cancelled
7702
+ // TWAP may have a slice in flight that filled_usd does not show yet.
7703
+ money_moved: filled !== undefined && filled > 0 ? true
7704
+ : ["failed", "expired", "rejected"].includes(status) && filled !== undefined ? false
7705
+ : filled !== undefined || status === "reconcile_required" ? "unknown" : null,
7706
+ ...(status === "cancelled" && (filled === undefined || filled === 0)
7707
+ ? { slice_may_be_in_flight: true, slice_note: "A slice already sent before the cancel can still fill. Read get_twap again in a few seconds for the final filled_usd." }
7708
+ : {}),
7709
+ ...(status === "reconcile_required" ? { reconciliation_required: true } : {}),
7710
+ next_action: TWAP_STATUS_TEXT[status] || "Read get_twap again for the current status.",
7711
+ };
7712
+ }
7713
+ function describeTwapResponse(out, phase) {
7714
+ if (out.ok === false) {
7715
+ const error = isRecord(out.error) ? out.error : {};
7716
+ const code = nonEmptyString(error.code) || "";
7717
+ const status = finiteNumber(isRecord(out._meta) ? out._meta.http_status : undefined);
7718
+ if (phase === "start" && code === "algo_order_conflict") {
7719
+ return { ...out, error: { ...error, hint: "An account can run at most 10 TWAPs. Cancel one with cancel_twap or wait for one to finish. Nothing was started." }, money_moved: false };
7720
+ }
7721
+ if (phase === "start" && (status === undefined || status >= 500)) {
7722
+ // Review r1: call() retries with the same key, so an earlier attempt may have stored the TWAP before this
7723
+ // failure (a lost response, then a 503). Never say nothing started.
7724
+ return {
7725
+ ...out,
7726
+ error: { ...error, hint: "Felix did not confirm whether this TWAP started. Call get_twap with no algo_id to list TWAPs and look for it before doing anything else. If it is not there, retry with the SAME idempotency_key, never a new one." },
7727
+ outcome_unknown: true,
7728
+ money_moved: "unknown",
7729
+ };
7730
+ }
7731
+ return out;
7732
+ }
7733
+ const record = isRecord(out.algo_order) ? out.algo_order : isRecord(out.twap) ? out.twap : out;
7734
+ const { _meta: meta, ok: _ok, ...fields } = record;
7735
+ return { ok: true, ...describeTwap(fields), ...(isRecord(out._meta) ? { _meta: out._meta } : meta ? { _meta: meta } : {}) };
7736
+ }
7737
+ // FUZZ_FIXES_20261123: a user's fuzzing run found results that looked fine but were not what was asked for.
7738
+ // Until the engine serves them exactly, the MCP says plainly what was served.
7739
+ function withServedResearchShape(out, args) {
7740
+ if (out.ok === false)
7741
+ return out;
7742
+ // Engine 1407de89f+ reports served_interval/served_bars itself; prefer them, count the cards otherwise.
7743
+ const servedInterval = nonEmptyString(out.served_interval) ?? nonEmptyString(out.interval);
7744
+ const cards = Array.isArray(out.cards) ? out.cards : [];
7745
+ const candleCard = cards.find((card) => isRecord(card) && Array.isArray(card.bars));
7746
+ const servedBars = finiteNumber(out.served_bars)
7747
+ ?? (candleCard && Array.isArray(candleCard.bars) ? candleCard.bars.length : 0);
7748
+ const requestedInterval = nonEmptyString(args.interval);
7749
+ const requestedBars = finiteNumber(args.bars);
7750
+ const intervalDiffers = requestedInterval !== undefined && servedInterval !== undefined && servedInterval !== requestedInterval;
7751
+ const barsShort = requestedBars !== undefined && servedBars < requestedBars;
7752
+ if (!intervalDiffers && !barsShort)
7753
+ return { ...out, served_interval: servedInterval ?? null, served_bars: servedBars };
7754
+ return {
7755
+ ...out,
7756
+ served_interval: servedInterval ?? null,
7757
+ served_bars: servedBars,
7758
+ request_not_fully_served: true,
7759
+ warning: `You asked for ${requestedBars ?? "default"} ${requestedInterval ?? "default"} bars; research served ${servedBars} ${servedInterval ?? "unknown"} bars. Research cards are daily summaries. For intraday history, use backtest data or the market stream (get_market_streaming_guide).`,
7760
+ };
7761
+ }
7762
+ function withOptionExpiryCounts(out) {
7763
+ if (out.ok === false || !Array.isArray(out.expiries_ts))
7764
+ return out;
7765
+ const total = finiteNumber(out.expiry_count);
7766
+ const listed = out.expiries_ts.length;
7767
+ return {
7768
+ ...out,
7769
+ expiries_listed: listed,
7770
+ ...(total !== undefined && total > listed ? {
7771
+ expiries_truncated: true,
7772
+ note: `expiries_ts lists the nearest ${listed} of ${total} expiries.`,
7773
+ } : { expiries_truncated: false }),
7774
+ };
7775
+ }
7776
+ function withAvailableToTradeCompleteness(out) {
7777
+ if (out.ok === false)
7778
+ return out;
7779
+ const values = Object.entries(out).filter(([key]) => !["ok", "_meta", "status", "message", "instrument", "refreshing"].includes(key));
7780
+ const known = values.some(([, value]) => value !== null && value !== undefined);
7781
+ if (known)
7782
+ return out;
7783
+ return {
7784
+ ...out,
7785
+ complete: false,
7786
+ hint: "Felix has no buying power to report for this instrument yet. If this persists, the account may not be set up for live trading: call get_trading_capabilities, and create_account if it has no Arc home. Do not size orders from this result.",
7787
+ };
7788
+ }
7789
+ function withManualTradingBlocker(out) {
7790
+ if (out.ok !== false)
7791
+ return out;
7792
+ const error = isRecord(out.error) ? out.error : {};
7793
+ const text = `${String(error.code || "")} ${String(error.message || "")} ${String(error.hint || "")}`.toLowerCase();
7794
+ const policyBlocked = /arc_home_required|execution_policy_required|review your trading authorization|execution policy registration could not be confirmed|arc home is not ready/.test(text);
7795
+ if (!policyBlocked)
7796
+ return out;
7797
+ return {
7798
+ ...out,
7799
+ error: {
7800
+ ...error,
7801
+ message: "Manual trading is not set up for this account yet, so no order was previewed or sent.",
7802
+ hint: "Manual trading needs the account's Arc home and its trading policy. If create_account has not finished for this account, call create_account again with its original idempotency_key (list_recent_operations shows it); it registers the trading policy. Then retry. Nothing was sent.",
7803
+ },
7804
+ upstream_error: { code: error.code ?? null, message: error.message ?? null },
7805
+ order_sent: false,
7806
+ money_moved: false,
7807
+ };
7808
+ }
7809
+ // LEGACY_ACCOUNT_HINT_20261123: accounts made before every account got an Arc home (most are old paper accounts)
7810
+ // answer wallet_not_ready, whose engine hint points at the retired client-owned Safe onboarding.
7811
+ function withLegacyAccountHint(out, accountId) {
7812
+ const error = isRecord(out.error) ? out.error : {};
7813
+ if (error.code !== "wallet_not_ready")
7814
+ return out;
7815
+ if (nonEmptyString(error.reason_code) || nonEmptyString(out.reason_code)) {
7816
+ // QA r17 F2: a new account whose Arc home is still being set up answers this too. Resume first.
7817
+ return {
7818
+ ...out,
7819
+ error: {
7820
+ ...error,
7821
+ hint: "Finish this account's setup by calling create_account again with the idempotency_key you first used; list_recent_operations shows it if setup started on this computer. If this is an older account that was never set up (for example an early simulation account) and you have no such key, create a new account with create_account instead. Nothing was changed.",
7822
+ },
7823
+ account_id: accountId,
7824
+ money_moved: false,
7825
+ };
7826
+ }
7827
+ return {
7828
+ ...out,
7829
+ error: {
7830
+ ...error,
7831
+ message: "This account was created before every Felix account got an Arc home wallet, so it cannot be selected as a trading session. Nothing was changed.",
7832
+ hint: "For simulation trading, create a new account with create_account and deploy simulation agents there (mode \"paper\"). This account stays readable from the launcher (list_accounts, get_account_statement with its account_id). Use archive_account to tidy it up once it holds nothing.",
7833
+ },
7834
+ account_id: accountId,
7835
+ legacy_account: true,
7836
+ money_moved: false,
7837
+ };
7838
+ }
7839
+ // STATUS_CLARITY_20261123: "key_capability_check_failed" alone left users unsure whether their key or Felix was
7840
+ // broken. Say which, from the status the key check actually got.
7841
+ function keyCheckFailure(subscription) {
7842
+ const error = isRecord(subscription.error) ? subscription.error : {};
7843
+ const meta = isRecord(subscription._meta) ? subscription._meta : {};
7844
+ const status = finiteNumber(meta.http_status);
7845
+ const code = nonEmptyString(error.code) || null;
7846
+ const cause = status === 401 ? "key_not_accepted"
7847
+ : status === 403 ? "key_lacks_permission"
7848
+ : status === 429 ? "rate_limited"
7849
+ : status === undefined || status >= 500 ? "felix_unreachable_or_degraded"
7850
+ : "key_check_refused";
7851
+ const explanation = {
7852
+ key_not_accepted: "Felix rejected this key (revoked or replaced). The platform itself is fine.",
7853
+ key_lacks_permission: "The key is valid but this check needs a permission it does not have.",
7854
+ rate_limited: "This key hit its rate limit; the key itself is fine. Retry after the reset time.",
7855
+ felix_unreachable_or_degraded: "Felix could not answer the key check right now. Your key was not rejected.",
7856
+ key_check_refused: "Felix refused the key check.",
7857
+ };
7858
+ return {
7859
+ can_place_live_orders: null,
7860
+ blocking_reason: "key_capability_check_failed",
7861
+ cause,
7862
+ explanation: explanation[cause],
7863
+ check_http_status: status ?? null,
7864
+ check_error_code: code,
7865
+ ...(nonEmptyString(error.hint) ? { hint: error.hint } : {}),
7866
+ };
7867
+ }
7868
+ // IDEMPOTENCY_UX_20261123: stage keys (fxwf-...) are derived from the caller's own key. They are never something
7869
+ // a user retries with, so they are reported as internal_step_key and hints point back to the original key.
7870
+ function isInternalStageKey(key) {
7871
+ return key.startsWith("fxwf-");
7872
+ }
7873
+ // KEY_RENEWAL_20261123 / MCP_UPDATE_NOTICE_20261123: make the three failures that strand users say exactly what
7874
+ // happened and the one command that fixes it.
7875
+ function annotateHttpFailure(status, out, usedKey, publicRequest) {
7876
+ const error = isRecord(out.error) ? out.error : {};
7877
+ if (status === 401 && !publicRequest) {
7878
+ const launcher = usedKey !== undefined && usedKey === START_KEY;
7879
+ const prefix = usedKey && API_KEY_RE.test(usedKey) ? usedKey.slice(0, 12) : null;
7880
+ return {
7881
+ ...out,
7882
+ error: {
7883
+ ...error,
7884
+ message: `Felix does not accept this ${launcher ? "launcher" : "account"} key${prefix ? ` (${prefix})` : ""}: it was revoked or replaced. Nothing was sent.`,
7885
+ hint: isHostedTransport()
7886
+ ? "Create a new key in the Felix app (Settings, API keys) and update the Authorization header in your MCP client. Your accounts and money are unchanged."
7887
+ : launcher
7888
+ ? "Run `felix-keys renew-key` in a terminal on this computer. It checks that Felix rejects the saved key, asks you to confirm, and issues a replacement for the same owner and account. Then call reload_launcher_key. Your accounts, agents and money are unchanged."
7889
+ : "Call reload_launcher_key, then use_child_account with this account's id and force_remint:true to issue a fresh account key. Your money is unchanged.",
7890
+ },
7891
+ key_rejected: true,
7892
+ key_role: launcher ? "launcher" : "account",
7893
+ money_moved: false,
7894
+ };
7895
+ }
7896
+ if (status === 426 || status === 410) {
7897
+ const notice = mcpUpdateNotice();
7898
+ return {
7899
+ ...out,
7900
+ error: {
7901
+ ...error,
7902
+ hint: status === 426
7903
+ ? (isHostedTransport()
7904
+ ? "This hosted Felix server is being updated for this action. Nothing was sent. Retry in a few minutes."
7905
+ : `This Felix MCP (${MCP_VERSION}) is older than this action needs. Nothing was sent. Run \`${MCP_UPDATE_COMMAND}\`, then restart or reconnect your MCP client.`)
7906
+ : `Felix retired the route this MCP version (${MCP_VERSION}) used. ${nonEmptyString(error.hint) || ""} If you are not on the latest felix-mcp, run \`${MCP_UPDATE_COMMAND}\` and reconnect; a newer build uses the current route.`.replace(/\s+/g, " ").trim(),
7907
+ },
7908
+ ...(notice ? { mcp_update: notice } : {}),
7909
+ };
7910
+ }
7911
+ return out;
7912
+ }
7328
7913
  async function call(method, path, body, opts = {}) {
7329
7914
  const binding = workflowBinding.getStore();
7330
7915
  if (binding && (binding.accountId !== runtimeManagedAccountId
@@ -7479,16 +8064,19 @@ async function call(method, path, body, opts = {}) {
7479
8064
  }
7480
8065
  const meta = {
7481
8066
  http_status: res.status,
8067
+ transport_attempts: attempt,
7482
8068
  ...(requestId ? { request_id: requestId } : {}),
7483
8069
  ...(retryAfter ? { retry_after: retryAfter } : {}),
7484
8070
  ...(serverLatencyMs !== undefined ? { server_latency_ms: serverLatencyMs } : {}),
7485
8071
  ...(Object.keys(rateLimit).length ? { rate_limit: rateLimit } : {}),
7486
8072
  ...(minimumMcpVersion ? { minimum_mcp_version: minimumMcpVersion } : {}),
7487
- ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
8073
+ ...(idempotencyKey ? (isInternalStageKey(idempotencyKey)
8074
+ ? { internal_step_key: idempotencyKey }
8075
+ : { idempotency_key: idempotencyKey }) : {}),
7488
8076
  };
7489
8077
  return res.ok
7490
8078
  ? { ...payload, _meta: meta }
7491
- : { ...payload, ok: false, _meta: meta };
8079
+ : annotateHttpFailure(res.status, { ...payload, ok: false, _meta: meta }, key, opts.public === true);
7492
8080
  }
7493
8081
  catch (error) {
7494
8082
  clearTimeout(timer);
@@ -7509,19 +8097,24 @@ async function call(method, path, body, opts = {}) {
7509
8097
  break;
7510
8098
  }
7511
8099
  }
8100
+ const internalStep = idempotencyKey !== undefined && isInternalStageKey(idempotencyKey);
7512
8101
  if (deadlineExceeded) {
7513
- return clientError("request_deadline_exceeded", `Felix stopped waiting after ${Math.round(overallTimeoutMs / 1000)} seconds.`, idempotencyKey
7514
- ? "The operation may still be reconciling. Retry the exact request with the same idempotency_key; never generate a new key for this operation."
7515
- : "Check get_status, then retry when the API is healthy.", {
7516
- ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
8102
+ return clientError("request_deadline_exceeded", `Felix stopped waiting after ${Math.round(overallTimeoutMs / 1000)} seconds.`, internalStep
8103
+ ? "This step may still be finishing. Call the same tool again with your original idempotency_key and arguments; Felix resumes the step itself. Never use a new key for it."
8104
+ : idempotencyKey
8105
+ ? "The operation may still be reconciling. Retry the exact request with the same idempotency_key; never generate a new key for this operation."
8106
+ : "Check get_status, then retry when the API is healthy.", {
8107
+ ...(idempotencyKey ? (internalStep ? { internal_step_key: idempotencyKey } : { idempotency_key: idempotencyKey }) : {}),
7517
8108
  retryable: true,
7518
8109
  outcome_unknown: Boolean(idempotencyKey),
7519
8110
  });
7520
8111
  }
7521
8112
  const message = lastError instanceof Error ? lastError.message : String(lastError);
7522
8113
  if (idempotencyKey && method !== "GET") {
7523
- return clientError("request_outcome_unknown", "The mutation's final API response was not received, so its outcome is unknown.", "Retry the exact same request with the same idempotency_key. Never generate a new key until Felix returns a terminal result.", {
7524
- idempotency_key: idempotencyKey,
8114
+ return clientError("request_outcome_unknown", "The mutation's final API response was not received, so its outcome is unknown.", internalStep
8115
+ ? "Call the same tool again with your original idempotency_key and arguments; Felix resumes this step itself. Never use a new key until Felix returns a final result."
8116
+ : "Retry the exact same request with the same idempotency_key. Never generate a new key until Felix returns a terminal result.", {
8117
+ ...(internalStep ? { internal_step_key: idempotencyKey } : { idempotency_key: idempotencyKey }),
7525
8118
  retryable: true,
7526
8119
  outcome_unknown: true,
7527
8120
  recovery_tool: "get_status",
@@ -9423,9 +10016,9 @@ async function executeFundMarketTool(a) {
9423
10016
  }
9424
10017
  setKey(cachedChildKey);
9425
10018
  }
9426
- if (process.platform === "darwin"
10019
+ if (localCredentialStoreUsable() && !EPHEMERAL_SESSION
9427
10020
  && !persistActiveChildSession(a.account_id, getKey())) {
9428
- return markMoneyNotStarted(clientError("credential_persistence_failed", "The requested child account could not be bound durably before funding.", "Call use_child_account after fixing macOS Keychain access, then retry with the same idempotency_key.", { account_id: a.account_id }));
10021
+ return markMoneyNotStarted(clientError("credential_persistence_failed", "The requested child account could not be bound durably before funding.", "Call use_child_account after fixing access to this computer's key storage, then retry with the same idempotency_key.", { account_id: a.account_id }));
9429
10022
  }
9430
10023
  setRuntimeOwnerPrivateKey(childOwnerKey);
9431
10024
  runtimeManagedAccountId = a.account_id;
@@ -11750,6 +12343,7 @@ const TOOL_RISK_GROUPS = {
11750
12343
  read: [
11751
12344
  "get_capital_move_recovery", "preview_home_funding", "get_home_funding", "get_withdrawal_confirmation",
11752
12345
  "get_arc_home_operation", "get_agent_capital", "preview_capital_move", "get_capital_move",
12346
+ "preview_venue_transfer", "get_venue_transfer", "list_venue_transfers",
11753
12347
  "get_status", "get_health", "get_metrics", "get_custody_recovery_status", "get_strategy_guide",
11754
12348
  "get_market_streaming_guide",
11755
12349
  "search_markets", "list_markets", "search_tokens", "inspect_token_risk",
@@ -11762,7 +12356,7 @@ const TOOL_RISK_GROUPS = {
11762
12356
  "preview_fleet_capacity", "preview_fleet_reallocation",
11763
12357
  "get_execution_quality", "get_exit_plan", "list_exit_plans",
11764
12358
  "get_trading_capabilities", "get_trading_details", "get_available_to_trade", "preview_manual_order",
11765
- "get_manual_order_receipt", "list_open_orders", "get_close_receipt", "get_position_protection",
12359
+ "get_manual_order_receipt", "list_open_orders", "get_close_receipt", "get_position_protection", "get_twap",
11766
12360
  "get_positions", "get_fills", "get_account_statement", "get_pnl", "get_portfolio", "get_balances",
11767
12361
  "get_money_map", "get_network_fee_status", "get_deposit_address",
11768
12362
  "verify_custody", "get_derive_onboarding", "get_money_operation",
@@ -11786,6 +12380,7 @@ const TOOL_RISK_GROUPS = {
11786
12380
  trading: [
11787
12381
  "place_order", "place_batch_orders", "cancel_order", "close_position",
11788
12382
  "place_manual_order", "cancel_open_order", "modify_order_price", "close_manual_position",
12383
+ "start_twap", "cancel_twap",
11789
12384
  "set_position_protection", "cancel_position_protection",
11790
12385
  "set_exit_plan", "cancel_exit_plan", "make_market",
11791
12386
  "get_polymarket_order_status", "get_order_status", "reconcile_polymarket_order",
@@ -11793,7 +12388,7 @@ const TOOL_RISK_GROUPS = {
11793
12388
  ],
11794
12389
  money: [
11795
12390
  "start_home_funding", "prepare_capital_allocation", "submit_capital_allocation", "submit_venue_bootstrap",
11796
- "start_capital_move",
12391
+ "start_capital_move", "transfer_between_venues",
11797
12392
  "resolve_network_fee", "swap_native_usdc", "fund_market",
11798
12393
  "start_fund_market", "bring_home", "start_bring_home", "resume_money_operation",
11799
12394
  "start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return", "invalidate_safe_nonce",
@@ -12066,9 +12661,9 @@ export async function executeSafeInvalidation(writer, operationId, expectedNonce
12066
12661
  }
12067
12662
  const LIVE_MONEY_TOOLS = new Set([
12068
12663
  "submit_capital_allocation", "submit_venue_bootstrap",
12069
- "start_capital_move",
12664
+ "start_capital_move", "transfer_between_venues",
12070
12665
  "place_order", "place_batch_orders", "close_position", "make_market",
12071
- "place_manual_order", "close_manual_position", "modify_order_price",
12666
+ "place_manual_order", "close_manual_position", "modify_order_price", "start_twap",
12072
12667
  "swap_native_usdc", "fund_market", "start_fund_market",
12073
12668
  "bring_home", "start_bring_home", "resume_money_operation", "resolve_network_fee",
12074
12669
  "start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return", "fund_polymarket_from_arc",
@@ -12348,7 +12943,7 @@ const TOOLS = [
12348
12943
  },
12349
12944
  {
12350
12945
  name: "onboard",
12351
- description: "Set up Felix for this owner from inside the chat: asks the owner to accept the Felix Terms of Service, Privacy Policy and Risk Disclosure, then creates the owner key in macOS Keychain, registers the launcher, writes and verifies the encrypted recovery file, and loads the identity into this session (no restart). When the MCP client can show questions, Felix asks the owner directly. Otherwise the first call returns the exact question: ask the owner in chat, and only if they say yes call again with owner_accepted_terms:true and terms_version; macOS then shows one native confirmation the owner must click. Never answer for the owner. Local stdio only. No key or recovery code is returned.",
12946
+ description: "Set up Felix for this owner from inside the chat: asks the owner to accept the Felix Terms of Service, Privacy Policy and Risk Disclosure, then creates the owner key in this computer's secure key storage (macOS Keychain, Windows protected storage, or the Linux keyring), registers the launcher, writes and verifies the encrypted recovery file, and loads the identity into this session (no restart). When the MCP client can show questions, Felix asks the owner directly. Otherwise the first call returns the exact question: ask the owner in chat, and only if they say yes call again with owner_accepted_terms:true and terms_version; the computer then shows one confirmation the owner must click. Never answer for the owner. Local stdio only. No key or recovery code is returned.",
12352
12947
  inputSchema: schema({
12353
12948
  owner_accepted_terms: booleanProp("Only when the client cannot ask the owner directly: true after the owner answered yes, in this chat, to the exact question this tool returned."),
12354
12949
  terms_version: stringProp("The terms version the owner accepted, exactly as returned by the first call."),
@@ -12356,7 +12951,7 @@ const TOOLS = [
12356
12951
  },
12357
12952
  {
12358
12953
  name: "reload_launcher_key",
12359
- description: "Reload the current launcher API key and owner signer from macOS Keychain, validate their encrypted workflow journal, and explicitly leave any child account. No secret is returned.",
12954
+ description: "Reload the current launcher API key and owner signer from this computer's key storage, validate their encrypted workflow journal, and explicitly leave any child account. No secret is returned.",
12360
12955
  inputSchema: schema({}),
12361
12956
  },
12362
12957
  {
@@ -12739,6 +13334,36 @@ const TOOLS = [
12739
13334
  description: "Live resting orders on Hyperliquid, Lighter and Polymarket (placed from the app or the API), with price, size, filled amount and status.",
12740
13335
  inputSchema: schema({}),
12741
13336
  },
13337
+ {
13338
+ name: "start_twap",
13339
+ description: "LIVE: buy or sell a total size_usd evenly over duration_minutes (TWAP). Felix runs it: every slice is a live market order under this key, within the key's caps and the account's risk rules, so this moves real money until it completes or you cancel_twap. Instrument format perp:SYM or lighter:SYM. Each slice is at least $10 and at least 30 seconds apart (default one slice a minute). price_limit is the worst price you accept: a buy waits while the price is above it, a sell while it is below. idempotency_key is required; reuse it to retry the exact same request, never a new key for the same TWAP. At most 10 run per account. Follow progress with get_twap.",
13340
+ inputSchema: schema({
13341
+ instrument: stringProp("perp:SYM or lighter:SYM, for example perp:BTC.", undefined, { pattern: "^(perp|lighter):[A-Za-z0-9._-]{1,40}$" }),
13342
+ side: stringProp("buy or sell.", ["buy", "sell"]),
13343
+ size_usd: numberProp("Total notional in USD across all slices (at least 10).", 10),
13344
+ duration_minutes: integerProp("How long to spread it over, 5 to 1440 minutes.", 5, 1440),
13345
+ slices: integerProp("Optional number of slices. Default: one a minute. Each slice must be at least $10 and 30 seconds apart.", 1, 2880),
13346
+ leverage: integerProp("Optional leverage, default 1, up to the venue maximum.", 1),
13347
+ reduce_only: booleanProp("Only reduce an existing position; never open or flip."),
13348
+ price_limit: numberProp("Optional worst acceptable price (see description).", 0),
13349
+ idempotency_key: stringProp("Required retry-safety key (8-128 characters). The same key always means the same TWAP.", undefined, { minLength: 8, maxLength: 128 }),
13350
+ }, ["instrument", "side", "size_usd", "duration_minutes", "idempotency_key"]),
13351
+ },
13352
+ {
13353
+ name: "get_twap",
13354
+ description: "Read one TWAP by algo_id (status, filled_usd, remaining_usd, slices sent and filled, next slice time, last error), or list this account's recent TWAPs when algo_id is omitted. Read-only.",
13355
+ inputSchema: schema({
13356
+ algo_id: stringProp("TWAP id from start_twap. Omit to list recent ones.", undefined, { pattern: UUID_RE.source }),
13357
+ limit: integerProp("List size, 1 to 100 (default 20).", 1, 100),
13358
+ }),
13359
+ },
13360
+ {
13361
+ name: "cancel_twap",
13362
+ description: "Stop a running TWAP: no new slices are sent. A slice already being sent still finishes and counts, so filled_usd can rise once after the cancel; read get_twap again after a few seconds for the final number. Cancelling a finished TWAP returns it unchanged. Never opens anything.",
13363
+ inputSchema: schema({
13364
+ algo_id: stringProp("TWAP id from start_twap.", undefined, { pattern: UUID_RE.source }),
13365
+ }, ["algo_id"]),
13366
+ },
12742
13367
  {
12743
13368
  name: "cancel_open_order",
12744
13369
  description: "Cancel one live resting order by its id from list_open_orders. Reduces risk; never opens anything.",
@@ -12875,10 +13500,11 @@ const TOOLS = [
12875
13500
  },
12876
13501
  {
12877
13502
  name: "get_account_statement",
12878
- description: "Stable, owner-scoped trade ledger for reconciliation and exports. Follow next_cursor until null. Rows label live, paper, and live-mock activity explicitly and disclose missing historical fee or PnL fields. This is not a tax statement and never moves money.",
13503
+ description: "Stable, owner-scoped trade ledger for reconciliation and exports. Follow next_cursor until null. Rows label live and live-mock activity explicitly and disclose missing historical fee or PnL fields. Simulation rows are included and labelled mode paper (never money activity); pass include_simulation:false for live activity only. This is not a tax statement and never moves money.",
12879
13504
  inputSchema: schema({
12880
13505
  limit: integerProp("Maximum trade rows in this page. Defaults to 100.", 1, 500),
12881
13506
  cursor: stringProp("Opaque next_cursor from the previous page.", undefined, { maxLength: 512 }),
13507
+ include_simulation: booleanProp("Include simulation rows (labelled mode paper). Default true."),
12882
13508
  }),
12883
13509
  },
12884
13510
  {
@@ -12995,6 +13621,47 @@ const TOOLS = [
12995
13621
  account_id: stringProp("Optional owned child account UUID.", undefined, { pattern: UUID_RE.source }),
12996
13622
  }, ["move_id"]),
12997
13623
  },
13624
+ // VENUE_TRANSFERS_2026_11_18 (engine routes_agent_capital.py /v1/agent-capital/transfers, app lib/venueTransfers.ts).
13625
+ {
13626
+ name: "preview_venue_transfer",
13627
+ description: "Read-only preview of moving free cash straight from one venue to another (Hyperliquid, Polymarket, Lighter), like Transfer in the Felix app: free cash on the source, the minimum, the route (front: the destination is funded at once from the Trading wallet; chain: through the Trading wallet) and an ETA in seconds. Omit amount_usd to preview all free cash. Open orders, positions and running agents keep their cash. Creates, reserves and signs nothing.",
13628
+ inputSchema: schema({
13629
+ from_venue: stringProp("Venue the money leaves.", [...VENUE_TRANSFER_VENUE_INPUTS]),
13630
+ to_venue: stringProp("Venue the money arrives on.", [...VENUE_TRANSFER_VENUE_INPUTS]),
13631
+ amount_usd: numberProp("USDC amount, at most six decimal places. Omit to preview all free cash.", 0.000001),
13632
+ account_id: stringProp("Optional owned child account UUID. Omit for the active account.", undefined, { pattern: UUID_RE.source }),
13633
+ }, ["from_venue", "to_venue"]),
13634
+ },
13635
+ {
13636
+ name: "transfer_between_venues",
13637
+ description: "LIVE: move the account's free cash from one venue to another (Hyperliquid, Polymarket, Lighter), exactly like Transfer in the Felix app. Felix signs it; no owner signature. Only the owner's own venue accounts and Trading wallet are paid, and open orders, positions and running agents keep their cash. Give exactly one of amount_usd or all_free_cash:true. Reuse the same idempotency_key to retry: it always returns the same transfer, never a second one. Most transfers finish in seconds to a few minutes (Lighter withdrawals can take longer). Set wait_seconds to wait for the result, or poll get_venue_transfer. Never start another transfer while one is sending or needs review.",
13638
+ inputSchema: schema({
13639
+ from_venue: stringProp("Venue the money leaves.", [...VENUE_TRANSFER_VENUE_INPUTS]),
13640
+ to_venue: stringProp("Venue the money arrives on.", [...VENUE_TRANSFER_VENUE_INPUTS]),
13641
+ amount_usd: numberProp("USDC amount, at most six decimal places. Omit only with all_free_cash:true.", 0.000001),
13642
+ all_free_cash: booleanProp("true moves all free cash on from_venue. Use instead of amount_usd."),
13643
+ idempotency_key: stringProp("Required, 8 to 128 printable characters. One key per transfer; reuse it after any timeout."),
13644
+ wait_seconds: integerProp("Optional: wait up to this many seconds (0 to 120) for a final state. Default 0.", 0, 120),
13645
+ account_id: stringProp("Optional owned child account UUID. Omit for the active account.", undefined, { pattern: UUID_RE.source }),
13646
+ }, ["from_venue", "to_venue", "idempotency_key"]),
13647
+ },
13648
+ {
13649
+ name: "get_venue_transfer",
13650
+ description: "Read one venue-to-venue transfer: state (sending, completed, partial, failed, needs_review), phase, the plain-language message, amounts credited and received. Read-only; never starts or retries a transfer.",
13651
+ inputSchema: schema({
13652
+ transfer_id: stringProp("transfer_id from transfer_between_venues.", undefined, { pattern: UUID_RE.source }),
13653
+ account_id: stringProp("Optional owned child account UUID. Omit for the active account.", undefined, { pattern: UUID_RE.source }),
13654
+ }, ["transfer_id"]),
13655
+ },
13656
+ {
13657
+ name: "list_venue_transfers",
13658
+ description: "The account's latest venue-to-venue transfers, newest first (for example one still sending after a restart). Read-only.",
13659
+ inputSchema: schema({
13660
+ open_only: booleanProp("true lists only transfers still sending."),
13661
+ limit: integerProp("How many to return, 1 to 20. Default 10.", 1, 20),
13662
+ account_id: stringProp("Optional owned child account UUID. Omit for the active account.", undefined, { pattern: UUID_RE.source }),
13663
+ }),
13664
+ },
12998
13665
  {
12999
13666
  name: "get_network_fee_status",
13000
13667
  description: "Inspect an interrupted funding network-fee workflow. New funding pays and confirms the fee before any venue transfer; this tool exists only to reconcile a legacy or interrupted obligation without paying twice.",
@@ -14083,6 +14750,34 @@ function liveMutationJournal() {
14083
14750
  : readMoneyWorkflowJournalAtPath(path, encryptionKey) || { version: 1, entries: {}, operations: {} },
14084
14751
  };
14085
14752
  }
14753
+ class LiveMutationKeyConflict extends Error {
14754
+ otherAccount;
14755
+ constructor(otherAccount) {
14756
+ super("live_mutation_key_conflict");
14757
+ this.otherAccount = otherAccount;
14758
+ }
14759
+ }
14760
+ // IDEMPOTENCY_UX_20261123: a request Felix refused outright (validation, 4xx before anything ran) must not
14761
+ // hold its key: the user fixes one argument and retries with the same key. Anything that may have run keeps it.
14762
+ function definiteNoEffectFailure(result) {
14763
+ // QA r17 F1: orders are never freed here (a retry's 4xx, or a prediction-market commit after the venue send,
14764
+ // can follow a real execution). Only deploy_agent, which moves no money, uses this, and only for an engine
14765
+ // validation refusal (400/422) that answered the first and only attempt.
14766
+ if (result.ok !== false || result.outcome_unknown === true || result.reconciliation_required === true)
14767
+ return false;
14768
+ for (const field of ["money_moved", "user_funds_moved", "order_sent", "operation_started"]) {
14769
+ if (result[field] === true || result[field] === "unknown")
14770
+ return false;
14771
+ }
14772
+ const error = isRecord(result.error) ? result.error : {};
14773
+ const code = nonEmptyString(error.code) || "";
14774
+ if (["idempotency_in_progress", "idempotency_send_unknown", "request_outcome_unknown", "request_deadline_exceeded",
14775
+ "mcp_internal_error", "timeout", "network_error", "invalid_server_response"].includes(code))
14776
+ return false;
14777
+ const meta = isRecord(result._meta) ? result._meta : {};
14778
+ const status = finiteNumber(meta.http_status);
14779
+ return (status === 400 || status === 422) && meta.transport_attempts === 1;
14780
+ }
14086
14781
  // Journal only the three live mutations whose retry keys may be generated here.
14087
14782
  // A new invocation always gets a new identity, even for identical arguments.
14088
14783
  function beginLiveMutation(operation, args) {
@@ -14093,16 +14788,18 @@ function beginLiveMutation(operation, args) {
14093
14788
  const requestPayload = { operation, arguments: { ...args, idempotency_key: key }, idempotency_key: key };
14094
14789
  const requestHash = createHash("sha256").update(JSON.stringify(requestPayload)).digest("hex");
14095
14790
  const storage = liveMutationJournal();
14791
+ let createdHere = false;
14096
14792
  const lock = acquireMoneyJournalMutationLock(storage.path);
14097
14793
  if (!lock)
14098
14794
  throw new Error("The live-operation journal is busy.");
14099
14795
  try {
14100
14796
  const journal = storage.read();
14101
14797
  const existing = journal.entries[entryKey];
14798
+ createdHere = existing === undefined;
14102
14799
  if (!generated && !existing)
14103
14800
  return undefined;
14104
14801
  if (existing && (!isDeepStrictEqual(existing.request_payload, requestPayload) || existing.account_id !== accountId)) {
14105
- throw new Error("The saved live-operation key belongs to a different request or account.");
14802
+ throw new LiveMutationKeyConflict(existing.account_id !== accountId);
14106
14803
  }
14107
14804
  journal.entries[entryKey] = {
14108
14805
  ...existing,
@@ -14126,6 +14823,11 @@ function beginLiveMutation(operation, args) {
14126
14823
  throw new Error("The live-operation journal is busy.");
14127
14824
  try {
14128
14825
  const journal = storage.read();
14826
+ if (operation === "deploy_agent" && createdHere && definiteNoEffectFailure(result)) {
14827
+ delete journal.entries[entryKey];
14828
+ writeMoneyWorkflowJournalRaw(journal, storage.encryptionKey, storage.path);
14829
+ return;
14830
+ }
14129
14831
  journal.entries[entryKey] = {
14130
14832
  ...journal.entries[entryKey],
14131
14833
  status: result.ok === true && result.outcome_unknown !== true
@@ -14142,16 +14844,29 @@ function beginLiveMutation(operation, args) {
14142
14844
  }
14143
14845
  // ONBOARD_CONSENT_20261117: shared by reload_launcher_key and onboard.
14144
14846
  async function reloadLauncherCredentials() {
14847
+ let storeError;
14848
+ const readStrict = (service) => {
14849
+ try {
14850
+ return readCredential(service) || "";
14851
+ }
14852
+ catch (error) {
14853
+ storeError = safeClientErrorMessage(error, "This computer's key storage could not be read.");
14854
+ return "";
14855
+ }
14856
+ };
14145
14857
  const candidateApiKey = KEYCHAIN_BACKED_CREDENTIALS
14146
- ? localKeychainCredential(KEYCHAIN_API_SERVICE)
14858
+ ? readStrict(KEYCHAIN_API_SERVICE)
14147
14859
  : START_KEY;
14148
14860
  const candidateOwnerKey = KEYCHAIN_BACKED_CREDENTIALS
14149
- ? localKeychainCredential(KEYCHAIN_OWNER_SERVICE)
14861
+ ? readStrict(KEYCHAIN_OWNER_SERVICE)
14150
14862
  : START_OWNER_KEY;
14863
+ if (storeError) {
14864
+ return clientError("credential_store_unreadable", storeError, "Unlock this computer's key storage and retry. No session credential was changed.");
14865
+ }
14151
14866
  if (!API_KEY_RE.test(candidateApiKey)
14152
14867
  || (KEYCHAIN_BACKED_CREDENTIALS && !EVM_PRIVATE_KEY_RE.test(candidateOwnerKey))) {
14153
14868
  return clientError("launcher_key_unavailable", KEYCHAIN_BACKED_CREDENTIALS
14154
- ? "macOS Keychain does not contain a complete valid Felix launcher identity."
14869
+ ? `${credentialStoreLabel()} does not contain a complete valid Felix launcher identity.`
14155
14870
  : "This MCP process was not launched with a complete valid Felix launcher identity.", "Run felix-keys status and restore the intended encrypted backup before retrying. No session credential was changed.");
14156
14871
  }
14157
14872
  try {
@@ -14336,13 +15051,16 @@ export function makeServer() {
14336
15051
  case "onboard": {
14337
15052
  // ONBOARD_CONSENT_20261117 (owner: "the ai should be able to accept these for the user ... do a question to
14338
15053
  // the user"): consent comes from the owner, through the client's own question when it has one, otherwise
14339
- // relayed by the agent and confirmed by one native macOS click before any key exists.
15054
+ // relayed by the agent and confirmed by one on-screen click (macOS, Windows, Linux desktop) before any key exists.
14340
15055
  if (isHostedTransport()) {
14341
- out = clientError("local_only", "onboard runs only in the local stdio MCP on the owner's Mac.", "Install felix-mcp locally and call onboard there.");
15056
+ out = clientError("local_only", "onboard runs only in the local stdio MCP on the owner's own computer.", "Install felix-mcp locally and call onboard there.");
14342
15057
  break;
14343
15058
  }
14344
- if (process.platform !== "darwin") {
14345
- out = clientError("macos_required", "Felix onboarding currently requires macOS Keychain.");
15059
+ try {
15060
+ credentialStoreKind();
15061
+ }
15062
+ catch (error) {
15063
+ out = clientError("credential_store_unavailable", safeClientErrorMessage(error, "Felix cannot store keys on this computer."), "Unset FELIX_CREDENTIAL_STORE or set it to a store this operating system supports, then call onboard again.");
14346
15064
  break;
14347
15065
  }
14348
15066
  if (API_KEY_RE.test(START_KEY) && EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)) {
@@ -14351,7 +15069,7 @@ export function makeServer() {
14351
15069
  break;
14352
15070
  }
14353
15071
  const termsUrl = "https://felix.trade/legal";
14354
- const question = `Do you accept the Felix Terms of Service, Privacy Policy and Risk Disclosure (${termsUrl}, version ${FELIX_LEGAL_BUNDLE_VERSION})? Felix will create your owner key in macOS Keychain. That key controls every dollar in your Felix accounts and never leaves this Mac.`;
15072
+ const question = `Do you accept the Felix Terms of Service, Privacy Policy and Risk Disclosure (${termsUrl}, version ${FELIX_LEGAL_BUNDLE_VERSION})? Felix will create your owner key in ${credentialStoreLabel()}. That key controls every dollar in your Felix accounts and never leaves this computer.`;
14355
15073
  let consent;
14356
15074
  const canAsk = Boolean(server.getClientCapabilities()?.elicitation);
14357
15075
  if (canAsk && a.owner_accepted_terms === undefined) {
@@ -14392,7 +15110,7 @@ export function makeServer() {
14392
15110
  question,
14393
15111
  terms_url: termsUrl,
14394
15112
  terms_version: FELIX_LEGAL_BUNDLE_VERSION,
14395
- instructions: "Ask the owner this exact question in chat. Only if they answer yes, call onboard again with owner_accepted_terms:true and this terms_version. macOS will then show one confirmation the owner must click. Never answer for the owner.",
15113
+ instructions: "Ask the owner this exact question in chat. Only if they answer yes, call onboard again with owner_accepted_terms:true and this terms_version. The computer will then show one confirmation the owner must click. Never answer for the owner.",
14396
15114
  };
14397
15115
  break;
14398
15116
  }
@@ -14402,15 +15120,23 @@ export function makeServer() {
14402
15120
  out = clientError("environment_credentials", "This MCP was launched with Felix credentials in its environment, so onboarding cannot run here. Nothing was created.", "Remove FELIX_API_KEY / FELIX_OWNER_PRIVATE_KEY from the MCP configuration (Felix reads Keychain by default), restart it, and call onboard again.");
14403
15121
  break;
14404
15122
  }
15123
+ if (consent === "relayed_with_mac_click" && !humanConfirmationAvailable(false)) {
15124
+ // CROSS_PLATFORM_KEYS_20261123: a headless Linux host cannot show the owner a confirmation, and an agent's
15125
+ // relayed "yes" alone never creates an owner key. The owner runs one command instead.
15126
+ out = clientError("owner_confirmation_unavailable", "This computer has no screen or terminal Felix can use to ask the owner directly, so nothing was created.", "The owner (not an agent) should run `felix-keys onboard --accept-terms --client none` themselves in a terminal on this computer after reading the terms, then call reload_launcher_key.", { money_moved: false });
15127
+ break;
15128
+ }
14405
15129
  const keyTool = fileURLToPath(new URL("./key-backup.js", import.meta.url));
14406
15130
  const cliArgs = [keyTool, "onboard", "--accept-terms", "--client", "none"];
14407
15131
  if (consent === "relayed_with_mac_click")
14408
15132
  cliArgs.push("--confirm-on-mac");
14409
15133
  reportProgress(1, 3, consent === "relayed_with_mac_click"
14410
- ? "Waiting for the owner to click Continue in the macOS confirmation."
15134
+ ? "Waiting for the owner to confirm on screen."
14411
15135
  : "Creating the owner key and registering the launcher.");
14412
15136
  const run = await new Promise((resolveRun) => {
14413
- const child = spawn(process.execPath, cliArgs, { stdio: ["ignore", "pipe", "pipe"], env: process.env });
15137
+ const child = spawn(process.execPath, cliArgs, {
15138
+ stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, FELIX_HUMAN_PROMPT_NO_TERMINAL: "1" }, windowsHide: false,
15139
+ });
14414
15140
  let stdout = "";
14415
15141
  child.stdout.on("data", (chunk) => { if (stdout.length < 256 * 1024)
14416
15142
  stdout += String(chunk); });
@@ -14431,7 +15157,7 @@ export function makeServer() {
14431
15157
  }
14432
15158
  if (!summary || summary.ok !== true) {
14433
15159
  out = clientError("onboarding_failed", consent === "relayed_with_mac_click" && run.code !== 0
14434
- ? "Onboarding stopped: the macOS confirmation was cancelled or setup failed. Nothing was replaced."
15160
+ ? "Onboarding stopped: the on-screen confirmation was cancelled or setup failed. Nothing was replaced."
14435
15161
  : "Felix onboarding did not complete. Nothing was replaced.", "Check felix-keys status in Terminal. Never create a second identity if one already exists.");
14436
15162
  break;
14437
15163
  }
@@ -14485,7 +15211,7 @@ export function makeServer() {
14485
15211
  call("GET", `/v1/mandates/current${qs({ account_id: accountId })}`, undefined, { authKey: cached, retryOnError: false, timeoutMs: 30_000 }),
14486
15212
  ]);
14487
15213
  if (custody.ok === false) {
14488
- out = custody;
15214
+ out = withLegacyAccountHint(custody, accountId);
14489
15215
  break;
14490
15216
  }
14491
15217
  if (custody.account_archived === true) {
@@ -14559,7 +15285,7 @@ export function makeServer() {
14559
15285
  keyInventoryPromise || Promise.resolve(undefined),
14560
15286
  ]);
14561
15287
  if (custody.ok === false) {
14562
- out = custody;
15288
+ out = withLegacyAccountHint(custody, accountId);
14563
15289
  break;
14564
15290
  }
14565
15291
  if (custody.account_archived === true) {
@@ -14735,12 +15461,12 @@ export function makeServer() {
14735
15461
  out = mandate;
14736
15462
  break;
14737
15463
  }
14738
- const selectionPersistenceSupported = process.platform === "darwin";
15464
+ const selectionPersistenceSupported = localCredentialStoreUsable() && !EPHEMERAL_SESSION;
14739
15465
  const selectionPersisted = selectionPersistenceSupported
14740
15466
  ? persistActiveChildAccount(accountId)
14741
15467
  : false;
14742
15468
  if (selectionPersistenceSupported && (!credentialCached || !selectionPersisted)) {
14743
- out = clientError("credential_persistence_failed", "The child credential or active-account binding could not be persisted securely.", "Fix macOS Keychain access, then retry use_child_account. The MCP session was not switched.", { account_id: accountId, credential_cached: credentialCached, selection_persisted: selectionPersisted });
15469
+ out = clientError("credential_persistence_failed", "The child credential or active-account binding could not be persisted securely.", "Fix access to this computer's key storage, then retry use_child_account. The MCP session was not switched.", { account_id: accountId, credential_cached: credentialCached, selection_persisted: selectionPersisted });
14744
15470
  break;
14745
15471
  }
14746
15472
  setKey(liveKey);
@@ -14809,8 +15535,8 @@ export function makeServer() {
14809
15535
  out = clientError("invalid_server_response", "Felix did not return a valid derived API key and account id.");
14810
15536
  }
14811
15537
  else {
14812
- if (process.platform === "darwin" && !persistActiveChildSession(accountId, derived)) {
14813
- out = clientError("credential_persistence_failed", "The derived account was created, but its credential binding could not be saved securely.", "Fix macOS Keychain access, then call use_child_account for this account.", { account_id: accountId });
15538
+ if (localCredentialStoreUsable() && !EPHEMERAL_SESSION && !persistActiveChildSession(accountId, derived)) {
15539
+ out = clientError("credential_persistence_failed", "The derived account was created, but its credential binding could not be saved securely.", "Fix access to this computer's key storage, then call use_child_account for this account.", { account_id: accountId });
14814
15540
  break;
14815
15541
  }
14816
15542
  runtimeManagedAccountId = accountId;
@@ -14850,11 +15576,20 @@ export function makeServer() {
14850
15576
  const subscriptionPromise = getKey()
14851
15577
  ? currentSubscriptionSnapshot()
14852
15578
  : undefined;
15579
+ const latestMcpPromise = isHostedTransport() ? Promise.resolve(undefined) : latestPublishedMcpVersion();
14853
15580
  const mcp = {
14854
15581
  version: MCP_VERSION,
14855
15582
  process_started_at: PROCESS_STARTED_AT,
14856
15583
  transport: isHostedTransport() ? "http" : "stdio",
14857
15584
  launcher_key_available: API_KEY_RE.test(START_KEY),
15585
+ credential_store: isHostedTransport() ? null : (() => {
15586
+ try {
15587
+ return credentialStoreDescription();
15588
+ }
15589
+ catch (error) {
15590
+ return { kind: null, error: safeClientErrorMessage(error, "No usable credential store.") };
15591
+ }
15592
+ })(),
14858
15593
  launcher_key_prefix: API_KEY_RE.test(START_KEY) ? START_KEY.slice(0, 12) : null,
14859
15594
  launcher_owner_address: EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)
14860
15595
  ? ownerAddressForPrivateKey(START_OWNER_KEY) : null,
@@ -14878,10 +15613,19 @@ export function makeServer() {
14878
15613
  binding_profile_id: KEYCHAIN_ACTIVE_ACCOUNT_SERVICE.slice(-24),
14879
15614
  legacy_global_binding_ignored: Boolean(!isHostedTransport() && localKeychainCredential(LEGACY_KEYCHAIN_ACTIVE_ACCOUNT_SERVICE)),
14880
15615
  };
14881
- const [platform, rawReadiness] = await Promise.all([
15616
+ const [platform, rawReadiness, latestMcp] = await Promise.all([
14882
15617
  platformPromise,
14883
15618
  readinessPromise,
15619
+ latestMcpPromise,
14884
15620
  ]);
15621
+ const update = mcpUpdateNotice(latestMcp) || {
15622
+ update_available: latestMcp ? false : null,
15623
+ current_version: MCP_VERSION,
15624
+ latest_version: latestMcp || null,
15625
+ ...(latestMcp ? {} : { note: isHostedTransport()
15626
+ ? "The hosted server is updated by Felix."
15627
+ : "The update check is off or the package registry was unreachable. Felix still refuses an outdated build before any money moves." }),
15628
+ };
14885
15629
  const readiness = normalizeReadinessStatus(rawReadiness);
14886
15630
  const minimumMcpVersion = nonEmptyString(platform.minimum_mcp_version);
14887
15631
  const compatible = minimumMcpVersion
@@ -14895,7 +15639,8 @@ export function makeServer() {
14895
15639
  ? "none"
14896
15640
  : compatible === false
14897
15641
  ? "Restart Felix with a current MCP build before any money mutation."
14898
- : "The API did not publish a compatibility floor; use read-only diagnostics until status is available.",
15642
+ : "Felix did not report its version floor just now. Every money request is still checked, and an outdated build is refused with client_upgrade_required before anything moves.",
15643
+ update,
14899
15644
  };
14900
15645
  const overallStatus = readiness.checked === false || readiness.ok === true
14901
15646
  ? platform.status
@@ -14908,13 +15653,12 @@ export function makeServer() {
14908
15653
  readiness,
14909
15654
  mcp: { ...mcp, compatibility },
14910
15655
  status_scope: "platform_and_venues",
14911
- current_key: subscription.key_access || {
14912
- can_place_live_orders: null,
14913
- blocking_reason: "key_capability_check_failed",
14914
- },
15656
+ current_key: subscription.key_access || keyCheckFailure(subscription),
14915
15657
  rate_limits: subscription.rate_limits || {
14916
15658
  available: false,
14917
- warning: "Rate-limit and quota status is temporarily unavailable.",
15659
+ warning: isRecord(subscription.error) && subscription.key_rejected === true
15660
+ ? "Rate limits are per key; this key is not accepted, so there is nothing to show."
15661
+ : "Rate-limit and quota status is temporarily unavailable.",
14918
15662
  },
14919
15663
  gas_sponsorship: subscription.gas_sponsorship || {
14920
15664
  model: "owner_gas_first",
@@ -14985,6 +15729,11 @@ export function makeServer() {
14985
15729
  : limit === undefined || !Number.isInteger(limit) || limit < 1 || limit > 200
14986
15730
  ? clientError("invalid_argument", "limit must be an integer between 1 and 200.")
14987
15731
  : await call("GET", `/v1/markets/catalog${qs({ venue, status, kind, q: query, cursor, limit })}`);
15732
+ // FUZZ_FIXES_20261123: a filtered provider page can come back empty while later pages have rows. Say so,
15733
+ // so an empty first page is never read as "no markets".
15734
+ if (out.ok !== false && Array.isArray(out.markets) && out.markets.length === 0 && nonEmptyString(out.next_cursor)) {
15735
+ out = { ...out, empty_page: true, hint: "This page had no matches after filtering, but more pages exist. Call list_markets again with next_cursor." };
15736
+ }
14988
15737
  break;
14989
15738
  }
14990
15739
  case "search_tokens": {
@@ -15053,7 +15802,7 @@ export function makeServer() {
15053
15802
  out = validateRequiredString(a, "instrument") || normalizeOrderbookPayload(await call("GET", `/v1/orderbook/${enc(nonEmptyString(a.instrument))}`));
15054
15803
  break;
15055
15804
  case "get_option_chain":
15056
- out = validateRequiredString(a, "underlying") || await call("GET", `/v1/options/${enc(nonEmptyString(a.underlying))}`);
15805
+ out = validateRequiredString(a, "underlying") || withOptionExpiryCounts(await call("GET", `/v1/options/${enc(nonEmptyString(a.underlying))}`));
15057
15806
  break;
15058
15807
  case "research_market": {
15059
15808
  const invalid = validateMarketSymbol(a)
@@ -15062,7 +15811,7 @@ export function makeServer() {
15062
15811
  : undefined)
15063
15812
  || (a.bars !== undefined ? parsePositiveInteger(a, "bars", 299, 5000) : undefined);
15064
15813
  const path = `/v1/research/${enc(nonEmptyString(a.symbol)?.toUpperCase())}${qs({ interval: a.interval, bars: a.bars, compact: true })}`;
15065
- out = invalid || await currentMarketDataSnapshot(path, () => call("GET", path));
15814
+ out = invalid || withServedResearchShape(await currentMarketDataSnapshot(path, () => call("GET", path)), a);
15066
15815
  break;
15067
15816
  }
15068
15817
  case "screen_markets": {
@@ -15826,10 +16575,10 @@ export function makeServer() {
15826
16575
  out = validateRequiredString(a, "instrument") || await call("GET", `/v1/manual/market?instrument=${enc(a.instrument)}`);
15827
16576
  break;
15828
16577
  case "get_available_to_trade":
15829
- out = validateRequiredString(a, "instrument") || await call("GET", `/v1/manual/balance?instrument=${enc(a.instrument)}`);
16578
+ out = validateRequiredString(a, "instrument") || withAvailableToTradeCompleteness(await call("GET", `/v1/manual/balance?instrument=${enc(a.instrument)}`));
15830
16579
  break;
15831
16580
  case "preview_manual_order":
15832
- out = await call("POST", "/v1/manual/preview", manualOrderBody(a));
16581
+ out = withManualTradingBlocker(await call("POST", "/v1/manual/preview", manualOrderBody(a)));
15833
16582
  break;
15834
16583
  case "place_manual_order": {
15835
16584
  // Same local pre-send checks as place_order: the operator's local cap on opening orders, an explicit
@@ -15871,7 +16620,7 @@ export function makeServer() {
15871
16620
  termsId: nonEmptyString(a.trading_policy_terms_id),
15872
16621
  });
15873
16622
  if (policy.ok === false && !manualTradingPolicyNotSupported(policy)) {
15874
- out = { ...policy, money_moved: false, order_sent: false };
16623
+ out = withManualTradingBlocker({ ...policy, money_moved: false, order_sent: false });
15875
16624
  break;
15876
16625
  }
15877
16626
  if (policy.ok !== false && isRecord(policy.policy))
@@ -15920,6 +16669,68 @@ export function makeServer() {
15920
16669
  case "list_open_orders":
15921
16670
  out = await call("GET", "/v1/manual/open-orders");
15922
16671
  break;
16672
+ case "start_twap": {
16673
+ const bad = validateTwapArgs(a);
16674
+ if (bad) {
16675
+ out = bad;
16676
+ break;
16677
+ }
16678
+ const body = {
16679
+ kind: "twap",
16680
+ instrument: String(a.instrument).trim(),
16681
+ side: String(a.side).toLowerCase(),
16682
+ size_usd: Number(a.size_usd),
16683
+ duration_minutes: Number(a.duration_minutes),
16684
+ ...(a.slices !== undefined ? { slices: Number(a.slices) } : {}),
16685
+ ...(a.leverage !== undefined ? { leverage: Number(a.leverage) } : {}),
16686
+ ...(a.reduce_only !== undefined ? { reduce_only: a.reduce_only === true } : {}),
16687
+ ...(a.price_limit !== undefined ? { price_limit: Number(a.price_limit) } : {}),
16688
+ };
16689
+ // Review r1: the slices are manual orders, so sign the account's trading policy first, like
16690
+ // place_manual_order. Otherwise the TWAP is accepted and then fails slice after slice.
16691
+ if (!isHostedTransport()) {
16692
+ const childId = activeChildAccountId();
16693
+ const ownerKey = await arcHomeOwnerKeyFor(childId);
16694
+ if (EVM_PRIVATE_KEY_RE.test(ownerKey)) {
16695
+ const policy = await ensureManualTradingPolicy(childId, ownerKey, childId ? START_KEY : undefined, {});
16696
+ if (policy.ok === false && !manualTradingPolicyNotSupported(policy)) {
16697
+ out = withManualTradingBlocker({ ...policy, money_moved: false, order_sent: false });
16698
+ break;
16699
+ }
16700
+ }
16701
+ }
16702
+ const started = await call("POST", "/v1/manual/algo-orders", body, {
16703
+ idempotent: true, idempotencyKey: String(a.idempotency_key), timeoutMs: 30_000,
16704
+ });
16705
+ out = describeTwapResponse(started, "start");
16706
+ break;
16707
+ }
16708
+ case "get_twap": {
16709
+ const limit = a.limit === undefined ? 20 : finiteNumber(a.limit);
16710
+ if (a.algo_id !== undefined) {
16711
+ out = validateUuid(a, "algo_id")
16712
+ || describeTwapResponse(await call("GET", `/v1/manual/algo-orders/${enc(a.algo_id)}`), "read");
16713
+ }
16714
+ else if (limit === undefined || !Number.isInteger(limit) || limit < 1 || limit > 100) {
16715
+ out = clientError("invalid_argument", "limit must be an integer between 1 and 100.");
16716
+ }
16717
+ else {
16718
+ const listed = await call("GET", `/v1/manual/algo-orders${qs({ limit })}`);
16719
+ if (listed.ok === false) {
16720
+ out = listed;
16721
+ break;
16722
+ }
16723
+ const rows = Array.isArray(listed.algo_orders) ? listed.algo_orders
16724
+ : Array.isArray(listed.items) ? listed.items : Array.isArray(listed.orders) ? listed.orders : [];
16725
+ const twaps = rows.filter(isRecord).map((row) => describeTwap(row));
16726
+ out = { ok: true, twaps, count: twaps.length, running: twaps.filter((row) => row.status === "running").length };
16727
+ }
16728
+ break;
16729
+ }
16730
+ case "cancel_twap":
16731
+ out = validateUuid(a, "algo_id")
16732
+ || describeTwapResponse(await call("POST", `/v1/manual/algo-orders/${enc(a.algo_id)}/cancel`, {}), "cancel");
16733
+ break;
15923
16734
  case "cancel_open_order":
15924
16735
  out = validateUuid(a, "order_id") || await call("POST", `/v1/manual/open-orders/${enc(a.order_id)}/cancel`, {}, { retryOnError: false });
15925
16736
  break;
@@ -16212,6 +17023,7 @@ export function makeServer() {
16212
17023
  out = guardAccountStatementResponse(await call("GET", `/v1/account/statement${qs({
16213
17024
  limit: a.limit,
16214
17025
  cursor: a.cursor,
17026
+ include_paper: a.include_simulation === false ? undefined : true,
16215
17027
  })}`), a.limit);
16216
17028
  break;
16217
17029
  case "get_pnl":
@@ -16500,6 +17312,126 @@ export function makeServer() {
16500
17312
  || await call("GET", `/v1/agent-capital/moves/${encodeURIComponent(String(a.move_id))}${qs({ account_id: a.account_id })}`);
16501
17313
  break;
16502
17314
  }
17315
+ case "preview_venue_transfer": {
17316
+ const parsed = venueTransferArgs(a);
17317
+ if (!("requestBody" in parsed)) {
17318
+ out = parsed.bad;
17319
+ break;
17320
+ }
17321
+ const { from, to, hasAmount, requestBody } = parsed;
17322
+ const preview = await call("POST", "/v1/agent-capital/transfers/preview", requestBody, { retryOnError: false });
17323
+ if (preview.ok === false) {
17324
+ out = withVenueTransferRefusalHint(preview);
17325
+ break;
17326
+ }
17327
+ if (preview.from_venue !== from || preview.to_venue !== to) {
17328
+ out = clientError("transfer_preview_unreadable", "Felix returned a preview for different venues. Nothing moved.", "Retry preview_venue_transfer.", { money_moved: false });
17329
+ break;
17330
+ }
17331
+ out = { ...preview, money_moved: false, signed: false, operation_created: false,
17332
+ next_action: "To move it, call transfer_between_venues with the same venues and "
17333
+ + (hasAmount ? "amount_usd" : "all_free_cash:true") + " and a new idempotency_key." };
17334
+ break;
17335
+ }
17336
+ case "transfer_between_venues": {
17337
+ const parsed = venueTransferArgs(a);
17338
+ if (!("requestBody" in parsed)) {
17339
+ out = parsed.bad;
17340
+ break;
17341
+ }
17342
+ const { from, to, hasAmount, requestBody } = parsed;
17343
+ // An omitted amount moves ALL free cash on the engine; that must be an explicit choice here.
17344
+ if (!hasAmount && a.all_free_cash !== true) {
17345
+ out = clientError("missing_argument", "Give amount_usd, or all_free_cash:true to move all free cash.", "preview_venue_transfer shows how much is free. Nothing moved.", { money_moved: false });
17346
+ break;
17347
+ }
17348
+ const key = requiredWorkflowKey(a);
17349
+ if (!key || key.length < 8) {
17350
+ out = clientError("missing_argument", "idempotency_key is required (8 to 128 printable characters).", "Use one new key per transfer and reuse it after any timeout. Nothing moved.", { money_moved: false });
17351
+ break;
17352
+ }
17353
+ const waitMs = Math.min(120, Math.max(0, Math.floor(Number(a.wait_seconds) || 0))) * 1_000;
17354
+ const deadline = Date.now() + waitMs;
17355
+ const start = () => call("POST", "/v1/agent-capital/transfers", requestBody, { idempotent: true, idempotencyKey: key, timeoutMs: 60_000 });
17356
+ let started = await start();
17357
+ // Arc admission frozen (engine release): the request is queued with nothing moved; the same key replays it.
17358
+ while (started.ok !== false && started.queued === true && Date.now() + VENUE_TRANSFER_POLL_MS < deadline) {
17359
+ await sleep(VENUE_TRANSFER_POLL_MS);
17360
+ started = await start();
17361
+ }
17362
+ if (started.ok === false) {
17363
+ const refused = withVenueTransferRefusalHint(started);
17364
+ out = refused !== started ? refused : withVenueTransferFailureOutcome(started);
17365
+ break;
17366
+ }
17367
+ if (started.queued === true) {
17368
+ const executing = started.status === "executing";
17369
+ out = { ...started, money_moved: executing ? "unknown" : false, state: executing ? "executing" : "queued",
17370
+ next_action: "Felix accepted the transfer and starts it in a moment. Call transfer_between_venues again "
17371
+ + "with the same arguments and idempotency_key to get the transfer." };
17372
+ break;
17373
+ }
17374
+ let transfer = parseVenueTransferRecord(started.transfer);
17375
+ const receiptAmount = transfer ? finiteNumber(transfer.amount_usd) : undefined;
17376
+ const amountMismatch = hasAmount && receiptAmount !== undefined
17377
+ && Math.abs(receiptAmount - Number(a.amount_usd)) > 0.0000005;
17378
+ if (!transfer || transfer.from_venue !== from || transfer.to_venue !== to || amountMismatch) {
17379
+ out = clientError("transfer_receipt_mismatch", "The transfer receipt did not match this request, so its outcome is not confirmed.", "Do not use a new idempotency_key. Check list_venue_transfers, or retry with the same key.", { money_moved: "unknown", outcome_unknown: true });
17380
+ break;
17381
+ }
17382
+ while (!VENUE_TRANSFER_FINAL.has(String(transfer.state)) && Date.now() + VENUE_TRANSFER_POLL_MS < deadline) {
17383
+ await sleep(VENUE_TRANSFER_POLL_MS);
17384
+ const read = await call("GET", `/v1/agent-capital/transfers/${encodeURIComponent(String(transfer.transfer_id))}`
17385
+ + qs({ account_id: a.account_id }));
17386
+ const latest = read.ok === false ? undefined : parseVenueTransferRecord(read.transfer);
17387
+ if (latest && latest.transfer_id === transfer.transfer_id)
17388
+ transfer = latest;
17389
+ }
17390
+ out = { ok: true, ...describeVenueTransfer(transfer), idempotency_key: key,
17391
+ ...(waitMs > 0 ? { wait_completed: VENUE_TRANSFER_FINAL.has(String(transfer.state)) } : {}) };
17392
+ break;
17393
+ }
17394
+ case "get_venue_transfer": {
17395
+ const bad = validateOptionalAccountId(a) || validateUuid(a, "transfer_id");
17396
+ if (bad) {
17397
+ out = bad;
17398
+ break;
17399
+ }
17400
+ const read = await call("GET", `/v1/agent-capital/transfers/${encodeURIComponent(String(a.transfer_id))}`
17401
+ + qs({ account_id: a.account_id }));
17402
+ if (read.ok === false) {
17403
+ out = read;
17404
+ break;
17405
+ }
17406
+ const transfer = parseVenueTransferRecord(read.transfer);
17407
+ out = transfer && String(transfer.transfer_id).toLowerCase() === String(a.transfer_id).toLowerCase()
17408
+ ? { ok: true, ...describeVenueTransfer(transfer) }
17409
+ : clientError("transfer_unreadable", "Felix returned an unreadable transfer.", "Retry shortly.");
17410
+ break;
17411
+ }
17412
+ case "list_venue_transfers": {
17413
+ const bad = validateOptionalAccountId(a)
17414
+ || (a.open_only !== undefined && typeof a.open_only !== "boolean"
17415
+ ? clientError("invalid_argument", "open_only must be true or false.") : undefined)
17416
+ || (a.limit !== undefined && (!Number.isInteger(a.limit) || Number(a.limit) < 1 || Number(a.limit) > 20)
17417
+ ? clientError("invalid_argument", "limit must be a whole number from 1 to 20.") : undefined);
17418
+ if (bad) {
17419
+ out = bad;
17420
+ break;
17421
+ }
17422
+ const read = await call("GET", `/v1/agent-capital/transfers${qs({ account_id: a.account_id,
17423
+ open_only: a.open_only === true ? "true" : undefined, limit: a.limit })}`);
17424
+ if (read.ok === false) {
17425
+ out = read;
17426
+ break;
17427
+ }
17428
+ const rows = Array.isArray(read.transfers) ? read.transfers : [];
17429
+ const transfers = rows.map(parseVenueTransferRecord).filter((row) => row !== undefined)
17430
+ .map(describeVenueTransfer);
17431
+ out = { ok: true, transfers, count: transfers.length,
17432
+ any_sending: transfers.some((row) => row.state === "sending") };
17433
+ break;
17434
+ }
16503
17435
  case "get_network_fee_status":
16504
17436
  if (a.account_id !== undefined && validateUuid(a, "account_id")) {
16505
17437
  out = validateUuid(a, "account_id");
@@ -16702,10 +17634,19 @@ export function makeServer() {
16702
17634
  out = clientError("invalid_argument", "reconcile must be a boolean when provided.");
16703
17635
  break;
16704
17636
  }
16705
- const plainRead = a.reconcile === false;
16706
- const result = plainRead
17637
+ let plainRead = a.reconcile === false;
17638
+ let reconcileSkipped = false;
17639
+ let result = plainRead
16707
17640
  ? await call("GET", `/v1/settlement/operations/${enc(operationId)}`)
16708
17641
  : await call("POST", `/v1/settlement/transfers/${enc(operationId)}/reconcile`, undefined, { retryOnError: false, timeoutMs: 30_000 });
17642
+ // Opus QA r15: the reconcile step needs manage+transfer (engine routes_settlement.py reconcile_transfer) and
17643
+ // only advances the caller's own journey; an account's read/trade key gets 403. Fall back to the read-scope view.
17644
+ if (!plainRead && result.ok === false && isRecord(result.error)
17645
+ && /lacks the '(?:manage|transfer)' scope/.test(String(result.error.message ?? ""))) {
17646
+ plainRead = true;
17647
+ reconcileSkipped = true;
17648
+ result = await call("GET", `/v1/settlement/operations/${enc(operationId)}`);
17649
+ }
16709
17650
  if (result.ok === false) {
16710
17651
  out = result;
16711
17652
  break;
@@ -16723,6 +17664,8 @@ export function makeServer() {
16723
17664
  source_transaction_hash: operation.source_transaction_hash ?? null,
16724
17665
  destination_transaction_hash: operation.destination_transaction_hash ?? null,
16725
17666
  operation,
17667
+ ...(reconcileSkipped ? { reconciled: false,
17668
+ note: "This key cannot run the reconcile step, so this is the plain read. Felix advances the journey on its own." } : {}),
16726
17669
  };
16727
17670
  break;
16728
17671
  }
@@ -17233,7 +18176,9 @@ export function makeServer() {
17233
18176
  updated_at: entry.updated_at,
17234
18177
  recovery_tool: entry.request_payload.operation,
17235
18178
  }));
17236
- const operations = [...liveOperations, ...(storage.ownerJournal ? listAsyncMoneyOperations(limit) : [])]
18179
+ const workflowOperations = storage.ownerJournal
18180
+ ? listMoneyWorkflowOperations(storage.read(), runtimeManagedAccountId || "launcher") : [];
18181
+ const operations = [...liveOperations, ...workflowOperations, ...(storage.ownerJournal ? listAsyncMoneyOperations(limit) : [])]
17237
18182
  .sort((left, right) => Date.parse(String(right.updated_at)) - Date.parse(String(left.updated_at)))
17238
18183
  .slice(0, limit);
17239
18184
  out = {
@@ -18721,6 +19666,10 @@ export function makeServer() {
18721
19666
  idempotent: true,
18722
19667
  idempotencyKey: nonEmptyString(a.idempotency_key),
18723
19668
  });
19669
+ if (out.ok !== false && nonEmptyString(a.mode)?.toLowerCase() === "paper") {
19670
+ // SIM_HONESTY_20261123: say plainly what paper results leave out, so they are not read as a live preview.
19671
+ out = { ...out, simulation_note: "Simulation fills do not model queue position or market impact, so simulation results usually look better than live ones. Size live budgets from walk_forward_backtest, not from simulation P&L." };
19672
+ }
18724
19673
  break;
18725
19674
  }
18726
19675
  case "list_agents": {
@@ -19425,8 +20374,8 @@ export function makeServer() {
19425
20374
  bootstrapRevocation = { ok: true, key_id: bootstrapKeyId };
19426
20375
  context.saveCheckpoint("account:bootstrap_revoked", bootstrapRevocation);
19427
20376
  }
19428
- if (process.platform === "darwin" && !persistActiveChildSession(accountId, apiKey)) {
19429
- return clientError("credential_persistence_failed", "The account is ready, but its live credential binding could not be saved securely.", "Fix macOS Keychain access, then resume create_account with the same idempotency_key.", { account_id: accountId });
20377
+ if (localCredentialStoreUsable() && !EPHEMERAL_SESSION && !persistActiveChildSession(accountId, apiKey)) {
20378
+ return clientError("credential_persistence_failed", "The account is ready, but its live credential binding could not be saved securely.", "Fix access to this computer's key storage, then resume create_account with the same idempotency_key.", { account_id: accountId });
19430
20379
  }
19431
20380
  setKey(apiKey);
19432
20381
  runtimeManagedAccountId = accountId;
@@ -19599,7 +20548,7 @@ export function makeServer() {
19599
20548
  };
19600
20549
  entry.updated_at = new Date().toISOString();
19601
20550
  }
19602
- if (process.platform === "darwin"
20551
+ if (localCredentialStoreUsable() && !EPHEMERAL_SESSION
19603
20552
  && !persistActiveChildSession(accountId, savedKey)) {
19604
20553
  throw new Error("The recovered child credential binding could not be persisted securely.");
19605
20554
  }
@@ -19945,6 +20894,13 @@ export function makeServer() {
19945
20894
  }
19946
20895
  }
19947
20896
  catch (error) {
20897
+ if (error instanceof LiveMutationKeyConflict) {
20898
+ out = clientError("idempotency_conflict", error.otherAccount
20899
+ ? "This idempotency_key was already used on a different account. Nothing was sent."
20900
+ : "This idempotency_key was already used for a different request (other arguments). Nothing was sent.", "Use a new idempotency_key for this request. To finish the earlier one, repeat it with its original arguments; list_recent_operations shows it.", { money_moved: false, order_sent: false, operation_started: false });
20901
+ out = withNewAccountNextStep(name, out, a);
20902
+ return toolOutput(out);
20903
+ }
19948
20904
  const moneyOutcomeUnknown = LIVE_MONEY_TOOLS.has(name);
19949
20905
  out = clientError("mcp_internal_error", safeClientErrorMessage(error, "Felix MCP encountered an unexpected local error."), moneyOutcomeUnknown
19950
20906
  ? "Do not retry with a new idempotency key. Inspect get_money_map and get_network_fee_status, then retry only the exact original key after reconciliation."
@@ -19991,4 +20947,9 @@ if (process.env.FELIX_MCP_TRANSPORT !== "http" && process.env.FELIX_MCP_LIBRARY_
19991
20947
  const transport = new StdioServerTransport();
19992
20948
  await server.connect(transport);
19993
20949
  console.error(redactOutput(`Felix MCP (stdio) against ${API} (${START_KEY ? "key loaded" : "no key"}).`));
20950
+ void latestPublishedMcpVersion().then((latest) => {
20951
+ const notice = mcpUpdateNotice(latest);
20952
+ if (notice)
20953
+ console.error(`Felix MCP ${MCP_VERSION} is out of date (latest ${String(notice.latest_version)}). Run: ${MCP_UPDATE_COMMAND}`);
20954
+ });
19994
20955
  }