felix-mcp 2.0.107 → 2.0.109

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
@@ -14,7 +14,7 @@ identity, creates an encrypted backup, pins the same reviewed package in Claude
14
14
  Code, and verifies the result:
15
15
 
16
16
  ```bash
17
- npx -y --package felix-mcp@2.0.107 felix-keys onboard --accept-terms --client claude
17
+ npx -y --package felix-mcp@2.0.109 felix-keys onboard --accept-terms --client claude
18
18
  ```
19
19
 
20
20
  Requires Node.js 20.10 or newer. The command checks the active runtime before
@@ -27,7 +27,9 @@ code are stored directly in macOS Keychain and are never printed or returned to
27
27
  the MCP client. The encrypted backup is created and authenticated automatically.
28
28
 
29
29
  Restart or reconnect the MCP after onboarding, then call `get_status` and
30
- confirm the client is compatible.
30
+ confirm the client is compatible. Call `get_custody_recovery_status` and
31
+ require `ready: true` before funding; no credential or recovery material is
32
+ returned.
31
33
 
32
34
  Claude Code requires one human action: open `/permissions` and allow the
33
35
  `mcp__felix` tool namespace. Felix cannot grant that permission itself.
@@ -39,7 +41,7 @@ For Claude Desktop:
39
41
  "mcpServers": {
40
42
  "felix": {
41
43
  "command": "npx",
42
- "args": ["-y", "felix-mcp@2.0.107"]
44
+ "args": ["-y", "felix-mcp@2.0.109"]
43
45
  }
44
46
  }
45
47
  }
@@ -109,26 +111,15 @@ can still cause loss. Read the Risk and Custody disclosures before funding.
109
111
 
110
112
  ## Back up the owner
111
113
 
112
- Guided onboarding creates the encrypted backup automatically. Backup and
113
- restore stay outside the MCP tool surface so an AI agent cannot request or
114
- receive private key material. The manual recovery commands are:
114
+ Guided onboarding creates and authenticates the encrypted recovery file in the
115
+ standard local documents folder automatically. The agent does not copy a key,
116
+ choose a password, or ask the user to run another terminal command. Verify it
117
+ with `get_custody_recovery_status`; require `ready: true` before funding.
115
118
 
116
- ```bash
117
- node dist/key-backup.js status
118
- node dist/key-backup.js backup
119
- felix-keys inspect --input ~/Documents/felix-custody-....json
120
- felix-keys verify --input ~/Documents/felix-custody-....json
121
- felix-keys restore --input ~/Documents/felix-custody-....json
122
- ```
123
-
124
- The guided flow generates a high-entropy recovery code and stores it in macOS
125
- Keychain automatically. No human-created backup password is required. For
126
- off-device recovery, a human can run `felix-keys export-recovery-code`; the code
127
- is shown only in a native dialog and never printed. Manual backup accepts a
128
- separate passphrase of at least 16 characters. Felix cannot recover a lost
129
- recovery code, passphrase, or owner key. Restoring a different identity is
130
- refused; use the explicit identity-replacement flow only when you understand
131
- that accounts owned by the previous key may become unreachable.
119
+ The recovery code remains in macOS Keychain and never enters model context.
120
+ Owner-controlled off-device recovery is optional and separate from normal
121
+ onboarding. Felix cannot recover a lost owner key and will not replace an
122
+ existing identity silently.
132
123
 
133
124
  ## Account binding and keys
134
125
 
@@ -146,7 +137,7 @@ authenticates that owner's encrypted money-workflow journal, and changes the
146
137
  session only after both checks pass.
147
138
 
148
139
  Money-workflow journals are encrypted and isolated per owner identity. Existing
149
- pre-2.0.107 journals migrate only after their authentication tag verifies. If a
140
+ pre-2.0.108 journals migrate only after their authentication tag verifies. If a
150
141
  tool returns `operation_state_unavailable`, preserve the journal and restore the
151
142
  matching owner backup; never delete local workflow state or retry an unresolved
152
143
  money action with a new idempotency key.
