felix-mcp 2.0.136 → 2.0.138

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/README.md CHANGED
@@ -9,7 +9,7 @@ previews, places and manages orders across crypto perpetuals, prediction
9
9
  markets and options, runs strategies, and moves money between venues, with
10
10
  your keys on your own computer. Orders are live by default.
11
11
 
12
- Package version: `felix-mcp@2.0.136`. Install with `felix-mcp@latest` so you
12
+ Package version: `felix-mcp@2.0.138`. Install with `felix-mcp@latest` so you
13
13
  always run the newest build; `get_status` tells you when an update is out.
14
14
 
15
15
  ## Quick start
@@ -70,7 +70,7 @@ felix-keys --help
70
70
  ```
71
71
 
72
72
  To build from a checkout instead: `npm ci`, `npm pack`, then
73
- `npm install --global ./felix-mcp-2.0.136.tgz`.
73
+ `npm install --global ./felix-mcp-2.0.138.tgz`.
74
74
 
75
75
  ### 2. Set up keys locally
76
76
 
@@ -566,12 +566,13 @@ export function sealedFilesPresent() {
566
566
  * Windows has no such flag, so the path is lstat-ed first and the opened file must be the same file.
567
567
  * A missing file still throws ENOENT so callers keep their "absent" handling.
568
568
  */
569
- export function openReadNoFollow(path) {
569
+ // writable: Windows only flushes a file through a handle opened for writing (fsync on a read-only handle is EPERM).
570
+ export function openReadNoFollow(path, writable = false) {
570
571
  const before = lstatSync(path);
571
572
  if (before.isSymbolicLink()) {
572
573
  throw Object.assign(new Error("Refusing to read a Felix file through a symbolic link."), { code: "ELOOP" });
573
574
  }
574
- const descriptor = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
575
+ const descriptor = openSync(path, (writable ? fsConstants.O_RDWR : fsConstants.O_RDONLY) | (fsConstants.O_NOFOLLOW ?? 0));
575
576
  try {
576
577
  const after = fstatSync(descriptor);
577
578
  if (after.ino !== before.ino || after.dev !== before.dev) {
@@ -18,7 +18,7 @@ then creates the identity and loads it into the session with no restart.
18
18
  Or let your AI agent run this single command:
19
19
 
20
20
  ~~~bash
21
- npx -y --package felix-mcp@2.0.136 felix-keys onboard --accept-terms --client claude
21
+ npx -y --package felix-mcp@2.0.138 felix-keys onboard --accept-terms --client claude
22
22
  ~~~
23
23
 
24
24
  After the user reviews the terms and explicitly authorizes acceptance, the agent
package/dist/index.js CHANGED
@@ -128,7 +128,7 @@ export function validatedApiBase(raw = process.env.FELIX_API_URL || `https://${O
128
128
  return parsed.origin;
129
129
  }
130
130
  const API = validatedApiBase();
131
- const MCP_VERSION = "2.0.136";
131
+ const MCP_VERSION = "2.0.138";
132
132
  // MCP_UPDATE_NOTICE_20261123: a user on an old build hears about it (with the exact command) before a retired
133
133
  // route fails mid-workflow. Only the public npm "latest" record is read; nothing about the user is sent.
134
134
  // Loopback and custom API hosts (tests, staging) stay offline unless FELIX_MCP_UPDATE_URL is set.
@@ -2923,7 +2923,13 @@ export async function executeArcPolygonFunding(amountUsd, minimumUsd, workflowKe
2923
2923
  if (amount === null || (minimumUsd !== undefined && minimum === null)) {
2924
2924
  return markMoneyNotStarted(clientError("invalid_amount", "Amounts must be exact USDC with at most six decimals."));
2925
2925
  }
2926
- return driveArcPolygonFunding({ amount_units: amount, minimum_credit_units: minimum }, buildArcPolygonDeps(workflowKey, context, accountId));
2926
+ const driven = await driveArcPolygonFunding({ amount_units: amount, minimum_credit_units: minimum }, buildArcPolygonDeps(workflowKey, context, accountId));
2927
+ // FUZZ_R2_20261124: a refusal before the first checkpoint (for example no verified Arc home Safe yet) never
2928
+ // reached Felix's funding route, so it is "not started", not "reconciliation required".
2929
+ if (driven.ok === false && driven.status === "refused" && driven.money_moved === false && !context.hasCheckpoints()) {
2930
+ return markMoneyNotStarted(driven);
2931
+ }
2932
+ return driven;
2927
2933
  }
2928
2934
  // ARC_HOME_MONEY_2026_09_24: Arc home Safe money paths, ported from the held
2929
2935
  // 2.0.115 client (ARC_HOME_2026_09_17) and re-checked against the current
@@ -4324,6 +4330,18 @@ const arrayProp = (description, items = {}, extra = {}) => ({
4324
4330
  items,
4325
4331
  ...extra,
4326
4332
  });
