felix-mcp 2.0.123 → 2.0.129

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
@@ -18,7 +18,7 @@ import * as nodeNet from "node:net";
18
18
  import { homedir, userInfo } from "node:os";
19
19
  import { dirname, join, resolve } from "node:path";
20
20
  import { setTimeout as sleep } from "node:timers/promises";
21
- import { spawnSync } from "node:child_process";
21
+ import { spawn, spawnSync } from "node:child_process";
22
22
  import { fileURLToPath } from "node:url";
23
23
  import { isDeepStrictEqual } from "node:util";
24
24
  import { privateKeyToAccount } from "viem/accounts";
@@ -39,14 +39,18 @@ import { hasFreshWorkflowIdentityMarker, legacyWorkflowJournalPath, scopedWorkfl
39
39
  import { isClientSignatureRequired, polymarketIntentReplay, } from "./polymarket-replay.js";
40
40
  import { discloseFundingOwnerDebit } from "./funding-accounting.js";
41
41
  import { driveHlArcReturn } from "./arc-hl-return.js";
42
- import { productionHlArcPorts } from "./arc-hl-return-ports.js";
42
+ import { hyperliquidPort, productionHlArcPorts, resolveHyperliquidEndpoint } from "./arc-hl-return-ports.js";
43
+ import { HYPERCORE_ACTIVATION_NEXT_ACTION, HYPERCORE_DIRECT_CLIENT_ENABLED, driveHypercoreFunding, readCappedText, } from "./arc-hypercore-funding.js";
44
+ import { HYPERCORE_RETURN_CLIENT_ENABLED, driveHypercoreReturn, } from "./arc-hypercore-return.js";
45
+ import { hypercoreAppPolicy, hypercoreReturnAppPolicy } from "./arc-venue-app-policy.js";
46
+ import { INVALIDATION_WRITERS, SHIPPED_INVALIDATION_POLICY, driveSafeInvalidation, isInvalidationWriter, } from "./arc-safe-invalidation.js";
43
47
  import { ARC_GATEWAY_DOMAIN, ARC_GATEWAY_MINTER, ARC_GATEWAY_WALLET, ARC_HOME_CHAIN, ARC_HOME_DEPOSIT_CHAINS, ARC_HOME_EXTERNAL_CHAINS, ARC_HOME_WITHDRAWAL_CHAINS, ARC_MAINNET_CHAIN_ID, ARC_USDC, ArcHomeError, arcHomeChainRpcUrl, arcHomeSafeFromDepositResponse, arcUsdToUnits, assertArcHomeBurnIntent, assertArcHomeSafeTx, assertArcHomeWithdrawalSafeTransactions, assertArcHomeSourceCalls, assertArcHubActivation, assertArcHubChallenge, broadcastOwnerCall, parseArcHomeAccount, parseArcHomeRecord, publicArcHomeRecord, signArcHomeBurnIntent, signArcHomeOwnerProof, signArcHomeSafeTx, unitsToAmountString, waitForOwnerReceipt, } from "./arc-home.js";
44
48
  import { PM_ARC_RETURN_CLIENT_ENABLED, drivePmArcReturn, } from "./arc-pm-return.js";
45
49
  import { signHyperliquidAgentApproval } from "./hyperliquid-onboarding.js";
46
50
  import { signPreparedSafePolicy, signPreparedWithdrawal } from "./safe-policy.js";
47
51
  import { policySubmitAmbiguity, policySubmitPending } from "./policy-workflow.js";
48
52
  import { executeSafeV3Migration, signSafeMigrationProof } from "./safe-migration.js";
49
- import { deriveAccountOwnerPrivateKey, ownerAddressForPrivateKey, ownerPrivateKeyForAccountIdentity, signLiveKeyGrant, signRiskMandate, signSafeOnboardingProof, signSafeOnboardingTransactions, } from "./safe-onboarding.js";
53
+ import { deriveAccountOwnerPrivateKey, ownerAddressForPrivateKey, ownerPrivateKeyForAccountIdentity, signLiveKeyGrant, signRiskMandate, RISK_MANDATE_VENUE_LIST, } from "./safe-onboarding.js";
50
54
  import { signDeriveOnboardingTransactions } from "./derive-onboarding.js";
51
55
  import { getCustodyRecoveryStatus } from "./key-backup.js";
52
56
  import { clearRuntimeOwnerPrivateKey, getRuntimeOwnerPrivateKey, setRuntimeOwnerPrivateKey, } from "./secret-state.js";
@@ -119,7 +123,7 @@ export function validatedApiBase(raw = process.env.FELIX_API_URL || `https://${O
119
123
  return parsed.origin;
120
124
  }
121
125
  const API = validatedApiBase();
122
- const MCP_VERSION = "2.0.123";
126
+ const MCP_VERSION = "2.0.129";
123
127
  const AES_GCM_IV_BYTES = 12;
124
128
  const AES_GCM_TAG_BYTES = 16;
125
129
  const MAX_MONEY_JOURNAL_BYTES = 16 * 1024 * 1024;
@@ -348,6 +352,25 @@ function persistActiveChildSession(accountId, apiKey) {
348
352
  return keyPersisted && persistActiveChildAccount(accountId);
349
353
  }
350
354
  const HOSTED_TRANSPORT = process.env.FELIX_MCP_TRANSPORT === "http";
355
+ // HOSTED_CLIENT_IP_FORWARD_20261115: on the hosted transport, forward the
356
+ // proxy-attributed caller address to the engine so its per-IP limits and
357
+ // auth-failure suspensions apply per caller instead of to this host. Only a
358
+ // loopback engine hop may receive it (the host's own nginx sets the engine's
359
+ // trusted header from it); a public API URL never does.
360
+ export function hostedClientIpHeader(apiBase = API, raw = process.env.FELIX_MCP_FORWARD_CLIENT_IP_HEADER) {
361
+ if (!HOSTED_TRANSPORT || !raw)
362
+ return "";
363
+ const name = raw.trim().toLowerCase();
364
+ if (!/^x-[a-z0-9-]{1,60}$/.test(name)) {
365
+ throw new Error("FELIX_MCP_FORWARD_CLIENT_IP_HEADER must be an x- header name.");
366
+ }
367
+ const host = new URL(apiBase).hostname.toLowerCase().replace(/^\[|\]$/g, "");
368
+ if (!LOOPBACK_API_HOSTS.has(host)) {
369
+ throw new Error("FELIX_MCP_FORWARD_CLIENT_IP_HEADER requires a loopback FELIX_API_URL.");
370
+ }
371
+ return name;
372
+ }
373
+ export const HOSTED_CLIENT_IP_HEADER = hostedClientIpHeader();
351
374
  // Hosted MCP requests authenticate independently through AsyncLocalStorage and
352
375
  // never need a process-wide launcher or signer credential.
353
376
  const API_CREDENTIAL_FROM_ENV = Object.prototype.hasOwnProperty.call(process.env, "FELIX_API_KEY");
@@ -427,7 +450,7 @@ const EVM_PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;
427
450
  if (EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)) {
428
451
  setRuntimeOwnerPrivateKey(START_OWNER_KEY);
429
452
  }
430
- const WEBHOOK_EVENTS = ["order.filled", "position.opened", "position.closed", "agent.decision", "agent.error"];
453
+ const WEBHOOK_EVENTS = ["order.filled", "position.opened", "position.closed", "position.liquidated", "agent.decision", "agent.error"];
431
454
  function maxLocalLiveOrderUsd() {
432
455
  const configured = Number(process.env.FELIX_MAX_LIVE_ORDER_USD || PRACTICAL_NO_CAP_USD);
433
456
  return Number.isFinite(configured)
@@ -902,7 +925,13 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
902
925
  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 });
903
926
  }
904
927
  existing.account_id = workflowAccountId;
905
- if (existing.status === "completed" && isRecord(existing.response)) {
928
+ // ARC_OWNER_BIND_MCP_20261117: a create_account that stopped on the retired Polygon Safe hub (410) moved no
929
+ // money and is resumed from its checkpoints (the reserved account is reused) instead of replaying the 410.
930
+ const retiredHubStop = operation === "create_live_account" && existing.status === "completed"
931
+ && isRecord(existing.response) && existing.response.ok === false
932
+ && isRecord(existing.response.error) && existing.response.error.code === "polygon_safe_hub_retired"
933
+ && existing.response.money_moved !== true && existing.response.user_funds_moved !== true;
934
+ if (existing.status === "completed" && isRecord(existing.response) && !retiredHubStop) {
906
935
  const replayOverride = await options.onCompletedReplay?.(existing);
907
936
  if (isRecord(replayOverride))
908
937
  return replayOverride;
@@ -917,8 +946,8 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
917
946
  const ownerSetupCanResume = ["create_live_account", "repair_derive_session", "archive_account"].includes(operation)
918
947
  && existing.status === "reconciliation_required"
919
948
  && progress.money_moved === false;
920
- if (!(options.resumeReconciliation || ownerSetupCanResume)
921
- || (existing.status !== "reconciliation_required" && !staleInProgress)) {
949
+ if (!retiredHubStop && (!(options.resumeReconciliation || options.resumable || ownerSetupCanResume)
950
+ || (existing.status !== "reconciliation_required" && !staleInProgress))) {
922
951
  return clientError("workflow_reconciliation_required", "This money workflow may have started but did not reach a saved terminal result.", progress.money_moved
923
952
  ? "Do not use a new key. Reconcile venue and wallet balances before resuming."
924
953
  : "Retry the same request key; Felix can resume because no user money moved.", { reconciliation_required: true, workflow: progress });
@@ -1016,8 +1045,15 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
1016
1045
  writeMoneyWorkflowJournal(journal, journalEncryptionKey);
1017
1046
  throw error;
1018
1047
  }
1019
- if (result.ok === false) {
1020
- if (result[MONEY_SIDE_EFFECT_NOT_STARTED] === true) {
1048
+ // A resumable driver's ok:true result that is not "completed" (in_progress:
1049
+ // a bridge or deposit still settling) is NOT terminal; it stays resumable.
1050
+ const resumableOpen = options.resumable === true && result.ok !== false && result.status !== "completed";
1051
+ if (result.ok === false || resumableOpen) {
1052
+ // A resumable run's "not started" answer on RESUME must never erase movement
1053
+ // evidence an earlier run journaled; only an entry with no checkpoints may go.
1054
+ const keepsEvidence = options.resumable === true && context.hasCheckpoints();
1055
+ if (result.ok === false && !keepsEvidence
1056
+ && result[MONEY_SIDE_EFFECT_NOT_STARTED] === true) {
1021
1057
  delete journal.entries[entryKey];
1022
1058
  writeMoneyWorkflowJournal(journal, journalEncryptionKey);
1023
1059
  return result;
@@ -1890,6 +1926,65 @@ function createAccountFundingGate(response, accountId, ownerAddress) {
1890
1926
  function createAccountArcError(error) {
1891
1927
  return clientError(error instanceof ArcHomeError ? error.code : "arc_home_verification_failed", safeClientErrorMessage(error, "Arc home onboarding could not be verified."), "Retry create_account with the same idempotency_key; do not start another account.", { money_moved: false });
1892
1928
  }
1929
+ // ARC_OWNER_BIND_MCP_20261117: bind a brand-new account's derived owner to its Arc home (owner-signed challenge).
1930
+ const ARC_OWNER_BIND_PURPOSE = "felix-arc-home-owner-bind:v1";
1931
+ async function bindArcHomeOwner(workflowKey, accountId, ownerKey) {
1932
+ const owner = ownerAddressForPrivateKey(ownerKey);
1933
+ const sameAddress = (value) => typeof value === "string" && EVM_ADDRESS_RE.test(value)
1934
+ && value.toLowerCase() === owner.toLowerCase();
1935
+ const challenge = await call("POST", "/v1/arc-home/owner/challenge", { account_id: accountId, owner_address: owner }, {
1936
+ authKey: START_KEY, retryOnError: false, timeoutMs: 60_000,
1937
+ idempotencyKey: workflowStageKey(workflowKey, "owner:challenge"),
1938
+ });
1939
+ if (challenge.ok === false)
1940
+ return challenge;
1941
+ const message = typeof challenge.message === "string" ? challenge.message : "";
1942
+ const token = nonEmptyString(challenge.challenge_token);
1943
+ const lines = message.split("\n");
1944
+ const value = (index, name) => (lines[index]?.startsWith(`${name}:`)
1945
+ ? lines[index].slice(name.length + 1) : undefined);
1946
+ const nonce = value(6, "nonce") || "";
1947
+ const issuedText = value(7, "issued_at") || "";
1948
+ const expiresText = value(8, "expires_at") || "";
1949
+ const issuedAt = /^[1-9][0-9]{0,11}$/.test(issuedText) ? Number(issuedText) : NaN;
1950
+ const expiresAt = /^[1-9][0-9]{0,11}$/.test(expiresText) ? Number(expiresText) : NaN;
1951
+ // Sign only Felix's exact owner-binding text for THIS account, owner and chain, rebuilt here byte for byte from
1952
+ // services/arc_owner_bind.challenge_message (never a hash, a transaction or any extra text).
1953
+ const canonical = Number.isSafeInteger(issuedAt) && Number.isSafeInteger(expiresAt) ? [
1954
+ "Felix Arc home owner binding",
1955
+ "domain:api.felix.trade",
1956
+ `purpose:${ARC_OWNER_BIND_PURPOSE}`,
1957
+ `account_id:${accountId}`,
1958
+ `chain_id:${ARC_MAINNET_CHAIN_ID}`,
1959
+ `owner:${owner}`,
1960
+ `nonce:${nonce}`,
1961
+ `issued_at:${issuedAt}`,
1962
+ `expires_at:${expiresAt}`,
1963
+ "Signing names this device wallet as the owner of your Felix Arc home. "
1964
+ + "It moves no money and authorizes no transaction.",
1965
+ ].join("\n") : undefined;
1966
+ const nowSeconds = Date.now() / 1_000;
1967
+ if (!token || canonical === undefined || message !== canonical || lines.length !== 10
1968
+ || !/^[0-9a-f]{32}$/.test(nonce)
1969
+ || expiresAt <= nowSeconds || expiresAt - issuedAt <= 0 || expiresAt - issuedAt > 600
1970
+ || issuedAt > nowSeconds + 120
1971
+ || challenge.account_id !== accountId || !sameAddress(challenge.owner_address)
1972
+ || Number(challenge.chain_id) !== ARC_MAINNET_CHAIN_ID || challenge.purpose !== ARC_OWNER_BIND_PURPOSE
1973
+ || challenge.sign_with !== "personal_sign") {
1974
+ return clientError("arc_owner_challenge_invalid", "Felix returned an owner-binding challenge that does not match this account and owner. Nothing was signed.", "Retry create_account with the same idempotency_key; do not create another account.", { money_moved: false });
1975
+ }
1976
+ const signature = await privateKeyToAccount(ownerKey).signMessage({ message });
1977
+ const bound = await call("POST", "/v1/arc-home/owner", { account_id: accountId, owner_address: owner, challenge_token: token, signature }, {
1978
+ authKey: START_KEY, retryOnError: false, timeoutMs: 60_000,
1979
+ idempotencyKey: workflowStageKey(workflowKey, `owner:bind:${nonce}`),
1980
+ });
1981
+ if (bound.ok === false)
1982
+ return bound;
1983
+ if (bound.status !== "arc_owner_bound" || bound.account_id !== accountId || !sameAddress(bound.owner_address)) {
1984
+ return clientError("arc_owner_bind_unconfirmed", "Felix did not confirm the Arc home owner binding for this account.", "Retry create_account with the same idempotency_key; do not create another account.", { money_moved: false });
1985
+ }
1986
+ return { ok: true, status: "arc_owner_bound", owner_address: owner, money_moved: false };
1987
+ }
1893
1988
  async function createAccountArcHome(workflowKey, context, accountId, ownerKey, limits) {
1894
1989
  const owner = ownerAddressForPrivateKey(ownerKey);
1895
1990
  const accountPath = `/v1/arc-home/account${qs({ account_id: accountId })}`;
@@ -2935,7 +3030,7 @@ let activeToolWorkflows = 0;
2935
3030
  let changingWorkflowIdentity = false;
2936
3031
  const IDENTITY_CHANGING_TOOLS = new Set([
2937
3032
  "use_child_account", "reload_launcher_key", "set_api_key", "derive_api_key",
2938
- "create_account", "archive_account",
3033
+ "create_account", "archive_account", "onboard",
2939
3034
  ]);
2940
3035
  async function withWorkflowBinding(name, args, action) {
2941
3036
  if (isHostedTransport()) {
@@ -2943,7 +3038,7 @@ async function withWorkflowBinding(name, args, action) {
2943
3038
  return session ? keyStore.run({ ...session }, action) : action();
2944
3039
  }
2945
3040
  const changesIdentity = IDENTITY_CHANGING_TOOLS.has(name)
2946
- || (["fund_market", "route_funds"].includes(name) && args.account_id !== undefined);
3041
+ || (name === "fund_market" && args.account_id !== undefined);
2947
3042
  if (changingWorkflowIdentity
2948
3043
  || (changesIdentity && (activeToolWorkflows > 0 || backgroundMoneyOperations.size > 0))) {
2949
3044
  return toolOutput(clientError("session_binding_busy", "An account workflow is still running. Retry after it completes."));
@@ -2990,7 +3085,11 @@ function isChildManagementRequest(method, path) {
2990
3085
  if (method === "GET" || method === "DELETE") {
2991
3086
  return pathname === "/v1/webhooks"
2992
3087
  || pathname.startsWith("/v1/webhooks/")
2993
- || pathname === "/v1/withdrawal-addresses";
3088
+ || pathname === "/v1/withdrawal-addresses"
3089
+ // A manage-scope Arc-home journey reads (status, readiness) on the SAME
3090
+ // credential that prepared it (engine binds some journeys to the preparing
3091
+ // key); the child is named by account_id (engine _target_context).
3092
+ || (method === "GET" && isArcHomeManageRoute(pathname));
2994
3093
  }
2995
3094
  if (method !== "POST")
2996
3095
  return false;
@@ -3013,7 +3112,33 @@ function isChildManagementRequest(method, path) {
3013
3112
  || pathname.startsWith("/v1/wallet/polymarket/approvals/")
3014
3113
  || pathname.startsWith("/v1/wallet/polymarket/agent/")
3015
3114
  || pathname.startsWith("/v1/wallet/funding/")
3016
- || pathname.startsWith("/v1/me/subscription/");
3115
+ || pathname.startsWith("/v1/me/subscription/")
3116
+ || isArcHomeManageRoute(pathname);
3117
+ }
3118
+ // Arc-home journeys whose engine routes require the "manage" scope. A child's
3119
+ // least-privilege read/trade key cannot call them, so they go out on the
3120
+ // launcher credential with the selected account_id, like every other
3121
+ // privileged child workflow above. Found by the 2.0.221 A7 production canary
3122
+ // ("This key lacks the 'manage' scope"). transfer-scope Arc routes
3123
+ // (withdrawals, deposits, operations reconcile/mint) are deliberately absent.
3124
+ const ARC_HOME_MANAGE_PREFIXES = [
3125
+ "/v1/arc-home/onboarding/",
3126
+ "/v1/arc-home/returns/",
3127
+ "/v1/arc-home/relay-returns/",
3128
+ "/v1/arc-home/pm-returns/",
3129
+ "/v1/arc-home/hl-relay-returns/",
3130
+ "/v1/arc-home/hypercore-returns/",
3131
+ "/v1/arc-home/hypercore-fundings/",
3132
+ "/v1/arc-home/polygon-fundings/",
3133
+ "/v1/arc-home/safe-invalidations/",
3134
+ "/v1/arc-home/derive-returns/",
3135
+ ];
3136
+ const ARC_HOME_MANAGE_CONTINUATION_RE = /^\/v1\/arc-home\/operations\/[^/]+\/(?:polymarket|hyperliquid|derive)-continuation\/[a-z-]+$/;
3137
+ export function isArcHomeManageRoute(pathname) {
3138
+ if (ARC_HOME_MANAGE_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {
3139
+ return !pathname.endsWith("/verify");
3140
+ }
3141
+ return ARC_HOME_MANAGE_CONTINUATION_RE.test(pathname);
3017
3142
  }
3018
3143
  function withTargetAccountQuery(path, accountId) {
3019
3144
  const parsed = new URL(path, "https://felix.invalid");
@@ -6559,6 +6684,9 @@ async function call(method, path, body, opts = {}) {
6559
6684
  headers["Idempotency-Key"] = idempotencyKey;
6560
6685
  if (opts.preferRespondAsync)
6561
6686
  headers.Prefer = "respond-async";
6687
+ const hostedClientIp = HOSTED_CLIENT_IP_HEADER ? keyStore.getStore()?.clientIp : undefined;
6688
+ if (hostedClientIp && nodeNet.isIP(hostedClientIp))
6689
+ headers[HOSTED_CLIENT_IP_HEADER] = hostedClientIp;
6562
6690
  const res = await fetch(`${API}${requestPath}`, {
6563
6691
  method,
6564
6692
  headers,
@@ -6855,6 +6983,18 @@ async function authorizeWithdrawalAddress(address, chain, requestedAccountId, ex
6855
6983
  owner_signature: signature,
6856
6984
  }, { idempotent: true, retryOnError: false, timeoutMs: TIMEOUT_MS });
6857
6985
  }
6986
+ // The public API scrubs venue names: a mandate's "venues" arrives as "accounts" with
6987
+ // asset-class aliases (engine services/public_api/app.py _scrub_venue). Map them back to
6988
+ // engine names in order; anything unexpected yields a non-matching value (re-sign).
6989
+ const MANDATE_ALIAS_TO_VENUE = {
6990
+ crypto: "hyperliquid", spot: "hyperliquid_spot", prediction_market: "polymarket", options: "derive",
6991
+ };
6992
+ export function currentMandateVenues(current) {
6993
+ const raw = Array.isArray(current.venues) ? current.venues : Array.isArray(current.accounts) ? current.accounts : null;
6994
+ if (!raw || !raw.every((v) => typeof v === "string"))
6995
+ return "";
6996
+ return raw.map((v) => MANDATE_ALIAS_TO_VENUE[v] ?? v).join(",");
6997
+ }
6858
6998
  function ownerRiskMandateMatches(current, options) {
6859
6999
  const expectedExpiryFloor = Math.floor(Date.now() / 1000) + 86_400;
6860
7000
  return current.ok !== false
@@ -6866,6 +7006,8 @@ function ownerRiskMandateMatches(current, options) {
6866
7006
  && finiteNumber(current.max_slippage_bps) === 200
6867
7007
  && finiteNumber(current.max_leverage) === 20
6868
7008
  && current.allow_reduce_only_after_expiry === true
7009
+ // A mandate signed before a venue was added (e.g. Lighter) is re-signed.
7010
+ && currentMandateVenues(current) === RISK_MANDATE_VENUE_LIST.join(",")
6869
7011
  && finiteNumber(current.mandate_expires_at) > expectedExpiryFloor;
6870
7012
  }
6871
7013
  async function ensureOwnerRiskMandate(options) {
@@ -6880,7 +7022,7 @@ async function ensureOwnerRiskMandate(options) {
6880
7022
  const prepared = await call("POST", "/v1/mandates/prepare", {
6881
7023
  account_id: options.accountId,
6882
7024
  api_key_id: options.apiKeyId,
6883
- venues: ["derive", "hyperliquid", "hyperliquid_spot", "polymarket"],
7025
+ venues: [...RISK_MANDATE_VENUE_LIST],
6884
7026
  instruments: ["*"],
6885
7027
  max_position_usd: options.maxDailyUsd,
6886
7028
  max_concentration_bps: 10_000,
@@ -10486,6 +10628,35 @@ async function ensureNativeUsdcFundingSource(venue, amountUsd, workflowKey, cont
10486
10628
  context.saveCheckpoint("native-usdc:auto-complete", output);
10487
10629
  return output;
10488
10630
  }
10631
+ /** Confirm a sent fee top-up and accept only Felix's exact credit for it (capital line F1). */
10632
+ async function confirmFeeCredit(prepared, hash, amountUsd, workflowKey) {
10633
+ const confirmFee = () => call("POST", "/v1/wallet/funding/fees/confirm", {
10634
+ intent_token: prepared.intent_token,
10635
+ transaction_hash: hash,
10636
+ }, { idempotencyKey: workflowStageKey(workflowKey, "confirm"), retryOnError: false });
10637
+ let confirmed = await confirmFee();
10638
+ // A retryable 503 (a provider head read behind its own finalized block) is a
10639
+ // transient proof read: the same intent and hash are re-confirmed a bounded
10640
+ // number of times, never re-paid.
10641
+ for (let attempt = 0; attempt < FEE_CONFIRM_TRANSIENT_RETRIES && feeConfirmTransient(confirmed); attempt++) {
10642
+ await sleep(FEE_CONFIRM_TRANSIENT_DELAY_MS);
10643
+ confirmed = await confirmFee();
10644
+ }
10645
+ if (confirmed.ok === false)
10646
+ return confirmed;
10647
+ if (confirmed.status === "pending") {
10648
+ return clientError("fee_credit_confirmation_pending", "The prepaid fee transfer is awaiting finalized receipt verification; no credit is confirmed yet.", "Retry top_up_fee_balance with the same amount and idempotency_key. Do not pay again.", { status: "pending", reconciliation_required: true, transaction_hash: hash });
10649
+ }
10650
+ if (confirmed.status !== "credited"
10651
+ || (prepared.settlement_home === "arc" && (confirmed.intent_id !== prepared.intent_id
10652
+ || nonEmptyString(confirmed.transaction_hash)?.toLowerCase() !== hash.toLowerCase()
10653
+ || confirmed.credited_usd !== amountUsd
10654
+ || confirmed.chain_id !== 5042 || confirmed.settlement_home !== "arc"
10655
+ || confirmed.collection_model !== "prepaid_before_live_execution"))) {
10656
+ return clientError("fee_credit_confirmation_invalid", "Felix did not confirm the exact prepaid fee transfer.", "Reconcile the saved transaction with the same idempotency_key; do not pay again.", { reconciliation_required: true, transaction_hash: hash });
10657
+ }
10658
+ return confirmed;
10659
+ }
10489
10660
  export async function topUpFeeBalance(workflowKey, context, amountUsd, allowLowOwnerBuffer = false) {
10490
10661
  let prepared = context.getCheckpoint("fee-credit:prepared");
10491
10662
  if (!isRecord(prepared)) {
@@ -10513,7 +10684,11 @@ export async function topUpFeeBalance(workflowKey, context, amountUsd, allowLowO
10513
10684
  });
10514
10685
  }
10515
10686
  try {
10516
- inspectFeeSettlementIntent(prepared, amountUsd);
10687
+ // A resumed intent may be past its signing TTL; executeFeeSettlement re-inspects it
10688
+ // fully before any NEW signature. Here only the requested amount must match.
10689
+ if (typeof prepared.amount_usd !== "number" || prepared.amount_usd !== amountUsd) {
10690
+ throw new Error("Felix changed the requested execution-fee top-up amount.");
10691
+ }
10517
10692
  const started = context.getCheckpoint("fee-credit:broadcast-started");
10518
10693
  let sent = context.getCheckpoint("fee-credit:sent");
10519
10694
  if (isRecord(started) && !isRecord(sent)) {
@@ -10534,6 +10709,8 @@ export async function topUpFeeBalance(workflowKey, context, amountUsd, allowLowO
10534
10709
  const hash = await executeFeeSettlement(prepared, {
10535
10710
  expectedAmountUsd: amountUsd,
10536
10711
  expectedNonce: isRecord(started) ? Number(started.nonce) : undefined,
10712
+ // NO_PUBLIC_RPC_20261115: the Arc fee top-up goes through Felix's intent-bound relay.
10713
+ access: fundingRpcAccess(),
10537
10714
  beforeBroadcast: ({ transaction_hash: transactionHash, nonce }) => (context.saveCheckpoint("fee-credit:broadcast-started", {
10538
10715
  transaction_hash: transactionHash,
10539
10716
  nonce,
@@ -10552,10 +10729,7 @@ export async function topUpFeeBalance(workflowKey, context, amountUsd, allowLowO
10552
10729
  if (!hash || !ORDER_HASH_RE.test(hash)) {
10553
10730
  return clientError("fee_credit_reconciliation_required", "The encrypted fee-credit checkpoint is invalid.", "Do not top up again. Reconcile the owner transfer with Felix support.", { reconciliation_required: true });
10554
10731
  }
10555
- return await call("POST", "/v1/wallet/funding/fees/confirm", {
10556
- intent_token: prepared.intent_token,
10557
- transaction_hash: hash,
10558
- }, { idempotencyKey: workflowStageKey(workflowKey, "confirm"), retryOnError: false });
10732
+ return await confirmFeeCredit(prepared, hash, amountUsd, workflowKey);
10559
10733
  }
10560
10734
  catch (error) {
10561
10735
  const started = context.getCheckpoint("fee-credit:broadcast-started");
@@ -10568,9 +10742,7 @@ export async function topUpFeeBalance(workflowKey, context, amountUsd, allowLowO
10568
10742
  && !await polygonFundingNonceUnchanged(prepared, nonce, fundingRpcAccess())) {
10569
10743
  context.saveCheckpoint("fee-credit:sent", { transaction_hash: hash });
10570
10744
  context.deleteCheckpoint("fee-credit:broadcast-started");
10571
- return await call("POST", "/v1/wallet/funding/fees/confirm", {
10572
- intent_token: prepared.intent_token, transaction_hash: hash,
10573
- }, { idempotencyKey: workflowStageKey(workflowKey, "confirm"), retryOnError: false });
10745
+ return await confirmFeeCredit(prepared, hash, amountUsd, workflowKey);
10574
10746
  }
10575
10747
  }
10576
10748
  catch { /* Keep the saved transfer available for exact-key reconciliation. */ }
@@ -10579,6 +10751,16 @@ export async function topUpFeeBalance(workflowKey, context, amountUsd, allowLowO
10579
10751
  return clientError("client_signing_failed", safeClientErrorMessage(error, "Local execution-fee top-up signing failed."), "The owner key stayed local. Check the transaction before retrying.");
10580
10752
  }
10581
10753
  }
10754
+ // Arc providers answered a head behind their own finalized block for up to
10755
+ // ~10 s on 2026-09-27 (two fee top-ups needed a manual re-confirm at 3 x 2 s).
10756
+ const FEE_CONFIRM_TRANSIENT_RETRIES = 6;
10757
+ const FEE_CONFIRM_TRANSIENT_DELAY_MS = Number(process.env.FELIX_FEE_CONFIRM_RETRY_DELAY_MS ?? 3_000);
10758
+ function feeConfirmTransient(response) {
10759
+ if (response.ok !== false)
10760
+ return false;
10761
+ const meta = isRecord(response._meta) ? response._meta : {};
10762
+ return meta.http_status === 503;
10763
+ }
10582
10764
  // Compatibility export for existing local integrations. This no longer settles
10583
10765
  // debt: it performs the same prepaid top-up as top_up_fee_balance.
10584
10766
  export async function settleLiveFees(workflowKey, context, amountUsd, allowLowOwnerBuffer = false) {
@@ -10845,7 +11027,7 @@ const TOOL_RISK_GROUPS = {
10845
11027
  ],
10846
11028
  local_credential: ["set_api_key", "reload_launcher_key"],
10847
11029
  account: [
10848
- "prepare_venue_bootstrap", "request_withdrawal_confirmation", "verify_withdrawal_confirmation", "use_child_account", "derive_api_key", "create_account", "archive_account"
11030
+ "prepare_venue_bootstrap", "request_withdrawal_confirmation", "verify_withdrawal_confirmation", "use_child_account", "derive_api_key", "create_account", "archive_account", "onboard"
10849
11031
  ],
10850
11032
  trading: [
10851
11033
  "place_order", "place_batch_orders", "cancel_order", "close_position",
@@ -10858,9 +11040,9 @@ const TOOL_RISK_GROUPS = {
10858
11040
  money: [
10859
11041
  "start_home_funding", "prepare_capital_allocation", "submit_capital_allocation", "submit_venue_bootstrap",
10860
11042
  "start_capital_move",
10861
- "resolve_network_fee", "swap_native_usdc", "route_funds", "fund_market",
11043
+ "resolve_network_fee", "swap_native_usdc", "fund_market",
10862
11044
  "start_fund_market", "bring_home", "start_bring_home", "resume_money_operation",
10863
- "start_arc_home_hl_return",
11045
+ "start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return", "invalidate_safe_nonce",
10864
11046
  "return_prediction_market_to_arc",
10865
11047
  "fund_polymarket_agent_wallet",
10866
11048
  "prepare_arc_transfer", "submit_arc_transfer",
@@ -10900,14 +11082,256 @@ for (const [riskClass, names] of Object.entries(TOOL_RISK_GROUPS)) {
10900
11082
  TOOL_RISK_CLASS.set(name, riskClass);
10901
11083
  }
10902
11084
  }
11085
+ // VENUE_MOVES_APP_MODEL_20261115: Arc home <-> Hyperliquid perps, ported from the certified
11086
+ // capital-line drivers with the app's trust model.
11087
+ const HYPERCORE_INFO_TIMEOUT_MS = 10_000;
11088
+ const HYPERCORE_INFO_MAX_BYTES = 256_000;
11089
+ async function hypercoreInfo(base, body) {
11090
+ const controller = new AbortController();
11091
+ const timer = setTimeout(() => controller.abort(), HYPERCORE_INFO_TIMEOUT_MS);
11092
+ try {
11093
+ const response = await fetch(`${base}/info`, {
11094
+ method: "POST", headers: { "content-type": "application/json", accept: "application/json" },
11095
+ body: JSON.stringify(body), signal: controller.signal, redirect: "error",
11096
+ });
11097
+ if (response.status !== 200) {
11098
+ controller.abort();
11099
+ throw new Error("Hyperliquid info unavailable");
11100
+ }
11101
+ // The byte cap is enforced while streaming: an oversized body is cancelled, never buffered.
11102
+ const text = await readCappedText(response, HYPERCORE_INFO_MAX_BYTES, () => controller.abort())
11103
+ .catch(() => { throw new Error("Hyperliquid info unavailable"); });
11104
+ return JSON.parse(text);
11105
+ }
11106
+ finally {
11107
+ clearTimeout(timer);
11108
+ }
11109
+ }
11110
+ export function buildHypercoreDeps(workflowKey, context, accountId, policy) {
11111
+ const ownerKey = () => {
11112
+ if (isHostedTransport())
11113
+ throw new Error("Local signing is disabled for the hosted multi-tenant transport.");
11114
+ const key = getRuntimeOwnerPrivateKey();
11115
+ if (!EVM_PRIVATE_KEY_RE.test(key || ""))
11116
+ throw new Error("A local owner key is required to sign this funding.");
11117
+ return key;
11118
+ };
11119
+ const base = resolveHyperliquidEndpoint();
11120
+ const ledger = hyperliquidPort(base).ledger;
11121
+ let owner = "";
11122
+ try {
11123
+ owner = privateKeyToAccount(ownerKey()).address;
11124
+ }
11125
+ catch {
11126
+ owner = "";
11127
+ }
11128
+ return {
11129
+ call: (method, path, body, opts) => call(method, path, body, opts),
11130
+ accountId,
11131
+ owner,
11132
+ expectedSafe: async () => {
11133
+ const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
11134
+ if (home.ok === false)
11135
+ throw new Error("The selected account has no verified Arc home Safe for this owner.");
11136
+ return arcHomeSafeFromDepositResponse(home, privateKeyToAccount(ownerKey()).address);
11137
+ },
11138
+ // Signs the CLIENT-BUILT typed data with the canonical SafeTx types only.
11139
+ signSafeTx: (typedData) => signArcHomeSafeTx(typedData, ownerKey()),
11140
+ hyperliquid: {
11141
+ abstraction: (who) => hypercoreInfo(base, { type: "userAbstraction", user: who }),
11142
+ ledger: (who, start, end) => ledger(who, start, end),
11143
+ },
11144
+ // VENUE_MOVES_APP_MODEL_20261115: the app's trust model (src/arc-venue-app-policy.ts).
11145
+ policy: policy ?? hypercoreAppPolicy(),
11146
+ getCheckpoint: (name) => context.getCheckpoint(name),
11147
+ saveCheckpoint: (name, value) => context.saveCheckpoint(name, value),
11148
+ stageKey: (stage) => workflowStageKey(workflowKey, stage),
11149
+ now: () => Date.now(),
11150
+ sleep: async (ms) => { await sleep(ms); },
11151
+ pollBudgetMs: 45_000,
11152
+ };
11153
+ }
11154
+ export async function executeHypercoreFunding(amountUsd, minimumUsd, workflowKey, context, accountId, acceptActivationUsd) {
11155
+ if (!HYPERCORE_DIRECT_CLIENT_ENABLED) {
11156
+ return markMoneyNotStarted(clientError("hypercore_direct_not_launch_enabled", "The direct Arc home -> HyperCore route is not enabled in this Felix MCP build.", "Nothing was prepared or signed."));
11157
+ }
11158
+ const toUnits = (value) => {
11159
+ const u = Math.round(value * 1_000_000);
11160
+ return Number.isSafeInteger(u) && Math.abs(u / 1_000_000 - value) <= 1e-9 ? BigInt(u) : null;
11161
+ };
11162
+ const amount = toUnits(amountUsd);
11163
+ const minimum = minimumUsd === undefined ? null : toUnits(minimumUsd);
11164
+ const acceptActivation = acceptActivationUsd === undefined ? null : toUnits(acceptActivationUsd);
11165
+ if (amount === null || (minimumUsd !== undefined && minimum === null)
11166
+ || (acceptActivationUsd !== undefined && acceptActivation === null)) {
11167
+ return markMoneyNotStarted(clientError("invalid_amount", "Amounts must be exact USDC with at most six decimals."));
11168
+ }
11169
+ const funded = await driveHypercoreFunding({ amount_units: amount, minimum_credit_units: minimum,
11170
+ accept_activation_cost_units: acceptActivation }, buildHypercoreDeps(workflowKey, context, accountId));
11171
+ if (funded.ok !== true || funded.status !== "completed" || funded.venue_usable !== true)
11172
+ return funded;
11173
+ const fundedPending = (error) => ({
11174
+ ...funded,
11175
+ ok: false,
11176
+ status: "reconciliation_required",
11177
+ error,
11178
+ funding_status: "completed",
11179
+ venue_funded: true,
11180
+ venue_usable: false,
11181
+ hyperliquid_status: "onboarding_pending",
11182
+ reconciliation_required: true,
11183
+ next_action: "resume_with_same_idempotency_key",
11184
+ });
11185
+ // The approval helper signs for the session's CURRENT child and owner key. A
11186
+ // concurrent use_child_account while the credit was being proven would make
11187
+ // it approve a different account's agent, so bind it to the funded one.
11188
+ const fundedOwner = isRecord(funded.destination) ? String(funded.destination.owner || "").toLowerCase() : "";
11189
+ let sessionOwner = "";
11190
+ try {
11191
+ sessionOwner = privateKeyToAccount(getRuntimeOwnerPrivateKey()).address.toLowerCase();
11192
+ }
11193
+ catch {
11194
+ sessionOwner = "";
11195
+ }
11196
+ if (runtimeManagedAccountId !== accountId || !fundedOwner || sessionOwner !== fundedOwner) {
11197
+ return fundedPending({
11198
+ code: "session_binding_mismatch",
11199
+ message: "HyperCore funding completed, but the MCP session no longer targets the funded child account.",
11200
+ hint: "Funds already reached HyperCore. Do not fund again. Restore the funded child with use_child_account, then resume fund_hypercore_from_arc with the same idempotency_key and arguments to finish trading-agent approval.",
11201
+ funded_account_id: accountId,
11202
+ active_account_id: runtimeManagedAccountId || null,
11203
+ });
11204
+ }
11205
+ // The driver checkpoints the proven cash leg first. Approval-only retries
11206
+ // reuse it, so an onboarding outage cannot start a second transfer.
11207
+ const hyperliquid = await ensureHyperliquidAfterFunding(workflowKey, context);
11208
+ if (hyperliquid.ok === false) {
11209
+ const error = isRecord(hyperliquid.error) ? hyperliquid.error : {};
11210
+ return fundedPending({
11211
+ ...error,
11212
+ hint: "Funds already reached HyperCore. Do not fund again. Resume fund_hypercore_from_arc with the same idempotency_key and arguments to finish trading-agent approval.",
11213
+ });
11214
+ }
11215
+ return { ...funded, hyperliquid_status: "ready", hyperliquid_agent_address: hyperliquid.agent_address };
11216
+ }
11217
+ export function buildHypercoreReturnDeps(workflowKey, context, accountId, policy) {
11218
+ const ownerKey = () => {
11219
+ if (isHostedTransport())
11220
+ throw new Error("Local signing is disabled for the hosted multi-tenant transport.");
11221
+ const key = getRuntimeOwnerPrivateKey();
11222
+ if (!EVM_PRIVATE_KEY_RE.test(key || ""))
11223
+ throw new Error("A local owner key is required to sign this return.");
11224
+ return key;
11225
+ };
11226
+ const base = resolveHyperliquidEndpoint();
11227
+ const ledger = hyperliquidPort(base).ledger;
11228
+ let owner = "";
11229
+ try {
11230
+ owner = privateKeyToAccount(ownerKey()).address;
11231
+ }
11232
+ catch {
11233
+ owner = "";
11234
+ }
11235
+ return {
11236
+ call: (method, path, body, opts) => call(method, path, body, opts),
11237
+ accountId,
11238
+ owner,
11239
+ expectedSafe: async () => {
11240
+ const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
11241
+ if (home.ok === false)
11242
+ throw new Error("The selected account has no verified Arc home Safe for this owner.");
11243
+ return arcHomeSafeFromDepositResponse(home, privateKeyToAccount(ownerKey()).address);
11244
+ },
11245
+ // Only the two client-built payload kinds are ever signed here.
11246
+ signTypedData: (typedData) => {
11247
+ if (typedData.primaryType !== "NonceMapping" && typedData.primaryType !== "HyperliquidTransaction:SendAsset") {
11248
+ throw new Error("Refusing to sign an unexpected typed-data kind.");
11249
+ }
11250
+ return privateKeyToAccount(ownerKey()).signTypedData(typedData);
11251
+ },
11252
+ hyperliquid: {
11253
+ abstraction: (who) => hypercoreInfo(base, { type: "userAbstraction", user: who }),
11254
+ clearinghouse: (who) => hypercoreInfo(base, { type: "clearinghouseState", user: who }),
11255
+ ledger: (who, start, end) => ledger(who, start, end),
11256
+ },
11257
+ // VENUE_MOVES_APP_MODEL_20261115: the app's trust model (src/arc-venue-app-policy.ts).
11258
+ policy: policy ?? hypercoreReturnAppPolicy(),
11259
+ getCheckpoint: (name) => context.getCheckpoint(name),
11260
+ saveCheckpoint: (name, value) => context.saveCheckpoint(name, value),
11261
+ stageKey: (stage) => workflowStageKey(workflowKey, stage),
11262
+ now: () => Date.now(),
11263
+ sleep: async (ms) => { await sleep(ms); },
11264
+ pollBudgetMs: 45_000,
11265
+ };
11266
+ }
11267
+ export async function executeHypercoreReturn(amountUsd, minimumUsd, workflowKey, context, accountId) {
11268
+ if (!HYPERCORE_RETURN_CLIENT_ENABLED) {
11269
+ return markMoneyNotStarted(clientError("arc_hypercore_return_not_launch_enabled", "The direct HyperCore -> Arc home return is not enabled in this Felix MCP build.", "Nothing was prepared or signed."));
11270
+ }
11271
+ const toUnits = (value) => {
11272
+ const u = Math.round(value * 1_000_000);
11273
+ return Number.isSafeInteger(u) && Math.abs(u / 1_000_000 - value) <= 1e-9 ? BigInt(u) : null;
11274
+ };
11275
+ const amount = toUnits(amountUsd);
11276
+ const minimum = minimumUsd === undefined ? null : toUnits(minimumUsd);
11277
+ if (amount === null || (minimumUsd !== undefined && minimum === null)) {
11278
+ return markMoneyNotStarted(clientError("invalid_amount", "Amounts must be exact USDC with at most six decimals."));
11279
+ }
11280
+ return driveHypercoreReturn({ amount_units: amount, minimum_credit_units: minimum }, buildHypercoreReturnDeps(workflowKey, context, accountId));
11281
+ }
11282
+ // VENUE_MOVES_APP_MODEL_20261115: Safe nonce invalidation (app trust model).
11283
+ export function buildSafeInvalidationDeps(workflowKey, context, accountId, policy) {
11284
+ const ownerKey = () => {
11285
+ if (isHostedTransport())
11286
+ throw new Error("Local signing is disabled for the hosted multi-tenant transport.");
11287
+ const key = getRuntimeOwnerPrivateKey();
11288
+ if (!EVM_PRIVATE_KEY_RE.test(key || ""))
11289
+ throw new Error("A local owner key is required to sign this invalidation.");
11290
+ return key;
11291
+ };
11292
+ let owner = "";
11293
+ try {
11294
+ owner = privateKeyToAccount(ownerKey()).address;
11295
+ }
11296
+ catch {
11297
+ owner = "";
11298
+ }
11299
+ return {
11300
+ call: (method, path, body, opts) => call(method, path, body, opts),
11301
+ accountId,
11302
+ owner,
11303
+ expectedSafe: async () => {
11304
+ const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
11305
+ if (home.ok === false)
11306
+ throw new Error("The selected account has no verified Arc home Safe for this owner.");
11307
+ return arcHomeSafeFromDepositResponse(home, privateKeyToAccount(ownerKey()).address);
11308
+ },
11309
+ signSafeTx: (typedData) => signArcHomeSafeTx(typedData, ownerKey()),
11310
+ // Astra BLOCK 2026-11-15: never Felix-attested; refuses until a verified chain check exists.
11311
+ policy: policy ?? SHIPPED_INVALIDATION_POLICY,
11312
+ getCheckpoint: (name) => context.getCheckpoint(name),
11313
+ saveCheckpoint: (name, value) => context.saveCheckpoint(name, value),
11314
+ stageKey: (stage) => workflowStageKey(workflowKey, stage),
11315
+ now: () => Date.now(),
11316
+ sleep: async (ms) => { await sleep(ms); },
11317
+ pollBudgetMs: 45_000,
11318
+ };
11319
+ }
11320
+ export async function executeSafeInvalidation(writer, operationId, expectedNonce, workflowKey, context, accountId, invalidationId = null) {
11321
+ if (!isInvalidationWriter(writer)) {
11322
+ return markMoneyNotStarted(clientError("invalid_argument", `original_writer must be one of ${INVALIDATION_WRITERS.join(", ")}.`));
11323
+ }
11324
+ return driveSafeInvalidation({ original_writer: writer, original_operation_id: operationId,
11325
+ expected_safe_nonce: expectedNonce, invalidation_id: invalidationId }, buildSafeInvalidationDeps(workflowKey, context, accountId));
11326
+ }
10903
11327
  const LIVE_MONEY_TOOLS = new Set([
10904
11328
  "submit_capital_allocation", "submit_venue_bootstrap",
10905
11329
  "start_capital_move",
10906
11330
  "place_order", "place_batch_orders", "close_position", "make_market",
10907
11331
  "place_manual_order", "close_manual_position", "modify_order_price",
10908
- "swap_native_usdc", "route_funds", "fund_market", "start_fund_market",
11332
+ "swap_native_usdc", "fund_market", "start_fund_market",
10909
11333
  "bring_home", "start_bring_home", "resume_money_operation", "resolve_network_fee",
10910
- "start_arc_home_hl_return",
11334
+ "start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return",
10911
11335
  "return_prediction_market_to_arc",
10912
11336
  "fund_polymarket_agent_wallet", "submit_arc_transfer",
10913
11337
  "arc_home_withdraw", "arc_home_deposit", "arc_home_fund_venue",
@@ -11182,6 +11606,14 @@ const TOOLS = [
11182
11606
  api_key: stringProp("Felix API key in fk_<32 lowercase hex> format.", undefined, { pattern: API_KEY_RE.source }),
11183
11607
  }, ["api_key"]),
11184
11608
  },
11609
+ {
11610
+ name: "onboard",
11611
+ 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.",
11612
+ inputSchema: schema({
11613
+ 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."),
11614
+ terms_version: stringProp("The terms version the owner accepted, exactly as returned by the first call."),
11615
+ }),
11616
+ },
11185
11617
  {
11186
11618
  name: "reload_launcher_key",
11187
11619
  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.",
@@ -11719,7 +12151,7 @@ const TOOLS = [
11719
12151
  },
11720
12152
  {
11721
12153
  name: "get_balances",
11722
- description: "Fast venue collateral snapshot plus Polygon cash and paper position count. Provider gaps are returned explicitly instead of hidden behind retries; set wait_for_complete:true to wait through the bounded Derive refresh cycle. This intentionally excludes marked Polymarket positions and owner-wallet balances on other chains; use get_money_map for canonical account-value and money-tracking decisions.",
12154
+ description: "NOT the account total: for the total account value the app shows (and 'how much do I have'), call get_money_map. This is a fast venue collateral snapshot plus Polygon cash and paper position count. Provider gaps are returned explicitly instead of hidden behind retries; set wait_for_complete:true to wait through the bounded Derive refresh cycle. This intentionally excludes marked Polymarket positions and owner-wallet balances on other chains; use get_money_map for canonical account-value and money-tracking decisions.",
11723
12155
  inputSchema: schema({
11724
12156
  wait_for_complete: booleanProp("Wait through up to two bounded Derive refresh attempts. Defaults to false for a fast, explicitly partial response."),
11725
12157
  }),
@@ -11880,19 +12312,6 @@ const TOOLS = [
11880
12312
  description: "Verify this account's Safe owner, threshold, enabled V3 module, immutable bindings, and policy against Polygon chain state.",
11881
12313
  inputSchema: schema({ account_id: stringProp("Optional owned child account UUID.", undefined, { pattern: UUID_RE.source }) }),
11882
12314
  },
11883
- {
11884
- name: "route_funds",
11885
- description: "Optional RFQ funding workflow. The RFQ endpoints are absent from the audited engine checkout, so this workflow is unavailable there. Use fund_market for supported owner-wallet funding. Venue-to-venue RFQ execution remains under certification. Allocated-capital returns to Arc Home use preview_capital_move and start_capital_move; a missing RFQ route cannot authorize a different money movement.",
11886
- inputSchema: schema({
11887
- market: stringProp("Destination for owner-wallet funding. Do not combine with source_market or destination_market.", ["prediction_market", "crypto", "options"]),
11888
- source_market: stringProp("Source venue for a venue-to-venue transfer.", ["prediction_market", "crypto", "options"]),
11889
- destination_market: stringProp("Destination venue for a venue-to-venue transfer. Must differ from source_market.", ["prediction_market", "crypto", "options"]),
11890
- amount_usd: numberProp("Amount to route.", 0),
11891
- minimum_receive_usd: numberProp("Optional minimum final venue credit.", 0),
11892
- idempotency_key: stringProp("Required RFQ and funding replay key. Reuse it after any timeout."),
11893
- account_id: stringProp("Optional owned child account UUID.", undefined, { pattern: UUID_RE.source }),
11894
- }, ["amount_usd", "idempotency_key"]),
11895
- },
11896
12315
  {
11897
12316
  name: "fund_market",
11898
12317
  description: "Route funds from the client-owned main EOA to a currently certified venue. Prediction-market and crypto funding are available; Derive/options funding is under release hold and must not be started. Native Polygon USDC is converted to USDC.e only as needed, with hashes disclosed. The owner key signs locally and never reaches Felix.",
@@ -12016,8 +12435,35 @@ const TOOLS = [
12016
12435
  }, ["amount_usd", "idempotency_key"]),
12017
12436
  },
12018
12437
  {
12438
+ name: "fund_hypercore_from_arc",
12439
+ description: "Move 5 to 25 USDC from the account's verified Arc home Safe directly to the SAME owner's Hyperliquid (HyperCore) perps balance via Relay. The Safe must also hold a separate 1.00 USDC Felix network fee: principal plus fee are paid atomically in the same owner-signed transaction. This fee is not refunded if Relay later returns the principal. Relay's quoted deduction is separately limited to 1% of principal; that limit excludes the Felix fee. A brand-new HyperCore account (none exists yet for the owner) also pays Hyperliquid's one-time account activation fee, passed on by Relay (about 1.20 USDC, at most 1.5), deducted from this funding's HyperCore credit, not from the Safe; later fundings do not pay it. It is never accepted automatically: without accept_activation_cost_usd such a funding is refused before anything is prepared, naming the exact cost and the re-call (with a new idempotency_key) that opts in. Before signing, the client independently verifies the Relay order, solver, fee, exact Safe calls and perps account mode, then journals its signature (the Safe nonce comes from Felix, as in the app). After verified perps credit with Relay-attested attribution, the local owner signer completes Hyperliquid trading-agent approval if needed; completed includes hyperliquid_status:ready. If funding succeeds but approval does not, venue_funded:true and venue_usable:false mean resume this same idempotency_key and arguments to finish approval without another funding transfer. Reuse the same idempotency_key after a timeout; never create a new funding to work around an uncertain outcome.",
12440
+ inputSchema: schema({
12441
+ amount_usd: numberProp("Exact transfer principal, 5 to 25 USDC, at most six decimals. Excludes the additional 1.00 USDC Felix fee.", 5, 25),
12442
+ minimum_credit_usd: numberProp("Optional: refuse unless Relay signs at least this perps credit.", 0.000001, 25),
12443
+ accept_activation_cost_usd: numberProp("Optional, owner opt-in: the most the owner accepts (USDC, more than 0 and at most 1.5, at most six decimals) for Hyperliquid's one-time activation of a HyperCore account that does not exist yet, deducted from this funding's credit. Pass only after the owner agreed to the exact cost a refusal named. Part of this idempotency_key: a resume must repeat the same value.", 0.000001, 1.5),
12444
+ idempotency_key: stringProp("Required workflow replay key. Reuse it to resume this exact funding."),
12445
+ }, ["amount_usd", "idempotency_key"]),
12446
+ }, {
12447
+ name: "arc_home_hypercore_return",
12448
+ description: "Return 5 to 25 USDC from the owner's OWN Hyperliquid (HyperCore) perps balance directly to the account's verified Arc home Safe via Relay: no Arbitrum and no withdraw3. The owner's HyperCore account must be in default mode and hold the amount as withdrawable. Before signing, the client verifies the solver-signed Relay order (HyperCore perps USDC in, exactly one Arc USDC payment to this Safe at or above a 1% floor, refunds only to the owner on HyperCore and the Safe on Arc), then builds and signs locally exactly two payloads: the Relay nonce mapping and one HyperCore sendAsset of the amount to Relay's pinned depository at the same nonce. Both are journaled before Felix submits them. Completion requires Felix's completion bound to this order and solver, and this client's own HyperCore ledger read of the send (the Arc credit is Felix's evidence, bound to the signed order and bounds, as in the app). No Felix fee is charged on this route. Reuse the same idempotency_key after a timeout; never start a new return to work around an uncertain one.",
12449
+ inputSchema: schema({
12450
+ amount_usd: numberProp("Exact USDC to send from HyperCore perps, 5 to 25, at most six decimals.", 5, 25),
12451
+ minimum_credit_usd: numberProp("Optional: refuse unless Relay signs at least this Arc credit.", 0.000001, 25),
12452
+ idempotency_key: stringProp("Required workflow replay key. Reuse it to resume this exact return."),
12453
+ }, ["amount_usd", "idempotency_key"]),
12454
+ }, {
12455
+ name: "invalidate_safe_nonce",
12456
+ description: "Not available in this build: refuses before any request (it needs an independent chain proof that the no-op executed, which this client does not have). Release a stuck Safe nonce in the Felix app (Wallet) instead. Release this account's Arc home Safe nonce that an earlier Felix operation reserved but never executed (an expired, cancelled or observe-only HyperCore or Polymarket funding, or a same-chain Arc withdrawal). While such a nonce is reserved, every later Felix Safe move is refused. The owner signs ONE no-op Safe transaction (a call to the owner's own address, value 0, no data) at that nonce: it moves no funds, and once it executes the original can never execute. Before signing, the client rebuilds the no-op itself, checks it is for this account's Safe at the original's nonce, and proves the Safe's current nonce on its own private Arc quorum (FELIX_ARC_PROOF_RPC_URLS). Completion requires the engine's proof, this client's own proof that exactly this no-op executed, and Felix closing the original operation. If the original executed first, nothing is closed; resume the original instead. Use the exact original_writer and original_operation_id from the next_action of the tool that reported the reserved nonce. Felix keeps ONE invalidation per Safe nonce: when one already exists (next_action complete_invalidation), pass its invalidation_id to complete it instead of preparing a new one. Never use this tool while the blocking operation's next_action is reconcile_blocking_operation: its Safe transaction may still execute. Reuse the same idempotency_key after a timeout; nothing is signed twice.",
12457
+ inputSchema: schema({
12458
+ original_writer: stringProp("The Felix writer that reserved the nonce: withdrawal_source (a same-chain Arc withdrawal), hypercore (fund_hypercore_from_arc) or polygon (fund_polymarket_from_arc).", [...INVALIDATION_WRITERS]),
12459
+ original_operation_id: stringProp("The original operation or funding id (UUID).", undefined, { pattern: UUID_RE.source }),
12460
+ expected_safe_nonce: integerProp("Optional: the original's Safe nonce, when the reporting tool named it. The no-op must be at exactly this nonce.", 0),
12461
+ invalidation_id: stringProp("Optional: an invalidation Felix already holds for this nonce (next_action complete_invalidation names it). It is completed instead of preparing a new one.", undefined, { pattern: UUID_RE.source }),
12462
+ idempotency_key: stringProp("Required workflow replay key. Reuse it to resume this exact invalidation."),
12463
+ }, ["original_writer", "original_operation_id", "idempotency_key"]),
12464
+ }, {
12019
12465
  name: "start_arc_home_hl_return",
12020
- description: "Start a durable Hyperliquid -> Arc home return: one owner-signed withdraw3 to the account's own Arbitrum wallet, then one Arc deposit into the account's verified Arc home Safe. Returns an operation_id immediately. SERVER-GATED: Felix refuses new returns until it enables this route; a refusal moves nothing. Completion means a finalized credit in the Arc home Safe. Reuse the same idempotency_key after any timeout; never start a second return to work around an uncertain one.",
12466
+ description: "Start a durable Hyperliquid -> Arc home return: one owner-signed withdraw3 to the account's own Arbitrum wallet, then one Arc deposit into the account's verified Arc home Safe. Returns an operation_id immediately. For 5 to 25 USDC prefer arc_home_hypercore_return (direct, no Arbitrum: the route the app uses); this legacy route also needs FELIX_ARBITRUM_RPC_URL set to a private Arbitrum RPC. A refusal moves nothing. Completion means a finalized credit in the Arc home Safe. Reuse the same idempotency_key after any timeout; never start a second return to work around an uncertain one.",
12021
12467
  inputSchema: schema({
12022
12468
  amount_usd: numberProp("USDC to withdraw from Hyperliquid (at least 2). The Hyperliquid and Circle fees come out of it.", 2),
12023
12469
  allow_high_fee_loss: booleanProp("Accept the proportionally high fixed fees of a return under $10."),
@@ -12749,7 +13195,7 @@ const TOOLS = [
12749
13195
  inputSchema: schema({
12750
13196
  idempotency_key: stringProp("Optional stable retry key. Reuse it after an interrupted registration."),
12751
13197
  url: stringProp("Public HTTPS URL. No localhost/private IPs.", undefined, { maxLength: 2048 }),
12752
- events: arrayProp("Events: order.filled, position.opened, position.closed, agent.decision, agent.error.", { type: "string", enum: WEBHOOK_EVENTS }, { minItems: 1, maxItems: WEBHOOK_EVENTS.length, uniqueItems: true }),
13198
+ events: arrayProp("Events: order.filled, position.opened, position.closed (every live close: app, agent, take-profit/stop-loss, liquidation, market resolution; close_reason is liquidation, market_resolved or null), position.liquidated, agent.decision, agent.error.", { type: "string", enum: WEBHOOK_EVENTS }, { minItems: 1, maxItems: WEBHOOK_EVENTS.length, uniqueItems: true }),
12753
13199
  }, ["url"]),
12754
13200
  },
12755
13201
  {
@@ -12916,6 +13362,68 @@ function beginLiveMutation(operation, args) {
12916
13362
  }
12917
13363
  } };
12918
13364
  }
13365
+ // ONBOARD_CONSENT_20261117: shared by reload_launcher_key and onboard.
13366
+ async function reloadLauncherCredentials() {
13367
+ const candidateApiKey = KEYCHAIN_BACKED_CREDENTIALS
13368
+ ? localKeychainCredential(KEYCHAIN_API_SERVICE)
13369
+ : START_KEY;
13370
+ const candidateOwnerKey = KEYCHAIN_BACKED_CREDENTIALS
13371
+ ? localKeychainCredential(KEYCHAIN_OWNER_SERVICE)
13372
+ : START_OWNER_KEY;
13373
+ if (!API_KEY_RE.test(candidateApiKey)
13374
+ || (KEYCHAIN_BACKED_CREDENTIALS && !EVM_PRIVATE_KEY_RE.test(candidateOwnerKey))) {
13375
+ return clientError("launcher_key_unavailable", KEYCHAIN_BACKED_CREDENTIALS
13376
+ ? "macOS Keychain does not contain a complete valid Felix launcher identity."
13377
+ : "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.");
13378
+ }
13379
+ try {
13380
+ // Authenticate local recovery state before changing either signer or
13381
+ // API identity. A corrupt same-owner journal remains a hard stop.
13382
+ if (EVM_PRIVATE_KEY_RE.test(candidateOwnerKey)) {
13383
+ readMoneyWorkflowJournal(moneyWorkflowEncryptionKey(candidateOwnerKey), candidateOwnerKey);
13384
+ }
13385
+ const authenticated = await call("GET", "/v1/me/subscription", undefined, {
13386
+ authKey: candidateApiKey,
13387
+ retryOnError: false,
13388
+ timeoutMs: 30_000,
13389
+ });
13390
+ if (authenticated.ok === false) {
13391
+ return clientError("launcher_key_rejected", "Felix rejected the launcher API key currently stored in Keychain.", "Restore the matching encrypted identity backup or register a fresh unfunded launcher. No session credential was changed.");
13392
+ }
13393
+ const previousOwner = EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)
13394
+ ? ownerAddressForPrivateKey(START_OWNER_KEY)
13395
+ : null;
13396
+ START_KEY = candidateApiKey;
13397
+ START_OWNER_KEY = candidateOwnerKey;
13398
+ launcherAccountIdCache = undefined;
13399
+ setKey(candidateApiKey);
13400
+ runtimeManagedAccountId = undefined;
13401
+ runtimeBindingError = undefined;
13402
+ forgetActiveChildAccount();
13403
+ if (EVM_PRIVATE_KEY_RE.test(candidateOwnerKey)) {
13404
+ setRuntimeOwnerPrivateKey(candidateOwnerKey);
13405
+ }
13406
+ else {
13407
+ clearRuntimeOwnerPrivateKey();
13408
+ }
13409
+ const currentOwner = EVM_PRIVATE_KEY_RE.test(candidateOwnerKey)
13410
+ ? ownerAddressForPrivateKey(candidateOwnerKey)
13411
+ : null;
13412
+ return {
13413
+ ok: true,
13414
+ message: "Current Keychain launcher credential, owner signer, and workflow journal restored for this MCP session.",
13415
+ identity_changed: Boolean(previousOwner && currentOwner
13416
+ && previousOwner.toLowerCase() !== currentOwner.toLowerCase()),
13417
+ workflow_journal_identity: currentOwner
13418
+ ? workflowIdentityFingerprint(candidateOwnerKey)
13419
+ : null,
13420
+ _meta: { source: "mcp_keychain", key_prefix: candidateApiKey.slice(0, 12) },
13421
+ };
13422
+ }
13423
+ catch (error) {
13424
+ return clientError("operation_state_unavailable", safeClientErrorMessage(error, "The encrypted money-workflow journal could not be validated; no session credential was changed."), "Preserve the journal and restore the matching owner backup. Never delete workflow state while a money operation may be unresolved.");
13425
+ }
13426
+ }
12919
13427
  export function makeServer() {
12920
13428
  const server = new Server({ name: "felix", version: MCP_VERSION }, { capabilities: { tools: {}, resources: {} } });
12921
13429
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
@@ -13046,73 +13554,130 @@ export function makeServer() {
13046
13554
  }
13047
13555
  break;
13048
13556
  }
13049
- case "reload_launcher_key": {
13557
+ case "onboard": {
13558
+ // ONBOARD_CONSENT_20261117 (owner: "the ai should be able to accept these for the user ... do a question to
13559
+ // the user"): consent comes from the owner, through the client's own question when it has one, otherwise
13560
+ // relayed by the agent and confirmed by one native macOS click before any key exists.
13050
13561
  if (isHostedTransport()) {
13051
- out = clientError("hosted_transport_stateless", "reload_launcher_key is unavailable on the stateless hosted transport.", "Reconnect with the intended Bearer token.");
13562
+ 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.");
13563
+ break;
13052
13564
  }
13053
- else {
13054
- const candidateApiKey = KEYCHAIN_BACKED_CREDENTIALS
13055
- ? localKeychainCredential(KEYCHAIN_API_SERVICE)
13056
- : START_KEY;
13057
- const candidateOwnerKey = KEYCHAIN_BACKED_CREDENTIALS
13058
- ? localKeychainCredential(KEYCHAIN_OWNER_SERVICE)
13059
- : START_OWNER_KEY;
13060
- if (!API_KEY_RE.test(candidateApiKey)
13061
- || (KEYCHAIN_BACKED_CREDENTIALS && !EVM_PRIVATE_KEY_RE.test(candidateOwnerKey))) {
13062
- out = clientError("launcher_key_unavailable", KEYCHAIN_BACKED_CREDENTIALS
13063
- ? "macOS Keychain does not contain a complete valid Felix launcher identity."
13064
- : "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.");
13565
+ if (process.platform !== "darwin") {
13566
+ out = clientError("macos_required", "Felix onboarding currently requires macOS Keychain.");
13567
+ break;
13568
+ }
13569
+ if (API_KEY_RE.test(START_KEY) && EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)) {
13570
+ out = { ok: true, status: "already_onboarded", owner_address: ownerAddressForPrivateKey(START_OWNER_KEY),
13571
+ next_step: "Call get_status, then create_account." };
13572
+ break;
13573
+ }
13574
+ const termsUrl = "https://felix.trade/legal";
13575
+ 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.`;
13576
+ let consent;
13577
+ const canAsk = Boolean(server.getClientCapabilities()?.elicitation);
13578
+ if (canAsk && a.owner_accepted_terms === undefined) {
13579
+ let answer;
13580
+ try {
13581
+ answer = await server.elicitInput({
13582
+ message: question,
13583
+ requestedSchema: {
13584
+ type: "object",
13585
+ properties: {
13586
+ accept_terms: {
13587
+ type: "boolean",
13588
+ title: "I accept the Felix terms",
13589
+ description: `Terms, Privacy Policy and Risk Disclosure at ${termsUrl} (version ${FELIX_LEGAL_BUNDLE_VERSION}).`,
13590
+ },
13591
+ },
13592
+ required: ["accept_terms"],
13593
+ },
13594
+ });
13595
+ }
13596
+ catch {
13597
+ out = clientError("owner_question_unavailable", "The MCP client could not show the question to the owner. Nothing was created.", "Ask the owner the question returned by onboard in chat, then call onboard with owner_accepted_terms and terms_version.");
13598
+ break;
13599
+ }
13600
+ if (answer.action !== "accept" || answer.content?.accept_terms !== true) {
13601
+ out = { ok: false, status: "owner_declined", message: "The owner did not accept the Felix terms. Nothing was created." };
13065
13602
  break;
13066
13603
  }
13604
+ consent = "asked_by_felix";
13605
+ }
13606
+ else if (a.owner_accepted_terms === true && a.terms_version === FELIX_LEGAL_BUNDLE_VERSION) {
13607
+ consent = "relayed_with_mac_click";
13608
+ }
13609
+ else {
13610
+ out = {
13611
+ ok: false,
13612
+ status: "owner_answer_required",
13613
+ question,
13614
+ terms_url: termsUrl,
13615
+ terms_version: FELIX_LEGAL_BUNDLE_VERSION,
13616
+ 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.",
13617
+ };
13618
+ break;
13619
+ }
13620
+ if (!KEYCHAIN_BACKED_CREDENTIALS) {
13621
+ // This process reads its identity from its environment, so a new Keychain identity could not be loaded
13622
+ // here (and would sit beside the configured one). Nothing is created.
13623
+ 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.");
13624
+ break;
13625
+ }
13626
+ const keyTool = fileURLToPath(new URL("./key-backup.js", import.meta.url));
13627
+ const cliArgs = [keyTool, "onboard", "--accept-terms", "--client", "none"];
13628
+ if (consent === "relayed_with_mac_click")
13629
+ cliArgs.push("--confirm-on-mac");
13630
+ reportProgress(1, 3, consent === "relayed_with_mac_click"
13631
+ ? "Waiting for the owner to click Continue in the macOS confirmation."
13632
+ : "Creating the owner key and registering the launcher.");
13633
+ const run = await new Promise((resolveRun) => {
13634
+ const child = spawn(process.execPath, cliArgs, { stdio: ["ignore", "pipe", "pipe"], env: process.env });
13635
+ let stdout = "";
13636
+ child.stdout.on("data", (chunk) => { if (stdout.length < 256 * 1024)
13637
+ stdout += String(chunk); });
13638
+ child.stderr.on("data", () => { });
13639
+ const timer = setTimeout(() => child.kill("SIGTERM"), 300_000);
13640
+ child.on("error", () => { clearTimeout(timer); resolveRun({ code: -1, stdout }); });
13641
+ child.on("close", (code) => { clearTimeout(timer); resolveRun({ code, stdout }); });
13642
+ });
13643
+ const at = run.stdout.lastIndexOf('{\n "ok": true');
13644
+ let summary;
13645
+ if (run.code === 0 && at >= 0) {
13067
13646
  try {
13068
- // Authenticate local recovery state before changing either signer or
13069
- // API identity. A corrupt same-owner journal remains a hard stop.
13070
- if (EVM_PRIVATE_KEY_RE.test(candidateOwnerKey)) {
13071
- readMoneyWorkflowJournal(moneyWorkflowEncryptionKey(candidateOwnerKey), candidateOwnerKey);
13072
- }
13073
- const authenticated = await call("GET", "/v1/me/subscription", undefined, {
13074
- authKey: candidateApiKey,
13075
- retryOnError: false,
13076
- timeoutMs: 30_000,
13077
- });
13078
- if (authenticated.ok === false) {
13079
- out = clientError("launcher_key_rejected", "Felix rejected the launcher API key currently stored in Keychain.", "Restore the matching encrypted identity backup or register a fresh unfunded launcher. No session credential was changed.");
13080
- break;
13081
- }
13082
- const previousOwner = EVM_PRIVATE_KEY_RE.test(START_OWNER_KEY)
13083
- ? ownerAddressForPrivateKey(START_OWNER_KEY)
13084
- : null;
13085
- START_KEY = candidateApiKey;
13086
- START_OWNER_KEY = candidateOwnerKey;
13087
- launcherAccountIdCache = undefined;
13088
- setKey(candidateApiKey);
13089
- runtimeManagedAccountId = undefined;
13090
- runtimeBindingError = undefined;
13091
- forgetActiveChildAccount();
13092
- if (EVM_PRIVATE_KEY_RE.test(candidateOwnerKey)) {
13093
- setRuntimeOwnerPrivateKey(candidateOwnerKey);
13094
- }
13095
- else {
13096
- clearRuntimeOwnerPrivateKey();
13097
- }
13098
- const currentOwner = EVM_PRIVATE_KEY_RE.test(candidateOwnerKey)
13099
- ? ownerAddressForPrivateKey(candidateOwnerKey)
13100
- : null;
13101
- out = {
13102
- ok: true,
13103
- message: "Current Keychain launcher credential, owner signer, and workflow journal restored for this MCP session.",
13104
- identity_changed: Boolean(previousOwner && currentOwner
13105
- && previousOwner.toLowerCase() !== currentOwner.toLowerCase()),
13106
- workflow_journal_identity: currentOwner
13107
- ? workflowIdentityFingerprint(candidateOwnerKey)
13108
- : null,
13109
- _meta: { source: "mcp_keychain", key_prefix: candidateApiKey.slice(0, 12) },
13110
- };
13647
+ summary = JSON.parse(run.stdout.slice(at));
13111
13648
  }
13112
- catch (error) {
13113
- out = clientError("operation_state_unavailable", safeClientErrorMessage(error, "The encrypted money-workflow journal could not be validated; no session credential was changed."), "Preserve the journal and restore the matching owner backup. Never delete workflow state while a money operation may be unresolved.");
13649
+ catch {
13650
+ summary = undefined;
13114
13651
  }
13115
13652
  }
13653
+ if (!summary || summary.ok !== true) {
13654
+ out = clientError("onboarding_failed", consent === "relayed_with_mac_click" && run.code !== 0
13655
+ ? "Onboarding stopped: the macOS confirmation was cancelled or setup failed. Nothing was replaced."
13656
+ : "Felix onboarding did not complete. Nothing was replaced.", "Check felix-keys status in Terminal. Never create a second identity if one already exists.");
13657
+ break;
13658
+ }
13659
+ reportProgress(2, 3, "Loading the new identity into this session.");
13660
+ const loaded = await reloadLauncherCredentials();
13661
+ reportProgress(3, 3, "Done.");
13662
+ out = {
13663
+ ok: loaded.ok !== false,
13664
+ status: loaded.ok !== false ? "onboarded" : "onboarded_restart_required",
13665
+ consent,
13666
+ terms_version: FELIX_LEGAL_BUNDLE_VERSION,
13667
+ owner_address: summary.owner_address,
13668
+ encrypted_backup: summary.encrypted_backup,
13669
+ backup_path: summary.backup_path,
13670
+ custody_recovery: summary.custody_recovery,
13671
+ session: loaded.ok !== false ? "identity_loaded" : "restart_the_mcp_server",
13672
+ secrets_displayed: false,
13673
+ next_step: "Call create_account (it returns a deposit address; the owner sends at least $5 themselves).",
13674
+ };
13675
+ break;
13676
+ }
13677
+ case "reload_launcher_key": {
13678
+ out = isHostedTransport()
13679
+ ? clientError("hosted_transport_stateless", "reload_launcher_key is unavailable on the stateless hosted transport.", "Reconnect with the intended Bearer token.")
13680
+ : await reloadLauncherCredentials();
13116
13681
  break;
13117
13682
  }
13118
13683
  case "use_child_account": {
@@ -15192,10 +15757,6 @@ export function makeServer() {
15192
15757
  : undefined,
15193
15758
  });
15194
15759
  break;
15195
- case "route_funds": {
15196
- out = await executeRouteFundsTool(a);
15197
- break;
15198
- }
15199
15760
  case "fund_market": {
15200
15761
  out = await executeFundMarketTool(a);
15201
15762
  break;
@@ -15621,6 +16182,105 @@ export function makeServer() {
15621
16182
  out = await postArcHomeOperationTool(a, "mint-submitted", { mint_tx_hash: hash }, true);
15622
16183
  break;
15623
16184
  }
16185
+ case "fund_hypercore_from_arc": {
16186
+ if (!HYPERCORE_DIRECT_CLIENT_ENABLED) {
16187
+ out = markMoneyNotStarted(clientError("hypercore_direct_not_launch_enabled", "The direct Arc home -> HyperCore route is not enabled in this Felix MCP build.", "Nothing was prepared or signed."));
16188
+ break;
16189
+ }
16190
+ const key = requiredWorkflowKey(a);
16191
+ const amount = finiteNumber(a.amount_usd);
16192
+ const minimum = a.minimum_credit_usd === undefined ? undefined : finiteNumber(a.minimum_credit_usd);
16193
+ // HYPERCORE_ACTIVATION_2026_09_28: the owner's explicit opt-in to a
16194
+ // one-time HyperCore account activation, exact USDC in (0, 1.5].
16195
+ const acceptActivation = a.accept_activation_cost_usd === undefined
16196
+ ? undefined : finiteNumber(a.accept_activation_cost_usd);
16197
+ const sixDecimals = (value) => Number.isSafeInteger(Math.round(value * 1_000_000))
16198
+ && Math.abs(Math.round(value * 1_000_000) / 1_000_000 - value) <= 1e-9;
16199
+ if (!key) {
16200
+ out = clientError("missing_argument", "idempotency_key is required (1-128 printable characters).");
16201
+ }
16202
+ else if (amount === undefined || amount < 5 || amount > 25
16203
+ || (a.minimum_credit_usd !== undefined && (minimum === undefined || minimum <= 0 || minimum > amount))) {
16204
+ out = markMoneyNotStarted(clientError("invalid_argument", "amount_usd must be 5 to 25; minimum_credit_usd, when set, must be positive and at most amount_usd."));
16205
+ }
16206
+ else if (a.accept_activation_cost_usd !== undefined && (acceptActivation === undefined || acceptActivation <= 0
16207
+ || acceptActivation > 1.5 || !sixDecimals(acceptActivation))) {
16208
+ out = markMoneyNotStarted(clientError("invalid_argument", "accept_activation_cost_usd, when set, must be more than 0 and at most 1.5 USDC with at most six decimals.", "Nothing was prepared or signed."));
16209
+ }
16210
+ else if (!runtimeManagedAccountId || !UUID_RE.test(runtimeManagedAccountId)) {
16211
+ out = markMoneyNotStarted(clientError("child_account_required", "Select the funding account with use_child_account first.", "Nothing was prepared or signed."));
16212
+ }
16213
+ else {
16214
+ const accountId = runtimeManagedAccountId;
16215
+ out = requireLocalSigner() || await runMoneyWorkflow(key, "arc_hypercore_funding",
16216
+ // The acceptance is bound to the key (only when given, so a key used
16217
+ // before it existed keeps its request hash): another value refuses.
16218
+ { amount_usd: amount, minimum_credit_usd: minimum ?? null, account_id: accountId,
16219
+ ...(acceptActivation === undefined ? {} : { accept_activation_cost_usd: acceptActivation }) }, (context) => executeHypercoreFunding(amount, minimum, key, context, accountId, acceptActivation), { resumable: true });
16220
+ // An activation refusal is definitive and bound to this key's request:
16221
+ // the way forward is the owner's opt-in on a NEW key (out.recall), not
16222
+ // a same-key resume, which only repeats the refusal.
16223
+ if (isRecord(out) && out.next_action === HYPERCORE_ACTIVATION_NEXT_ACTION) {
16224
+ out = { ...out, resume_with: "a NEW idempotency_key with accept_activation_cost_usd, only if the owner accepts the cost (see recall)" };
16225
+ }
16226
+ }
16227
+ break;
16228
+ }
16229
+ case "arc_home_hypercore_return": {
16230
+ if (!HYPERCORE_RETURN_CLIENT_ENABLED) {
16231
+ out = markMoneyNotStarted(clientError("arc_hypercore_return_not_launch_enabled", "The direct HyperCore -> Arc home return is not enabled in this Felix MCP build.", "Nothing was prepared or signed."));
16232
+ break;
16233
+ }
16234
+ const key = requiredWorkflowKey(a);
16235
+ const amount = finiteNumber(a.amount_usd);
16236
+ const minimum = a.minimum_credit_usd === undefined ? undefined : finiteNumber(a.minimum_credit_usd);
16237
+ if (!key) {
16238
+ out = clientError("missing_argument", "idempotency_key is required (1-128 printable characters).");
16239
+ }
16240
+ else if (amount === undefined || amount < 5 || amount > 25
16241
+ || (a.minimum_credit_usd !== undefined && (minimum === undefined || minimum <= 0 || minimum > amount))) {
16242
+ out = markMoneyNotStarted(clientError("invalid_argument", "amount_usd must be 5 to 25; minimum_credit_usd, when set, must be positive and at most amount_usd."));
16243
+ }
16244
+ else if (!runtimeManagedAccountId || !UUID_RE.test(runtimeManagedAccountId)) {
16245
+ out = markMoneyNotStarted(clientError("child_account_required", "Select the returning account with use_child_account first.", "Nothing was prepared or signed."));
16246
+ }
16247
+ else {
16248
+ const accountId = runtimeManagedAccountId;
16249
+ out = requireLocalSigner() || await runMoneyWorkflow(key, "arc_hypercore_return", { amount_usd: amount, minimum_credit_usd: minimum ?? null, account_id: accountId, source: "hypercore_perps" }, (context) => executeHypercoreReturn(amount, minimum, key, context, accountId), { resumable: true });
16250
+ }
16251
+ break;
16252
+ }
16253
+ case "invalidate_safe_nonce": {
16254
+ const key = requiredWorkflowKey(a);
16255
+ const writer = nonEmptyString(a.original_writer);
16256
+ const operationId = nonEmptyString(a.original_operation_id)?.toLowerCase();
16257
+ const nonce = a.expected_safe_nonce === undefined ? null : a.expected_safe_nonce;
16258
+ const childId = a.invalidation_id === undefined ? null : nonEmptyString(a.invalidation_id)?.toLowerCase() ?? "";
16259
+ if (!key) {
16260
+ out = clientError("missing_argument", "idempotency_key is required (1-128 printable characters).");
16261
+ }
16262
+ else if (!isInvalidationWriter(writer)) {
16263
+ out = markMoneyNotStarted(clientError("invalid_argument", `original_writer must be one of ${INVALIDATION_WRITERS.join(", ")}.`));
16264
+ }
16265
+ else if (!operationId || !UUID_RE.test(operationId)) {
16266
+ out = markMoneyNotStarted(clientError("invalid_argument", "original_operation_id must be a UUID."));
16267
+ }
16268
+ else if (nonce !== null && (typeof nonce !== "number" || !Number.isSafeInteger(nonce) || nonce < 0)) {
16269
+ out = markMoneyNotStarted(clientError("invalid_argument", "expected_safe_nonce must be a non-negative integer."));
16270
+ }
16271
+ else if (childId !== null && !UUID_RE.test(childId)) {
16272
+ out = markMoneyNotStarted(clientError("invalid_argument", "invalidation_id must be a UUID."));
16273
+ }
16274
+ else if (!runtimeManagedAccountId || !UUID_RE.test(runtimeManagedAccountId)) {
16275
+ out = markMoneyNotStarted(clientError("child_account_required", "Select the account whose Safe nonce is reserved with use_child_account first.", "Nothing was prepared or signed."));
16276
+ }
16277
+ else {
16278
+ const accountId = runtimeManagedAccountId;
16279
+ out = requireLocalSigner() || await runMoneyWorkflow(key, "arc_safe_invalidation", { original_writer: writer, original_operation_id: operationId, expected_safe_nonce: nonce, account_id: accountId,
16280
+ ...(childId ? { invalidation_id: childId } : {}) }, (context) => executeSafeInvalidation(writer, operationId, nonce, key, context, accountId, childId), { resumable: true });
16281
+ }
16282
+ break;
16283
+ }
15624
16284
  case "start_arc_home_hl_return": {
15625
16285
  out = requireLocalSigner() || startAsyncArcHomeHlReturn(a);
15626
16286
  break;
@@ -17136,6 +17796,46 @@ export function makeServer() {
17136
17796
  });
17137
17797
  break;
17138
17798
  case "deploy_agent": {
17799
+ // ONBOARD_CONSENT_20261117: a live agent's capital and limits are the owner's answer. When the agent did
17800
+ // not pass confirmed_budget_usd and the client can ask, Felix asks the owner directly (never a generic yes).
17801
+ if (nonEmptyString(a.mode)?.toLowerCase() !== "paper" && a.confirmed_budget_usd === undefined
17802
+ && typeof a.budget_usd === "number" && Number.isFinite(a.budget_usd)
17803
+ && server.getClientCapabilities()?.elicitation) {
17804
+ let reviewed;
17805
+ try {
17806
+ reviewed = await server.elicitInput({
17807
+ message: `Review this LIVE Felix agent before it can trade real money. Strategy ${String(a.strategy_id)}, markets ${JSON.stringify(a.markets)}, budget $${Number(a.budget_usd).toFixed(2)}. Proposed max position: ${typeof a.max_position_usd === "number" ? `$${a.max_position_usd}` : "none"}; proposed max daily loss: ${typeof a.max_daily_loss_usd === "number" ? `$${a.max_daily_loss_usd}` : "none"}. Type the exact budget to confirm it. The limits you enter here are the ones used.`,
17808
+ requestedSchema: {
17809
+ type: "object",
17810
+ properties: {
17811
+ confirmed_budget_usd: { type: "number", title: "Budget you approve (USD)", description: `Must be exactly ${Number(a.budget_usd).toFixed(2)}.`, minimum: 1 },
17812
+ max_position_usd: { type: "number", title: "Max position (USD, optional)", minimum: 0,
17813
+ ...(typeof a.max_position_usd === "number" ? { default: a.max_position_usd } : {}) },
17814
+ max_daily_loss_usd: { type: "number", title: "Max daily loss (USD, optional)", minimum: 0,
17815
+ ...(typeof a.max_daily_loss_usd === "number" ? { default: a.max_daily_loss_usd } : {}) },
17816
+ },
17817
+ required: ["confirmed_budget_usd"],
17818
+ },
17819
+ });
17820
+ }
17821
+ catch {
17822
+ reviewed = undefined;
17823
+ }
17824
+ if (reviewed && reviewed.action !== "accept") {
17825
+ out = { ok: false, status: "owner_declined", message: "The owner did not approve this live agent. Nothing was deployed." };
17826
+ break;
17827
+ }
17828
+ const answer = (reviewed?.content || {});
17829
+ if (reviewed && typeof answer.confirmed_budget_usd === "number") {
17830
+ a.confirmed_budget_usd = answer.confirmed_budget_usd;
17831
+ // The owner's numbers always win over the agent's proposal; a limit the owner left empty keeps the
17832
+ // proposal they were shown (never loosened behind their back).
17833
+ for (const field of ["max_position_usd", "max_daily_loss_usd"]) {
17834
+ if (typeof answer[field] === "number" && Number.isFinite(answer[field]))
17835
+ a[field] = answer[field];
17836
+ }
17837
+ }
17838
+ }
17139
17839
  const invalid = validateDeployAgentArgs(a);
17140
17840
  if (invalid) {
17141
17841
  out = invalid;
@@ -17454,99 +18154,16 @@ export function makeServer() {
17454
18154
  const accountId = nonEmptyString(account.account_id);
17455
18155
  const accountOwnerKey = deriveAccountOwnerPrivateKey(rootOwnerKey, accountId);
17456
18156
  const accountOwnerAddress = ownerAddressForPrivateKey(accountOwnerKey);
17457
- const walletInitBody = {
17458
- account_id: accountId,
17459
- owner_address: accountOwnerAddress,
17460
- home_address: accountOwnerAddress,
17461
- max_operation_usd: maxOrderUsd,
17462
- daily_limit_usd: maxDailyUsd,
17463
- lifetime_limit_usd: lifetimeLimitUsd,
17464
- delegation_days: delegationDays,
17465
- };
17466
- let initialized = context.getCheckpoint("wallet:initialized");
17467
- if (!initialized) {
17468
- initialized = await call("POST", "/v1/wallet/onboarding/init", walletInitBody, {
17469
- idempotencyKey: workflowStageKey(workflowKey, "wallet:init"),
17470
- timeoutMs: 60_000,
17471
- });
17472
- if (initialized.ok === false)
17473
- return initialized;
17474
- context.saveCheckpoint("wallet:initialized", initialized);
17475
- }
17476
- let onboardingId = nonEmptyString(initialized.onboarding_id);
17477
- if (!onboardingId || !UUID_RE.test(onboardingId)) {
17478
- throw new Error("Felix returned an invalid wallet onboarding id.");
17479
- }
17480
- let deployed = context.getCheckpoint("wallet:deployed");
17481
- if (!deployed) {
17482
- let onboardingState = await call("GET", `/v1/wallet/onboarding/${enc(onboardingId)}${qs({ account_id: accountId })}`, undefined, { authKey: START_KEY, timeoutMs: 60_000 });
17483
- if (onboardingState.ok === false)
17484
- return onboardingState;
17485
- const challengeExpiry = Date.parse(nonEmptyString(onboardingState.expires_at) || "");
17486
- if (["deployment_failed", "expired"].includes(String(onboardingState.status))
17487
- || (onboardingState.status === "challenge"
17488
- && (!Number.isFinite(challengeExpiry) || challengeExpiry <= Date.now()))) {
17489
- initialized = await call("POST", "/v1/wallet/onboarding/init", walletInitBody, {
17490
- idempotencyKey: workflowStageKey(workflowKey, `wallet:init:recovery:${onboardingId}`),
17491
- retryOnError: false,
17492
- timeoutMs: 60_000,
17493
- });
17494
- if (initialized.ok === false)
17495
- return initialized;
17496
- context.saveCheckpoint("wallet:initialized", initialized);
17497
- onboardingId = nonEmptyString(initialized.onboarding_id);
17498
- if (!onboardingId || !UUID_RE.test(onboardingId)) {
17499
- throw new Error("Felix returned an invalid recovery onboarding id.");
17500
- }
17501
- onboardingState = { status: "challenge" };
17502
- }
17503
- if (["deployed", "completing"].includes(String(onboardingState.status))) {
17504
- deployed = onboardingState;
17505
- }
17506
- else if (onboardingState.status === "challenge") {
17507
- const proofSignature = await signSafeOnboardingProof(initialized, accountOwnerKey);
17508
- deployed = await call("POST", "/v1/wallet/onboarding/deploy", {
17509
- account_id: accountId,
17510
- onboarding_id: onboardingId,
17511
- proof_signature: proofSignature,
17512
- }, {
17513
- idempotencyKey: workflowStageKey(workflowKey, `wallet:deploy:${onboardingId}`),
17514
- retryOnError: false,
17515
- timeoutMs: 240_000,
17516
- });
17517
- if (deployed.ok === false) {
17518
- const deploymentError = isRecord(deployed.error) ? deployed.error : {};
17519
- if (deploymentError.code === "account_funding_required") {
17520
- return createAccountFundingGate(deployed, accountId, accountOwnerAddress)
17521
- || clientError("account_funding_response_invalid", "The funding gate did not return a usable Polygon owner address.", "Do not send funds. Retry create_account with this same idempotency_key.", { account_id: accountId });
17522
- }
17523
- return deployed;
17524
- }
17525
- }
17526
- else {
17527
- return clientError("wallet_onboarding_reconciliation_required", `Safe onboarding is ${String(onboardingState.status || "unknown")}.`, "Retry this same create_account idempotency key after the current deployment settles.", { account_id: accountId, onboarding_id: onboardingId });
17528
- }
17529
- context.saveCheckpoint("wallet:deployed", deployed);
17530
- }
17531
- let wallet = context.getCheckpoint("wallet:complete");
17532
- if (!wallet) {
17533
- const signatures = await signSafeOnboardingTransactions({
17534
- ...deployed,
17535
- proof_message: initialized.proof_message,
17536
- }, accountOwnerKey);
17537
- wallet = await call("POST", "/v1/wallet/onboarding/complete", {
17538
- account_id: accountId,
17539
- onboarding_id: onboardingId,
17540
- enable_signature: signatures.enableSignature,
17541
- fallback_signature: signatures.fallbackSignature,
17542
- }, {
17543
- idempotencyKey: workflowStageKey(workflowKey, "wallet:complete"),
17544
- retryOnError: false,
17545
- timeoutMs: 240_000,
17546
- });
17547
- if (wallet.ok === false)
17548
- return wallet;
17549
- context.saveCheckpoint("wallet:complete", wallet);
18157
+ // ARC_OWNER_BIND_MCP_20261117: the engine retired the Polygon Safe hub (410 polygon_safe_hub_retired,
18158
+ // b6a7ece28); a new account's wallet is its Arc home. Its device owner is bound with an owner-signed,
18159
+ // single-use challenge (POST /v1/arc-home/owner/challenge, then /v1/arc-home/owner), exactly as the app
18160
+ // does. Accounts whose Polygon Safe steps already completed keep their checkpoints and skip this.
18161
+ const legacyWallet = context.getCheckpoint("wallet:complete");
18162
+ if (!legacyWallet && !context.getCheckpoint("owner:bound")) {
18163
+ const bound = await bindArcHomeOwner(workflowKey, accountId, accountOwnerKey);
18164
+ if (bound.ok === false)
18165
+ return { ...bound, account_id: accountId };
18166
+ context.saveCheckpoint("owner:bound", bound);
17550
18167
  }
17551
18168
  let arcHomeReady = context.getCheckpoint("arc_home:ready");
17552
18169
  if (!arcHomeReady) {
@@ -17816,11 +18433,13 @@ export function makeServer() {
17816
18433
  account_id: accountId,
17817
18434
  wallet_status: "ready",
17818
18435
  custody: "non_custodial",
17819
- deposit_address: wallet.deposit_address,
18436
+ // ARC_OWNER_BIND_MCP_20261117: legacy accounts keep their Polygon Safe facts; new ones fund the
18437
+ // client-held owner address (the Arc home funding gate's address) and their wallet is the Arc home.
18438
+ deposit_address: legacyWallet ? legacyWallet.deposit_address : accountOwnerAddress,
17820
18439
  deposit_address_role: "client_held_account_owner_eoa",
17821
18440
  account_owner_address: accountOwnerAddress,
17822
18441
  account_owner_derivation: "hkdf-sha256/felix-account-owner-v1",
17823
- safe: wallet.safe,
18442
+ safe: legacyWallet ? legacyWallet.safe : confirmedArcHome.safe,
17824
18443
  safe_role: "owner_controlled_policy_wallet",
17825
18444
  arc_home_status: "ready",
17826
18445
  arc_home_safe: confirmedArcHome.safe,