@@ -13,7 +13,7 @@ the current legal bundle at https://felix.trade/legal before accepting it.
13
13
  Let your AI agent run this single command:
14
14
 
15
15
  ~~~bash
16
- npx -y --package felix-mcp@2.0.107 felix-keys onboard --accept-terms --client claude
16
+ npx -y --package felix-mcp@2.0.109 felix-keys onboard --accept-terms --client claude
17
17
  ~~~
18
18
 
19
19
  After the user reviews the terms and explicitly authorizes acceptance, the agent
@@ -31,15 +31,14 @@ valid registration and matching backup state are reused rather than replaced.
31
31
  Requires Node.js 20.10 or newer. If an old Node is active, onboarding stops
32
32
  before creating or changing any credential and prints the exact installed
33
33
  version. Never put a key or recovery code in a prompt, command-line argument,
34
- environment variable, or chat. For optional off-device recovery, a human may
35
- later run 'felix-keys export-recovery-code'; it shows the code only in a native
36
- dialog and never prints it.
34
+ environment variable, or chat. Optional owner-controlled off-device recovery
35
+ is separate from onboarding and never returns recovery material to the agent.
37
36
 
38
37
  Reconnect the MCP after onboarding. Claude Code also requires one host-level
39
38
  permission: allow the 'mcp__felix' tool namespace. Felix cannot approve its own
40
- tools. Call 'get_status' and confirm
41
- that the API key, owner signer, and client compatibility are healthy before
42
- creating an account.
39
+ tools. Call 'get_status' and confirm that the API key, owner signer, and client
40
+ compatibility are healthy. Then call 'get_custody_recovery_status' and require
41
+ 'ready: true' before creating or funding an account.
43
42
 
44
43
  ### Explore without funds: explicit paper sandbox
45
44
 
@@ -90,8 +89,9 @@ The workflow resumes completed checkpoints and reports whether any money moved.
90
89
  The MCP derives a unique account owner from the local root owner, verifies and
91
90
  signs the exact Safe policy locally, activates the wallet, enables supported
92
91
  venues, mints a least-privilege live key, stores the account binding in
93
- Keychain, and activates it. Back up the root owner before depositing meaningful
94
- funds.
92
+ Keychain, and activates it. Guided onboarding already created the encrypted
93
+ recovery file; require 'get_custody_recovery_status.ready: true' before
94
+ depositing meaningful funds.
95
95
 
96
96
  Registration, key minting, and an unfunded account reservation do not spend
97
97
  chain gas. Felix covers initial wallet-activation gas only after the owner
@@ -197,8 +197,8 @@ allowlist, limit, or expiry before signing.
197
197
 
198
198
  ## Recovery and help
199
199
 
200
- - Missing launcher key: run 'felix-keys register' for a new identity, or
201
- 'felix-keys set-api-key' only for an already-issued key, then reconnect.
200
+ - Missing launcher key on a new device: rerun the pinned guided onboarding
201
+ command, then reconnect. It safely reuses a matching installed identity.
202
202
  - Missing owner key: restore the correct encrypted backup. Never create a new
203
203
  owner for an already-funded account.
204
204
  - Wrong child after reconnect: stop. MCP 2.0.96+ isolates persisted selection
@@ -206,7 +206,7 @@ allowlist, limit, or expiry before signing.
206
206
  reconnect can restore only that session's child. Call 'use_child_account'
207
207
  explicitly and verify 'get_status.mcp.active_account_id' before money work.
208
208
  - Launcher identity changed while the MCP was running: call
209
- 'reload_launcher_key'. MCP 2.0.107+ rereads the current Keychain pair and
209
+ 'reload_launcher_key'. MCP 2.0.108+ rereads the current Keychain pair and
210
210
  authenticates its owner-scoped encrypted money journal before changing the
211
211
  session. If it returns 'operation_state_unavailable', preserve local state
212
212
  and restore the matching owner backup; never delete the journal or invent a
package/dist/index.js CHANGED
@@ -37,6 +37,7 @@ import { policySubmitAmbiguity, policySubmitPending } from "./policy-workflow.js
37
37
  import { executeSafeV3Migration, signSafeMigrationProof } from "./safe-migration.js";
