felix-mcp 2.0.134 → 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.134";
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();
@@ -3691,6 +3816,11 @@ async function withWorkflowBinding(name, args, action) {
3691
3816
  }
3692
3817
  }
3693
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
+ }
3694
3824
  return {
3695
3825
  isError: out.ok === false,
3696
3826
  content: [
@@ -4422,6 +4552,12 @@ async function fundMarketPrecheck(venue, amountUsd, resuming, autoSwapNativeUsdc
4422
4552
  const error = isRecord(balances.error) ? balances.error : {};
4423
4553
  const status = finiteNumber(isRecord(balances._meta) ? balances._meta.http_status : undefined);
4424
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
+ }
4425
4561
  // ARC_TRADE_KEY_FUNDING_20261117: an Arc-home account has no Polygon owner wallet to fund from. Its money
4426
4562
  // is in the Arc home, and the app funds a venue from there as part of the order.
4427
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 }));
@@ -4576,9 +4712,36 @@ function accountStatementNullableNonnegative(value) {
4576
4712
  function accountStatementCloseEnough(actual, expected) {
4577
4713
  return Math.abs(actual - expected) <= Math.max(1e-8, Math.abs(expected) * 1e-9);
4578
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
+ }
4579
4738
  function validAccountStatementTrade(value) {
4580
4739
  if (!isRecord(value))
4581
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);
4582
4745
  const closed = value.status === "closed";
4583
4746
  if (!boundedStatementText(value.trade_id, 64) || !UUID_RE.test(value.trade_id)
4584
4747
  || !(value.agent_id === null
@@ -4694,9 +4857,14 @@ function guardAccountStatementResponse(out, requestedLimit) {
4694
4857
  // server's own derivation rather than against an assumption that nothing
4695
4858
  // was ever excluded.
4696
4859
  && out.page_complete === (excludedCount === 0)
4697
- && 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)
4698
4864
  && excludedCount === 0
4699
4865
  && unpageableCount === 0)
4866
+ || (out.records_complete === false
4867
+ && trades.some((trade) => trade.mode === "paper")))
4700
4868
  && out.has_more === (out.next_cursor !== null);
4701
4869
  for (let index = 1; internallyConsistent && index < trades.length; index += 1) {
4702
4870
  const previous = trades[index - 1];
@@ -6413,7 +6581,14 @@ export function normalizeMarketSearchPayload(out) {
6413
6581
  return item;
6414
6582
  }
6415
6583
  });
6416
- 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
+ };
6417
6592
  }
6418
6593
  function canonicalTokenAddress(chain, value) {
6419
6594
  const address = nonEmptyString(value);
@@ -7467,6 +7642,274 @@ function closeAmountError(a) {
7467
7642
  }
7468
7643
  return undefined;
7469
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
+ }
7470
7913
  async function call(method, path, body, opts = {}) {
7471
7914
  const binding = workflowBinding.getStore();
7472
7915
  if (binding && (binding.accountId !== runtimeManagedAccountId
@@ -7621,16 +8064,19 @@ async function call(method, path, body, opts = {}) {
7621
8064
  }
7622
8065
  const meta = {
7623
8066
  http_status: res.status,
8067
+ transport_attempts: attempt,
7624
8068
  ...(requestId ? { request_id: requestId } : {}),
7625
8069
  ...(retryAfter ? { retry_after: retryAfter } : {}),
7626
8070
  ...(serverLatencyMs !== undefined ? { server_latency_ms: serverLatencyMs } : {}),
7627
8071
  ...(Object.keys(rateLimit).length ? { rate_limit: rateLimit } : {}),
7628
8072
  ...(minimumMcpVersion ? { minimum_mcp_version: minimumMcpVersion } : {}),
7629
- ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
8073
+ ...(idempotencyKey ? (isInternalStageKey(idempotencyKey)
8074
+ ? { internal_step_key: idempotencyKey }
8075
+ : { idempotency_key: idempotencyKey }) : {}),
7630
8076
  };
7631
8077
  return res.ok
7632
8078
  ? { ...payload, _meta: meta }
7633
- : { ...payload, ok: false, _meta: meta };
8079
+ : annotateHttpFailure(res.status, { ...payload, ok: false, _meta: meta }, key, opts.public === true);
7634
8080
  }
7635
8081
  catch (error) {
7636
8082
  clearTimeout(timer);
@@ -7651,19 +8097,24 @@ async function call(method, path, body, opts = {}) {
7651
8097
  break;
7652
8098
  }
7653
8099
  }
8100
+ const internalStep = idempotencyKey !== undefined && isInternalStageKey(idempotencyKey);
7654
8101
  if (deadlineExceeded) {
7655
- return clientError("request_deadline_exceeded", `Felix stopped waiting after ${Math.round(overallTimeoutMs / 1000)} seconds.`, idempotencyKey
7656
- ? "The operation may still be reconciling. Retry the exact request with the same idempotency_key; never generate a new key for this operation."
7657
- : "Check get_status, then retry when the API is healthy.", {
7658
- ...(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 }) : {}),
7659
8108
  retryable: true,
7660
8109
  outcome_unknown: Boolean(idempotencyKey),
7661
8110
  });
7662
8111
  }
