@totalreclaw/mcp-server 3.3.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 (152) hide show
  1. package/README.md +61 -2
  2. package/SKILL.md +1 -1
  3. package/dist/claims-helper.d.ts +1 -1
  4. package/dist/claims-helper.d.ts.map +1 -1
  5. package/dist/claims-helper.js +31 -31
  6. package/dist/claims-helper.js.map +1 -1
  7. package/dist/cli/setup.d.ts +10 -0
  8. package/dist/cli/setup.d.ts.map +1 -1
  9. package/dist/cli/setup.js +15 -5
  10. package/dist/cli/setup.js.map +1 -1
  11. package/dist/consolidation.d.ts +3 -5
  12. package/dist/consolidation.d.ts.map +1 -1
  13. package/dist/consolidation.js +47 -122
  14. package/dist/consolidation.js.map +1 -1
  15. package/dist/contradiction-sync.d.ts +2 -2
  16. package/dist/contradiction-sync.d.ts.map +1 -1
  17. package/dist/contradiction-sync.js +17 -16
  18. package/dist/contradiction-sync.js.map +1 -1
  19. package/dist/dispatch.d.ts +95 -0
  20. package/dist/dispatch.d.ts.map +1 -0
  21. package/dist/dispatch.js +191 -0
  22. package/dist/dispatch.js.map +1 -0
  23. package/dist/embedding-codec.d.ts +81 -0
  24. package/dist/embedding-codec.d.ts.map +1 -0
  25. package/dist/embedding-codec.js +223 -0
  26. package/dist/embedding-codec.js.map +1 -0
  27. package/dist/extraction/extractor.d.ts +1 -0
  28. package/dist/extraction/extractor.d.ts.map +1 -1
  29. package/dist/extraction/extractor.js +15 -15
  30. package/dist/extraction/extractor.js.map +1 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +484 -767
  33. package/dist/index.js.map +1 -1
  34. package/dist/pair-remote-client.d.ts +41 -0
  35. package/dist/pair-remote-client.d.ts.map +1 -1
  36. package/dist/pair-remote-client.js +130 -32
  37. package/dist/pair-remote-client.js.map +1 -1
  38. package/dist/prompts.d.ts +3 -4
  39. package/dist/prompts.d.ts.map +1 -1
  40. package/dist/prompts.js +3 -9
  41. package/dist/prompts.js.map +1 -1
  42. package/dist/server-setup.d.ts +35 -0
  43. package/dist/server-setup.d.ts.map +1 -0
  44. package/dist/server-setup.js +102 -0
  45. package/dist/server-setup.js.map +1 -0
  46. package/dist/subgraph/bundle.d.ts +129 -0
  47. package/dist/subgraph/bundle.d.ts.map +1 -0
  48. package/dist/subgraph/bundle.js +232 -0
  49. package/dist/subgraph/bundle.js.map +1 -0
  50. package/dist/subgraph/chain-config.d.ts +128 -0
  51. package/dist/subgraph/chain-config.d.ts.map +1 -0
  52. package/dist/subgraph/chain-config.js +135 -0
  53. package/dist/subgraph/chain-config.js.map +1 -0
  54. package/dist/subgraph/credentials.d.ts +83 -0
  55. package/dist/subgraph/credentials.d.ts.map +1 -0
  56. package/dist/subgraph/credentials.js +210 -0
  57. package/dist/subgraph/credentials.js.map +1 -0
  58. package/dist/subgraph/search.js +13 -13
  59. package/dist/subgraph/search.js.map +1 -1
  60. package/dist/subgraph/store.d.ts +39 -2
  61. package/dist/subgraph/store.d.ts.map +1 -1
  62. package/dist/subgraph/store.js +48 -13
  63. package/dist/subgraph/store.js.map +1 -1
  64. package/dist/tools/account.d.ts +5 -2
  65. package/dist/tools/account.d.ts.map +1 -1
  66. package/dist/tools/account.js +17 -4
  67. package/dist/tools/account.js.map +1 -1
  68. package/dist/tools/consolidate.d.ts +2 -2
  69. package/dist/tools/consolidate.d.ts.map +1 -1
  70. package/dist/tools/consolidate.js +2 -1
  71. package/dist/tools/consolidate.js.map +1 -1
  72. package/dist/tools/debrief.d.ts +2 -2
  73. package/dist/tools/debrief.d.ts.map +1 -1
  74. package/dist/tools/debrief.js +2 -1
  75. package/dist/tools/debrief.js.map +1 -1
  76. package/dist/tools/export.d.ts +2 -2
  77. package/dist/tools/export.d.ts.map +1 -1
  78. package/dist/tools/export.js +2 -1
  79. package/dist/tools/export.js.map +1 -1
  80. package/dist/tools/forget.d.ts +8 -2
  81. package/dist/tools/forget.d.ts.map +1 -1
  82. package/dist/tools/forget.js +14 -7
  83. package/dist/tools/forget.js.map +1 -1
  84. package/dist/tools/helpers.d.ts +40 -0
  85. package/dist/tools/helpers.d.ts.map +1 -0
  86. package/dist/tools/helpers.js +64 -0
  87. package/dist/tools/helpers.js.map +1 -0
  88. package/dist/tools/import-batch.d.ts +2 -1
  89. package/dist/tools/import-batch.d.ts.map +1 -1
  90. package/dist/tools/import-batch.js +1 -1
  91. package/dist/tools/import-batch.js.map +1 -1
  92. package/dist/tools/import-from.d.ts +2 -2
  93. package/dist/tools/import-from.d.ts.map +1 -1
  94. package/dist/tools/import-from.js +2 -1
  95. package/dist/tools/import-from.js.map +1 -1
  96. package/dist/tools/import.d.ts +2 -2
  97. package/dist/tools/import.d.ts.map +1 -1
  98. package/dist/tools/import.js +4 -3
  99. package/dist/tools/import.js.map +1 -1
  100. package/dist/tools/index.d.ts +2 -2
  101. package/dist/tools/index.d.ts.map +1 -1
  102. package/dist/tools/index.js +7 -9
  103. package/dist/tools/index.js.map +1 -1
  104. package/dist/tools/pair.d.ts +2 -1
  105. package/dist/tools/pair.d.ts.map +1 -1
  106. package/dist/tools/pair.js +67 -4
  107. package/dist/tools/pair.js.map +1 -1
  108. package/dist/tools/pin.d.ts +10 -7
  109. package/dist/tools/pin.d.ts.map +1 -1
  110. package/dist/tools/pin.js +43 -49
  111. package/dist/tools/pin.js.map +1 -1
  112. package/dist/tools/recall.d.ts +2 -2
  113. package/dist/tools/recall.d.ts.map +1 -1
  114. package/dist/tools/recall.js +22 -47
  115. package/dist/tools/recall.js.map +1 -1
  116. package/dist/tools/remember.d.ts +2 -2
  117. package/dist/tools/remember.d.ts.map +1 -1
  118. package/dist/tools/remember.js +30 -48
  119. package/dist/tools/remember.js.map +1 -1
  120. package/dist/tools/retype.d.ts +6 -1
  121. package/dist/tools/retype.d.ts.map +1 -1
  122. package/dist/tools/retype.js +37 -33
  123. package/dist/tools/retype.js.map +1 -1
  124. package/dist/tools/set-scope.d.ts +6 -1
  125. package/dist/tools/set-scope.d.ts.map +1 -1
  126. package/dist/tools/set-scope.js +14 -10
  127. package/dist/tools/set-scope.js.map +1 -1
  128. package/dist/tools/status.d.ts +2 -1
  129. package/dist/tools/status.d.ts.map +1 -1
  130. package/dist/tools/status.js +14 -12
  131. package/dist/tools/status.js.map +1 -1
  132. package/dist/tools/support.d.ts +5 -3
  133. package/dist/tools/support.d.ts.map +1 -1
  134. package/dist/tools/support.js +9 -8
  135. package/dist/tools/support.js.map +1 -1
  136. package/dist/tools/types.d.ts +38 -0
  137. package/dist/tools/types.d.ts.map +1 -0
  138. package/dist/tools/types.js +17 -0
  139. package/dist/tools/types.js.map +1 -0
  140. package/dist/tools/upgrade.d.ts +2 -1
  141. package/dist/tools/upgrade.d.ts.map +1 -1
  142. package/dist/tools/upgrade.js +6 -4
  143. package/dist/tools/upgrade.js.map +1 -1
  144. package/package.json +3 -4
  145. package/dist/subgraph/index.d.ts +0 -7
  146. package/dist/subgraph/index.d.ts.map +0 -1
  147. package/dist/subgraph/index.js +0 -23
  148. package/dist/subgraph/index.js.map +0 -1
  149. package/dist/tools/migrate.d.ts +0 -88
  150. package/dist/tools/migrate.d.ts.map +0 -1
  151. package/dist/tools/migrate.js +0 -273
  152. package/dist/tools/migrate.js.map +0 -1