38
38
  import { deriveAccountOwnerPrivateKey, ownerAddressForPrivateKey, ownerPrivateKeyForAccountIdentity, signLiveKeyGrant, signRiskMandate, signSafeOnboardingProof, signSafeOnboardingTransactions, } from "./safe-onboarding.js";
39
39
  import { signDeriveOnboardingTransactions } from "./derive-onboarding.js";
40
+ import { getCustodyRecoveryStatus } from "./key-backup.js";
40
41
  import { clearRuntimeOwnerPrivateKey, getRuntimeOwnerPrivateKey, setRuntimeOwnerPrivateKey, } from "./secret-state.js";
41
42
  import { STRATEGY_CTX_GUIDE, STRATEGY_EXAMPLES, STRATEGY_EXAMPLES_URI, STRATEGY_GUIDE_URI, STRATEGY_RESOURCES, strategyResourceText, } from "./strategy-guide.js";
42
43
  import { AGENT_OPERATIONS_RESOURCES, agentOperationsResourceText, } from "./agent-ops-guide.js";
@@ -107,7 +108,7 @@ export function validatedApiBase(raw = process.env.FELIX_API_URL || `https://${O
107
108
  return parsed.origin;
108
109
  }
109
110
  const API = validatedApiBase();
110
- const MCP_VERSION = "2.0.107";
111
+ const MCP_VERSION = "2.0.109";
111
112
  const PRACTICAL_NO_CAP_USD = 1_000_000_000;
112
113
  const DEFAULT_WALLET_OPERATION_USD = 10_000_000;
113
114
  const DEFAULT_WALLET_DAILY_USD = 100_000_000;
@@ -640,7 +641,7 @@ function readMoneyWorkflowJournal(encryptionKey = moneyWorkflowEncryptionKey(),
640
641
  if (existsSync(freshWorkflowIdentityMarkerPath(ownerKey))) {
641
642
  return empty;
642
643
  }
643
- // One-time compatibility migration for pre-2.0.107 installations. Migration
644
+ // One-time compatibility migration for pre-2.0.108 installations. Migration
644
645
  // is permitted only after the legacy AES-GCM tag authenticates with this
645
646
  // owner. This read remains side-effect-free; the next locked mutation writes
646
647
  // the authenticated state to the scoped path.
@@ -3105,7 +3106,7 @@ async function call(method, path, body, opts = {}) {
3105
3106
  }
3106
3107
  }
3107
3108
  if (!key && !opts.public) {
3108
- return clientError("missing_api_key", "Set FELIX_API_KEY to a Felix fk_ key.", "Store a bootstrap key with felix-keys in a human-operated terminal, then restart the MCP. A manage key can create isolated paper child keys with derive_api_key.");
3109
+ return clientError("missing_api_key", "Set FELIX_API_KEY to a Felix fk_ key.", "Run the pinned felix-keys onboard command, then restart the MCP. It creates the local identity and encrypted recovery file automatically.");
3109
3110
  }
3110
3111
  const idempotencyKey = opts.idempotencyKey || (opts.idempotent ? randomUUID() : undefined);
3111
3112
  const transportAttempts = opts.retryOnError === false ? 1 : (method === "GET" || idempotencyKey ? 2 : 1);
@@ -6726,7 +6727,7 @@ function normalizedPolymarketOrderBody(args) {
6726
6727
  }
6727
6728
  const TOOL_RISK_GROUPS = {
6728
6729
  read: [
6729
- "get_status", "get_health", "get_metrics", "get_strategy_guide",
6730
+ "get_status", "get_health", "get_metrics", "get_custody_recovery_status", "get_strategy_guide",
6730
6731
  "get_market_streaming_guide",
6731
6732
  "search_markets", "list_markets", "get_quote", "get_orderbook", "get_option_chain",
6732
6733
  "research_market", "screen_markets", "get_earnings_calendar",
@@ -6883,6 +6884,11 @@ const TOOLS = [
6883
6884
  description: "Authenticated guide to client-observable reliability fields: request ID, server latency, retry timing, and the public status URL. Process and platform diagnostics are not returned.",
6884
6885
  inputSchema: schema({}),
6885
6886
  },
6887
+ {
6888
+ name: "get_custody_recovery_status",
6889
+ description: "Verify that guided onboarding created an encrypted local recovery file which authenticates to the currently installed owner and launcher identity. Returns status only; no key, recovery code, credential, or file contents are exposed.",
6890
+ inputSchema: schema({}),
6891
+ },
6886
6892
  {
6887
6893
  name: "get_strategy_guide",
6888
6894
  description: `Return the bundled think(ctx) API and hand-written strategy examples without an API key, network request, or generation quota. The same content is published as ${STRATEGY_GUIDE_URI} and ${STRATEGY_EXAMPLES_URI}.`,
@@ -8014,6 +8020,20 @@ export function makeServer() {
8014
8020
  }
8015
8021
  try {
8016
8022
  switch (name) {
8023
+ case "get_custody_recovery_status": {
8024
+ out = isHostedTransport()
8025
+ ? {
8026
+ ok: true,
8027
+ available: false,
8028
+ status: "local_stdio_required",
8029
+ ready: false,
8030
+ secrets_displayed: false,
8031
+ action_required: true,
8032
+ next_step: "Call this tool from the trusted local stdio MCP after guided onboarding.",
8033
+ }
8034
+ : await getCustodyRecoveryStatus();
8035
+ break;
8036
+ }
8017
8037
  case "get_strategy_guide": {
8018
8038
  const section = nonEmptyString(a.section)?.toLowerCase() || "all";
8019
8039
  if (!new Set(["api", "examples", "all"]).has(section)) {
@@ -8048,7 +8068,7 @@ export function makeServer() {
8048
8068
  }
8049
8069
  case "set_api_key": {
8050
8070
  if (!SET_API_KEY_TOOL_ENABLED) {
8051
- out = clientError("tool_disabled", "set_api_key is disabled to keep credentials out of model and tool transcripts.", "Configure the launcher key with felix-keys in a human-operated terminal, then restart or use reload_launcher_key.");
8071
+ out = clientError("tool_disabled", "set_api_key is disabled to keep credentials out of model and tool transcripts.", "Run the pinned felix-keys onboard command, then restart or use reload_launcher_key. Guided onboarding creates and verifies the encrypted recovery file automatically.");
8052
8072
  break;
8053
8073
  }
8054
8074
  else if (isHostedTransport()) {
@@ -11921,7 +11941,7 @@ export function makeServer() {
11921
11941
  note: "After an interruption, retry create_account with the exact same idempotency_key. Felix resumes completed checkpoints instead of creating another account.",
11922
11942
  },
11923
11943
  next_actions: [
11924
- "Back up the local owner identity with felix-keys backup before depositing meaningful funds.",
11944
+ "Call get_custody_recovery_status and require ready:true before depositing meaningful funds.",
11925
11945
  "Send Polygon native USDC or USDC.e to deposit_address, then call get_money_map.",
11926
11946
  ...(deriveDeferred ? [
11927
11947
  "No manual Derive setup is required: the first fund_market call for options completes owner-signed onboarding before moving venue funds.",
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { constants as fsConstants, chmodSync, closeSync, existsSync, fstatSync, fsyncSync, linkSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync, } from "node:fs";
2
+ import { constants as fsConstants, chmodSync, closeSync, copyFileSync, existsSync, fstatSync, fsyncSync, linkSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, } from "node:fs";
3
3
  import { homedir, userInfo } from "node:os";
4
4
  import { basename, delimiter, dirname, join, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -12,6 +12,7 @@ import { markFreshWorkflowIdentity } from "./money-journal-identity.js";
12
12
  export const OWNER_KEYCHAIN_SERVICE = "trade.felix.owner-key.v1";
13
13
  export const API_KEYCHAIN_SERVICE = "trade.felix.api-key.v1";
14
14
  export const BACKUP_RECOVERY_KEYCHAIN_SERVICE = "trade.felix.backup-recovery.v1";
15
+ export const BACKUP_PATH_KEYCHAIN_SERVICE = "trade.felix.backup-path.v1";
15
16
  const BACKUP_FORMAT = "felix-custody-backup";
16
17
  const BACKUP_VERSION = 1;
17
18
  const PRIVATE_KEY_RE = /^0x[0-9a-fA-F]{64}$/;
@@ -393,7 +394,7 @@ function requireInteractiveMac() {
393
394
  throw new Error("Felix Keychain backup currently requires macOS.");
394
395
  }
395
396
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
396
- throw new Error("Run felix-keys directly in a human-operated interactive terminal.");
397
+ throw new Error("This optional owner-recovery command requires an interactive macOS session.");
397
398
  }
398
399
  }
399
400
  function requireNativeMacSession() {
@@ -414,6 +415,119 @@ function defaultBackupPath(ownerAddress) {
414
415
  const day = new Date().toISOString().slice(0, 10);
415
416
  return join(directory, `felix-custody-${ownerAddress.slice(2, 10)}-${day}.json`);
416
417
  }
418
+ function standardBackupDirectory() {
419
+ return existsSync(join(homedir(), "Documents"))
420
+ ? join(homedir(), "Documents") : homedir();
421
+ }
422
+ function guidedBackupCandidates(ownerAddress) {
423
+ const directory = standardBackupDirectory();
424
+ const prefix = `felix-custody-${ownerAddress.slice(2, 10)}-`;
425
+ const candidates = [];
426
+ const storedPath = readKeychainPassword(BACKUP_PATH_KEYCHAIN_SERVICE);
427
+ if (storedPath && storedPath.length <= 4_096 && existsSync(expandPath(storedPath))) {
428
+ candidates.push(expandPath(storedPath));
429
+ }
430
+ const today = defaultBackupPath(ownerAddress);
431
+ if (existsSync(today))
432
+ candidates.push(today);
433
+ try {
434
+ candidates.push(...readdirSync(directory, { withFileTypes: true })
435
+ .filter((entry) => entry.isFile()
436
+ && entry.name.startsWith(prefix)
437
+ && /^felix-custody-[0-9a-fA-F]{8}-\d{4}-\d{2}-\d{2}\.json$/.test(entry.name))
438
+ .map((entry) => join(directory, entry.name)));
439
+ }
440
+ catch { /* Direct-file verification still works when folder listing is denied. */ }
441
+ return [...new Set(candidates)].sort().reverse().slice(0, 16);
442
+ }
443
+ function recoveryStatus(status, overrides = {}) {
444
+ const ready = status === "ready";
445
+ const nextSteps = {
446
+ ready: "none",
447
+ unsupported: "Run guided onboarding on a supported macOS device with Keychain available.",
448
+ identity_incomplete: "Run the pinned felix-keys onboard command; it creates and verifies the missing local identity and recovery file automatically.",
449
+ recovery_material_missing: "Do not fund this identity. Preserve any existing recovery file and restore its matching recovery material before continuing.",
450
+ backup_missing: "Run the pinned felix-keys onboard command again; it will create and authenticate the encrypted recovery file automatically.",
451
+ backup_verification_failed: "Do not fund or rotate this identity. Preserve the existing recovery files and resolve the failed authentication before continuing.",
452
+ };
453
+ return {
454
+ ok: true,
455
+ available: status !== "unsupported",
456
+ status,
457
+ ready,
458
+ automatic_backup: true,
459
+ local_identity_complete: false,
460
+ encrypted_backup_present: false,
461
+ backup_authenticated: false,
462
+ backup_matches_installed_identity: false,
463
+ recovery_material_stored_in_keychain: false,
464
+ secrets_displayed: false,
465
+ action_required: !ready,
466
+ next_step: nextSteps[status],
467
+ ...overrides,
468
+ };
469
+ }
470
+ export async function assessCustodyRecoveryArtifacts(input) {
471
+ const ownerValid = Boolean(input.ownerKey && PRIVATE_KEY_RE.test(input.ownerKey));
472
+ const apiValid = Boolean(input.apiKey && API_KEY_RE.test(input.apiKey));
473
+ if (!ownerValid || !apiValid)
474
+ return recoveryStatus("identity_incomplete");
475
+ const identity = { local_identity_complete: true };
476
+ const candidates = (input.candidatePaths || []).slice(0, 16);
477
+ if (!input.recoveryCode || !isValidBackupRecoveryCode(input.recoveryCode)) {
478
+ return recoveryStatus("recovery_material_missing", {
479
+ ...identity,
480
+ encrypted_backup_present: candidates.length > 0,
481
+ });
482
+ }
483
+ if (candidates.length === 0) {
484
+ return recoveryStatus("backup_missing", {
485
+ ...identity,
486
+ recovery_material_stored_in_keychain: true,
487
+ });
488
+ }
489
+ let authenticated = false;
490
+ for (const candidate of candidates) {
491
+ try {
492
+ const credentials = await openBackupEnvelope(parseBackupEnvelope(readPrivateFile(candidate)), input.recoveryCode);
493
+ authenticated = true;
494
+ if (credentials.root_owner_private_key === input.ownerKey
495
+ && credentials.launcher_api_key === input.apiKey) {
496
+ return recoveryStatus("ready", {
497
+ ...identity,
498
+ encrypted_backup_present: true,
499
+ backup_authenticated: true,
500
+ backup_matches_installed_identity: true,
501
+ recovery_material_stored_in_keychain: true,
502
+ });
503
+ }
504
+ }
505
+ catch {
506
+ // Keep checking bounded candidates; no path or decryption detail is exposed.
507
+ }
508
+ }
509
+ return recoveryStatus("backup_verification_failed", {
510
+ ...identity,
511
+ encrypted_backup_present: true,
512
+ backup_authenticated: authenticated,
513
+ recovery_material_stored_in_keychain: true,
514
+ });
515
+ }
516
+ export async function getCustodyRecoveryStatus() {
517
+ if (process.platform !== "darwin")
518
+ return recoveryStatus("unsupported");
519
+ const ownerKey = readKeychainPassword(OWNER_KEYCHAIN_SERVICE);
520
+ const apiKey = readKeychainPassword(API_KEYCHAIN_SERVICE);
521
+ const recoveryCode = readKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
522
+ const ownerAddress = ownerKey && PRIVATE_KEY_RE.test(ownerKey)
523
+ ? canonicalAddress(ownerKey) : undefined;
524
+ return assessCustodyRecoveryArtifacts({
525
+ ownerKey,
526
+ apiKey,
527
+ recoveryCode,
528
+ candidatePaths: ownerAddress ? guidedBackupCandidates(ownerAddress) : [],
529
+ });
530
+ }
417
531
  export function writePrivateFile(pathValue, contents) {
418
532
  const target = expandPath(pathValue);
419
533
  const parent = dirname(target);
@@ -423,27 +537,79 @@ export function writePrivateFile(pathValue, contents) {
423
537
  throw new Error("Backup destination already exists.");
424
538
  const temporary = join(parentReal, `.${basename(target)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
425
539
  let descriptor;
540
+ let finalDescriptor;
541
+ let directoryDescriptor;
542
+ let destinationCreated = false;
426
543
  try {
427
544
  descriptor = openSync(temporary, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600);
428
545
  writeFileSync(descriptor, contents, { encoding: "utf8" });
429
546
  fsyncSync(descriptor);
430
547
  closeSync(descriptor);
431
548
  descriptor = undefined;
432
- linkSync(temporary, targetResolved);
433
549
  try {
434
- unlinkSync(temporary);
550
+ linkSync(temporary, targetResolved);
551
+ destinationCreated = true;
552
+ }
553
+ catch (error) {
554
+ const code = error.code;
555
+ if (code === "EEXIST")
556
+ throw new Error("Backup destination already exists.");
557
+ if (!new Set(["EPERM", "EOPNOTSUPP", "EXDEV"]).has(String(code)))
558
+ throw error;
559
+ // Some cloud-managed Documents folders reject hard links. COPYFILE_EXCL
560
+ // preserves no-clobber behavior without weakening file permissions.
561
+ try {
562
+ copyFileSync(temporary, targetResolved, fsConstants.COPYFILE_EXCL);
563
+ destinationCreated = true;
564
+ }
565
+ catch (copyError) {
566
+ if (copyError.code === "EEXIST") {
567
+ throw new Error("Backup destination already exists.");
568
+ }
569
+ throw copyError;
570
+ }
435
571
  }
436
- catch { /* final hard link is already durable */ }
437
572
  chmodSync(targetResolved, 0o600);
573
+ finalDescriptor = openSync(targetResolved, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
574
+ fsyncSync(finalDescriptor);
575
+ closeSync(finalDescriptor);
576
+ finalDescriptor = undefined;
577
+ try {
578
+ directoryDescriptor = openSync(parentReal, fsConstants.O_RDONLY);
579
+ fsyncSync(directoryDescriptor);
580
+ closeSync(directoryDescriptor);
581
+ directoryDescriptor = undefined;
582
+ }
583
+ catch (error) {
584
+ if (directoryDescriptor !== undefined)
585
+ closeSync(directoryDescriptor);
586
+ directoryDescriptor = undefined;
587
+ const code = error.code;
588
+ // macOS privacy controls can permit file creation while rejecting a
589
+ // directory descriptor. The completed file itself was already fsynced.
590
+ if (!new Set(["EPERM", "EACCES"]).has(String(code)))
591
+ throw error;
592
+ }
593
+ unlinkSync(temporary);
438
594
  return targetResolved;
439
595
  }
440
596
  catch (error) {
441
597
  if (descriptor !== undefined)
442
598
  closeSync(descriptor);
599
+ if (finalDescriptor !== undefined)
600
+ closeSync(finalDescriptor);
601
+ if (directoryDescriptor !== undefined)
602
+ closeSync(directoryDescriptor);
443
603
  try {
444
604
  unlinkSync(temporary);
445
605
  }
446
606
  catch { /* best effort */ }
607
+ if (destinationCreated) {
608
+ try {
609
+ unlinkSync(targetResolved);
610
+ }
611
+ catch { /* best effort */ }
612
+ }
447
613
  if (error instanceof Error && error.message === "Backup destination already exists.")
448
614
  throw error;
449
615
  throw new Error("Encrypted backup file could not be written.");
@@ -628,7 +794,7 @@ function setupCommand() {
628
794
  if (verified !== ownerKey)
629
795
  throw new Error("Owner Keychain write did not verify.");
630
796
  console.log(`Felix owner key created for ${canonicalAddress(ownerKey)}.`);
631
- console.log("No private key was printed. Configure the launcher API key, then run felix-keys backup.");
797
+ console.log("No private key was printed. Run guided onboarding to register and create the encrypted recovery file automatically.");
632
798
  }
633
799
  catch {
634
800
  try {
@@ -871,7 +1037,7 @@ async function registerCommand(allowExisting = false, agentManaged = false) {
871
1037
  console.log(`Felix account created: ${String(registered.account_id || "")}`);
872
1038
  console.log(`Owner address: ${account.address}`);
873
1039
  console.log(`API key stored in Keychain (prefix ${String(registered.prefix || "")}). The key itself was not printed.`);
874
- console.log("Run felix-keys backup now: losing the owner key means losing the funds, permanently.");
1040
+ console.log("Run guided onboarding to create and authenticate the encrypted recovery file automatically before funding.");
875
1041
  }
876
1042
  async function onboardCommand(client = "claude", output) {
877
1043
  requireNativeMacSession();
@@ -887,7 +1053,7 @@ async function onboardCommand(client = "claude", output) {
887
1053
  let recoveryCode = readKeychainPassword(BACKUP_RECOVERY_KEYCHAIN_SERVICE);
888
1054
  let recoveryCodeCreated = false;
889
1055
  if (recoveryCode && !isValidBackupRecoveryCode(recoveryCode)) {
890
- throw new Error("The Felix backup-recovery Keychain item is invalid. No backup was changed; resolve it in a human-operated terminal.");
1056
+ throw new Error("The Felix backup-recovery Keychain item is invalid. No backup was changed or replaced.");
891
1057
  }
892
1058
  if (existsSync(target)) {
893
1059
  const existing = parseBackupEnvelope(readPrivateFile(target));
@@ -944,15 +1110,31 @@ async function onboardCommand(client = "claude", output) {
944
1110
  throw error;
945
1111
  }
946
1112
  }
1113
+ writeKeychainPassword(BACKUP_PATH_KEYCHAIN_SERVICE, "Felix encrypted-backup path", target);
1114
+ if (readKeychainPassword(BACKUP_PATH_KEYCHAIN_SERVICE) !== target) {
1115
+ throw new Error("The encrypted recovery file was created, but its local status reference did not verify. Rerun guided onboarding; the identity and file were not replaced.");
1116
+ }
947
1117
  const clientState = client === "claude" ? configureClaudeMcp(true) : "skipped";
1118
+ const custodyRecovery = await assessCustodyRecoveryArtifacts({
1119
+ ownerKey,
1120
+ apiKey,
1121
+ recoveryCode,
1122
+ candidatePaths: [target],
1123
+ });
1124
+ if (!custodyRecovery.ready) {
1125
+ throw new Error("The encrypted recovery file did not verify after guided onboarding.");
1126
+ }
1127
+ const publicBackupPath = target.startsWith(`${homedir()}/`)
1128
+ ? `~/${target.slice(homedir().length + 1)}` : basename(target);
948
1129
  console.log(JSON.stringify({
949
1130
  ok: true,
950
1131
  owner_address: ownerAddress,
951
1132
  registration: "ready",
952
1133
  encrypted_backup: backupState,
953
- backup_path: target,
1134
+ backup_path: publicBackupPath,
954
1135
  backup_recovery: "macos_keychain",
955
- portable_recovery_exported: false,
1136
+ custody_recovery: custodyRecovery,
1137
+ off_device_recovery_copy: "optional_not_required_for_onboarding",
956
1138
  mcp_client: client,
957
1139
  mcp_configuration: clientState,
958
1140
  secrets_displayed: false,
@@ -980,9 +1162,9 @@ Usage:
980
1162
  onboard lets an agent complete registration, encrypted backup, MCP client
981
1163
  configuration, and verification after the user explicitly accepts the current
982
1164
  terms. The owner key, API key, and generated recovery code stay in macOS
983
- Keychain and never enter agent output. export-recovery-code is an optional
984
- human-only step for storing recovery material off-device. Manual backup and
985
- restore require a human-operated macOS terminal and native dialogs.
1165
+ Keychain and never enter agent output. No follow-up copy/paste or terminal
1166
+ backup step is required. Optional disaster-recovery export and restore actions
1167
+ remain owner-controlled native dialogs outside the normal agent workflow.
986
1168
  restore refuses to replace a different installed identity; replace is the
987
1169
  explicit identity-rotation command. Passphrases and keys cannot be supplied
988
1170
  through command-line arguments.`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "felix-mcp",
3
- "version": "2.0.107",
3
+ "version": "2.0.109",
4
4
  "mcpName": "trade.felix/mcp",
5
5
  "description": "Non-custodial trading infrastructure for AI agents: one wallet, one risk policy, every market.",
6
6
  "homepage": "https://felix.trade/docs",
@@ -110,7 +110,7 @@
110
110
  "overrides": {
111
111
  "ws": "8.21.0",
112
112
  "axios": "1.18.1",
113
- "fast-uri": "3.1.5",
113
+ "fast-uri": "3.1.6",
114
114
  "hono": "4.13.0",
115
115
  "ip-address": "10.4.0",
116
116
  "@hono/node-server": "2.0.11"
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "trade.felix/mcp",
4
4
  "title": "Felix MCP",
5
5
  "description": "Non-custodial trading infrastructure for AI agents across prediction markets, crypto, and options.",
6
- "version": "2.0.107",
6
+ "version": "2.0.109",
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.107",
28
+ "version": "2.0.109",
29
29
  "transport": {
30
30
  "type": "stdio"
31
31
  }