4333
+ // XPLAT_E2E_20261124: felix-keys writes one "Felix credentials: <reason>" line on failure. Return that reason to the
4334
+ // agent (secrets scrubbed, bounded) so a failed onboard on any OS says why instead of only "did not complete".
4335
+ export function onboardFailureReason(stderr) {
4336
+ const lines = String(stderr || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
4337
+ const line = [...lines].reverse().find((l) => l.startsWith("Felix credentials:"));
4338
+ if (!line)
4339
+ return undefined;
4340
+ return line.replace(/^Felix credentials:\s*/, "")
4341
+ .replace(/fk_[0-9a-fA-F]{8,}/g, "fk_[redacted]")
4342
+ .replace(/0x[0-9a-fA-F]{64}/g, "0x[redacted]")
4343
+ .slice(0, 300);
4344
+ }
4327
4345
  function clientError(code, message, hint, extra = {}) {
4328
4346
  return {
4329
4347
  ok: false,
@@ -4986,9 +5004,23 @@ function guardFundingPreviewResponse(out, request) {
4986
5004
  const hasSafeErrorContract = out.ok === false || isRecord(out.error);
4987
5005
  const errorFieldsAreSafe = FUNDING_PREVIEW_FALSE_FIELDS.every((field) => out[field] === undefined || out[field] === false);
4988
5006
  if (hasSafeErrorContract) {
4989
- return errorFieldsAreSafe && !fundingPreviewContainsPrivateField(out)
4990
- ? out
4991
- : invalidFundingPreviewResponse();
5007
+ if (!errorFieldsAreSafe || fundingPreviewContainsPrivateField(out))
5008
+ return invalidFundingPreviewResponse();
5009
+ // FUZZ_R2_20261124 (engine 095dc285f): accounts that fund through Felix Home get 409
5010
+ // funding_preview_not_applicable (reason_code home_funded_account) instead of a 502. Steer, never retry.
5011
+ const error = isRecord(out.error) ? out.error : {};
5012
+ const reason = nonEmptyString(error.reason_code) ?? nonEmptyString(out.reason_code);
5013
+ if (error.code === "funding_preview_not_applicable" || reason === "home_funded_account") {
5014
+ return {
5015
+ ...out,
5016
+ error: {
5017
+ ...error,
5018
+ hint: "This account funds venues from its Felix Home, so there is no wallet funding route to preview. Use arc_home_fund_venue to move money from the Home to a venue. Do not retry this preview.",
5019
+ },
5020
+ retryable: false, money_moved: false, next_tool: "arc_home_fund_venue",
5021
+ };
5022
+ }
5023
+ return out;
4992
5024
  }
4993
5025
  const accountId = nonEmptyString(out.account_id);
4994
5026
  const amount = finiteNumber(out.amount_usd);
@@ -7643,14 +7675,98 @@ function closeAmountError(a) {
7643
7675
  return undefined;
7644
7676
  }
7645
7677
  // TWAP_20261123 (Felix Infra 2 spec, engine kit algo1): Felix-run TWAP on the manual-trading key.
7678
+ // ALGO_KINDS_20261124 (engine algo2 13195c4e7): iceberg, scale and trailing_stop share the algo-order routes.
7646
7679
  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.",
7680
+ running: "Orders are being sent as planned. Read get_twap for progress; cancel_twap stops future orders.",
7681
+ completed: "All orders finished.",
7682
+ cancelled: "Stopped. An order that was already being sent at cancel time still counts; read get_twap again in a few seconds for the final filled_usd.",
7650
7683
  failed: "Stopped after three refusals in a row; last_error says why. Nothing more will be sent.",
7651
7684
  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.",
7685
+ reconcile_required: "An order could not be confirmed. Check get_positions and get_fills before any new order; never restart it blind.",
7653
7686
  };
7687
+ const ALGO_KIND_LABEL = { twap: "TWAP", iceberg: "iceberg order", scale: "scale order", trailing_stop: "trailing stop" };
7688
+ function validateAlgoKindArgs(kind, a) {
7689
+ const fail = (message) => clientError("invalid_argument", message, "Nothing was sent.", { money_moved: false, order_sent: false });
7690
+ const instrument = nonEmptyString(a.instrument);
7691
+ const size = finiteNumber(a.size_usd);
7692
+ const key = nonEmptyString(a.idempotency_key);
7693
+ const num = (n) => (a[n] === undefined ? undefined : finiteNumber(a[n]));
7694
+ const bad = (n, ok) => a[n] !== undefined && (num(n) === undefined || !ok(num(n)));
7695
+ if (!instrument || !/^(perp|lighter):[A-Za-z0-9._-]{1,40}$/i.test(instrument))
7696
+ return fail("instrument must be perp:SYM or lighter:SYM.");
7697
+ if (!["buy", "sell"].includes(String(a.side || "").toLowerCase()))
7698
+ return fail("side must be buy or sell.");
7699
+ if (size === undefined || size < 10 || size > PRACTICAL_NO_CAP_USD)
7700
+ return fail("size_usd must be at least 10.");
7701
+ if (bad("slippage_bps", (v) => Number.isInteger(v) && v >= 1 && v <= 10_000))
7702
+ return fail("slippage_bps must be a whole number from 1 to 10000.");
7703
+ if (bad("leverage", (v) => Number.isInteger(v) && v >= 1))
7704
+ return fail("leverage must be a whole number of at least 1.");
7705
+ if (a.reduce_only !== undefined && typeof a.reduce_only !== "boolean")
7706
+ return fail("reduce_only must be true or false.");
7707
+ if (kind === "iceberg") {
7708
+ const clip = num("clip_usd");
7709
+ const limit = num("price_limit");
7710
+ if (clip === undefined || clip < 10)
7711
+ return fail("clip_usd is required for an iceberg and must be at least 10.");
7712
+ if (clip > size)
7713
+ return fail("clip_usd cannot be larger than size_usd.");
7714
+ if (limit === undefined || limit <= 0)
7715
+ return fail("price_limit is required for an iceberg and must be a positive price.");
7716
+ if (bad("clip_interval_seconds", (v) => v >= 5 && v <= 3600))
7717
+ return fail("clip_interval_seconds must be from 5 to 3600.");
7718
+ if (bad("expires_minutes", (v) => v >= 1 && v <= 1440))
7719
+ return fail("expires_minutes for an iceberg must be from 1 to 1440.");
7720
+ }
7721
+ else if (kind === "scale") {
7722
+ const steps = num("steps");
7723
+ const from = num("price_from");
7724
+ const to = num("price_to");
7725
+ if (steps === undefined || !Number.isInteger(steps) || steps < 2 || steps > 50)
7726
+ return fail("steps is required for a scale order and must be a whole number from 2 to 50.");
7727
+ if (from === undefined || from <= 0 || to === undefined || to <= 0)
7728
+ return fail("price_from and price_to are required and must be positive prices.");
7729
+ if (from === to)
7730
+ return fail("price_from and price_to must be different prices.");
7731
+ if (size / steps < 10)
7732
+ return fail(`Each step must be at least $10: ${steps} steps of $${(size / steps).toFixed(2)} is too small. Use fewer steps or a larger size_usd.`);
7733
+ if (bad("expires_minutes", (v) => v >= 1 && v <= 43_200))
7734
+ return fail("expires_minutes must be from 1 to 43200.");
7735
+ }
7736
+ else {
7737
+ const trail = num("trail_percent");
7738
+ if (trail === undefined || trail < 0.1 || trail > 50)
7739
+ return fail("trail_percent is required for a trailing stop and must be from 0.1 to 50 (percent).");
7740
+ if (bad("activation_price", (v) => v > 0))
7741
+ return fail("activation_price must be a positive price.");
7742
+ if (bad("expires_minutes", (v) => v >= 1 && v <= 43_200))
7743
+ return fail("expires_minutes must be from 1 to 43200.");
7744
+ if (a.reduce_only === false)
7745
+ return fail("A trailing stop is always reduce-only; it only closes an existing position.");
7746
+ }
7747
+ if (!key || key.length < 8 || key.length > 128 || /[^\x21-\x7e]/.test(key)) {
7748
+ return clientError("missing_argument", "idempotency_key is required (8-128 printable characters).", `Choose one key per ${ALGO_KIND_LABEL[kind]} and reuse it only to retry the exact same request. Nothing was sent.`, { money_moved: false, order_sent: false });
7749
+ }
7750
+ if (kind !== "trailing_stop" && a.reduce_only !== true && size > maxLocalLiveOrderUsd()) {
7751
+ return clientError("local_safety_cap", `This ${ALGO_KIND_LABEL[kind]}'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 });
7752
+ }
7753
+ return undefined;
7754
+ }
7755
+ function algoKindBody(kind, a) {
7756
+ const pick = (names) => Object.fromEntries(names.filter((n) => a[n] !== undefined).map((n) => [n, Number(a[n])]));
7757
+ return {
7758
+ kind,
7759
+ instrument: String(a.instrument).trim(),
7760
+ side: String(a.side).toLowerCase(),
7761
+ size_usd: Number(a.size_usd),
7762
+ ...(kind === "iceberg" ? pick(["clip_usd", "price_limit", "clip_interval_seconds"]) : {}),
7763
+ ...(kind === "scale" ? pick(["steps", "price_from", "price_to"]) : {}),
7764
+ ...(kind === "trailing_stop" ? pick(["trail_percent", "activation_price"]) : {}),
7765
+ ...pick(["slippage_bps", "expires_minutes", ...(kind === "trailing_stop" ? [] : ["leverage"])]),
7766
+ ...(kind === "trailing_stop" ? { reduce_only: true }
7767
+ : a.reduce_only !== undefined ? { reduce_only: a.reduce_only === true } : {}),
7768
+ };
7769
+ }
7654
7770
  function validateTwapArgs(a) {
7655
7771
  const instrument = nonEmptyString(a.instrument);
7656
7772
  const size = finiteNumber(a.size_usd);
@@ -7689,12 +7805,58 @@ function validateTwapArgs(a) {
7689
7805
  }
7690
7806
  return undefined;
7691
7807
  }
7808
+ // SIMGUARD_20261124: the position's own "mode" ("live" | "paper"), from GET /v1/positions. Undefined when unread.
7809
+ async function positionModeFor(positionId) {
7810
+ const listed = await call("GET", "/v1/positions", undefined, { timeoutMs: 15_000, retryOnError: false });
7811
+ if (listed.ok === false)
7812
+ return undefined;
7813
+ const target = positionId.toLowerCase();
7814
+ for (const [group, rows] of Object.entries(listed)) {
7815
+ if (!Array.isArray(rows))
7816
+ continue;
7817
+ for (const row of rows) {
7818
+ if (!isRecord(row))
7819
+ continue;
7820
+ const id = String(row.position_id ?? row.id ?? "").toLowerCase();
7821
+ if (id !== target)
7822
+ continue;
7823
+ // Key on the row's own mode; the list it sits in is only a fallback.
7824
+ return nonEmptyString(row.mode)?.toLowerCase() ?? (group === "live" || group === "paper" ? group : undefined);
7825
+ }
7826
+ }
7827
+ return undefined;
7828
+ }
7829
+ async function guardExitPlanMode(out, positionId, positionMode, key) {
7830
+ if (out.ok === false) {
7831
+ const error = isRecord(out.error) ? out.error : {};
7832
+ if (/not available for simulation agent positions/i.test(String(error.message || ""))) {
7833
+ return { ...out, retryable: false, money_moved: false,
7834
+ error: { ...error, hint: "Final: this position is a simulation agent position. Do not retry; nothing was changed." } };
7835
+ }
7836
+ return out;
7837
+ }
7838
+ const plan = isRecord(out.exit_plan) ? out.exit_plan : isRecord(out.plan) ? out.plan : out;
7839
+ const planMode = nonEmptyString(plan.mode)?.toLowerCase();
7840
+ if (planMode === "live" && positionMode !== undefined && positionMode !== "live") {
7841
+ const cancelled = await call("DELETE", `/v1/positions/${enc(positionId)}/exit-plan`, undefined, {
7842
+ idempotent: true, idempotencyKey: `${key.slice(0, 100)}-simguard`,
7843
+ });
7844
+ if (cancelled.ok === false) {
7845
+ // Review r1: never say "cancelled" when the cancel itself was not confirmed.
7846
+ return clientError("exit_plan_mode_mismatch", "Felix armed a live exit plan on a simulation position, and this client could not confirm cancelling it.", "Call cancel_exit_plan for this position now, then get_exit_plan to confirm it is gone. Report this to Felix support.", { money_moved: false, retryable: false, position_mode: positionMode, plan_mode: planMode,
7847
+ cancel_confirmed: false, next_tool: "cancel_exit_plan" });
7848
+ }
7849
+ return clientError("exit_plan_mode_mismatch", "Felix armed a live exit plan on a simulation position, so this client cancelled it straight away. No live order was sent.", "Report this to Felix support. Do not retry.", { money_moved: false, retryable: false, position_mode: positionMode, plan_mode: planMode, cancel_confirmed: true });
7850
+ }
7851
+ return out;
7852
+ }
7692
7853
  function describeTwap(record) {
7693
7854
  const status = nonEmptyString(record.status)?.toLowerCase() || "unknown";
7694
7855
  const filled = finiteNumber(record.filled_usd);
7695
7856
  return {
7696
7857
  ...record,
7697
7858
  algo_id: record.algo_id ?? record.id ?? null,
7859
+ kind: nonEmptyString(record.kind) || "twap",
7698
7860
  status,
7699
7861
  final: ["completed", "cancelled", "failed", "expired"].includes(status),
7700
7862
  // An unconfirmed slice may have filled even when filled_usd does not show it yet.
@@ -7710,20 +7872,29 @@ function describeTwap(record) {
7710
7872
  next_action: TWAP_STATUS_TEXT[status] || "Read get_twap again for the current status.",
7711
7873
  };
7712
7874
  }
7713
- function describeTwapResponse(out, phase) {
7875
+ function describeTwapResponse(out, phase, kind = "twap") {
7876
+ const label = ALGO_KIND_LABEL[kind] || "algo order";
7877
+ const httpStatus = finiteNumber(isRecord(out._meta) ? out._meta.http_status : undefined);
7878
+ // Review r1: only a definite refusal (4xx) can be a setup answer; a 5xx or lost answer stays "outcome unknown".
7879
+ if (out.ok === false && phase === "start" && httpStatus !== undefined && httpStatus < 500) {
7880
+ const blocked = withManualTradingBlocker(out);
7881
+ if (blocked !== out)
7882
+ return blocked;
7883
+ }
7714
7884
  if (out.ok === false) {
7715
7885
  const error = isRecord(out.error) ? out.error : {};
7716
7886
  const code = nonEmptyString(error.code) || "";
7717
7887
  const status = finiteNumber(isRecord(out._meta) ? out._meta.http_status : undefined);
7718
7888
  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 };
7889
+ return { ...out, error: { ...error, hint: "An account can run at most 10 algo orders at once. Cancel one with cancel_twap or wait for one to finish. Nothing was started." }, money_moved: false };
7720
7890
  }
7721
7891
  if (phase === "start" && (status === undefined || status >= 500)) {
7722
7892
  // Review r1: call() retries with the same key, so an earlier attempt may have stored the TWAP before this
7723
7893
  // failure (a lost response, then a 503). Never say nothing started.
7724
7894
  return {
7725
7895
  ...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." },
7896
+ // Engine algo2: create is idempotent per (key, Idempotency-Key), so the same key returns the same order.
7897
+ error: { ...error, hint: `Felix did not confirm whether this ${label} started. Retry with the SAME idempotency_key: Felix returns the existing order if it started, and starts it once if it did not. Never use a new key. get_twap with no algo_id lists recent ones.` },
7727
7898
  outcome_unknown: true,
7728
7899
  money_moved: "unknown",
7729
7900
  };
@@ -7734,6 +7905,22 @@ function describeTwapResponse(out, phase) {
7734
7905
  const { _meta: meta, ok: _ok, ...fields } = record;
7735
7906
  return { ok: true, ...describeTwap(fields), ...(isRecord(out._meta) ? { _meta: out._meta } : meta ? { _meta: meta } : {}) };
7736
7907
  }
7908
+ /** Sign the account's manual trading policy (as place_manual_order does), then POST one algo order. */
7909
+ async function startAlgoOrder(body, idempotencyKey) {
7910
+ const kind = String(body.kind || "twap");
7911
+ if (!isHostedTransport()) {
7912
+ const childId = activeChildAccountId();
7913
+ const ownerKey = await arcHomeOwnerKeyFor(childId);
7914
+ if (EVM_PRIVATE_KEY_RE.test(ownerKey)) {
7915
+ const policy = await ensureManualTradingPolicy(childId, ownerKey, childId ? START_KEY : undefined, {});
7916
+ if (policy.ok === false && !manualTradingPolicyNotSupported(policy)) {
7917
+ return withManualTradingBlocker({ ...policy, money_moved: false, order_sent: false });
7918
+ }
7919
+ }
7920
+ }
7921
+ const started = await call("POST", "/v1/manual/algo-orders", body, { idempotent: true, idempotencyKey, timeoutMs: 30_000 });
7922
+ return describeTwapResponse(started, "start", kind);
7923
+ }
7737
7924
  // FUZZ_FIXES_20261123: a user's fuzzing run found results that looked fine but were not what was asked for.
7738
7925
  // Until the engine serves them exactly, the MCP says plainly what was served.
7739
7926
  function withServedResearchShape(out, args) {
@@ -7791,7 +7978,25 @@ function withManualTradingBlocker(out) {
7791
7978
  return out;
7792
7979
  const error = isRecord(out.error) ? out.error : {};
7793
7980
  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);
7981
+ const setupFlag = out.setup_required === true || error.setup_required === true;
7982
+ const code = String(error.code || "").toLowerCase();
7983
+ // SETUP_REQUIRED_20261124 (engine 324be7d16): a 409 {code, setup_required:true}. registration_required is the
7984
+ // only retryable one (Retry-After about 2 s): Felix is still registering the policy it was just given.
7985
+ if ((code === "registration_required" || code === "execution_policy_registration_required")
7986
+ && (setupFlag || error.retryable === true || out.retryable === true)) {
7987
+ return {
7988
+ ...out,
7989
+ error: {
7990
+ ...error,
7991
+ message: "Felix is still registering this account's trading policy, so no order was sent yet.",
7992
+ hint: "Retry the same request with the same idempotency_key in a few seconds. Nothing was sent.",
7993
+ },
7994
+ upstream_error: { code: error.code ?? null, message: error.message ?? null },
7995
+ retryable: true, retry_after_seconds: 2, order_sent: false, money_moved: false,
7996
+ };
7997
+ }
7998
+ const policyBlocked = setupFlag
7999
+ || /arc_home_required|execution_policy_required|execution_policy_expired|registration_required|execution_policy_registration_required|review your trading authorization|execution policy registration could not be confirmed|arc home is not ready/.test(text);
7795
8000
  if (!policyBlocked)
7796
8001
  return out;
7797
8002
  return {
@@ -7802,6 +8007,8 @@ function withManualTradingBlocker(out) {
7802
8007
  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
8008
  },
7804
8009
  upstream_error: { code: error.code ?? null, message: error.message ?? null },
8010
+ setup_required: true,
8011
+ retryable: false,
7805
8012
  order_sent: false,
7806
8013
  money_moved: false,
7807
8014
  };
@@ -12380,7 +12587,7 @@ const TOOL_RISK_GROUPS = {
12380
12587
  trading: [
12381
12588
  "place_order", "place_batch_orders", "cancel_order", "close_position",
12382
12589
  "place_manual_order", "cancel_open_order", "modify_order_price", "close_manual_position",
12383
- "start_twap", "cancel_twap",
12590
+ "start_twap", "start_iceberg", "start_scale_order", "start_trailing_stop", "cancel_twap",
12384
12591
  "set_position_protection", "cancel_position_protection",
12385
12592
  "set_exit_plan", "cancel_exit_plan", "make_market",
12386
12593
  "get_polymarket_order_status", "get_order_status", "reconcile_polymarket_order",
@@ -12664,6 +12871,7 @@ const LIVE_MONEY_TOOLS = new Set([
12664
12871
  "start_capital_move", "transfer_between_venues",
12665
12872
  "place_order", "place_batch_orders", "close_position", "make_market",
12666
12873
  "place_manual_order", "close_manual_position", "modify_order_price", "start_twap",
12874
+ "start_iceberg", "start_scale_order", "start_trailing_stop",
12667
12875
  "swap_native_usdc", "fund_market", "start_fund_market",
12668
12876
  "bring_home", "start_bring_home", "resume_money_operation", "resolve_network_fee",
12669
12877
  "start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return", "fund_polymarket_from_arc",
@@ -13131,7 +13339,7 @@ const TOOLS = [
13131
13339
  asset: stringProp("Canonical Derive underlying returned by get_portfolio_risk.", undefined, { pattern: "^[A-Za-z][A-Za-z0-9]{0,15}$" }),
13132
13340
  metric: stringProp("Net higher-order sensitivity to reduce.", ["gamma", "theta", "vega"]),
13133
13341
  max_size_usd: numberProp("Maximum premium and immediate venue cost budget for each exact candidate preview.", 0.000001, 1_000_000_000),
13134
- target_abs_net: numberProp("Optional absolute-net target in Derive venue-native position-Greek units. Omit to use the owner mandate.", 0, 1_000_000_000_000),
13342
+ target_abs_net: numberProp("Absolute-net target in Derive venue-native position-Greek units. Omit it only when the owner mandate sets a net limit for this Greek; otherwise it is required.", 0, 1_000_000_000_000),
13135
13343
  max_candidates: integerProp("Maximum exact quote previews after bounded chain preselection. Defaults to 4.", 1, 4),
13136
13344
  }, ["asset", "metric", "max_size_usd"]),
13137
13345
  },
@@ -13349,19 +13557,67 @@ const TOOLS = [
13349
13557
  idempotency_key: stringProp("Required retry-safety key (8-128 characters). The same key always means the same TWAP.", undefined, { minLength: 8, maxLength: 128 }),
13350
13558
  }, ["instrument", "side", "size_usd", "duration_minutes", "idempotency_key"]),
13351
13559
  },
13560
+ {
13561
+ name: "start_iceberg",
13562
+ description: "LIVE: buy or sell a total size_usd in clips of clip_usd, one clip on the market at a time. Felix runs it: every clip 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, expires or you cancel_twap. price_limit is required and is a SEND condition, not a fill cap: a buy clip is sent only while the price is at or below it, a sell clip only while it is at or above it. Each fill is bounded by slippage_bps from the quote at send time (default 25). idempotency_key is required; the same key always returns the same order, so after an unclear answer retry with the SAME key. Follow progress with get_twap.",
13563
+ inputSchema: schema({
13564
+ instrument: stringProp("perp:SYM or lighter:SYM, for example perp:BTC.", undefined, { pattern: "^(perp|lighter):[A-Za-z0-9._-]{1,40}$" }),
13565
+ side: stringProp("buy or sell.", ["buy", "sell"]),
13566
+ size_usd: numberProp("Total notional in USD across all clips (at least 10).", 10),
13567
+ clip_usd: numberProp("Size of each clip in USD (at least 10, at most size_usd).", 10),
13568
+ price_limit: numberProp("Required send condition (see description).", 0),
13569
+ slippage_bps: integerProp("Optional worst fill vs the quote at send time for each clip, 1 to 10000 basis points (default 25).", 1, 10_000),
13570
+ clip_interval_seconds: numberProp("Optional wait between clips, 5 to 3600 seconds (default 10).", 5, 3600),
13571
+ expires_minutes: numberProp("Optional: cancel the rest after this many minutes, 1 to 1440 (default 60).", 1, 1440),
13572
+ leverage: integerProp("Optional leverage, default 1, up to the venue maximum.", 1),
13573
+ reduce_only: booleanProp("Only reduce an existing position; never open or flip."),
13574
+ idempotency_key: stringProp("Required retry-safety key (8-128 characters). The same key always means the same order.", undefined, { minLength: 8, maxLength: 128 }),
13575
+ }, ["instrument", "side", "size_usd", "clip_usd", "price_limit", "idempotency_key"]),
13576
+ },
13577
+ {
13578
+ name: "start_scale_order",
13579
+ description: "LIVE: split size_usd into steps equal orders across the price range price_from to price_to. A buy fills from the top level down as the price falls; a sell from the bottom level up as it rises. Felix runs it: each step is a live market order under this key when the price reaches its level, within the key's caps and risk rules, so this moves real money until it completes, expires (default 24 hours) or you cancel_twap. Each fill is bounded by slippage_bps from the quote at send time. Each step must be at least $10. idempotency_key is required; the same key always returns the same order. Follow progress with get_twap.",
13580
+ inputSchema: schema({
13581
+ instrument: stringProp("perp:SYM or lighter:SYM, for example perp:BTC.", undefined, { pattern: "^(perp|lighter):[A-Za-z0-9._-]{1,40}$" }),
13582
+ side: stringProp("buy or sell.", ["buy", "sell"]),
13583
+ size_usd: numberProp("Total notional in USD across all steps (at least $10 per step).", 10),
13584
+ steps: integerProp("Number of equal orders, 2 to 50.", 2, 50),
13585
+ price_from: numberProp("One end of the price range.", 0),
13586
+ price_to: numberProp("The other end of the price range.", 0),
13587
+ slippage_bps: integerProp("Optional worst fill vs the quote at send time for each step, 1 to 10000 basis points.", 1, 10_000),
13588
+ expires_minutes: numberProp("Optional: cancel the rest after this many minutes, 1 to 43200 (default 1440).", 1, 43_200),
13589
+ leverage: integerProp("Optional leverage, default 1, up to the venue maximum.", 1),
13590
+ reduce_only: booleanProp("Only reduce an existing position; never open or flip."),
13591
+ idempotency_key: stringProp("Required retry-safety key (8-128 characters). The same key always means the same order.", undefined, { minLength: 8, maxLength: 128 }),
13592
+ }, ["instrument", "side", "size_usd", "steps", "price_from", "price_to", "idempotency_key"]),
13593
+ },
13594
+ {
13595
+ name: "start_trailing_stop",
13596
+ description: "LIVE: a reduce-only stop that follows the price. side is the side that closes the position (sell closes a long, buy closes a short). Once it is trailing (immediately, or after activation_price is reached), Felix tracks the best price and sends a live reduce-only market close for size_usd if the price comes back by trail_percent from that level. It never opens or flips a position. The fill is bounded by slippage_bps from the quote at send time. Runs until it fires, expires (default 7 days) or you cancel_twap. idempotency_key is required; the same key always returns the same stop. Follow it with get_twap.",
13597
+ inputSchema: schema({
13598
+ instrument: stringProp("perp:SYM or lighter:SYM of the open position, for example perp:BTC.", undefined, { pattern: "^(perp|lighter):[A-Za-z0-9._-]{1,40}$" }),
13599
+ side: stringProp("The closing side: sell closes a long, buy closes a short.", ["buy", "sell"]),
13600
+ size_usd: numberProp("USD notional to close when it fires (at least 10).", 10),
13601
+ trail_percent: numberProp("How far, in percent, the price may come back from its best level before the stop closes (0.1 to 50).", 0.1, 50),
13602
+ activation_price: numberProp("Optional: start trailing only once the price reaches this level.", 0),
13603
+ slippage_bps: integerProp("Optional worst fill vs the quote at send time, 1 to 10000 basis points.", 1, 10_000),
13604
+ expires_minutes: numberProp("Optional: cancel after this many minutes, 1 to 43200 (default 10080).", 1, 43_200),
13605
+ idempotency_key: stringProp("Required retry-safety key (8-128 characters). The same key always means the same stop.", undefined, { minLength: 8, maxLength: 128 }),
13606
+ }, ["instrument", "side", "size_usd", "trail_percent", "idempotency_key"]),
13607
+ },
13352
13608
  {
13353
13609
  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.",
13610
+ description: "Read one algo order (TWAP, iceberg, scale or trailing stop) by algo_id: kind, status, filled_usd, remaining_usd, orders sent and filled, next send time, last error. Omit algo_id to list this account's recent algo orders. Read-only.",
13355
13611
  inputSchema: schema({
13356
- algo_id: stringProp("TWAP id from start_twap. Omit to list recent ones.", undefined, { pattern: UUID_RE.source }),
13612
+ algo_id: stringProp("Algo order id from start_twap, start_iceberg, start_scale_order or start_trailing_stop. Omit to list recent ones.", undefined, { pattern: UUID_RE.source }),
13357
13613
  limit: integerProp("List size, 1 to 100 (default 20).", 1, 100),
13358
13614
  }),
13359
13615
  },
13360
13616
  {
13361
13617
  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.",
13618
+ description: "Stop any running algo order (TWAP, iceberg, scale or trailing stop): nothing new is sent. An order 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 one returns it unchanged. Never opens anything.",
13363
13619
  inputSchema: schema({
13364
- algo_id: stringProp("TWAP id from start_twap.", undefined, { pattern: UUID_RE.source }),
13620
+ algo_id: stringProp("Algo order id from any start_ algo tool.", undefined, { pattern: UUID_RE.source }),
13365
13621
  }, ["algo_id"]),
13366
13622
  },
13367
13623
  {
@@ -15140,10 +15396,12 @@ export function makeServer() {
15140
15396
  let stdout = "";
15141
15397
  child.stdout.on("data", (chunk) => { if (stdout.length < 256 * 1024)
15142
15398
  stdout += String(chunk); });
15143
- child.stderr.on("data", () => { });
15399
+ let stderr = "";
15400
+ child.stderr.on("data", (chunk) => { if (stderr.length < 16 * 1024)
15401
+ stderr += String(chunk); });
15144
15402
  const timer = setTimeout(() => child.kill("SIGTERM"), 300_000);
15145
- child.on("error", () => { clearTimeout(timer); resolveRun({ code: -1, stdout }); });
15146
- child.on("close", (code) => { clearTimeout(timer); resolveRun({ code, stdout }); });
15403
+ child.on("error", () => { clearTimeout(timer); resolveRun({ code: -1, stdout, stderr }); });
15404
+ child.on("close", (code) => { clearTimeout(timer); resolveRun({ code, stdout, stderr }); });
15147
15405
  });
15148
15406
  const at = run.stdout.lastIndexOf('{\n "ok": true');
15149
15407
  let summary;
@@ -15158,7 +15416,7 @@ export function makeServer() {
15158
15416
  if (!summary || summary.ok !== true) {
15159
15417
  out = clientError("onboarding_failed", consent === "relayed_with_mac_click" && run.code !== 0
15160
15418
  ? "Onboarding stopped: the on-screen confirmation was cancelled or setup failed. Nothing was replaced."
15161
- : "Felix onboarding did not complete. Nothing was replaced.", "Check felix-keys status in Terminal. Never create a second identity if one already exists.");
15419
+ : "Felix onboarding did not complete. Nothing was replaced.", "Check felix-keys status in Terminal. Never create a second identity if one already exists.", { reason: onboardFailureReason(run.stderr), money_moved: false });
15162
15420
  break;
15163
15421
  }
15164
15422
  reportProgress(2, 3, "Loading the new identity into this session.");
@@ -16656,6 +16914,9 @@ export function makeServer() {
16656
16914
  },
16657
16915
  };
16658
16916
  }
16917
+ else {
16918
+ out = withManualTradingBlocker(out);
16919
+ }
16659
16920
  }
16660
16921
  if (signedTradingPolicy)
16661
16922
  out = { ...out, trading_policy: signedTradingPolicy };
@@ -16686,23 +16947,15 @@ export function makeServer() {
16686
16947
  ...(a.reduce_only !== undefined ? { reduce_only: a.reduce_only === true } : {}),
16687
16948
  ...(a.price_limit !== undefined ? { price_limit: Number(a.price_limit) } : {}),
16688
16949
  };
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");
16950
+ // Review r1: the slices are manual orders, so the trading policy is signed first, like place_manual_order.
16951
+ out = await startAlgoOrder(body, String(a.idempotency_key));
16952
+ break;
16953
+ }
16954
+ case "start_iceberg":
16955
+ case "start_scale_order":
16956
+ case "start_trailing_stop": {
16957
+ const kind = name === "start_iceberg" ? "iceberg" : name === "start_scale_order" ? "scale" : "trailing_stop";
16958
+ out = validateAlgoKindArgs(kind, a) || await startAlgoOrder(algoKindBody(kind, a), String(a.idempotency_key));
16706
16959
  break;
16707
16960
  }
16708
16961
  case "get_twap": {
@@ -16723,7 +16976,7 @@ export function makeServer() {
16723
16976
  const rows = Array.isArray(listed.algo_orders) ? listed.algo_orders
16724
16977
  : Array.isArray(listed.items) ? listed.items : Array.isArray(listed.orders) ? listed.orders : [];
16725
16978
  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 };
16979
+ out = { ok: true, twaps, count: twaps.length, running: twaps.filter((row) => row.final !== true && row.status !== "reconcile_required").length };
16727
16980
  }
16728
16981
  break;
16729
16982
  }
@@ -16955,12 +17208,18 @@ export function makeServer() {
16955
17208
  const badPosition = validateUuid(a, "position_id");
16956
17209
  const badPlan = validateExitPlanArgs(a);
16957
17210
  const key = nonEmptyString(a.idempotency_key);
16958
- out = badPosition || badPlan || (!key
16959
- ? clientError("missing_argument", "idempotency_key is required for set_exit_plan.")
16960
- : await call("PUT", `/v1/positions/${enc(a.position_id)}/exit-plan`, exitPlanBody(a), {
16961
- idempotent: true,
16962
- idempotencyKey: key,
16963
- }));
17211
+ if (badPosition || badPlan || !key) {
17212
+ out = badPosition || badPlan || clientError("missing_argument", "idempotency_key is required for set_exit_plan.");
17213
+ break;
17214
+ }
17215
+ // SIMGUARD_20261124 (engine c9db2a5dd): a plan armed on a simulation position must never take the live path.
17216
+ // The engine refuses it; this client also checks the position's own mode against the plan it gets back.
17217
+ const positionMode = await positionModeFor(String(a.position_id));
17218
+ out = await call("PUT", `/v1/positions/${enc(a.position_id)}/exit-plan`, exitPlanBody(a), {
17219
+ idempotent: true,
17220
+ idempotencyKey: key,
17221
+ });
17222
+ out = await guardExitPlanMode(out, String(a.position_id), positionMode, key);
16964
17223
  break;
16965
17224
  }
16966
17225
  case "get_exit_plan":
@@ -535,26 +535,29 @@ export function writePrivateFile(pathValue, contents) {
535
535
  }
536
536
  }
537
537
  chmodSync(targetResolved, 0o600);
538
- finalDescriptor = openReadNoFollow(targetResolved);
538
+ // XPLAT_E2E_20261124: Windows flushes only through a writable handle and cannot open a directory to fsync it
539
+ // (NTFS journals the directory entry itself). Before this, every Windows backup write failed and onboarding stopped.
540
+ finalDescriptor = openReadNoFollow(targetResolved, process.platform === "win32");
539
541
  fsyncSync(finalDescriptor);
540
542
  closeSync(finalDescriptor);
541
543
  finalDescriptor = undefined;
542
- try {
543
- directoryDescriptor = openSync(parentReal, fsConstants.O_RDONLY);
544
- fsyncSync(directoryDescriptor);
545
- closeSync(directoryDescriptor);
546
- directoryDescriptor = undefined;
547
- }
548
- catch (error) {
549
- if (directoryDescriptor !== undefined)
544
+ if (process.platform !== "win32")
545
+ try {
546
+ directoryDescriptor = openSync(parentReal, fsConstants.O_RDONLY);
547
+ fsyncSync(directoryDescriptor);
550
548
  closeSync(directoryDescriptor);
551
- directoryDescriptor = undefined;
552
- const code = error.code;
553
- // macOS privacy controls can permit file creation while rejecting a
554
- // directory descriptor. The completed file itself was already fsynced.
555
- if (!new Set(["EPERM", "EACCES"]).has(String(code)))
556
- throw error;
557
- }
549
+ directoryDescriptor = undefined;
550
+ }
551
+ catch (error) {
552
+ if (directoryDescriptor !== undefined)
553
+ closeSync(directoryDescriptor);
554
+ directoryDescriptor = undefined;
555
+ const code = error.code;
556
+ // macOS privacy controls can permit file creation while rejecting a
557
+ // directory descriptor. The completed file itself was already fsynced.
558
+ if (!new Set(["EPERM", "EACCES"]).has(String(code)))
559
+ throw error;
560
+ }
558
561
  unlinkSync(temporary);
559
562
  return targetResolved;
560
563
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "felix-mcp",
3
- "version": "2.0.136",
3
+ "version": "2.0.138",
4
4
  "mcpName": "trade.felix/mcp",
5
5
  "description": "Agentic trading infrastructure for everyone: crypto perpetuals, prediction markets and options for AI agents.",
6
6
  "homepage": "https://felix.trade/docs",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "trade.felix/mcp",
4
4
  "title": "Felix MCP",
5
5
  "description": "Agentic trading infrastructure for everyone: crypto perpetuals, prediction markets and options.",
6
- "version": "2.0.136",
6
+ "version": "2.0.138",
7
7
  "websiteUrl": "https://felix.trade/docs",
8
8
  "icons": [
9
9
  {
@@ -25,7 +25,7 @@
25
25
  {
26
26
  "registryType": "npm",
27
27
  "identifier": "felix-mcp",
28
- "version": "2.0.136",
28
+ "version": "2.0.138",
29
29
  "transport": {
30
30
  "type": "stdio"
31
31
  }