7663
8112
  const message = lastError instanceof Error ? lastError.message : String(lastError);
7664
8113
  if (idempotencyKey && method !== "GET") {
7665
- 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.", {
7666
- 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 }),
7667
8118
  retryable: true,
7668
8119
  outcome_unknown: true,
7669
8120
  recovery_tool: "get_status",
@@ -9565,9 +10016,9 @@ async function executeFundMarketTool(a) {
9565
10016
  }
9566
10017
  setKey(cachedChildKey);
9567
10018
  }
9568
- if (process.platform === "darwin"
10019
+ if (localCredentialStoreUsable() && !EPHEMERAL_SESSION
9569
10020
  && !persistActiveChildSession(a.account_id, getKey())) {
9570
- 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 }));
9571
10022
  }
9572
10023
  setRuntimeOwnerPrivateKey(childOwnerKey);
9573
10024
  runtimeManagedAccountId = a.account_id;
@@ -11905,7 +12356,7 @@ const TOOL_RISK_GROUPS = {
11905
12356
  "preview_fleet_capacity", "preview_fleet_reallocation",
11906
12357
  "get_execution_quality", "get_exit_plan", "list_exit_plans",
11907
12358
  "get_trading_capabilities", "get_trading_details", "get_available_to_trade", "preview_manual_order",
11908
- "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",
11909
12360
  "get_positions", "get_fills", "get_account_statement", "get_pnl", "get_portfolio", "get_balances",
11910
12361
  "get_money_map", "get_network_fee_status", "get_deposit_address",
11911
12362
  "verify_custody", "get_derive_onboarding", "get_money_operation",
@@ -11929,6 +12380,7 @@ const TOOL_RISK_GROUPS = {
11929
12380
  trading: [
11930
12381
  "place_order", "place_batch_orders", "cancel_order", "close_position",
11931
12382
  "place_manual_order", "cancel_open_order", "modify_order_price", "close_manual_position",
12383
+ "start_twap", "cancel_twap",
11932
12384
  "set_position_protection", "cancel_position_protection",
11933
12385
  "set_exit_plan", "cancel_exit_plan", "make_market",
11934
12386
  "get_polymarket_order_status", "get_order_status", "reconcile_polymarket_order",
@@ -12211,7 +12663,7 @@ const LIVE_MONEY_TOOLS = new Set([
12211
12663
  "submit_capital_allocation", "submit_venue_bootstrap",
12212
12664
  "start_capital_move", "transfer_between_venues",
12213
12665
  "place_order", "place_batch_orders", "close_position", "make_market",
12214
- "place_manual_order", "close_manual_position", "modify_order_price",
12666
+ "place_manual_order", "close_manual_position", "modify_order_price", "start_twap",
12215
12667
  "swap_native_usdc", "fund_market", "start_fund_market",
12216
12668
  "bring_home", "start_bring_home", "resume_money_operation", "resolve_network_fee",
12217
12669
  "start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return", "fund_polymarket_from_arc",
@@ -12491,7 +12943,7 @@ const TOOLS = [
12491
12943
  },
12492
12944
  {
12493
12945
  name: "onboard",
12494
- 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.",
12495
12947
  inputSchema: schema({
12496
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."),
12497
12949
  terms_version: stringProp("The terms version the owner accepted, exactly as returned by the first call."),
@@ -12499,7 +12951,7 @@ const TOOLS = [
12499
12951
  },
12500
12952
  {
12501
12953
  name: "reload_launcher_key",
12502
- 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.",
12503
12955
  inputSchema: schema({}),
12504
12956
  },
12505
12957
  {
@@ -12882,6 +13334,36 @@ const TOOLS = [
12882
13334
  description: "Live resting orders on Hyperliquid, Lighter and Polymarket (placed from the app or the API), with price, size, filled amount and status.",
12883
13335
  inputSchema: schema({}),
12884
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
+ },
12885
13367
  {
12886
13368
  name: "cancel_open_order",
12887
13369
  description: "Cancel one live resting order by its id from list_open_orders. Reduces risk; never opens anything.",
@@ -13018,10 +13500,11 @@ const TOOLS = [
13018
13500
  },
13019
13501
  {
13020
13502
  name: "get_account_statement",
13021
- 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.",
13022
13504
  inputSchema: schema({
13023
13505
  limit: integerProp("Maximum trade rows in this page. Defaults to 100.", 1, 500),
13024
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."),
13025
13508
  }),
13026
13509
  },
13027
13510
  {
@@ -14267,6 +14750,34 @@ function liveMutationJournal() {
14267
14750
  : readMoneyWorkflowJournalAtPath(path, encryptionKey) || { version: 1, entries: {}, operations: {} },
14268
14751
  };
14269
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
+ }
14270
14781
  // Journal only the three live mutations whose retry keys may be generated here.
14271
14782
  // A new invocation always gets a new identity, even for identical arguments.
14272
14783
  function beginLiveMutation(operation, args) {
@@ -14277,16 +14788,18 @@ function beginLiveMutation(operation, args) {
14277
14788
  const requestPayload = { operation, arguments: { ...args, idempotency_key: key }, idempotency_key: key };
14278
14789
  const requestHash = createHash("sha256").update(JSON.stringify(requestPayload)).digest("hex");
14279
14790
  const storage = liveMutationJournal();
14791
+ let createdHere = false;
14280
14792
  const lock = acquireMoneyJournalMutationLock(storage.path);
14281
14793
  if (!lock)
14282
14794
  throw new Error("The live-operation journal is busy.");
14283
14795
  try {
14284
14796
  const journal = storage.read();
14285
14797
  const existing = journal.entries[entryKey];
14798
+ createdHere = existing === undefined;
14286
14799
  if (!generated && !existing)
14287
14800
  return undefined;
14288
14801
  if (existing && (!isDeepStrictEqual(existing.request_payload, requestPayload) || existing.account_id !== accountId)) {
14289
- throw new Error("The saved live-operation key belongs to a different request or account.");
14802
+ throw new LiveMutationKeyConflict(existing.account_id !== accountId);
14290
14803
  }
14291
14804
  journal.entries[entryKey] = {
14292
14805
  ...existing,
@@ -14310,6 +14823,11 @@ function beginLiveMutation(operation, args) {
14310
14823
  throw new Error("The live-operation journal is busy.");
14311
14824
  try {
14312
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
+ }
14313
14831
  journal.entries[entryKey] = {
14314
14832
  ...journal.entries[entryKey],
14315
14833
  status: result.ok === true && result.outcome_unknown !== true
@@ -14326,16 +14844,29 @@ function beginLiveMutation(operation, args) {
14326
14844
  }
14327
14845
  // ONBOARD_CONSENT_20261117: shared by reload_launcher_key and onboard.
14328
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
+ };
14329
14857
  const candidateApiKey = KEYCHAIN_BACKED_CREDENTIALS
14330
- ? localKeychainCredential(KEYCHAIN_API_SERVICE)
14858
+ ? readStrict(KEYCHAIN_API_SERVICE)
14331
14859
  : START_KEY;
14332
14860
  const candidateOwnerKey = KEYCHAIN_BACKED_CREDENTIALS
14333
- ? localKeychainCredential(KEYCHAIN_OWNER_SERVICE)
14861
+ ? readStrict(KEYCHAIN_OWNER_SERVICE)
14334
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
+ }
14335
14866
  if (!API_KEY_RE.test(candidateApiKey)
14336
14867
  || (KEYCHAIN_BACKED_CREDENTIALS && !EVM_PRIVATE_KEY_RE.test(candidateOwnerKey))) {
14337
14868
  return clientError("launcher_key_unavailable", KEYCHAIN_BACKED_CREDENTIALS
14338
- ? "macOS Keychain does not contain a complete valid Felix launcher identity."
14869
+ ? `${credentialStoreLabel()} does not contain a complete valid Felix launcher identity.`
14339
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.");
14340
14871
  }
14341
14872
  try {
@@ -14520,13 +15051,16 @@ export function makeServer() {
14520
15051
  case "onboard": {
14521
15052
  // ONBOARD_CONSENT_20261117 (owner: "the ai should be able to accept these for the user ... do a question to
14522
15053
  // the user"): consent comes from the owner, through the client's own question when it has one, otherwise
14523
- // 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.
14524
15055
  if (isHostedTransport()) {
14525
- 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.");
14526
15057
  break;
14527
15058
  }
14528
- if (process.platform !== "darwin") {
14529
- 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.");
14530
15064
  break;
14531
15065
  }
14532
15066
  if (API_KEY_RE.test(START_KEY) && EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)) {
@@ -14535,7 +15069,7 @@ export function makeServer() {
14535
15069
  break;
14536
15070
  }
14537
15071
  const termsUrl = "https://felix.trade/legal";
14538
- 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.`;
14539
15073
  let consent;
14540
15074
  const canAsk = Boolean(server.getClientCapabilities()?.elicitation);
14541
15075
  if (canAsk && a.owner_accepted_terms === undefined) {
@@ -14576,7 +15110,7 @@ export function makeServer() {
14576
15110
  question,
14577
15111
  terms_url: termsUrl,
14578
15112
  terms_version: FELIX_LEGAL_BUNDLE_VERSION,
14579
- 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.",
14580
15114
  };
14581
15115
  break;
14582
15116
  }
@@ -14586,15 +15120,23 @@ export function makeServer() {
14586
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.");
14587
15121
  break;
14588
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
+ }
14589
15129
  const keyTool = fileURLToPath(new URL("./key-backup.js", import.meta.url));
14590
15130
  const cliArgs = [keyTool, "onboard", "--accept-terms", "--client", "none"];
14591
15131
  if (consent === "relayed_with_mac_click")
14592
15132
  cliArgs.push("--confirm-on-mac");
14593
15133
  reportProgress(1, 3, consent === "relayed_with_mac_click"
14594
- ? "Waiting for the owner to click Continue in the macOS confirmation."
15134
+ ? "Waiting for the owner to confirm on screen."
14595
15135
  : "Creating the owner key and registering the launcher.");
14596
15136
  const run = await new Promise((resolveRun) => {
14597
- 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
+ });
14598
15140
  let stdout = "";
14599
15141
  child.stdout.on("data", (chunk) => { if (stdout.length < 256 * 1024)
14600
15142
  stdout += String(chunk); });
@@ -14615,7 +15157,7 @@ export function makeServer() {
14615
15157
  }
14616
15158
  if (!summary || summary.ok !== true) {
14617
15159
  out = clientError("onboarding_failed", consent === "relayed_with_mac_click" && run.code !== 0
14618
- ? "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."
14619
15161
  : "Felix onboarding did not complete. Nothing was replaced.", "Check felix-keys status in Terminal. Never create a second identity if one already exists.");
14620
15162
  break;
14621
15163
  }
@@ -14669,7 +15211,7 @@ export function makeServer() {
14669
15211
  call("GET", `/v1/mandates/current${qs({ account_id: accountId })}`, undefined, { authKey: cached, retryOnError: false, timeoutMs: 30_000 }),
14670
15212
  ]);
14671
15213
  if (custody.ok === false) {
14672
- out = custody;
15214
+ out = withLegacyAccountHint(custody, accountId);
14673
15215
  break;
14674
15216
  }
14675
15217
  if (custody.account_archived === true) {
@@ -14743,7 +15285,7 @@ export function makeServer() {
14743
15285
  keyInventoryPromise || Promise.resolve(undefined),
14744
15286
  ]);
14745
15287
  if (custody.ok === false) {
14746
- out = custody;
15288
+ out = withLegacyAccountHint(custody, accountId);
14747
15289
  break;
14748
15290
  }
14749
15291
  if (custody.account_archived === true) {
@@ -14919,12 +15461,12 @@ export function makeServer() {
14919
15461
  out = mandate;
14920
15462
  break;
14921
15463
  }
14922
- const selectionPersistenceSupported = process.platform === "darwin";
15464
+ const selectionPersistenceSupported = localCredentialStoreUsable() && !EPHEMERAL_SESSION;
14923
15465
  const selectionPersisted = selectionPersistenceSupported
14924
15466
  ? persistActiveChildAccount(accountId)
14925
15467
  : false;
14926
15468
  if (selectionPersistenceSupported && (!credentialCached || !selectionPersisted)) {
14927
- 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 });
14928
15470
  break;
14929
15471
  }
14930
15472
  setKey(liveKey);
@@ -14993,8 +15535,8 @@ export function makeServer() {
14993
15535
  out = clientError("invalid_server_response", "Felix did not return a valid derived API key and account id.");
14994
15536
  }
14995
15537
  else {
14996
- if (process.platform === "darwin" && !persistActiveChildSession(accountId, derived)) {
14997
- 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 });
14998
15540
  break;
14999
15541
  }
15000
15542
  runtimeManagedAccountId = accountId;
@@ -15034,11 +15576,20 @@ export function makeServer() {
15034
15576
  const subscriptionPromise = getKey()
15035
15577
  ? currentSubscriptionSnapshot()
15036
15578
  : undefined;
15579
+ const latestMcpPromise = isHostedTransport() ? Promise.resolve(undefined) : latestPublishedMcpVersion();
15037
15580
  const mcp = {
15038
15581
  version: MCP_VERSION,
15039
15582
  process_started_at: PROCESS_STARTED_AT,
15040
15583
  transport: isHostedTransport() ? "http" : "stdio",
15041
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
+ })(),
15042
15593
  launcher_key_prefix: API_KEY_RE.test(START_KEY) ? START_KEY.slice(0, 12) : null,
15043
15594
  launcher_owner_address: EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)
15044
15595
  ? ownerAddressForPrivateKey(START_OWNER_KEY) : null,
@@ -15062,10 +15613,19 @@ export function makeServer() {
15062
15613
  binding_profile_id: KEYCHAIN_ACTIVE_ACCOUNT_SERVICE.slice(-24),
15063
15614
  legacy_global_binding_ignored: Boolean(!isHostedTransport() && localKeychainCredential(LEGACY_KEYCHAIN_ACTIVE_ACCOUNT_SERVICE)),
15064
15615
  };
15065
- const [platform, rawReadiness] = await Promise.all([
15616
+ const [platform, rawReadiness, latestMcp] = await Promise.all([
15066
15617
  platformPromise,
15067
15618
  readinessPromise,
15619
+ latestMcpPromise,
15068
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
+ };
15069
15629
  const readiness = normalizeReadinessStatus(rawReadiness);
15070
15630
  const minimumMcpVersion = nonEmptyString(platform.minimum_mcp_version);
15071
15631
  const compatible = minimumMcpVersion
@@ -15079,7 +15639,8 @@ export function makeServer() {
15079
15639
  ? "none"
15080
15640
  : compatible === false
15081
15641
  ? "Restart Felix with a current MCP build before any money mutation."
15082
- : "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,
15083
15644
  };
15084
15645
  const overallStatus = readiness.checked === false || readiness.ok === true
15085
15646
  ? platform.status
@@ -15092,13 +15653,12 @@ export function makeServer() {
15092
15653
  readiness,
15093
15654
  mcp: { ...mcp, compatibility },
15094
15655
  status_scope: "platform_and_venues",
15095
- current_key: subscription.key_access || {
15096
- can_place_live_orders: null,
15097
- blocking_reason: "key_capability_check_failed",
15098
- },
15656
+ current_key: subscription.key_access || keyCheckFailure(subscription),
15099
15657
  rate_limits: subscription.rate_limits || {
15100
15658
  available: false,
15101
- 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.",
15102
15662
  },
15103
15663
  gas_sponsorship: subscription.gas_sponsorship || {
15104
15664
  model: "owner_gas_first",
@@ -15169,6 +15729,11 @@ export function makeServer() {
15169
15729
  : limit === undefined || !Number.isInteger(limit) || limit < 1 || limit > 200
15170
15730
  ? clientError("invalid_argument", "limit must be an integer between 1 and 200.")
15171
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
+ }
15172
15737
  break;
15173
15738
  }
15174
15739
  case "search_tokens": {
@@ -15237,7 +15802,7 @@ export function makeServer() {
15237
15802
  out = validateRequiredString(a, "instrument") || normalizeOrderbookPayload(await call("GET", `/v1/orderbook/${enc(nonEmptyString(a.instrument))}`));
15238
15803
  break;
15239
15804
  case "get_option_chain":
15240
- 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))}`));
15241
15806
  break;
15242
15807
  case "research_market": {
15243
15808
  const invalid = validateMarketSymbol(a)
@@ -15246,7 +15811,7 @@ export function makeServer() {
15246
15811
  : undefined)
15247
15812
  || (a.bars !== undefined ? parsePositiveInteger(a, "bars", 299, 5000) : undefined);
15248
15813
  const path = `/v1/research/${enc(nonEmptyString(a.symbol)?.toUpperCase())}${qs({ interval: a.interval, bars: a.bars, compact: true })}`;
15249
- out = invalid || await currentMarketDataSnapshot(path, () => call("GET", path));
15814
+ out = invalid || withServedResearchShape(await currentMarketDataSnapshot(path, () => call("GET", path)), a);
15250
15815
  break;
15251
15816
  }
15252
15817
  case "screen_markets": {
@@ -16010,10 +16575,10 @@ export function makeServer() {
16010
16575
  out = validateRequiredString(a, "instrument") || await call("GET", `/v1/manual/market?instrument=${enc(a.instrument)}`);
16011
16576
  break;
16012
16577
  case "get_available_to_trade":
16013
- 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)}`));
16014
16579
  break;
16015
16580
  case "preview_manual_order":
16016
- out = await call("POST", "/v1/manual/preview", manualOrderBody(a));
16581
+ out = withManualTradingBlocker(await call("POST", "/v1/manual/preview", manualOrderBody(a)));
16017
16582
  break;
16018
16583
  case "place_manual_order": {
16019
16584
  // Same local pre-send checks as place_order: the operator's local cap on opening orders, an explicit
@@ -16055,7 +16620,7 @@ export function makeServer() {
16055
16620
  termsId: nonEmptyString(a.trading_policy_terms_id),
16056
16621
  });
16057
16622
  if (policy.ok === false && !manualTradingPolicyNotSupported(policy)) {
16058
- out = { ...policy, money_moved: false, order_sent: false };
16623
+ out = withManualTradingBlocker({ ...policy, money_moved: false, order_sent: false });
16059
16624
  break;
16060
16625
  }
16061
16626
  if (policy.ok !== false && isRecord(policy.policy))
@@ -16104,6 +16669,68 @@ export function makeServer() {
16104
16669
  case "list_open_orders":
16105
16670
  out = await call("GET", "/v1/manual/open-orders");
16106
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;
16107
16734
  case "cancel_open_order":
16108
16735
  out = validateUuid(a, "order_id") || await call("POST", `/v1/manual/open-orders/${enc(a.order_id)}/cancel`, {}, { retryOnError: false });
16109
16736
  break;
@@ -16396,6 +17023,7 @@ export function makeServer() {
16396
17023
  out = guardAccountStatementResponse(await call("GET", `/v1/account/statement${qs({
16397
17024
  limit: a.limit,
16398
17025
  cursor: a.cursor,
17026
+ include_paper: a.include_simulation === false ? undefined : true,
16399
17027
  })}`), a.limit);
16400
17028
  break;
16401
17029
  case "get_pnl":
@@ -17548,7 +18176,9 @@ export function makeServer() {
17548
18176
  updated_at: entry.updated_at,
17549
18177
  recovery_tool: entry.request_payload.operation,
17550
18178
  }));
17551
- 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) : [])]
17552
18182
  .sort((left, right) => Date.parse(String(right.updated_at)) - Date.parse(String(left.updated_at)))
17553
18183
  .slice(0, limit);
17554
18184
  out = {
@@ -19036,6 +19666,10 @@ export function makeServer() {
19036
19666
  idempotent: true,
19037
19667
  idempotencyKey: nonEmptyString(a.idempotency_key),
19038
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
+ }
19039
19673
  break;
19040
19674
  }
19041
19675
  case "list_agents": {
@@ -19740,8 +20374,8 @@ export function makeServer() {
19740
20374
  bootstrapRevocation = { ok: true, key_id: bootstrapKeyId };
19741
20375
  context.saveCheckpoint("account:bootstrap_revoked", bootstrapRevocation);
19742
20376
  }
19743
- if (process.platform === "darwin" && !persistActiveChildSession(accountId, apiKey)) {
19744
- 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 });
19745
20379
  }
19746
20380
  setKey(apiKey);
19747
20381
  runtimeManagedAccountId = accountId;
@@ -19914,7 +20548,7 @@ export function makeServer() {
19914
20548
  };
19915
20549
  entry.updated_at = new Date().toISOString();
19916
20550
  }
19917
- if (process.platform === "darwin"
20551
+ if (localCredentialStoreUsable() && !EPHEMERAL_SESSION
19918
20552
  && !persistActiveChildSession(accountId, savedKey)) {
19919
20553
  throw new Error("The recovered child credential binding could not be persisted securely.");
19920
20554
  }
@@ -20260,6 +20894,13 @@ export function makeServer() {
20260
20894
  }
20261
20895
  }
20262
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
+ }
20263
20904
  const moneyOutcomeUnknown = LIVE_MONEY_TOOLS.has(name);
20264
20905
  out = clientError("mcp_internal_error", safeClientErrorMessage(error, "Felix MCP encountered an unexpected local error."), moneyOutcomeUnknown
20265
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."
@@ -20306,4 +20947,9 @@ if (process.env.FELIX_MCP_TRANSPORT !== "http" && process.env.FELIX_MCP_LIBRARY_
20306
20947
  const transport = new StdioServerTransport();
20307
20948
  await server.connect(transport);
20308
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
+ });
20309
20955
  }