package/dist/index.js CHANGED
@@ -38,31 +38,33 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
38
  };
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
40
  exports.getSessionId = void 0;
41
- const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
42
41
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
43
- const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
44
42
  const client_1 = require("@totalreclaw/client");
45
- const index_js_2 = require("./tools/index.js");
43
+ const index_js_1 = require("./tools/index.js");
46
44
  const status_js_1 = require("./tools/status.js");
47
- const remember_js_1 = require("./tools/remember.js");
48
45
  const consolidation_js_1 = require("./consolidation.js");
49
- const prompts_js_1 = require("./prompts.js");
50
- const index_js_3 = require("./resources/index.js");
46
+ const index_js_2 = require("./resources/index.js");
47
+ const server_setup_js_1 = require("./server-setup.js");
48
+ const dispatch_js_1 = require("./dispatch.js");
51
49
  // Subgraph imports (lazy usage -- only when managed service is active)
52
50
  const crypto_js_1 = require("./subgraph/crypto.js");
53
51
  const lsh_js_1 = require("./subgraph/lsh.js");
54
52
  const embedding_js_1 = require("./subgraph/embedding.js");
55
53
  const reranker_js_1 = require("./subgraph/reranker.js");
56
54
  const store_js_1 = require("./subgraph/store.js");
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");
57
58
  const search_js_1 = require("./subgraph/search.js");
58
59
  const confirm_indexed_js_1 = require("./subgraph/confirm-indexed.js");
60
+ const embedding_codec_js_1 = require("./embedding-codec.js");
59
61
  const contradiction_sync_js_1 = require("./contradiction-sync.js");
60
62
  const pin_js_1 = require("./tools/pin.js");
61
63
  const retype_js_1 = require("./tools/retype.js");
62
64
  const set_scope_js_1 = require("./tools/set-scope.js");
63
65
  const claims_helper_js_1 = require("./claims-helper.js");
64
66
  const memory_types_js_1 = require("./memory-types.js");
65
- const remember_js_2 = require("./tools/remember.js");
67
+ const remember_js_1 = require("./tools/remember.js");
66
68
  const bip39_1 = require("@scure/bip39");
67
69
  const english_js_1 = require("@scure/bip39/wordlists/english.js");
68
70
  const accounts_1 = require("viem/accounts");
