@totalreclaw/mcp-server 3.4.0 → 3.5.0

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.
Files changed (46) hide show
  1. package/README.md +61 -2
  2. package/SKILL.md +1 -1
  3. package/dist/cli/setup.d.ts +10 -0
  4. package/dist/cli/setup.d.ts.map +1 -1
  5. package/dist/cli/setup.js +10 -0
  6. package/dist/cli/setup.js.map +1 -1
  7. package/dist/contradiction-sync.d.ts.map +1 -1
  8. package/dist/contradiction-sync.js +5 -4
  9. package/dist/contradiction-sync.js.map +1 -1
  10. package/dist/embedding-codec.d.ts +81 -0
  11. package/dist/embedding-codec.d.ts.map +1 -0
  12. package/dist/embedding-codec.js +223 -0
  13. package/dist/embedding-codec.js.map +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +289 -47
  16. package/dist/index.js.map +1 -1
  17. package/dist/pair-remote-client.d.ts +41 -0
  18. package/dist/pair-remote-client.d.ts.map +1 -1
  19. package/dist/pair-remote-client.js +130 -32
  20. package/dist/pair-remote-client.js.map +1 -1
  21. package/dist/prompts.d.ts +3 -3
  22. package/dist/prompts.d.ts.map +1 -1
  23. package/dist/prompts.js +2 -2
  24. package/dist/subgraph/bundle.d.ts +129 -0
  25. package/dist/subgraph/bundle.d.ts.map +1 -0
  26. package/dist/subgraph/bundle.js +232 -0
  27. package/dist/subgraph/bundle.js.map +1 -0
  28. package/dist/subgraph/chain-config.d.ts +86 -3
  29. package/dist/subgraph/chain-config.d.ts.map +1 -1
  30. package/dist/subgraph/chain-config.js +71 -2
  31. package/dist/subgraph/chain-config.js.map +1 -1
  32. package/dist/subgraph/credentials.d.ts +83 -0
  33. package/dist/subgraph/credentials.d.ts.map +1 -0
  34. package/dist/subgraph/credentials.js +210 -0
  35. package/dist/subgraph/credentials.js.map +1 -0
  36. package/dist/subgraph/store.d.ts +39 -2
  37. package/dist/subgraph/store.d.ts.map +1 -1
  38. package/dist/subgraph/store.js +44 -12
  39. package/dist/subgraph/store.js.map +1 -1
  40. package/dist/tools/account.d.ts.map +1 -1
  41. package/dist/tools/account.js +6 -0
  42. package/dist/tools/account.js.map +1 -1
  43. package/dist/tools/pair.d.ts.map +1 -1
  44. package/dist/tools/pair.js +63 -0
  45. package/dist/tools/pair.js.map +1 -1
  46. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AA+JA,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAgLA,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,CAAC"}
package/dist/index.js CHANGED
@@ -53,8 +53,11 @@ const embedding_js_1 = require("./subgraph/embedding.js");
53
53
  const reranker_js_1 = require("./subgraph/reranker.js");
54
54
  const store_js_1 = require("./subgraph/store.js");
55
55
  const chain_config_js_1 = require("./subgraph/chain-config.js");
56
+ const credentials_js_1 = require("./subgraph/credentials.js");
57
+ const bundle_js_1 = require("./subgraph/bundle.js");
56
58
  const search_js_1 = require("./subgraph/search.js");
57
59
  const confirm_indexed_js_1 = require("./subgraph/confirm-indexed.js");
60
+ const embedding_codec_js_1 = require("./embedding-codec.js");
58
61
  const contradiction_sync_js_1 = require("./contradiction-sync.js");
59
62
  const pin_js_1 = require("./tools/pin.js");
60
63
  const retype_js_1 = require("./tools/retype.js");
@@ -123,6 +126,19 @@ function buildRelayHeaders(overrides = {}) {
123
126
  headers['X-TotalReclaw-Session'] = sid;
124
127
  return { ...headers, ...overrides };
125
128
  }
129
+ /**
130
+ * Legacy mnemonic-only credential read.
131
+ *
132
+ * **Self-hosted mode ONLY as of Option E Phase 2 (#581, P2-13).** Self-
133
+ * hosted mode reads whatever this returns as a literal `MASTER_PASSWORD`
134
+ * string (see `getClient()` below) — it has no BIP-39 root at all
135
+ * (derived-bundle-v1.md §4.5.1) and must never be routed through bundle
136
+ * detection. Managed-service (subgraph) mode instead calls
137
+ * `resolveManagedCredential()` (`subgraph/credentials.ts`), which
138
+ * understands both the legacy mnemonic shape AND `derived-bundle-v1`
139
+ * `version: 2` bundles. Kept here, unchanged in behaviour, purely as the
140
+ * self-hosted gate — see `main()`.
141
+ */
126
142
  function resolveMnemonic() {
127
143
  // Priority 1: env var
128
144
  if (MASTER_PASSWORD)
@@ -200,12 +216,15 @@ function getMaxCandidatePool(k) {
200
216
  }
201
217
  /**
202
218
  * Build the getSubgraphConfig override for a managed-service write, threading
203
- * the billing-resolved chain + DataEdge onto every on-chain write site (#439).
219
+ * the billing-resolved chain + DataEdge onto every on-chain write site (#439),
220
+ * and the correct signing source (mnemonic vs bundle-mode private key, #581
221
+ * P2-13) onto every on-chain SIGNING site.
204
222
  */
205
223
  function stateWriteOverrides(state) {
206
224
  return (0, chain_config_js_1.buildSubgraphOverrides)({
207
225
  relayUrl: state.serverUrl,
208
226
  mnemonic: state.mnemonic,
227
+ ownerPrivateKeyHex: state.ownerPrivateKeyHex,
209
228
  authKeyHex: Buffer.from(state.authKey).toString('hex'),
210
229
  walletAddress: state.smartAccountAddress,
211
230
  chainId: state.chainId,
@@ -273,34 +292,50 @@ async function initSubgraphState(mnemonic) {
273
292
  // the legacy Free → Base Sepolia (84532) mapping was retired. Consuming the
274
293
  // relay's values verbatim means a future chain move needs zero client release.
275
294
  // (The client `TOTALRECLAW_CHAIN_ID` override was removed in v1.)
276
- let chainId = 100; // Gnosis default when billing is unreachable
277
- let dataEdgeAddress; // undefined ⇒ env/store default
278
- {
279
- try {
280
- const billingUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/billing/status?wallet_address=${encodeURIComponent(smartAccountAddress)}`;
281
- const resp = await fetch(billingUrl, {
282
- method: 'GET',
283
- headers: buildRelayHeaders({
284
- 'Authorization': `Bearer ${authKeyHex}`,
285
- }),
286
- signal: AbortSignal.timeout(5000),
287
- });
288
- if (resp.ok) {
289
- const billing = (await resp.json());
290
- const resolved = (0, chain_config_js_1.resolveChainConfig)(billing);
291
- chainId = resolved.chainId;
292
- dataEdgeAddress = resolved.dataEdgeAddress;
293
- console.error(`TotalReclaw: tier=${billing.tier ?? 'unknown'}, chain=${chainId}` +
294
- (dataEdgeAddress ? `, dataEdge=${dataEdgeAddress}` : '') + '.');
295
- }
296
- }
297
- catch {
298
- // Best-effort — fall back to the Gnosis default if billing is unreachable.
299
- }
295
+ //
296
+ // #581 P2-13: this is now `fetchChainConfig` (subgraph/chain-config.ts) —
297
+ // the SAME function `initSubgraphStateFromBundle` below calls, so there is
298
+ // no code path that can independently "forget" to make this call.
299
+ //
300
+ // Mnemonic mode keeps the pre-existing #439 behaviour on a failed billing
301
+ // lookup: fall back to the Gnosis default / no DataEdge override (the
302
+ // store then falls to env / its own PROD default) rather than blocking
303
+ // startup. #618 adversarial-review fixup: that silent fallback used to
304
+ // have NO log line at all when the billing call failed outright — add
305
+ // one, naming the prod default explicitly, so a mnemonic-mode write that
306
+ // silently lands on production (e.g. a staging run with an unreachable
307
+ // relay and no TOTALRECLAW_DATA_EDGE_ADDRESS override) leaves a trace in
308
+ // stderr instead of looking identical to a normal write.
309
+ const { chainId, dataEdgeAddress, billingResolved } = await (0, chain_config_js_1.fetchChainConfig)({
310
+ serverUrl: SERVER_URL,
311
+ smartAccountAddress,
312
+ authKeyHex,
313
+ headers: buildRelayHeaders(),
314
+ fallbackChainId: 100, // Gnosis default when billing is unreachable
315
+ onResolved: (billing, resolved) => {
316
+ console.error(`TotalReclaw: tier=${billing.tier ?? 'unknown'}, chain=${resolved.chainId}` +
317
+ (resolved.dataEdgeAddress ? `, dataEdge=${resolved.dataEdgeAddress}` : '') + '.');
318
+ },
319
+ onBillingUnavailable: (reason) => {
320
+ console.error(`TotalReclaw: billing lookup failed (${reason}).`);
321
+ },
322
+ });
323
+ if (!billingResolved && !process.env.TOTALRECLAW_DATA_EDGE_ADDRESS) {
324
+ console.error(`TotalReclaw: proceeding without a confirmed DataEdge — writes will target the ` +
325
+ `PRODUCTION default (${store_js_1.DEFAULT_DATA_EDGE_ADDRESS}) unless TOTALRECLAW_DATA_EDGE_ADDRESS ` +
326
+ 'is set. Retry once the relay is reachable if this is not the intended environment.');
300
327
  }
301
328
  // Register auth key with relay (idempotent — relay returns 200 for existing users).
302
329
  // Without this, all relay queries return 401 when using env var mnemonic path
303
330
  // (the setup wizard handles registration, but the env var path previously skipped it).
331
+ //
332
+ // MNEMONIC-MODE ONLY. Bundle-mode construction (`initSubgraphStateFromBundle`)
333
+ // MUST NOT call this — derived-bundle-v1.md §4.5's normative rule: "clients
334
+ // configured from a bundle MUST NOT call POST /v1/register. The vault is
335
+ // registered by the provisioning origin, which holds the root." A bundle
336
+ // client calling register() would be attempting to register with no salt
337
+ // of its own (bundle mode carries none — see the `SubgraphState.salt` doc
338
+ // comment) and would violate the spec even if it somehow succeeded.
304
339
  try {
305
340
  const authKeyHashForReg = (0, crypto_js_1.computeAuthKeyHash)(authKey);
306
341
  const saltHexForReg = Buffer.from(salt).toString('hex');
@@ -313,6 +348,7 @@ async function initSubgraphState(mnemonic) {
313
348
  }
314
349
  return {
315
350
  mode: 'subgraph',
351
+ credentialKind: 'mnemonic',
316
352
  mnemonic,
317
353
  authKey,
318
354
  encryptionKey,
@@ -325,6 +361,130 @@ async function initSubgraphState(mnemonic) {
325
361
  dataEdgeAddress,
326
362
  };
327
363
  }
364
+ /**
365
+ * Initialize subgraph state from an already-validated `derived-bundle-v1`
366
+ * bundle (Option E Phase 2 / #581, P2-13).
367
+ *
368
+ * Contrasts with `initSubgraphState` (mnemonic mode) in exactly the ways
369
+ * derived-bundle-v1.md §4.6 requires:
370
+ *
371
+ * 1. No mnemonic anywhere — the four vault keys come directly from
372
+ * `bundle.vault` (already validated by `parseBundleV1`'s §4.7 checks),
373
+ * never re-derived.
374
+ * 2. `wallet_address` (`smartAccountAddress`) resolves from
375
+ * `bundle.account.smart_account` VERBATIM — no CREATE2 RPC round-trip,
376
+ * no `mnemonicToAccount`/`toSimpleSmartAccount` call. Point 3 of the
377
+ * consumption contract: never re-derive, because the owner EOA may be
378
+ * absent under a future `session-key` bundle.
379
+ * 3. `registerWithServer` is NEVER called — the normative rule in
380
+ * derived-bundle-v1.md §4.5: the provisioning origin, which holds the
381
+ * root, is the only party able to register correctly.
382
+ * 4. Chain/DataEdge resolution still calls `fetchChainConfig` — the exact
383
+ * same function `initSubgraphState` calls above — with `fallbackChainId`
384
+ * seeded from `bundle.account.chain_id` rather than the free-tier
385
+ * default 100. This closes the SKIPPED-BILLING-CALL variant of the bug
386
+ * found in the Hermes round (2026-08-03, S1): an earlier revision
387
+ * treated the bundle's own `chain_id` as sufficient and skipped the
388
+ * billing call entirely, which left `dataEdgeAddress` unset and
389
+ * silently defaulted every write to core's PRODUCTION DataEdge — even
390
+ * when running against a staging relay. The bundle has no
391
+ * `data_edge_address` field at all; that value ONLY ever comes from
392
+ * `/v1/billing/status`. See
393
+ * `python/src/totalreclaw/client.py::from_bundle`'s docstring for the
394
+ * identical bug + fix on the Python side, and
395
+ * `mcp/tests/chain-config.test.ts`'s "REGRESSION (Lesson 1)" test for
396
+ * the automated check.
397
+ *
398
+ * A SIBLING variant survived that fix (#618 adversarial review): the
399
+ * billing call being MADE but FAILING (network error, timeout,
400
+ * non-200) still fell through to the same silent PROD-default outcome,
401
+ * because `fetchChainConfig`'s failure branch always returned
402
+ * `dataEdgeAddress: undefined` with no signal that the fetch itself
403
+ * never succeeded. Below, `billingResolved === false` with no
404
+ * `TOTALRECLAW_DATA_EDGE_ADDRESS` override now throws rather than
405
+ * proceeding — bundle mode has no other way to learn which DataEdge
406
+ * belongs to this environment, so guessing "production" is never
407
+ * acceptable. Mnemonic mode (`initSubgraphState` above) deliberately
408
+ * keeps the pre-existing #439 fallback instead of throwing — a
409
+ * scoped, reviewed decision (loud `console.error` naming the prod
410
+ * default, no throw), not an oversight.
411
+ *
412
+ * Only `signing.kind === "owner-eoa"` is supported (Phase 2's shipping
413
+ * configuration). A `session-key` bundle is parsed and validated fine at
414
+ * the core layer (forward-compatible schema) but this function cannot yet
415
+ * configure a server from one — that lands with the signing-delegation
416
+ * phase (Phase 3). Throws rather than guessing or silently downgrading to
417
+ * `owner-eoa` semantics.
418
+ */
419
+ async function initSubgraphStateFromBundle(bundle) {
420
+ if (bundle.signing.kind !== 'owner-eoa') {
421
+ throw new Error(`derived-bundle-v1: signing.kind=${JSON.stringify(bundle.signing.kind)} is not supported yet — ` +
422
+ 'session-key signing requires the signing-delegation phase (Phase 3). Only ' +
423
+ "'owner-eoa' bundles can configure the MCP server today.");
424
+ }
425
+ const vault = (0, bundle_js_1.bundleVaultToBuffers)(bundle);
426
+ const dims = (0, embedding_js_1.getEmbeddingDims)();
427
+ const lshHasher = new lsh_js_1.LSHHasher(vault.lshSeed, dims);
428
+ // account.smart_account is already resolved — no RPC round-trip, no
429
+ // mnemonic-derived owner. See the docstring above, point 2.
430
+ const smartAccountAddress = bundle.account.smart_account.toLowerCase();
431
+ const authKeyHex = vault.authKey.toString('hex');
432
+ // See the docstring above, point 4 — the load-bearing fix.
433
+ const { chainId, dataEdgeAddress, billingResolved } = await (0, chain_config_js_1.fetchChainConfig)({
434
+ serverUrl: SERVER_URL,
435
+ smartAccountAddress,
436
+ authKeyHex,
437
+ headers: buildRelayHeaders(),
438
+ fallbackChainId: bundle.account.chain_id,
439
+ onResolved: (billing, resolved) => {
440
+ console.error(`TotalReclaw: bundle-mode, tier=${billing.tier ?? 'unknown'}, chain=${resolved.chainId}` +
441
+ (resolved.dataEdgeAddress ? `, dataEdge=${resolved.dataEdgeAddress}` : '') + '.');
442
+ },
443
+ onBillingUnavailable: (reason) => {
444
+ console.error(`TotalReclaw: bundle-mode billing lookup failed (${reason}).`);
445
+ },
446
+ });
447
+ // FAIL CLOSED (#618 adversarial review — the sibling variant of the S1
448
+ // bug, see the docstring above, point 4). A bundle carries no
449
+ // `data_edge_address` of its own — the ONLY source is this billing call.
450
+ // If the call failed outright and no explicit env override exists, this
451
+ // process has literally no confirmed environment to write to. Proceeding
452
+ // would silently fall through to `getSubgraphConfig`'s
453
+ // DEFAULT_DATA_EDGE_ADDRESS, which is the PRODUCTION contract — exactly
454
+ // the outcome this whole function exists to prevent. Refuse to guess.
455
+ // Extracted to `assertDataEdgeResolvable` (chain-config.ts) so this exact
456
+ // decision is directly unit-tested — see the regression test named for
457
+ // it in mcp/tests/chain-config.test.ts.
458
+ (0, chain_config_js_1.assertDataEdgeResolvable)({
459
+ billingResolved,
460
+ envDataEdgeOverride: process.env.TOTALRECLAW_DATA_EDGE_ADDRESS,
461
+ serverUrl: SERVER_URL,
462
+ });
463
+ console.error(`TotalReclaw: configured from derived-bundle-v1 — ${JSON.stringify((0, bundle_js_1.redactedBundleSummary)(bundle))}`);
464
+ // NO registerWithServer() call here — see the docstring above, point 3.
465
+ return {
466
+ mode: 'subgraph',
467
+ credentialKind: 'bundle',
468
+ // `mnemonic` deliberately omitted (not set to `undefined` explicitly) —
469
+ // `SubgraphState.mnemonic` is optional and omission reads back
470
+ // identically to `undefined`. Also keeps the compiled dist/ free of a
471
+ // `mnemonic:` object-key emission for phrase-safety-dist.test.ts's
472
+ // static scanner to flag (it does not special-case an explicit
473
+ // `undefined` value the way its sibling `.recovery_phrase = undefined`
474
+ // allowance does for property-assignment shape).
475
+ ownerPrivateKeyHex: bundle.signing.private_key,
476
+ authKey: vault.authKey,
477
+ encryptionKey: vault.encryptionKey,
478
+ dedupKey: vault.dedupKey,
479
+ // Bundle mode carries no salt — see the SubgraphState.salt doc comment.
480
+ salt: Buffer.alloc(0),
481
+ lshHasher,
482
+ serverUrl: SERVER_URL,
483
+ smartAccountAddress,
484
+ chainId,
485
+ dataEdgeAddress,
486
+ };
487
+ }
328
488
  const clientState = {
329
489
  client: null,
330
490
  userId: null,
@@ -388,27 +548,36 @@ async function saveCredentials(path, credentials) {
388
548
  /**
389
549
  * Encrypt an embedding vector for on-chain storage.
390
550
  *
391
- * Concatenates the float array into a Buffer, encrypts with XChaCha20-Poly1305,
392
- * and returns base64. The subgraph stores this as a string field.
551
+ * The pre-encryption payload is canonical f16 when @totalreclaw/core exposes
552
+ * the codec (encodeEmbeddingPayload returns the canonical base64), else the
553
+ * legacy little-endian f32 packing the MCP server has always used (signaled by
554
+ * the LEGACY_F32_MARKER — the f32→f16 rounding stays in core, never here; see
555
+ * embedding-codec.ts, #479 Part B). Either payload is then XChaCha20-Poly1305
556
+ * encrypted; the subgraph stores the ciphertext as a string field.
393
557
  */
394
558
  function encryptEmbedding(embedding, encryptionKey) {
559
+ const payload = (0, embedding_codec_js_1.encodeEmbeddingPayload)(embedding);
560
+ const preEncryption = payload === embedding_codec_js_1.LEGACY_F32_MARKER ? packLegacyF32(embedding) : payload;
561
+ return (0, crypto_js_1.encrypt)(preEncryption, encryptionKey);
562
+ }
563
+ /** Legacy f32-binary packing (the historical MCP/Python write). */
564
+ function packLegacyF32(embedding) {
395
565
  const buf = Buffer.alloc(embedding.length * 4);
396
566
  for (let i = 0; i < embedding.length; i++) {
397
567
  buf.writeFloatLE(embedding[i], i * 4);
398
568
  }
399
- return (0, crypto_js_1.encrypt)(buf.toString('base64'), encryptionKey);
569
+ return buf.toString('base64');
400
570
  }
401
571
  /**
402
572
  * Decrypt an encrypted embedding back to a number array.
573
+ *
574
+ * Universal decode (#479 Part B): reads canonical f16, legacy JSON array (TS
575
+ * plugin), and legacy f32 binary (old Python / MCP) — so a mixed-client vault
576
+ * no longer silently degrades foreign-format facts to word-index matching.
403
577
  */
404
578
  function decryptEmbedding(encryptedEmbedding, encryptionKey) {
405
- const decryptedBase64 = (0, crypto_js_1.decrypt)(encryptedEmbedding, encryptionKey);
406
- const buf = Buffer.from(decryptedBase64, 'base64');
407
- const floats = [];
408
- for (let i = 0; i < buf.length; i += 4) {
409
- floats.push(buf.readFloatLE(i));
410
- }
411
- return floats;
579
+ const decryptedPayload = (0, crypto_js_1.decrypt)(encryptedEmbedding, encryptionKey);
580
+ return (0, embedding_codec_js_1.decodeEmbeddingUniversal)(decryptedPayload);
412
581
  }
413
582
  /**
414
583
  * Handle remember in subgraph mode: encrypt, generate indices, submit on-chain.
@@ -1399,8 +1568,17 @@ async function accountHandler(args) {
1399
1568
  };
1400
1569
  }
1401
1570
  const authKeyHex = Buffer.from(subgraphState.authKey).toString('hex');
1402
- const words = subgraphState.mnemonic.split(/\s+/);
1403
- const mnemonicHint = `${words[0]} ... ${words[words.length - 1]}`;
1571
+ // #581 P2-13: bundle-mode state has no `mnemonic` (derived-bundle-v1.md
1572
+ // §4.6 point 1 — no code path may reconstruct one), so there is no phrase
1573
+ // to hint at. `.split()` on `undefined` would throw; branch explicitly
1574
+ // instead and surface the credential kind so the agent can tell the user
1575
+ // why no phrase hint is available.
1576
+ const mnemonicHint = subgraphState.credentialKind === 'mnemonic' && subgraphState.mnemonic
1577
+ ? (() => {
1578
+ const words = subgraphState.mnemonic.split(/\s+/);
1579
+ return `${words[0]} ... ${words[words.length - 1]}`;
1580
+ })()
1581
+ : '(no recovery phrase on this host — configured from a derived-bundle-v1 credential)';
1404
1582
  const getFactCount = () => (0, search_js_1.getOwnerFactCount)(subgraphState.smartAccountAddress, subgraphState.serverUrl, authKeyHex);
1405
1583
  return (0, index_js_1.handleAccount)({
1406
1584
  serverUrl: SERVER_URL,
@@ -1506,18 +1684,82 @@ async function main() {
1506
1684
  await showPhrase();
1507
1685
  return;
1508
1686
  }
1509
- // Resolve mnemonic from env var or credentials.json
1510
- const mnemonic = resolveMnemonic();
1511
- currentMode = detectServerMode(mnemonic);
1512
- if (currentMode === 'subgraph' && mnemonic) {
1513
- subgraphState = await initSubgraphState(mnemonic);
1514
- console.error(`TotalReclaw MCP server started (managed service, owner: ${subgraphState.smartAccountAddress})`);
1515
- }
1516
- else if (currentMode === 'http') {
1517
- console.error('TotalReclaw MCP server started (self-hosted mode)');
1687
+ // ── Credential resolution (Option E Phase 2 / #581, P2-13) ─────────────
1688
+ //
1689
+ // Self-hosted mode is a COMPLETELY SEPARATE credential system with no
1690
+ // BIP-39 root at all (derived-bundle-v1.md §4.5.1: self-hosted's `salt`
1691
+ // is random, self-generated, and unrelated to the managed-mode HKDF
1692
+ // salt) — it must NEVER be routed through bundle detection. Gate on it
1693
+ // first and keep its path byte-identical to before this phase:
1694
+ // `resolveMnemonic()` (legacy, mnemonic-only) is still what feeds
1695
+ // self-hosted's `getClient()` login (`MASTER_PASSWORD` read directly from
1696
+ // env there), unchanged.
1697
+ if (process.env.TOTALRECLAW_SELF_HOSTED === 'true') {
1698
+ const mnemonic = resolveMnemonic();
1699
+ currentMode = detectServerMode(mnemonic);
1700
+ if (currentMode === 'http') {
1701
+ console.error('TotalReclaw MCP server started (self-hosted mode)');
1702
+ }
1703
+ else if ((0, credentials_js_1.isV2BundleCredentialsFile)(setup_js_1.CREDENTIALS_PATH)) {
1704
+ // #618 adversarial review, item 2: a bundle credentials.json under
1705
+ // TOTALRECLAW_SELF_HOSTED=true is not "unconfigured" — it's
1706
+ // misconfigured. `derived-bundle-v1` is a managed-mode-only credential
1707
+ // (derived-bundle-v1.md §4.5.1: self-hosted has no BIP-39 root to
1708
+ // derive from at all), and `resolveMnemonic()` correctly finds no
1709
+ // usable mnemonic in it (a v2 file has no top-level `mnemonic` field)
1710
+ // — but telling the operator to "set TOTALRECLAW_RECOVERY_PHRASE" is
1711
+ // actively misleading when the real fix is "unset
1712
+ // TOTALRECLAW_SELF_HOSTED", since the credential they already have IS
1713
+ // valid, just for the other mode. Plain JSON read only — no WASM, no
1714
+ // parseBundleV1 — self-hosted mode must never touch bundle parsing.
1715
+ console.error('TotalReclaw MCP server started (unconfigured) — ~/.totalreclaw/credentials.json is a ' +
1716
+ 'derived-bundle-v1 bundle (version: 2), which is managed-service-only ' +
1717
+ '(docs/specs/totalreclaw/client-consistency.md, "Credential Material"). Self-hosted mode ' +
1718
+ 'has no use for it. Unset TOTALRECLAW_SELF_HOSTED to use this bundle, or configure ' +
1719
+ 'self-hosted mode with its own master password / credentials.');
1720
+ }
1721
+ else {
1722
+ console.error('TotalReclaw MCP server started (unconfigured — set TOTALRECLAW_RECOVERY_PHRASE in the MCP host config; see docs/guides/claude-code-setup.md)');
1723
+ }
1518
1724
  }
1519
1725
  else {
1520
- console.error('TotalReclaw MCP server started (unconfigured — set TOTALRECLAW_RECOVERY_PHRASE in the MCP host config; see docs/guides/claude-code-setup.md)');
1726
+ // Managed-service (subgraph) mode: resolve either a mnemonic OR a
1727
+ // derived-bundle-v1 bundle, per the four-state precedence in
1728
+ // subgraph/credentials.ts (mirrors
1729
+ // python/src/totalreclaw/agent/state.py::_try_auto_configure).
1730
+ let credential;
1731
+ try {
1732
+ credential = (0, credentials_js_1.resolveManagedCredential)();
1733
+ }
1734
+ catch (err) {
1735
+ // Loud, actionable, FATAL — never a silent downgrade. An unknown
1736
+ // credentials.json `version`, a `keychain_wrapped` file this server
1737
+ // can't unwrap, or a bundle that fails §4.7 validation are all
1738
+ // evidence of a corrupted/tampered/misconfigured credential store,
1739
+ // not transient conditions to paper over with a caught exception.
1740
+ // Crashing the process with the error on stderr IS the correct loud
1741
+ // posture for a long-running server — see derived-bundle-v1.md §3.2's
1742
+ // "the one place a well-meaning try/except would create a security
1743
+ // bug" warning, and mcp/tests/credentials.test.ts's coverage of every
1744
+ // one of these throw paths.
1745
+ const msg = err instanceof Error ? err.message : String(err);
1746
+ console.error(`TotalReclaw MCP: fatal credential error: ${msg}`);
1747
+ throw err;
1748
+ }
1749
+ if (credential?.kind === 'bundle') {
1750
+ currentMode = 'subgraph';
1751
+ subgraphState = await initSubgraphStateFromBundle(credential.bundle);
1752
+ console.error(`TotalReclaw MCP server started (managed service, bundle-mode, owner: ${subgraphState.smartAccountAddress})`);
1753
+ }
1754
+ else if (credential?.kind === 'mnemonic' && detectServerMode(credential.mnemonic) === 'subgraph') {
1755
+ currentMode = 'subgraph';
1756
+ subgraphState = await initSubgraphState(credential.mnemonic);
1757
+ console.error(`TotalReclaw MCP server started (managed service, owner: ${subgraphState.smartAccountAddress})`);
1758
+ }
1759
+ else {
1760
+ currentMode = 'unconfigured';
1761
+ console.error('TotalReclaw MCP server started (unconfigured — set TOTALRECLAW_RECOVERY_PHRASE in the MCP host config; see docs/guides/claude-code-setup.md)');
1762
+ }
1521
1763
  }
1522
1764
  // ── Trajectory poller (mcp-server 3.3.0-rc.3) ─────────────────────────
1523
1765
  // Auto-extraction without relying on OpenClaw plugin's `agent_end` hook