@@ -124,14 +126,27 @@ function buildRelayHeaders(overrides = {}) {
124
126
  headers['X-TotalReclaw-Session'] = sid;
125
127
  return { ...headers, ...overrides };
126
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
+ */
127
142
  function resolveMnemonic() {
128
143
  // Priority 1: env var
129
144
  if (MASTER_PASSWORD)
130
145
  return MASTER_PASSWORD.trim();
131
146
  // Priority 2: credentials.json mnemonic field
132
147
  try {
133
- const data = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
134
- const parsed = JSON.parse(data);
148
+ const credentialsRaw = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
149
+ const parsed = JSON.parse(credentialsRaw);
135
150
  if (parsed.mnemonic && typeof parsed.mnemonic === 'string') {
136
151
  const trimmed = parsed.mnemonic.trim();
137
152
  const words = trimmed.split(/\s+/);
@@ -199,6 +214,23 @@ function getMaxCandidatePool(k) {
199
214
  // Fallback to local formula
200
215
  return Math.max(k * 50, 400);
201
216
  }
217
+ /**
218
+ * Build the getSubgraphConfig override for a managed-service write, threading
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.
222
+ */
223
+ function stateWriteOverrides(state) {
224
+ return (0, chain_config_js_1.buildSubgraphOverrides)({
225
+ relayUrl: state.serverUrl,
226
+ mnemonic: state.mnemonic,
227
+ ownerPrivateKeyHex: state.ownerPrivateKeyHex,
228
+ authKeyHex: Buffer.from(state.authKey).toString('hex'),
229
+ walletAddress: state.smartAccountAddress,
230
+ chainId: state.chainId,
231
+ dataEdgeAddress: state.dataEdgeAddress,
232
+ });
233
+ }
202
234
  let subgraphState = null;
203
235
  /**
204
236
  * Detect server mode based on environment configuration.
@@ -254,37 +286,56 @@ async function initSubgraphState(mnemonic) {
254
286
  },
255
287
  });
256
288
  const smartAccountAddress = smartAccount.address.toLowerCase();
257
- // Determine chain ID: always auto-detect from billing tier.
258
- // Free tier → Base Sepolia (84532, testnet — Pimlico sponsors gas for free).
259
- // Pro tier → Gnosis mainnet (100, permanent on-chain storage).
260
- // TOTALRECLAW_CHAIN_ID user-facing override was removed in v1.
261
- let chainId = 84532; // default free tier
262
- // Auto-detect Pro tier from billing endpoint.
263
- {
264
- try {
265
- const billingUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/billing/status?wallet_address=${encodeURIComponent(smartAccountAddress)}`;
266
- const resp = await fetch(billingUrl, {
267
- method: 'GET',
268
- headers: buildRelayHeaders({
269
- 'Authorization': `Bearer ${authKeyHex}`,
270
- }),
271
- signal: AbortSignal.timeout(5000),
272
- });
273
- if (resp.ok) {
274
- const billing = (await resp.json());
275
- if (billing.tier === 'pro') {
276
- chainId = 100;
277
- console.error('TotalReclaw: Pro tier detected — using Gnosis mainnet (chain 100).');
278
- }
279
- }
280
- }
281
- catch {
282
- // Best-effort — default to free tier chain if billing is unreachable.
283
- }
289
+ // Resolve chain + DataEdge from the relay's billing response, verbatim (#439).
290
+ // The relay is authoritative: it returns `chain_id` + `data_edge_address` in
291
+ // GET /v1/billing/status. After ops-1 both tiers run on Gnosis (chain 100);
292
+ // the legacy Free → Base Sepolia (84532) mapping was retired. Consuming the
293
+ // relay's values verbatim means a future chain move needs zero client release.
294
+ // (The client `TOTALRECLAW_CHAIN_ID` override was removed in v1.)
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.');
284
327
  }
285
328
  // Register auth key with relay (idempotent — relay returns 200 for existing users).
286
329
  // Without this, all relay queries return 401 when using env var mnemonic path
287
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.
288
339
  try {
289
340
  const authKeyHashForReg = (0, crypto_js_1.computeAuthKeyHash)(authKey);
290
341
  const saltHexForReg = Buffer.from(salt).toString('hex');
@@ -297,6 +348,7 @@ async function initSubgraphState(mnemonic) {
297
348
  }
298
349
  return {
299
350
  mode: 'subgraph',
351
+ credentialKind: 'mnemonic',
300
352
  mnemonic,
301
353
  authKey,
302
354
  encryptionKey,
@@ -305,6 +357,132 @@ async function initSubgraphState(mnemonic) {
305
357
  lshHasher,
306
358
  serverUrl: SERVER_URL,
307
359
  smartAccountAddress,
360
+ chainId,
361
+ dataEdgeAddress,
362
+ };
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,
308
486
  };
309
487
  }
310
488
  const clientState = {
@@ -349,8 +527,8 @@ async function credentialsExist(path) {
349
527
  }
350
528
  async function loadCredentials(path) {
351
529
  const fs = await import('fs/promises');
352
- const data = await fs.readFile(path, 'utf-8');
353
- const parsed = JSON.parse(data);
530
+ const fileContents = await fs.readFile(path, 'utf-8');
531
+ const parsed = JSON.parse(fileContents);
354
532
  return {
355
533
  userId: parsed.userId,
356
534
  salt: Buffer.from(parsed.salt, 'hex'),
@@ -360,37 +538,46 @@ async function saveCredentials(path, credentials) {
360
538
  const fs = await import('fs/promises');
361
539
  const dir = path.substring(0, path.lastIndexOf('/'));
362
540
  await fs.mkdir(dir, { recursive: true }).catch(() => { });
363
- const data = {
541
+ const storedCredentials = {
364
542
  userId: credentials.userId,
365
543
  salt: credentials.salt.toString('hex'),
366
544
  };
367
- await fs.writeFile(path, JSON.stringify(data, null, 2), 'utf-8');
545
+ await fs.writeFile(path, JSON.stringify(storedCredentials, null, 2), 'utf-8');
368
546
  }
369
547
  // ── Subgraph handlers ───────────────────────────────────────────────────────
370
548
  /**
371
549
  * Encrypt an embedding vector for on-chain storage.
372
550
  *
373
- * Concatenates the float array into a Buffer, encrypts with XChaCha20-Poly1305,
374
- * 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.
375
557
  */
376
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) {
377
565
  const buf = Buffer.alloc(embedding.length * 4);
378
566
  for (let i = 0; i < embedding.length; i++) {
379
567
  buf.writeFloatLE(embedding[i], i * 4);
380
568
  }
381
- return (0, crypto_js_1.encrypt)(buf.toString('base64'), encryptionKey);
569
+ return buf.toString('base64');
382
570
  }
383
571
  /**
384
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.
385
577
  */
386
578
  function decryptEmbedding(encryptedEmbedding, encryptionKey) {
387
- const decryptedBase64 = (0, crypto_js_1.decrypt)(encryptedEmbedding, encryptionKey);
388
- const buf = Buffer.from(decryptedBase64, 'base64');
389
- const floats = [];
390
- for (let i = 0; i < buf.length; i += 4) {
391
- floats.push(buf.readFloatLE(i));
392
- }
393
- return floats;
579
+ const decryptedPayload = (0, crypto_js_1.decrypt)(encryptedEmbedding, encryptionKey);
580
+ return (0, embedding_codec_js_1.decodeEmbeddingUniversal)(decryptedPayload);
394
581
  }
395
582
  /**
396
583
  * Handle remember in subgraph mode: encrypt, generate indices, submit on-chain.
@@ -413,8 +600,8 @@ async function handleRememberSubgraph(state, args) {
413
600
  text: f.text.trim(),
414
601
  importance: f.importance ?? 5,
415
602
  type: resolveType(f.type),
416
- typeV1: (0, remember_js_2.normalizeTypeToV1)(f.type),
417
- scope: (0, remember_js_2.normalizeScope)(f.scope),
603
+ typeV1: (0, remember_js_1.normalizeTypeToV1)(f.type),
604
+ scope: (0, remember_js_1.normalizeScope)(f.scope),
418
605
  reasoning: typeof f.reasoning === 'string' && f.reasoning.trim().length > 0
419
606
  ? f.reasoning.trim()
420
607
  : undefined,
@@ -430,13 +617,13 @@ async function handleRememberSubgraph(state, args) {
430
617
  const topLevelReasoning = typeof input?.reasoning === 'string'
431
618
  ? input.reasoning
432
619
  : undefined;
433
- const resolvedScope = (0, remember_js_2.normalizeScope)(topLevelScope ?? singleMetadata?.scope);
620
+ const resolvedScope = (0, remember_js_1.normalizeScope)(topLevelScope ?? singleMetadata?.scope);
434
621
  const resolvedReasoning = topLevelReasoning ?? (typeof singleMetadata?.reasoning === 'string' ? singleMetadata.reasoning : undefined);
435
622
  textsToStore.push({
436
623
  text: factText.trim(),
437
624
  importance: input?.importance ?? 5,
438
625
  type: resolveType(singleMetadata?.type),
439
- typeV1: (0, remember_js_2.normalizeTypeToV1)(singleMetadata?.type),
626
+ typeV1: (0, remember_js_1.normalizeTypeToV1)(singleMetadata?.type),
440
627
  scope: resolvedScope,
441
628
  reasoning: resolvedReasoning && resolvedReasoning.trim().length > 0
442
629
  ? resolvedReasoning.trim()
@@ -722,12 +909,7 @@ async function handleRememberSubgraph(state, args) {
722
909
  // Batch-submit all payloads (tombstones + facts) in a single UserOp
723
910
  if (pendingPayloads.length > 0) {
724
911
  try {
725
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
726
- relayUrl: state.serverUrl,
727
- mnemonic: state.mnemonic,
728
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
729
- walletAddress: state.smartAccountAddress,
730
- });
912
+ const batchConfig = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
731
913
  const batchResult = await (0, store_js_1.submitFactBatchOnChain)(pendingPayloads, batchConfig);
732
914
  for (const meta of pendingFactMeta) {
733
915
  results.push({
@@ -826,12 +1008,7 @@ async function handleDebriefSubgraph(state, args) {
826
1008
  agentId: 'mcp-server',
827
1009
  encryptedEmbedding: encryptedEmb,
828
1010
  };
829
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
830
- relayUrl: state.serverUrl,
831
- mnemonic: state.mnemonic,
832
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
833
- walletAddress: state.smartAccountAddress,
834
- });
1011
+ const batchConfig = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
835
1012
  const batchResult = await (0, store_js_1.submitFactBatchOnChain)([(0, store_js_1.encodeFactProtobuf)(factPayload)], batchConfig);
836
1013
  console.error(`Crystal debrief stored (tx=${batchResult.txHash.slice(0, 10)}...)`);
837
1014
  return {
@@ -853,7 +1030,7 @@ async function handleDebriefSubgraph(state, args) {
853
1030
  }],
854
1031
  };
855
1032
  }
856
- const validated = (0, index_js_2.parseDebriefResponse)(JSON.stringify(factsInput));
1033
+ const validated = (0, index_js_1.parseDebriefResponse)(JSON.stringify(factsInput));
857
1034
  if (validated.length === 0) {
858
1035
  return {
859
1036
  content: [{ type: 'text', text: JSON.stringify({ success: true, stored: 0, message: 'No valid debrief items to store (filtered by validation)' }) }],
@@ -899,12 +1076,7 @@ async function handleDebriefSubgraph(state, args) {
899
1076
  const results = [];
900
1077
  if (pendingPayloads.length > 0) {
901
1078
  try {
902
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
903
- relayUrl: state.serverUrl,
904
- mnemonic: state.mnemonic,
905
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
906
- walletAddress: state.smartAccountAddress,
907
- });
1079
+ const batchConfig = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
908
1080
  const batchResult = await (0, store_js_1.submitFactBatchOnChain)(pendingPayloads, batchConfig);
909
1081
  for (const meta of pendingFactMeta) {
910
1082
  results.push({ success: batchResult.success, fact_id: meta.factId, tx_hash: batchResult.txHash });
@@ -1050,8 +1222,10 @@ async function handleRecallSubgraph(state, args) {
1050
1222
  // argument is accepted for API stability but ignored -- core handles
1051
1223
  // intent-weighting internally based on per-candidate cosine scores.
1052
1224
  const reranked = (0, reranker_js_1.rerank)(query.trim(), queryEmbedding, decryptedCandidates, k, weights,
1053
- /* applySourceWeights (Retrieval v2 Tier 1) */ true);
1225
+ /* applySourceWeights (Retrieval v2 Tier 1) */ false);
1054
1226
  // 8. Format results
1227
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
1228
+ const subgraphCore = require('@totalreclaw/core');
1055
1229
  const memories = reranked.map((r) => ({
1056
1230
  fact_id: r.id,
1057
1231
  fact_text: r.text,
@@ -1066,6 +1240,9 @@ async function handleRecallSubgraph(state, args) {
1066
1240
  age_days: r.createdAt
1067
1241
  ? Math.floor((Date.now() / 1000 - r.createdAt) / 86400)
1068
1242
  : 0,
1243
+ date: r.createdAt != null
1244
+ ? subgraphCore.formatMemoryDate(BigInt(r.createdAt))
1245
+ : '',
1069
1246
  }));
1070
1247
  return {
1071
1248
  content: [{
@@ -1134,12 +1311,7 @@ async function handleForgetSubgraph(state, args) {
1134
1311
  agentId: 'mcp-server',
1135
1312
  };
1136
1313
  const protobuf = (0, store_js_1.encodeFactProtobuf)(tombstonePayload);
1137
- const config = (0, store_js_1.getSubgraphConfig)({
1138
- relayUrl: state.serverUrl,
1139
- mnemonic: state.mnemonic,
1140
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
1141
- walletAddress: state.smartAccountAddress,
1142
- });
1314
+ const config = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
1143
1315
  const { txHash, success } = await (0, store_js_1.submitFactOnChain)(protobuf, config);
1144
1316
  // Read-after-write: poll the subgraph until the fact is no longer
1145
1317
  // active (forget flips isActive=false). On timeout we still report
@@ -1203,14 +1375,9 @@ function buildPinDepsFromState(state) {
1203
1375
  return Buffer.from(base64, 'base64').toString('hex');
1204
1376
  },
1205
1377
  submitBatch: async (payloads) => {
1206
- const config = (0, store_js_1.getSubgraphConfig)({
1207
- relayUrl: state.serverUrl,
1208
- mnemonic: state.mnemonic,
1209
- authKeyHex: Buffer.from(state.authKey).toString('hex'),
1210
- walletAddress: state.smartAccountAddress,
1211
- });
1212
- const result = await (0, store_js_1.submitFactBatchOnChain)(payloads, config);
1213
- return { txHash: result.txHash, success: result.success };
1378
+ const config = (0, store_js_1.getSubgraphConfig)(stateWriteOverrides(state));
1379
+ const batchResult = await (0, store_js_1.submitFactBatchOnChain)(payloads, config);
1380
+ return { txHash: batchResult.txHash, success: batchResult.success };
1214
1381
  },
1215
1382
  generateIndices: async (text, entityNames) => {
1216
1383
  if (!text)
@@ -1234,12 +1401,12 @@ function buildPinDepsFromState(state) {
1234
1401
  },
1235
1402
  confirmIndexed: async (factId, expect) => {
1236
1403
  const subgraphUrl = process.env.TOTALRECLAW_SUBGRAPH_URL || `${state.serverUrl}/v1/subgraph`;
1237
- const result = await (0, confirm_indexed_js_1.confirmIndexed)(factId, {
1404
+ const confirmation = await (0, confirm_indexed_js_1.confirmIndexed)(factId, {
1238
1405
  subgraphUrl,
1239
1406
  authKeyHex: Buffer.from(state.authKey).toString('hex'),
1240
1407
  expect,
1241
1408
  });
1242
- return result.indexed;
1409
+ return confirmation.indexed;
1243
1410
  },
1244
1411
  };
1245
1412
  }
@@ -1269,238 +1436,6 @@ async function handleUnpinSubgraph(state, args) {
1269
1436
  const deps = buildPinDepsFromState(state);
1270
1437
  return await (0, pin_js_1.handleUnpinSubgraphWithDeps)(args, deps);
1271
1438
  }
1272
- // ── Migration handler ─────────────────────────────────────────────────────────
1273
- /** Maximum facts per UserOp batch during migration */
1274
- const MIGRATION_BATCH_SIZE = 15;
1275
- /**
1276
- * Handle the testnet-to-mainnet migration tool call.
1277
- *
1278
- * This function:
1279
- * 1. Validates the user is on subgraph mode with Pro tier
1280
- * 2. Fetches all active facts from the testnet (Base Sepolia) subgraph
1281
- * 3. Fetches existing mainnet content fingerprints for idempotency
1282
- * 4. In dry-run mode: returns a preview of what would be migrated
1283
- * 5. In confirm mode: re-encodes and batch-submits facts to mainnet
1284
- */
1285
- async function handleMigrateFromIndex(args) {
1286
- const input = args;
1287
- const confirm = input?.confirm === true;
1288
- // Must be in subgraph mode
1289
- if (!subgraphState) {
1290
- return {
1291
- content: [{
1292
- type: 'text',
1293
- text: JSON.stringify({
1294
- success: false,
1295
- error: 'Migration is only available with the managed service (subgraph mode). Self-hosted mode does not use chain-based storage.',
1296
- }),
1297
- }],
1298
- };
1299
- }
1300
- const authKeyHex = Buffer.from(subgraphState.authKey).toString('hex');
1301
- // 1. Check billing tier — must be Pro
1302
- const billing = await (0, index_js_2.checkBillingTier)(SERVER_URL, subgraphState.smartAccountAddress, authKeyHex);
1303
- if (billing.error) {
1304
- return {
1305
- content: [{
1306
- type: 'text',
1307
- text: JSON.stringify({
1308
- success: false,
1309
- error: `Failed to verify billing tier: ${billing.error}`,
1310
- }),
1311
- }],
1312
- };
1313
- }
1314
- if (billing.tier !== 'pro') {
1315
- return {
1316
- content: [{
1317
- type: 'text',
1318
- text: JSON.stringify({
1319
- success: false,
1320
- error: 'Migration requires Pro tier. Use totalreclaw_upgrade to upgrade first, then run migration.',
1321
- current_tier: billing.tier,
1322
- }),
1323
- }],
1324
- };
1325
- }
1326
- // 2. Fetch all active facts from the TESTNET subgraph
1327
- // The relay routes Pro users to the mainnet subgraph, so we need to
1328
- // explicitly request the testnet subgraph via the ?chain=testnet query param.
1329
- const testnetSubgraphUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/subgraph?chain=testnet`;
1330
- const mainnetSubgraphUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/subgraph`;
1331
- console.error(`[migrate] Fetching testnet facts for owner ${subgraphState.smartAccountAddress}...`);
1332
- const testnetFacts = await (0, index_js_2.fetchAllFactsFromSubgraph)(testnetSubgraphUrl, subgraphState.smartAccountAddress, authKeyHex);
1333
- if (testnetFacts.length === 0) {
1334
- return {
1335
- content: [{
1336
- type: 'text',
1337
- text: JSON.stringify({
1338
- success: true,
1339
- mode: 'dry_run',
1340
- testnet_facts: 0,
1341
- already_on_mainnet: 0,
1342
- to_migrate: 0,
1343
- migrated: 0,
1344
- failed_batches: 0,
1345
- batch_results: [],
1346
- message: 'No facts found on testnet. Nothing to migrate.',
1347
- }),
1348
- }],
1349
- };
1350
- }
1351
- // 3. Check which facts already exist on mainnet (by contentFp)
1352
- console.error(`[migrate] Checking mainnet for existing facts...`);
1353
- const mainnetFps = await (0, index_js_2.fetchMainnetContentFps)(mainnetSubgraphUrl, subgraphState.smartAccountAddress, authKeyHex);
1354
- // Filter to facts that need migration
1355
- const factsToMigrate = testnetFacts.filter(f => {
1356
- if (!f.contentFp)
1357
- return true; // No fingerprint — migrate it
1358
- return !mainnetFps.has(f.contentFp);
1359
- });
1360
- const alreadyOnMainnet = testnetFacts.length - factsToMigrate.length;
1361
- console.error(`[migrate] Testnet: ${testnetFacts.length} facts, already on mainnet: ${alreadyOnMainnet}, to migrate: ${factsToMigrate.length}`);
1362
- // 4. Dry-run mode: just report
1363
- if (!confirm) {
1364
- return {
1365
- content: [{
1366
- type: 'text',
1367
- text: JSON.stringify({
1368
- success: true,
1369
- mode: 'dry_run',
1370
- testnet_facts: testnetFacts.length,
1371
- already_on_mainnet: alreadyOnMainnet,
1372
- to_migrate: factsToMigrate.length,
1373
- migrated: 0,
1374
- failed_batches: 0,
1375
- batch_results: [],
1376
- message: factsToMigrate.length === 0
1377
- ? `All ${testnetFacts.length} testnet facts already exist on mainnet. Nothing to migrate.`
1378
- : `Found ${factsToMigrate.length} facts to migrate from testnet to Gnosis mainnet (${alreadyOnMainnet} already on mainnet). Call with confirm=true to proceed.`,
1379
- }),
1380
- }],
1381
- };
1382
- }
1383
- // 5. Execute migration: re-encode and batch-submit
1384
- if (factsToMigrate.length === 0) {
1385
- return {
1386
- content: [{
1387
- type: 'text',
1388
- text: JSON.stringify({
1389
- success: true,
1390
- mode: 'executed',
1391
- testnet_facts: testnetFacts.length,
1392
- already_on_mainnet: alreadyOnMainnet,
1393
- to_migrate: 0,
1394
- migrated: 0,
1395
- failed_batches: 0,
1396
- batch_results: [],
1397
- message: `All ${testnetFacts.length} testnet facts already exist on mainnet. Nothing to migrate.`,
1398
- }),
1399
- }],
1400
- };
1401
- }
1402
- // Fetch blind indices from testnet for all facts to migrate.
1403
- // The protobuf payload must include blind indices for the subgraph to create
1404
- // BlindIndex entities on mainnet (required for search to work).
1405
- console.error(`[migrate] Fetching blind indices for ${factsToMigrate.length} facts...`);
1406
- const factIdsToMigrate = factsToMigrate.map(f => f.id);
1407
- const blindIndicesMap = await (0, index_js_2.fetchBlindIndicesForFacts)(testnetSubgraphUrl, factIdsToMigrate, authKeyHex);
1408
- // Build protobuf payloads with blind indices
1409
- const finalPayloads = [];
1410
- for (const fact of factsToMigrate) {
1411
- const blobHex = fact.encryptedBlob.startsWith('0x')
1412
- ? fact.encryptedBlob.slice(2)
1413
- : fact.encryptedBlob;
1414
- const indices = blindIndicesMap.get(fact.id) || [];
1415
- const factPayload = {
1416
- id: fact.id,
1417
- timestamp: new Date().toISOString(),
1418
- owner: subgraphState.smartAccountAddress,
1419
- encryptedBlob: blobHex,
1420
- blindIndices: indices,
1421
- decayScore: parseFloat(fact.decayScore) || 0.5,
1422
- source: fact.source || 'migration',
1423
- contentFp: fact.contentFp || '',
1424
- agentId: fact.agentId || 'mcp-server',
1425
- encryptedEmbedding: fact.encryptedEmbedding || undefined,
1426
- };
1427
- finalPayloads.push((0, store_js_1.encodeFactProtobuf)(factPayload));
1428
- }
1429
- // Batch into groups of MIGRATION_BATCH_SIZE
1430
- const batches = [];
1431
- for (let i = 0; i < finalPayloads.length; i += MIGRATION_BATCH_SIZE) {
1432
- batches.push(finalPayloads.slice(i, i + MIGRATION_BATCH_SIZE));
1433
- }
1434
- console.error(`[migrate] Submitting ${finalPayloads.length} facts in ${batches.length} batch(es)...`);
1435
- const batchConfig = (0, store_js_1.getSubgraphConfig)({
1436
- relayUrl: subgraphState.serverUrl,
1437
- mnemonic: subgraphState.mnemonic,
1438
- authKeyHex,
1439
- walletAddress: subgraphState.smartAccountAddress,
1440
- });
1441
- let migrated = 0;
1442
- let failedBatches = 0;
1443
- const batchResults = [];
1444
- for (let i = 0; i < batches.length; i++) {
1445
- const batch = batches[i];
1446
- const batchNum = i + 1;
1447
- console.error(`[migrate] Batch ${batchNum}/${batches.length} (${batch.length} facts)...`);
1448
- try {
1449
- const result = await (0, store_js_1.submitFactBatchOnChain)(batch, batchConfig);
1450
- if (result.success) {
1451
- migrated += batch.length;
1452
- batchResults.push({
1453
- batch_number: batchNum,
1454
- size: batch.length,
1455
- success: true,
1456
- tx_hash: result.txHash,
1457
- });
1458
- console.error(`[migrate] Batch ${batchNum} succeeded (tx=${result.txHash.slice(0, 10)}...)`);
1459
- }
1460
- else {
1461
- failedBatches++;
1462
- batchResults.push({
1463
- batch_number: batchNum,
1464
- size: batch.length,
1465
- success: false,
1466
- tx_hash: result.txHash,
1467
- error: 'UserOp included but marked as failed',
1468
- });
1469
- console.error(`[migrate] Batch ${batchNum} included but failed (tx=${result.txHash.slice(0, 10)}...)`);
1470
- }
1471
- }
1472
- catch (err) {
1473
- failedBatches++;
1474
- const errMsg = err instanceof Error ? err.message : String(err);
1475
- batchResults.push({
1476
- batch_number: batchNum,
1477
- size: batch.length,
1478
- success: false,
1479
- error: errMsg,
1480
- });
1481
- console.error(`[migrate] Batch ${batchNum} error: ${errMsg}`);
1482
- }
1483
- }
1484
- const resultMessage = failedBatches === 0
1485
- ? `Successfully migrated ${migrated} memories from testnet to Gnosis mainnet in ${batches.length} batch(es).`
1486
- : `Migrated ${migrated}/${factsToMigrate.length} memories. ${failedBatches} batch(es) failed — re-run to retry (idempotent).`;
1487
- return {
1488
- content: [{
1489
- type: 'text',
1490
- text: JSON.stringify({
1491
- success: failedBatches === 0,
1492
- mode: 'executed',
1493
- testnet_facts: testnetFacts.length,
1494
- already_on_mainnet: alreadyOnMainnet,
1495
- to_migrate: factsToMigrate.length,
1496
- migrated,
1497
- failed_batches: failedBatches,
1498
- batch_results: batchResults,
1499
- message: resultMessage,
1500
- }),
1501
- }],
1502
- };
1503
- }
1504
1439
  // ── Auth error helper ────────────────────────────────────────────────────────
1505
1440
  const AUTH_HINT_MESSAGE = 'Authentication failed. If using a recovery phrase, check that all 12 words are in the correct order and spelled correctly.';
1506
1441
  /**
@@ -1551,26 +1486,16 @@ function quotaExceededResponse() {
1551
1486
  // phrase from the OpenClaw / Hermes browser pair flow (or an offline BIP-39
1552
1487
  // generator) and paste it into the MCP host config themselves. No tool path
1553
1488
  // exists for the agent to ever see the phrase.
1554
- // ── Layer 1: Server with instructions ────────────────────────────────────────
1555
- const server = new index_js_1.Server({ name: 'totalreclaw', version: '1.0.0' }, {
1556
- capabilities: {
1557
- tools: {},
1558
- prompts: {},
1559
- resources: { subscribe: true, listChanged: true },
1560
- },
1561
- instructions: prompts_js_1.SERVER_INSTRUCTIONS,
1562
- });
1563
- // ── Wire up cache invalidation ───────────────────────────────────────────────
1564
- // When facts are stored, invalidate the memory context resource cache
1565
- (0, remember_js_1.setOnRememberCallback)(() => {
1566
- (0, index_js_3.invalidateMemoryContextCache)();
1567
- // Notify subscribed clients that the resource has been updated
1568
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1569
- });
1489
+ // ── Server wiring ─────────────────────────────────────────────────────────
1490
+ // The MCP `Server` is constructed in `main()` via `createTotalReclawServer`
1491
+ // (see `./server-setup.js`) and its request routing is delegated to the single
1492
+ // dispatch table in `./dispatch.js`. This section builds the mode-appropriate
1493
+ // handler bundles + cross-cutting deps the dispatcher needs.
1494
+ let server;
1570
1495
  // ── Client identification (resolved after initialize handshake) ──────────────
1571
1496
  function getClientIdentifier() {
1572
1497
  if (!clientIdentifierResolved) {
1573
- const clientInfo = server.getClientVersion();
1498
+ const clientInfo = server?.getClientVersion();
1574
1499
  if (clientInfo?.name) {
1575
1500
  const name = clientInfo.name.toLowerCase().replace(/\s+/g, '-');
1576
1501
  (0, client_id_js_1.setClientId)(`mcp-server:${name}`);
@@ -1580,441 +1505,161 @@ function getClientIdentifier() {
1580
1505
  }
1581
1506
  return (0, client_id_js_1.getClientId)();
1582
1507
  }
1583
- // ── Layer 2 + 3: Tool handlers ───────────────────────────────────────────────
1584
- server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
1585
- tools: [
1586
- index_js_2.rememberToolDefinition,
1587
- index_js_2.recallToolDefinition,
1588
- index_js_2.forgetToolDefinition,
1589
- index_js_2.exportToolDefinition,
1590
- index_js_2.importToolDefinition,
1591
- index_js_2.importFromToolDefinition,
1592
- index_js_2.importBatchToolDefinition,
1593
- index_js_2.consolidateToolDefinition,
1594
- index_js_2.statusToolDefinition,
1595
- index_js_2.upgradeToolDefinition,
1596
- index_js_2.migrateToolDefinition,
1597
- index_js_2.debriefToolDefinition,
1598
- index_js_2.supportToolDefinition,
1599
- index_js_2.accountToolDefinition,
1600
- pin_js_1.pinToolDefinition,
1601
- pin_js_1.unpinToolDefinition,
1602
- retype_js_1.retypeToolDefinition,
1603
- set_scope_js_1.setScopeToolDefinition,
1604
- index_js_2.pairToolDefinition,
1605
- ],
1606
- }));
1607
- server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
1608
- const { name, arguments: args } = request.params;
1609
- // `totalreclaw_setup` was removed in 3.2.1 (security: phrase-safety).
1610
- // Onboarding now follows the URL-driven flow at
1611
- // `docs/guides/claude-code-setup.md`. If a stale agent / host catalog
1612
- // still calls the old tool name, return a structured error pointing at
1613
- // the canonical install guide — without surfacing any phrase in payload.
1614
- if (name === 'totalreclaw_setup') {
1615
- return {
1616
- content: [{
1617
- type: 'text',
1618
- text: JSON.stringify({
1619
- error: 'tool_removed',
1620
- message: 'The totalreclaw_setup tool was removed in @totalreclaw/mcp-server@3.2.1 ' +
1621
- 'for phrase-safety. Follow the URL-driven install flow at ' +
1622
- 'https://github.com/p-diogo/totalreclaw/blob/main/docs/guides/claude-code-setup.md. ' +
1623
- 'The user sources their recovery phrase out-of-band (OpenClaw or Hermes ' +
1624
- 'browser pair flow, or an offline BIP-39 generator) and pastes it directly ' +
1625
- 'into TOTALRECLAW_RECOVERY_PHRASE in the MCP host config — never into chat.',
1626
- }),
1627
- }],
1628
- isError: true,
1629
- };
1630
- }
1631
- // Handle support tool (available in all modes, including unconfigured)
1632
- if (name === 'totalreclaw_support') {
1633
- const walletAddress = subgraphState?.smartAccountAddress ?? null;
1634
- return (0, index_js_2.handleSupport)(walletAddress);
1635
- }
1636
- // Handle pair tool (available in all modes — primary unconfigured-mode entry
1637
- // point so a user with no credentials can run an MCP-only install end-to-end:
1638
- // host adds MCP server → agent calls totalreclaw_pair → tool returns URL+PIN
1639
- // → user pairs in browser → server writes ~/.totalreclaw/credentials.json
1640
- // → user restarts host → server boots in subgraph mode).
1641
- if (name === 'totalreclaw_pair') {
1642
- return await (0, index_js_2.handlePair)(args);
1643
- }
1644
- // In unconfigured mode, all other tools return setup guidance pointing at
1645
- // the URL-driven install flow (NOT the deleted totalreclaw_setup tool).
1646
- if (currentMode === 'unconfigured') {
1647
- return {
1648
- content: [{
1649
- type: 'text',
1650
- text: JSON.stringify({
1651
- error: 'not_configured',
1652
- message: 'TotalReclaw is not configured yet. Follow the URL-driven install flow ' +
1653
- 'at https://github.com/p-diogo/totalreclaw/blob/main/docs/guides/claude-code-setup.md — ' +
1654
- 'the user pastes their recovery phrase directly into the MCP host config (TOTALRECLAW_RECOVERY_PHRASE), ' +
1655
- 'never into chat.',
1656
- }),
1657
- }],
1658
- isError: true,
1659
- };
1660
- }
1661
- const mode = subgraphState ? 'subgraph' : 'http';
1508
+ // ── Cross-cutting dispatch deps ──────────────────────────────────────────────
1509
+ /** Invalidate the memory-context resource cache + notify subscribed clients. */
1510
+ function onMutate() {
1511
+ (0, index_js_2.invalidateMemoryContextCache)();
1512
+ server
1513
+ ?.sendResourceUpdated({ uri: index_js_2.memoryContextResource.uri })
1514
+ .catch((err) => console.error('Failed to send resource update:', err));
1515
+ }
1516
+ /** Standard authentication-failure envelope (shared quota → auth funnel). */
1517
+ function authHintResponse() {
1518
+ return {
1519
+ content: [{ type: 'text', text: JSON.stringify({ error: AUTH_HINT_MESSAGE }) }],
1520
+ isError: true,
1521
+ };
1522
+ }
1523
+ // ── Mode-independent tool handlers (status / upgrade / account) ───────────────
1524
+ // These talk to the relay directly and behave identically in both storage
1525
+ // modes. `subgraphState` supplies the auth key + wallet when present.
1526
+ async function statusHandler(args) {
1527
+ const authKeyHex = subgraphState
1528
+ ? Buffer.from(subgraphState.authKey).toString('hex')
1529
+ : '';
1530
+ const enrichedArgs = {
1531
+ ...args,
1532
+ wallet_address: args?.wallet_address ||
1533
+ subgraphState?.smartAccountAddress,
1534
+ };
1535
+ const statusResult = await (0, index_js_1.handleStatus)({ serverUrl: SERVER_URL, authKeyHex }, enrichedArgs);
1536
+ // Cache billing features for candidate-pool sizing. handleStatus stores the
1537
+ // raw response; extract max_candidate_pool from it.
1662
1538
  try {
1663
- // ── Billing tools (mode-independent, always use HTTP relay) ────────────
1664
- if (name === 'totalreclaw_status') {
1665
- const authKeyHex = subgraphState
1666
- ? Buffer.from(subgraphState.authKey).toString('hex')
1667
- : '';
1668
- const enrichedArgs = {
1669
- ...args,
1670
- wallet_address: args?.wallet_address ||
1671
- subgraphState?.smartAccountAddress,
1539
+ const raw = (0, status_js_1.getLastBillingResponse)();
1540
+ if (raw?.features) {
1541
+ billingCache = {
1542
+ max_candidate_pool: raw.features.max_candidate_pool,
1543
+ checked_at: Date.now(),
1672
1544
  };
1673
- const statusResult = await (0, index_js_2.handleStatus)(SERVER_URL, authKeyHex, enrichedArgs);
1674
- // Cache billing features for candidate pool sizing.
1675
- // handleStatus stores the raw response; extract max_candidate_pool from it.
1676
- try {
1677
- const raw = (0, status_js_1.getLastBillingResponse)();
1678
- if (raw?.features) {
1679
- billingCache = {
1680
- max_candidate_pool: raw.features.max_candidate_pool,
1681
- checked_at: Date.now(),
1682
- };
1683
- }
1684
- }
1685
- catch {
1686
- // Best-effort cache — don't fail the status call
1687
- }
1688
- return statusResult;
1689
- }
1690
- if (name === 'totalreclaw_upgrade') {
1691
- const authKeyHex = subgraphState
1692
- ? Buffer.from(subgraphState.authKey).toString('hex')
1693
- : '';
1694
- return await (0, index_js_2.handleUpgrade)(SERVER_URL, authKeyHex, args);
1695
- }
1696
- if (name === 'totalreclaw_account') {
1697
- if (!subgraphState) {
1698
- return {
1699
- content: [{
1700
- type: 'text',
1701
- text: JSON.stringify({
1702
- error: 'Account details require managed service mode (subgraph). Self-hosted mode does not track billing.',
1703
- }),
1704
- }],
1705
- isError: true,
1706
- };
1707
- }
1708
- const authKeyHex = Buffer.from(subgraphState.authKey).toString('hex');
1709
- const words = subgraphState.mnemonic.split(/\s+/);
1710
- const mnemonicHint = `${words[0]} ... ${words[words.length - 1]}`;
1711
- const getFactCount = () => (0, search_js_1.getOwnerFactCount)(subgraphState.smartAccountAddress, subgraphState.serverUrl, authKeyHex);
1712
- return await (0, index_js_2.handleAccount)(SERVER_URL, authKeyHex, subgraphState.smartAccountAddress, mnemonicHint, getFactCount);
1713
- }
1714
- if (name === 'totalreclaw_migrate') {
1715
- return await handleMigrateFromIndex(args);
1716
- }
1717
- // ── Subgraph mode ─────────────────────────────────────────────────────
1718
- if (subgraphState) {
1719
- switch (name) {
1720
- case 'totalreclaw_remember': {
1721
- try {
1722
- const result = await handleRememberSubgraph(subgraphState, args);
1723
- // Invalidate cache after successful store
1724
- (0, index_js_3.invalidateMemoryContextCache)();
1725
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1726
- return result;
1727
- }
1728
- catch (error) {
1729
- if (isQuotaExceededError(error)) {
1730
- return quotaExceededResponse();
1731
- }
1732
- throw error;
1733
- }
1734
- }
1735
- case 'totalreclaw_recall':
1736
- return await handleRecallSubgraph(subgraphState, args);
1737
- case 'totalreclaw_forget': {
1738
- const result = await handleForgetSubgraph(subgraphState, args);
1739
- (0, index_js_3.invalidateMemoryContextCache)();
1740
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1741
- return result;
1742
- }
1743
- case 'totalreclaw_export':
1744
- // Export not yet implemented for the managed service -- fall through to error
1745
- return {
1746
- content: [{
1747
- type: 'text',
1748
- text: JSON.stringify({
1749
- error: 'Export is not yet supported with the managed service. Use self-hosted mode for export.',
1750
- }),
1751
- }],
1752
- isError: true,
1753
- };
1754
- case 'totalreclaw_import':
1755
- return {
1756
- content: [{
1757
- type: 'text',
1758
- text: JSON.stringify({
1759
- error: 'Import is not yet supported with the managed service. Use self-hosted mode for import.',
1760
- }),
1761
- }],
1762
- isError: true,
1763
- };
1764
- case 'totalreclaw_import_from':
1765
- return {
1766
- content: [{
1767
- type: 'text',
1768
- text: JSON.stringify({
1769
- error: 'Import from external sources is not yet supported with the managed service. Use self-hosted mode for import.',
1770
- }),
1771
- }],
1772
- isError: true,
1773
- };
1774
- case 'totalreclaw_consolidate':
1775
- return {
1776
- content: [{
1777
- type: 'text',
1778
- text: JSON.stringify({
1779
- error: 'Consolidation is not supported with the managed service. On-chain facts require tombstone-based dedup which is handled automatically at store time.',
1780
- }),
1781
- }],
1782
- isError: true,
1783
- };
1784
- case 'totalreclaw_debrief': {
1785
- try {
1786
- const result = await handleDebriefSubgraph(subgraphState, args);
1787
- (0, index_js_3.invalidateMemoryContextCache)();
1788
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1789
- return result;
1790
- }
1791
- catch (error) {
1792
- if (isQuotaExceededError(error)) {
1793
- return quotaExceededResponse();
1794
- }
1795
- throw error;
1796
- }
1797
- }
1798
- case 'totalreclaw_pin': {
1799
- try {
1800
- const result = await handlePinSubgraph(subgraphState, args);
1801
- (0, index_js_3.invalidateMemoryContextCache)();
1802
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1803
- return result;
1804
- }
1805
- catch (error) {
1806
- if (isQuotaExceededError(error)) {
1807
- return quotaExceededResponse();
1808
- }
1809
- throw error;
1810
- }
1811
- }
1812
- case 'totalreclaw_unpin': {
1813
- try {
1814
- const result = await handleUnpinSubgraph(subgraphState, args);
1815
- (0, index_js_3.invalidateMemoryContextCache)();
1816
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1817
- return result;
1818
- }
1819
- catch (error) {
1820
- if (isQuotaExceededError(error)) {
1821
- return quotaExceededResponse();
1822
- }
1823
- throw error;
1824
- }
1825
- }
1826
- case 'totalreclaw_retype': {
1827
- try {
1828
- const deps = buildMetadataOpDepsFromState(subgraphState);
1829
- const result = await (0, retype_js_1.handleRetypeWithDeps)(args, deps);
1830
- (0, index_js_3.invalidateMemoryContextCache)();
1831
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1832
- return result;
1833
- }
1834
- catch (error) {
1835
- if (isQuotaExceededError(error)) {
1836
- return quotaExceededResponse();
1837
- }
1838
- throw error;
1839
- }
1840
- }
1841
- case 'totalreclaw_set_scope': {
1842
- try {
1843
- const deps = buildMetadataOpDepsFromState(subgraphState);
1844
- const result = await (0, set_scope_js_1.handleSetScopeWithDeps)(args, deps);
1845
- (0, index_js_3.invalidateMemoryContextCache)();
1846
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1847
- return result;
1848
- }
1849
- catch (error) {
1850
- if (isQuotaExceededError(error)) {
1851
- return quotaExceededResponse();
1852
- }
1853
- throw error;
1854
- }
1855
- }
1856
- default:
1857
- return {
1858
- content: [{
1859
- type: 'text',
1860
- text: JSON.stringify({ error: `Unknown tool: ${name}` }),
1861
- }],
1862
- isError: true,
1863
- };
1864
- }
1865
- }
1866
- // ── HTTP mode (existing behavior) ─────────────────────────────────────
1867
- const client = await getClient();
1868
- switch (name) {
1869
- case 'totalreclaw_remember': {
1870
- try {
1871
- const result = await (0, index_js_2.handleRemember)(client, args);
1872
- return result;
1873
- }
1874
- catch (error) {
1875
- if (isQuotaExceededError(error)) {
1876
- return quotaExceededResponse();
1877
- }
1878
- throw error;
1879
- }
1880
- }
1881
- case 'totalreclaw_recall':
1882
- return await (0, index_js_2.handleRecall)(client, args);
1883
- case 'totalreclaw_forget': {
1884
- const result = await (0, index_js_2.handleForget)(client, args);
1885
- // Invalidate cache on forget too
1886
- (0, index_js_3.invalidateMemoryContextCache)();
1887
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1888
- return result;
1889
- }
1890
- case 'totalreclaw_export':
1891
- return await (0, index_js_2.handleExport)(client, args);
1892
- case 'totalreclaw_import':
1893
- return await (0, index_js_2.handleImport)(client, args);
1894
- case 'totalreclaw_import_from':
1895
- return await (0, index_js_2.handleImportFrom)(client, args);
1896
- case 'totalreclaw_import_batch':
1897
- return await (0, index_js_2.handleImportBatch)(args);
1898
- case 'totalreclaw_consolidate': {
1899
- const result = await (0, index_js_2.handleConsolidate)(client, args);
1900
- // Invalidate cache after consolidation (facts may have been deleted)
1901
- (0, index_js_3.invalidateMemoryContextCache)();
1902
- server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1903
- return result;
1904
- }
1905
- case 'totalreclaw_debrief': {
1906
- try {
1907
- const result = await (0, index_js_2.handleDebrief)(client, args);
1908
- return result;
1909
- }
1910
- catch (error) {
1911
- if (isQuotaExceededError(error)) {
1912
- return quotaExceededResponse();
1913
- }
1914
- throw error;
1915
- }
1916
- }
1917
- case 'totalreclaw_pin':
1918
- return await (0, pin_js_1.handlePin)(args);
1919
- case 'totalreclaw_unpin':
1920
- return await (0, pin_js_1.handleUnpin)(args);
1921
- case 'totalreclaw_retype':
1922
- return await (0, retype_js_1.handleRetype)(args);
1923
- case 'totalreclaw_set_scope':
1924
- return await (0, set_scope_js_1.handleSetScope)(args);
1925
- default:
1926
- return {
1927
- content: [{
1928
- type: 'text',
1929
- text: JSON.stringify({ error: `Unknown tool: ${name}` }),
1930
- }],
1931
- isError: true,
1932
- };
1933
1545
  }
1934
1546
  }
1935
- catch (error) {
1936
- // Final catch-all: check for quota error at the top level too
1937
- if (isQuotaExceededError(error)) {
1938
- return quotaExceededResponse();
1939
- }
1940
- // Provide a helpful hint for authentication failures
1941
- if (isAuthError(error)) {
1942
- return {
1943
- content: [{
1944
- type: 'text',
1945
- text: JSON.stringify({
1946
- error: AUTH_HINT_MESSAGE,
1947
- }),
1948
- }],
1949
- isError: true,
1950
- };
1951
- }
1547
+ catch {
1548
+ // Best-effort cache — don't fail the status call.
1549
+ }
1550
+ return statusResult;
1551
+ }
1552
+ async function upgradeHandler(args) {
1553
+ const authKeyHex = subgraphState
1554
+ ? Buffer.from(subgraphState.authKey).toString('hex')
1555
+ : '';
1556
+ return (0, index_js_1.handleUpgrade)({ serverUrl: SERVER_URL, authKeyHex }, args);
1557
+ }
1558
+ async function accountHandler(args) {
1559
+ if (!subgraphState) {
1952
1560
  return {
1953
1561
  content: [{
1954
1562
  type: 'text',
1955
1563
  text: JSON.stringify({
1956
- error: error instanceof Error ? error.message : 'Unknown error',
1564
+ error: 'Account details require managed service mode (subgraph). Self-hosted mode does not track billing.',
1957
1565
  }),
1958
1566
  }],
1959
1567
  isError: true,
1960
1568
  };
1961
1569
  }
1962
- });
1963
- // ── Layer 4: Resources ───────────────────────────────────────────────────────
1964
- server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
1965
- resources: [index_js_3.memoryContextResource],
1966
- }));
1967
- server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
1968
- const { uri } = request.params;
1969
- if (uri === index_js_3.memoryContextResource.uri) {
1970
- // With the managed service, resource reading is not supported yet
1971
- if (subgraphState) {
1972
- return {
1973
- contents: [
1974
- {
1975
- uri: index_js_3.memoryContextResource.uri,
1976
- mimeType: 'text/markdown',
1977
- text: '*Memory context resource is not available with the managed service. Use totalreclaw_recall to search memories.*',
1978
- },
1979
- ],
1980
- };
1981
- }
1982
- const client = await getClient();
1983
- const content = await (0, index_js_3.readMemoryContext)(client);
1984
- return {
1985
- contents: [
1986
- {
1987
- uri: index_js_3.memoryContextResource.uri,
1988
- mimeType: 'text/markdown',
1989
- text: content,
1990
- },
1991
- ],
1992
- };
1993
- }
1994
- throw new Error(`Unknown resource: ${uri}`);
1995
- });
1996
- // ── Layer 5: Prompts ─────────────────────────────────────────────────────────
1997
- server.setRequestHandler(types_js_1.ListPromptsRequestSchema, async () => ({
1998
- prompts: [
1999
- // Legacy instructions prompt (backward compat)
2000
- {
2001
- name: 'totalreclaw_instructions',
2002
- description: 'Instructions for using TotalReclaw tools',
2003
- },
2004
- // New auto-memory prompt fallbacks
2005
- ...prompts_js_1.PROMPT_DEFINITIONS,
2006
- ],
2007
- }));
2008
- server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request) => {
2009
- const { name, arguments: args } = request.params;
2010
- const messages = (0, prompts_js_1.getPromptMessages)(name, args);
2011
- return { messages };
1570
+ const authKeyHex = Buffer.from(subgraphState.authKey).toString('hex');
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)';
1582
+ const getFactCount = () => (0, search_js_1.getOwnerFactCount)(subgraphState.smartAccountAddress, subgraphState.serverUrl, authKeyHex);
1583
+ return (0, index_js_1.handleAccount)({
1584
+ serverUrl: SERVER_URL,
1585
+ authKeyHex,
1586
+ walletAddress: subgraphState.smartAccountAddress,
1587
+ mnemonicHint,
1588
+ getFactCount,
1589
+ }, args);
1590
+ }
1591
+ const commonHandlers = {
1592
+ totalreclaw_status: statusHandler,
1593
+ totalreclaw_upgrade: upgradeHandler,
1594
+ totalreclaw_account: accountHandler,
1595
+ };
1596
+ // ── Managed-service (subgraph) tool bundle ───────────────────────────────────
1597
+ // Tools with no managed-service equivalent return an explicit "use self-hosted
1598
+ // mode" envelope; `totalreclaw_import_batch` is intentionally absent so it
1599
+ // falls through to the standard unknown-tool error, matching pre-refactor
1600
+ // behaviour.
1601
+ function unsupportedInSubgraph(message) {
1602
+ return { content: [{ type: 'text', text: JSON.stringify({ error: message }) }], isError: true };
1603
+ }
1604
+ function subgraphBundle(state) {
1605
+ return {
1606
+ totalreclaw_remember: (args) => handleRememberSubgraph(state, args),
1607
+ totalreclaw_recall: (args) => handleRecallSubgraph(state, args),
1608
+ totalreclaw_forget: (args) => handleForgetSubgraph(state, args),
1609
+ totalreclaw_debrief: (args) => handleDebriefSubgraph(state, args),
1610
+ totalreclaw_pin: (args) => handlePinSubgraph(state, args),
1611
+ totalreclaw_unpin: (args) => handleUnpinSubgraph(state, args),
1612
+ totalreclaw_retype: (args) => (0, retype_js_1.handleRetypeWithDeps)(args, buildMetadataOpDepsFromState(state)),
1613
+ totalreclaw_set_scope: (args) => (0, set_scope_js_1.handleSetScopeWithDeps)(args, buildMetadataOpDepsFromState(state)),
1614
+ totalreclaw_export: async () => unsupportedInSubgraph('Export is not yet supported with the managed service. Use self-hosted mode for export.'),
1615
+ totalreclaw_import: async () => unsupportedInSubgraph('Import is not yet supported with the managed service. Use self-hosted mode for import.'),
1616
+ totalreclaw_import_from: async () => unsupportedInSubgraph('Import from external sources is not yet supported with the managed service. Use self-hosted mode for import.'),
1617
+ totalreclaw_consolidate: async () => unsupportedInSubgraph('Consolidation is not supported with the managed service. On-chain facts require tombstone-based dedup which is handled automatically at store time.'),
1618
+ };
1619
+ }
1620
+ // ── Self-hosted (HTTP) tool bundle ───────────────────────────────────────────
1621
+ function httpBundle(ctx) {
1622
+ return {
1623
+ totalreclaw_remember: (args) => (0, index_js_1.handleRemember)(ctx, args),
1624
+ totalreclaw_recall: (args) => (0, index_js_1.handleRecall)(ctx, args),
1625
+ totalreclaw_forget: (args) => (0, index_js_1.handleForget)(ctx, args),
1626
+ totalreclaw_export: (args) => (0, index_js_1.handleExport)(ctx, args),
1627
+ totalreclaw_import: (args) => (0, index_js_1.handleImport)(ctx, args),
1628
+ totalreclaw_import_from: (args) => (0, index_js_1.handleImportFrom)(ctx, args),
1629
+ totalreclaw_import_batch: (args) => (0, index_js_1.handleImportBatch)(ctx, args),
1630
+ totalreclaw_consolidate: (args) => (0, index_js_1.handleConsolidate)(ctx, args),
1631
+ totalreclaw_debrief: (args) => (0, index_js_1.handleDebrief)(ctx, args),
1632
+ totalreclaw_pin: (args) => (0, pin_js_1.handlePin)(ctx, args),
1633
+ totalreclaw_unpin: (args) => (0, pin_js_1.handleUnpin)(ctx, args),
1634
+ totalreclaw_retype: (args) => (0, retype_js_1.handleRetype)(ctx, args),
1635
+ totalreclaw_set_scope: (args) => (0, set_scope_js_1.handleSetScope)(ctx, args),
1636
+ };
1637
+ }
1638
+ /** Resolve the handler bundle for the current storage mode. */
1639
+ async function resolveBundle(mode) {
1640
+ if (mode === 'subgraph')
1641
+ return subgraphBundle(subgraphState);
1642
+ const client = await getClient();
1643
+ return httpBundle({ client });
1644
+ }
1645
+ // ── The single CallTool router ───────────────────────────────────────────────
1646
+ const callToolHandler = (0, dispatch_js_1.createCallToolHandler)({
1647
+ getMode: () => currentMode,
1648
+ handleSupport: (args) => (0, index_js_1.handleSupport)({ walletAddress: subgraphState?.smartAccountAddress ?? null }, args),
1649
+ handlePair: (args) => (0, index_js_1.handlePair)({}, args),
1650
+ common: commonHandlers,
1651
+ resolveBundle,
1652
+ isQuotaExceededError,
1653
+ quotaExceededResponse,
1654
+ isAuthError,
1655
+ authHintResponse,
1656
+ onMutate,
2012
1657
  });
2013
1658
  // ── Show-phrase CLI subcommand ────────────────────────────────────────────────
2014
1659
  async function showPhrase() {
2015
1660
  try {
2016
- const data = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
2017
- const parsed = JSON.parse(data);
1661
+ const credentialsRaw = fs.readFileSync(setup_js_1.CREDENTIALS_PATH, 'utf-8');
1662
+ const parsed = JSON.parse(credentialsRaw);
2018
1663
  if (parsed.mnemonic) {
2019
1664
  console.log(parsed.mnemonic);
2020
1665
  }
@@ -2039,18 +1684,82 @@ async function main() {
2039
1684
  await showPhrase();
2040
1685
  return;
2041
1686
  }
2042
- // Resolve mnemonic from env var or credentials.json
2043
- const mnemonic = resolveMnemonic();
2044
- currentMode = detectServerMode(mnemonic);
2045
- if (currentMode === 'subgraph' && mnemonic) {
2046
- subgraphState = await initSubgraphState(mnemonic);
2047
- console.error(`TotalReclaw MCP server started (managed service, owner: ${subgraphState.smartAccountAddress})`);
2048
- }
2049
- else if (currentMode === 'http') {
2050
- 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
+ }
2051
1724
  }
2052
1725
  else {
2053
- 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
+ }
2054
1763
  }
2055
1764
  // ── Trajectory poller (mcp-server 3.3.0-rc.3) ─────────────────────────
2056
1765
  // Auto-extraction without relying on OpenClaw plugin's `agent_end` hook
@@ -2069,6 +1778,14 @@ async function main() {
2069
1778
  // recovery phrase never crosses into the extraction LLM — see the
2070
1779
  // top-of-file rationale in `extraction/extractor.ts`.
2071
1780
  startPollerSafely();
1781
+ // Construct the MCP server and wire its request handlers to the single
1782
+ // dispatch router. Created here (not at module load) so importing this file
1783
+ // in tests does not stand up a server or connect a transport.
1784
+ server = (0, server_setup_js_1.createTotalReclawServer)({
1785
+ callTool: callToolHandler,
1786
+ isManagedMode: () => !!subgraphState,
1787
+ getClient,
1788
+ });
2072
1789
  const transport = new stdio_js_1.StdioServerTransport();
2073
1790
  await server.connect(transport);
2074
1791
  }