@totalreclaw/mcp-server 3.2.0 → 3.3.0-rc.1

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 (49) hide show
  1. package/README.md +2 -1
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +119 -168
  5. package/dist/index.js.map +1 -1
  6. package/dist/pair-crypto.d.ts +95 -0
  7. package/dist/pair-crypto.d.ts.map +1 -0
  8. package/dist/pair-crypto.js +223 -0
  9. package/dist/pair-crypto.js.map +1 -0
  10. package/dist/pair-remote-client.d.ts +78 -0
  11. package/dist/pair-remote-client.d.ts.map +1 -0
  12. package/dist/pair-remote-client.js +355 -0
  13. package/dist/pair-remote-client.js.map +1 -0
  14. package/dist/prompts.d.ts +3 -2
  15. package/dist/prompts.d.ts.map +1 -1
  16. package/dist/prompts.js +14 -7
  17. package/dist/prompts.js.map +1 -1
  18. package/dist/session-id.d.ts +17 -0
  19. package/dist/session-id.d.ts.map +1 -0
  20. package/dist/session-id.js +26 -0
  21. package/dist/session-id.js.map +1 -0
  22. package/dist/subgraph/confirm-indexed.d.ts +37 -0
  23. package/dist/subgraph/confirm-indexed.d.ts.map +1 -0
  24. package/dist/subgraph/confirm-indexed.js +99 -0
  25. package/dist/subgraph/confirm-indexed.js.map +1 -0
  26. package/dist/subgraph/reranker.d.ts +49 -134
  27. package/dist/subgraph/reranker.d.ts.map +1 -1
  28. package/dist/subgraph/reranker.js +84 -376
  29. package/dist/subgraph/reranker.js.map +1 -1
  30. package/dist/tools/index.d.ts +1 -0
  31. package/dist/tools/index.d.ts.map +1 -1
  32. package/dist/tools/index.js +7 -1
  33. package/dist/tools/index.js.map +1 -1
  34. package/dist/tools/pair.d.ts +118 -0
  35. package/dist/tools/pair.d.ts.map +1 -0
  36. package/dist/tools/pair.js +399 -0
  37. package/dist/tools/pair.js.map +1 -0
  38. package/dist/tools/pin.d.ts +12 -0
  39. package/dist/tools/pin.d.ts.map +1 -1
  40. package/dist/tools/pin.js +14 -0
  41. package/dist/tools/pin.js.map +1 -1
  42. package/dist/tools/retype.d.ts +15 -0
  43. package/dist/tools/retype.d.ts.map +1 -1
  44. package/dist/tools/retype.js +17 -0
  45. package/dist/tools/retype.js.map +1 -1
  46. package/dist/tools/status.d.ts.map +1 -1
  47. package/dist/tools/status.js +19 -5
  48. package/dist/tools/status.js.map +1 -1
  49. package/package.json +4 -2
@@ -0,0 +1,118 @@
1
+ /**
2
+ * TotalReclaw MCP — totalreclaw_pair tool
3
+ *
4
+ * Browser-mediated TotalReclaw account setup. The user opens the returned
5
+ * URL on their phone or another browser, the browser generates (or imports)
6
+ * a 12-word BIP-39 recovery phrase, encrypts it via x25519 ECDH + AES-256-GCM,
7
+ * and uploads the ciphertext to the same relay this MCP server already talks
8
+ * to. The MCP server decrypts the phrase locally and writes
9
+ * `~/.totalreclaw/credentials.json` so a host restart picks the user up in
10
+ * configured mode.
11
+ *
12
+ * Phrase-safety invariants (see project_phrase_safety_rule):
13
+ * - The phrase NEVER appears in the tool's return payload.
14
+ * - The phrase NEVER passes through stdout / stderr / logs.
15
+ * - The phrase is generated in the browser; the MCP server only ever sees
16
+ * the decrypted plaintext in-memory inside `completePairing` and writes
17
+ * it to the 0600-mode credentials.json on disk.
18
+ *
19
+ * Flow:
20
+ * 1. Tool handler resolves the relay URL from
21
+ * `TOTALRECLAW_PAIR_RELAY_URL` (preferred) or `TOTALRECLAW_SERVER_URL`
22
+ * (rewrites http→ws / https→wss). Falls back to `wss://api.totalreclaw.xyz`.
23
+ * 2. Opens a relay pair session (`openRemotePairSession`) and returns
24
+ * `{url, pin, expires_at_ms}` to the agent immediately.
25
+ * 3. Schedules a background `awaitPhraseUpload` task so the WS stays open
26
+ * across the tool's return. When the browser POSTs the encrypted
27
+ * phrase, completePairing decrypts, derives keys, registers with the
28
+ * relay, and writes credentials.json.
29
+ *
30
+ * MCP-process lifecycle note: stdio MCP servers stay alive until the host
31
+ * disconnects, so the background WS-await runs to completion or the relay
32
+ * 5-minute TTL, whichever is first. There is a 60-second hard timeout
33
+ * (matching the plugin) so a slow / abandoned browser flow doesn't hold the
34
+ * process hostage. After completion the user must restart their MCP host
35
+ * (Claude Desktop / Cursor / Claude Code) for the server to re-read
36
+ * credentials.json and switch out of `unconfigured` mode.
37
+ *
38
+ * Reference implementation: `skill/plugin/index.ts` (totalreclaw_pair tool
39
+ * handler) and `skill/plugin/pair-cli-relay.ts` (CLI runner). The crypto +
40
+ * WS-client code in `pair-crypto.ts` and `pair-remote-client.ts` is a
41
+ * verbatim port of the plugin equivalents.
42
+ */
43
+ import { type RemotePairSession } from '../pair-remote-client.js';
44
+ export declare const pairToolDefinition: {
45
+ name: string;
46
+ description: string;
47
+ inputSchema: {
48
+ type: string;
49
+ properties: {
50
+ mode: {
51
+ type: string;
52
+ enum: string[];
53
+ description: string;
54
+ default: string;
55
+ };
56
+ };
57
+ additionalProperties: boolean;
58
+ };
59
+ annotations: {
60
+ readOnlyHint: boolean;
61
+ destructiveHint: boolean;
62
+ idempotentHint: boolean;
63
+ };
64
+ };
65
+ /**
66
+ * Resolve the relay base URL for the pair WS.
67
+ *
68
+ * Order:
69
+ * 1. `TOTALRECLAW_PAIR_RELAY_URL` if set (explicit override).
70
+ * 2. `TOTALRECLAW_SERVER_URL` rewritten http→ws / https→wss (matches
71
+ * plugin's 3.3.12-rc.2 behavior — pair WS lives on the same host as
72
+ * the rest of the API, so RC users on api-staging stay on staging).
73
+ * 3. Default `wss://api.totalreclaw.xyz`.
74
+ */
75
+ export declare function resolvePairRelayUrl(env?: NodeJS.ProcessEnv): string;
76
+ /**
77
+ * Run the full WS-await + decrypt + register + write-credentials pipeline.
78
+ * Exported for testing — the tool handler schedules this as a background
79
+ * task so the agent can return URL/PIN to the user immediately.
80
+ *
81
+ * Phrase NEVER leaves this function. Logs only the relay token prefix +
82
+ * userId prefix.
83
+ */
84
+ export declare function runPairBackgroundTask(opts: {
85
+ session: RemotePairSession;
86
+ relayBaseUrl: string;
87
+ serverUrl: string;
88
+ hardTimeoutMs?: number;
89
+ log?: (level: 'info' | 'warn' | 'error', msg: string) => void;
90
+ }): Promise<void>;
91
+ export interface HandlePairOptions {
92
+ /** Override relay URL — for tests. */
93
+ relayBaseUrl?: string;
94
+ /** Override server URL written into credentials.json — defaults to env. */
95
+ serverUrl?: string;
96
+ /**
97
+ * If true, await the background task before returning. Used by tests so
98
+ * they can assert on the post-completion state. In production this is
99
+ * false — the tool handler returns immediately after URL/PIN emit so the
100
+ * agent can hand the URL to the user.
101
+ */
102
+ awaitBackground?: boolean;
103
+ /** Logger override (tests). Default writes to stderr. */
104
+ log?: (level: 'info' | 'warn' | 'error', msg: string) => void;
105
+ }
106
+ /**
107
+ * Handle a totalreclaw_pair tool call. Returns the URL + PIN + expires_at_ms
108
+ * structured payload immediately and schedules the encrypted-phrase WS-await
109
+ * as a background task.
110
+ */
111
+ export declare function handlePair(args: Record<string, unknown> | undefined, opts?: HandlePairOptions): Promise<{
112
+ content: Array<{
113
+ type: string;
114
+ text: string;
115
+ }>;
116
+ isError?: boolean;
117
+ }>;
118
+ //# sourceMappingURL=pair.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pair.d.ts","sourceRoot":"","sources":["../../src/tools/pair.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAUH,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,0BAA0B,CAAC;AAwBlC,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;CAuB9B,CAAC;AAMF;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,CAchF;AAuED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CAAC,IAAI,EAAE;IAChD,OAAO,EAAE,iBAAiB,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/D,GAAG,OAAO,CAAC,IAAI,CAAC,CAgGhB;AAMD,MAAM,WAAW,iBAAiB;IAChC,sCAAsC;IACtC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,2EAA2E;IAC3E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,yDAAyD;IACzD,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/D;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAC9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACzC,IAAI,GAAE,iBAAsB,GAC3B,OAAO,CAAC;IAAE,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CAsFhF"}
@@ -0,0 +1,399 @@
1
+ "use strict";
2
+ /**
3
+ * TotalReclaw MCP — totalreclaw_pair tool
4
+ *
5
+ * Browser-mediated TotalReclaw account setup. The user opens the returned
6
+ * URL on their phone or another browser, the browser generates (or imports)
7
+ * a 12-word BIP-39 recovery phrase, encrypts it via x25519 ECDH + AES-256-GCM,
8
+ * and uploads the ciphertext to the same relay this MCP server already talks
9
+ * to. The MCP server decrypts the phrase locally and writes
10
+ * `~/.totalreclaw/credentials.json` so a host restart picks the user up in
11
+ * configured mode.
12
+ *
13
+ * Phrase-safety invariants (see project_phrase_safety_rule):
14
+ * - The phrase NEVER appears in the tool's return payload.
15
+ * - The phrase NEVER passes through stdout / stderr / logs.
16
+ * - The phrase is generated in the browser; the MCP server only ever sees
17
+ * the decrypted plaintext in-memory inside `completePairing` and writes
18
+ * it to the 0600-mode credentials.json on disk.
19
+ *
20
+ * Flow:
21
+ * 1. Tool handler resolves the relay URL from
22
+ * `TOTALRECLAW_PAIR_RELAY_URL` (preferred) or `TOTALRECLAW_SERVER_URL`
23
+ * (rewrites http→ws / https→wss). Falls back to `wss://api.totalreclaw.xyz`.
24
+ * 2. Opens a relay pair session (`openRemotePairSession`) and returns
25
+ * `{url, pin, expires_at_ms}` to the agent immediately.
26
+ * 3. Schedules a background `awaitPhraseUpload` task so the WS stays open
27
+ * across the tool's return. When the browser POSTs the encrypted
28
+ * phrase, completePairing decrypts, derives keys, registers with the
29
+ * relay, and writes credentials.json.
30
+ *
31
+ * MCP-process lifecycle note: stdio MCP servers stay alive until the host
32
+ * disconnects, so the background WS-await runs to completion or the relay
33
+ * 5-minute TTL, whichever is first. There is a 60-second hard timeout
34
+ * (matching the plugin) so a slow / abandoned browser flow doesn't hold the
35
+ * process hostage. After completion the user must restart their MCP host
36
+ * (Claude Desktop / Cursor / Claude Code) for the server to re-read
37
+ * credentials.json and switch out of `unconfigured` mode.
38
+ *
39
+ * Reference implementation: `skill/plugin/index.ts` (totalreclaw_pair tool
40
+ * handler) and `skill/plugin/pair-cli-relay.ts` (CLI runner). The crypto +
41
+ * WS-client code in `pair-crypto.ts` and `pair-remote-client.ts` is a
42
+ * verbatim port of the plugin equivalents.
43
+ */
44
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
45
+ if (k2 === undefined) k2 = k;
46
+ var desc = Object.getOwnPropertyDescriptor(m, k);
47
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
48
+ desc = { enumerable: true, get: function() { return m[k]; } };
49
+ }
50
+ Object.defineProperty(o, k2, desc);
51
+ }) : (function(o, m, k, k2) {
52
+ if (k2 === undefined) k2 = k;
53
+ o[k2] = m[k];
54
+ }));
55
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
56
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
57
+ }) : function(o, v) {
58
+ o["default"] = v;
59
+ });
60
+ var __importStar = (this && this.__importStar) || (function () {
61
+ var ownKeys = function(o) {
62
+ ownKeys = Object.getOwnPropertyNames || function (o) {
63
+ var ar = [];
64
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
65
+ return ar;
66
+ };
67
+ return ownKeys(o);
68
+ };
69
+ return function (mod) {
70
+ if (mod && mod.__esModule) return mod;
71
+ var result = {};
72
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
73
+ __setModuleDefault(result, mod);
74
+ return result;
75
+ };
76
+ })();
77
+ Object.defineProperty(exports, "__esModule", { value: true });
78
+ exports.pairToolDefinition = void 0;
79
+ exports.resolvePairRelayUrl = resolvePairRelayUrl;
80
+ exports.runPairBackgroundTask = runPairBackgroundTask;
81
+ exports.handlePair = handlePair;
82
+ const fs = __importStar(require("node:fs"));
83
+ const path = __importStar(require("node:path"));
84
+ const os = __importStar(require("node:os"));
85
+ const bip39_1 = require("@scure/bip39");
86
+ const english_js_1 = require("@scure/bip39/wordlists/english.js");
87
+ const prompts_js_1 = require("../prompts.js");
88
+ const pair_remote_client_js_1 = require("../pair-remote-client.js");
89
+ const setup_js_1 = require("../cli/setup.js");
90
+ // ---------------------------------------------------------------------------
91
+ // Constants
92
+ // ---------------------------------------------------------------------------
93
+ const CREDENTIALS_DIR = path.join(os.homedir(), '.totalreclaw');
94
+ const CREDENTIALS_PATH = path.join(CREDENTIALS_DIR, 'credentials.json');
95
+ /**
96
+ * Hard timeout for the background WS-await. Matches the plugin
97
+ * (`PAIR_TOOL_HARD_TIMEOUT_MS = 60_000`) — long enough for a slow
98
+ * scan-and-paste, short enough that a stuck browser doesn't hold the
99
+ * MCP process indefinitely.
100
+ */
101
+ const PAIR_TOOL_HARD_TIMEOUT_MS = 60_000;
102
+ const DEFAULT_RELAY_URL_WSS = 'wss://api.totalreclaw.xyz';
103
+ // ---------------------------------------------------------------------------
104
+ // Tool definition
105
+ // ---------------------------------------------------------------------------
106
+ exports.pairToolDefinition = {
107
+ name: 'totalreclaw_pair',
108
+ description: prompts_js_1.PAIR_TOOL_DESCRIPTION,
109
+ inputSchema: {
110
+ type: 'object',
111
+ properties: {
112
+ mode: {
113
+ type: 'string',
114
+ enum: ['generate', 'import'],
115
+ description: '"generate" = the browser will create a NEW recovery phrase. "import" = the ' +
116
+ 'browser will accept an EXISTING phrase that the user pastes in their browser ' +
117
+ '(never through chat).',
118
+ default: 'generate',
119
+ },
120
+ },
121
+ additionalProperties: false,
122
+ },
123
+ annotations: {
124
+ readOnlyHint: false,
125
+ destructiveHint: false,
126
+ idempotentHint: false,
127
+ },
128
+ };
129
+ // ---------------------------------------------------------------------------
130
+ // Internal helpers
131
+ // ---------------------------------------------------------------------------
132
+ /**
133
+ * Resolve the relay base URL for the pair WS.
134
+ *
135
+ * Order:
136
+ * 1. `TOTALRECLAW_PAIR_RELAY_URL` if set (explicit override).
137
+ * 2. `TOTALRECLAW_SERVER_URL` rewritten http→ws / https→wss (matches
138
+ * plugin's 3.3.12-rc.2 behavior — pair WS lives on the same host as
139
+ * the rest of the API, so RC users on api-staging stay on staging).
140
+ * 3. Default `wss://api.totalreclaw.xyz`.
141
+ */
142
+ function resolvePairRelayUrl(env = process.env) {
143
+ const explicit = env.TOTALRECLAW_PAIR_RELAY_URL;
144
+ if (explicit && explicit.trim().length > 0) {
145
+ return explicit.trim().replace(/\/+$/, '');
146
+ }
147
+ const serverUrl = env.TOTALRECLAW_SERVER_URL;
148
+ if (serverUrl && serverUrl.trim().length > 0) {
149
+ return serverUrl
150
+ .trim()
151
+ .replace(/^https:\/\//, 'wss://')
152
+ .replace(/^http:\/\//, 'ws://')
153
+ .replace(/\/+$/, '');
154
+ }
155
+ return DEFAULT_RELAY_URL_WSS;
156
+ }
157
+ /**
158
+ * Convert a wss:// or ws:// relay URL back to https:// or http:// for the
159
+ * REST `/v1/register` call. Used by the background completePairing handler.
160
+ */
161
+ function relayBaseToHttps(relayBase) {
162
+ return relayBase
163
+ .replace(/^wss:\/\//, 'https://')
164
+ .replace(/^ws:\/\//, 'http://')
165
+ .replace(/\/+$/, '');
166
+ }
167
+ /**
168
+ * Write credentials.json with 0600 permissions. Mirrors `cli/setup.ts`
169
+ * `saveCredentials` but accepts a richer payload (`mnemonic`, `salt` hex,
170
+ * `userId`, `serverUrl`).
171
+ */
172
+ function writePairedCredentials(creds) {
173
+ if (!fs.existsSync(CREDENTIALS_DIR)) {
174
+ fs.mkdirSync(CREDENTIALS_DIR, { recursive: true, mode: 0o700 });
175
+ }
176
+ fs.writeFileSync(CREDENTIALS_PATH, JSON.stringify(creds, null, 2) + '\n', {
177
+ encoding: 'utf-8',
178
+ mode: 0o600,
179
+ });
180
+ }
181
+ /**
182
+ * POST /v1/register — best-effort. Returns user_id on success, or undefined
183
+ * on USER_EXISTS (in which case the caller derives userId from the
184
+ * auth-key hash). Other errors throw — the caller logs and continues with
185
+ * mnemonic-only credentials so the next MCP-host restart can retry.
186
+ */
187
+ async function registerUser(httpsBase, authKeyHash, saltHex) {
188
+ const url = `${httpsBase}/v1/register`;
189
+ const response = await fetch(url, {
190
+ method: 'POST',
191
+ headers: { 'Content-Type': 'application/json' },
192
+ body: JSON.stringify({
193
+ auth_key_hash: authKeyHash,
194
+ salt: saltHex,
195
+ }),
196
+ });
197
+ if (!response.ok) {
198
+ const body = await response.text().catch(() => '');
199
+ if (body.includes('USER_EXISTS') || response.status === 409) {
200
+ return undefined;
201
+ }
202
+ throw new Error(`register failed (HTTP ${response.status}): ${body || response.statusText}`);
203
+ }
204
+ const data = (await response.json());
205
+ if (!data.user_id) {
206
+ throw new Error('register: response missing user_id');
207
+ }
208
+ return data.user_id;
209
+ }
210
+ // ---------------------------------------------------------------------------
211
+ // Background completion task
212
+ // ---------------------------------------------------------------------------
213
+ /**
214
+ * Run the full WS-await + decrypt + register + write-credentials pipeline.
215
+ * Exported for testing — the tool handler schedules this as a background
216
+ * task so the agent can return URL/PIN to the user immediately.
217
+ *
218
+ * Phrase NEVER leaves this function. Logs only the relay token prefix +
219
+ * userId prefix.
220
+ */
221
+ async function runPairBackgroundTask(opts) {
222
+ const log = opts.log ??
223
+ ((level, msg) => {
224
+ // Default logger goes to stderr so MCP stdout (JSON-RPC framing) stays clean.
225
+ const prefix = `totalreclaw_pair[${level}]:`;
226
+ if (level === 'error') {
227
+ console.error(prefix, msg);
228
+ }
229
+ else {
230
+ console.error(prefix, msg);
231
+ }
232
+ });
233
+ const hardTimeoutMs = opts.hardTimeoutMs ?? PAIR_TOOL_HARD_TIMEOUT_MS;
234
+ const httpsBase = relayBaseToHttps(opts.relayBaseUrl);
235
+ const tokenTail = opts.session.token.slice(0, 8);
236
+ const phraseUploadPromise = (0, pair_remote_client_js_1.awaitPhraseUpload)(opts.session, {
237
+ phraseValidator: (p) => (0, bip39_1.validateMnemonic)(p, english_js_1.wordlist),
238
+ completePairing: async ({ mnemonic }) => {
239
+ try {
240
+ // Derive auth key + salt — matches setup.ts deriveAuthKey shape.
241
+ const { authKeyHex, saltHex } = (0, setup_js_1.deriveAuthKey)(mnemonic);
242
+ const authKeyHash = (0, setup_js_1.computeAuthKeyHash)(authKeyHex);
243
+ // Register with relay — best-effort. USER_EXISTS → derive userId
244
+ // deterministically from the auth-key hash so credentials are
245
+ // still complete. Other errors → continue with mnemonic-only
246
+ // creds and let the next host restart retry register.
247
+ let registeredUserId;
248
+ try {
249
+ registeredUserId = await registerUser(httpsBase, authKeyHash, saltHex);
250
+ if (registeredUserId) {
251
+ log('info', `pair: registered user_id=${registeredUserId.slice(0, 8)}…`);
252
+ }
253
+ else {
254
+ registeredUserId = authKeyHash.slice(0, 32);
255
+ log('info', `pair: USER_EXISTS — using derived userId=${registeredUserId.slice(0, 8)}…`);
256
+ }
257
+ }
258
+ catch (regErr) {
259
+ const m = regErr instanceof Error ? regErr.message : String(regErr);
260
+ log('warn', `pair: /v1/register failed (best-effort, will retry on host restart): ${m}`);
261
+ registeredUserId = authKeyHash.slice(0, 32);
262
+ }
263
+ try {
264
+ writePairedCredentials({
265
+ userId: registeredUserId,
266
+ salt: saltHex,
267
+ serverUrl: opts.serverUrl,
268
+ mnemonic,
269
+ });
270
+ }
271
+ catch (writeErr) {
272
+ const m = writeErr instanceof Error ? writeErr.message : String(writeErr);
273
+ log('error', `pair: credentials.json write failed: ${m}`);
274
+ return { state: 'error', error: 'credentials_write_failed' };
275
+ }
276
+ log('info', `pair: session ${tokenTail}… completed; credentials written (userId=${registeredUserId.slice(0, 8)}…)`);
277
+ return { state: 'active' };
278
+ }
279
+ catch (err) {
280
+ const msg = err instanceof Error ? err.message : String(err);
281
+ log('error', `pair: completePairing failed: ${msg}`);
282
+ return { state: 'error', error: msg };
283
+ }
284
+ },
285
+ timeoutMs: hardTimeoutMs,
286
+ });
287
+ // Outer race against a hard timeout — covers the case where the WS stays
288
+ // open but the browser never POSTs (rare; matches plugin's 3.3.4-rc.2 fix).
289
+ const TIMEOUT_SENTINEL = {
290
+ status: 'timed_out',
291
+ message: `Pair flow timed out (${hardTimeoutMs / 1000}s) — generate a new URL with totalreclaw_pair.`,
292
+ };
293
+ let hardTimer;
294
+ const hardTimeoutPromise = new Promise((resolve) => {
295
+ hardTimer = setTimeout(() => resolve(TIMEOUT_SENTINEL), hardTimeoutMs);
296
+ });
297
+ try {
298
+ const raced = await Promise.race([phraseUploadPromise, hardTimeoutPromise]);
299
+ if (raced &&
300
+ typeof raced === 'object' &&
301
+ raced.status === 'timed_out') {
302
+ log('warn', `pair: hard timeout (token=${tokenTail}…)`);
303
+ }
304
+ }
305
+ catch (bgErr) {
306
+ const bgMsg = bgErr instanceof Error ? bgErr.message : String(bgErr);
307
+ log('warn', `pair: background task ended for token=${tokenTail}…: ${bgMsg}`);
308
+ }
309
+ finally {
310
+ if (hardTimer)
311
+ clearTimeout(hardTimer);
312
+ }
313
+ }
314
+ /**
315
+ * Handle a totalreclaw_pair tool call. Returns the URL + PIN + expires_at_ms
316
+ * structured payload immediately and schedules the encrypted-phrase WS-await
317
+ * as a background task.
318
+ */
319
+ async function handlePair(args, opts = {}) {
320
+ const rawMode = args?.mode;
321
+ const mode = rawMode === 'import' ? 'import' : 'generate';
322
+ const relayBaseUrl = opts.relayBaseUrl ?? resolvePairRelayUrl();
323
+ const serverUrl = opts.serverUrl ?? process.env.TOTALRECLAW_SERVER_URL ?? 'https://api.totalreclaw.xyz';
324
+ let session;
325
+ try {
326
+ session = await (0, pair_remote_client_js_1.openRemotePairSession)({
327
+ relayBaseUrl,
328
+ mode: mode === 'generate' ? 'generate' : 'import',
329
+ });
330
+ }
331
+ catch (err) {
332
+ const msg = err instanceof Error ? err.message : String(err);
333
+ return {
334
+ content: [
335
+ {
336
+ type: 'text',
337
+ text: JSON.stringify({
338
+ error: 'pair_session_open_failed',
339
+ message: `Failed to open relay pair session: ${msg}`,
340
+ relay_base_url: relayBaseUrl,
341
+ }),
342
+ },
343
+ ],
344
+ isError: true,
345
+ };
346
+ }
347
+ // ISO-8601 → ms for tool-payload parity with the plugin.
348
+ const parsedExpiresMs = Date.parse(session.expiresAt);
349
+ const expiresAtMs = Number.isFinite(parsedExpiresMs)
350
+ ? parsedExpiresMs
351
+ : Date.now() + 5 * 60_000;
352
+ // Schedule the background WS-await. In production we DO NOT await it —
353
+ // the tool returns URL+PIN immediately so the agent can hand the URL to
354
+ // the user. The MCP server process stays alive (stdio host child) so the
355
+ // background task can run to completion.
356
+ const bgPromise = runPairBackgroundTask({
357
+ session,
358
+ relayBaseUrl,
359
+ serverUrl,
360
+ log: opts.log,
361
+ });
362
+ if (opts.awaitBackground) {
363
+ await bgPromise;
364
+ }
365
+ else {
366
+ // Detach; surface unhandled rejections via the same logger.
367
+ bgPromise.catch((err) => {
368
+ const msg = err instanceof Error ? err.message : String(err);
369
+ const log = opts.log ??
370
+ ((level, m) => console.error(`totalreclaw_pair[${level}]:`, m));
371
+ log('warn', `pair: background task rejected: ${msg}`);
372
+ });
373
+ }
374
+ const instructions = mode === 'generate'
375
+ ? `The browser will generate a NEW 12-word recovery phrase and ask the user to write it down + retype 3 words before finalizing.`
376
+ : `The browser will accept an EXISTING phrase that the user pastes in the browser (never through chat).`;
377
+ return {
378
+ content: [
379
+ {
380
+ type: 'text',
381
+ text: JSON.stringify({
382
+ url: session.url,
383
+ pin: session.pin,
384
+ expires_at_ms: expiresAtMs,
385
+ mode,
386
+ relay_base_url: relayBaseUrl,
387
+ instructions: [
388
+ `Open the URL above on the user's phone or another browser (copy-paste).`,
389
+ instructions,
390
+ `Enter the 6-digit PIN shown above into the browser.`,
391
+ `The encrypted phrase uploads to this MCP server — it NEVER touches the LLM.`,
392
+ `After the browser shows "Pairing complete", restart the MCP host (Claude Desktop / Cursor / Claude Code) so the server re-reads ~/.totalreclaw/credentials.json. The session expires in ~5 minutes.`,
393
+ ],
394
+ }),
395
+ },
396
+ ],
397
+ };
398
+ }
399
+ //# sourceMappingURL=pair.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pair.js","sourceRoot":"","sources":["../../src/tools/pair.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EH,kDAcC;AA+ED,sDAsGC;AA2BD,gCAyFC;AAlYD,4CAA8B;AAC9B,gDAAkC;AAClC,4CAA8B;AAE9B,wCAAgD;AAChD,kEAA6D;AAE7D,8CAAsD;AACtD,oEAIkC;AAClC,8CAAoE;AAEpE,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,cAAc,CAAC,CAAC;AA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B,MAAM,SAAS,CAAC;IAClB,CAAC;SAAM,CAAC;QACN,4DAA4D;QAC5D,SAAS,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YACtB,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC7D,MAAM,GAAG,GACP,IAAI,CAAC,GAAG;gBACR,CAAC,CAAC,KAAa,EAAE,CAAS,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,oBAAoB,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;YAClF,GAAG,CAAC,MAAM,EAAE,mCAAmC,GAAG,EAAE,CAAC,CAAC;QACxD,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,YAAY,GAChB,IAAI,KAAK,UAAU;QACjB,CAAC,CAAC,+HAA+H;QACjI,CAAC,CAAC,sGAAsG,CAAC;IAE7G,OAAO;QACL,OAAO,EAAE;YACP;gBACE,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;oBACnB,GAAG,EAAE,OAAO,CAAC,GAAG;oBAChB,GAAG,EAAE,OAAO,CAAC,GAAG;oBAChB,aAAa,EAAE,WAAW;oBAC1B,IAAI;oBACJ,cAAc,EAAE,YAAY;oBAC5B,YAAY,EAAE;wBACZ,yEAAyE;wBACzE,YAAY;wBACZ,qDAAqD;wBACrD,6EAA6E;wBAC7E,qMAAqM;qBACtM;iBACF,CAAC;aACH;SACF;KACF,CAAC;AACJ,CAAC"}
@@ -142,6 +142,12 @@ export interface PinOpDeps {
142
142
  blindIndices: string[];
143
143
  encryptedEmbedding?: string;
144
144
  }>;
145
+ /**
146
+ * Optional read-after-write hook. Called after submitBatch returns success;
147
+ * polls the subgraph for the new fact id. Returning `false` causes the
148
+ * result to surface `partial: true`. When undefined, the op skips the wait.
149
+ */
150
+ confirmIndexed?: (factId: string, expect?: 'active' | 'inactive') => Promise<boolean>;
145
151
  }
146
152
  export interface PinOpResult {
147
153
  success: boolean;
@@ -153,6 +159,12 @@ export interface PinOpResult {
153
159
  tx_hash?: string;
154
160
  reason?: string;
155
161
  error?: string;
162
+ /**
163
+ * On-chain pin/unpin succeeded but the subgraph indexer hasn't confirmed
164
+ * the new fact id within the timeout window. `tx_hash` is observable on
165
+ * the explorer; a follow-up recall/export may briefly show stale state.
166
+ */
167
+ partial?: boolean;
156
168
  }
157
169
  /**
158
170
  * Execute a pin or unpin operation on a single fact.
@@ -1 +1 @@
1
- {"version":3,"file":"pin.d.ts","sourceRoot":"","sources":["../../src/tools/pin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAgBH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAwBhE,uEAAuE;AACvE,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,qEAAqE;AACrE,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,oBAAoB,GAAG,UAAU,GAAG,QAAQ,CAAC;IACrD,MAAM,CAAC,EAAE,iBAAiB,GAAG,eAAe,GAAG,UAAU,CAAC;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EAAE,eAAe,CAAC;IACpC,gBAAgB,CAAC,EAAE,eAAe,CAAC;IACnC;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC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C;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,CAAC,CAQ7D;AAED,uEAAuE;AACvE,wBAAsB,WAAW,CAC/B,IAAI,EAAE,OAAO,GACZ,OAAO,CAAC;IAAE,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,CAAC,CAQ7D;AAiCD,gGAAgG;AAChG,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,OAAO,EACb,IAAI,EAAE,SAAS,GACd,OAAO,CAAC;IAAE,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,CAAC,CAK7D;AAED,wBAAsB,2BAA2B,CAC/C,IAAI,EAAE,OAAO,EACb,IAAI,EAAE,SAAS,GACd,OAAO,CAAC;IAAE,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,CAAC,CAK7D"}
package/dist/tools/pin.js CHANGED
@@ -628,6 +628,19 @@ async function executePinOperation(factId, targetStatus, deps, reason) {
628
628
  tx_hash: txHash,
629
629
  };
630
630
  }
631
+ // 8. Read-after-write — wait for the subgraph to index the new fact id
632
+ // before returning success. On timeout we still claim success (chain
633
+ // write IS acknowledged) but flag `partial: true` so callers can
634
+ // explain that recall/export may briefly surface stale state.
635
+ let indexed = true;
636
+ if (deps.confirmIndexed) {
637
+ try {
638
+ indexed = await deps.confirmIndexed(newFactId, 'active');
639
+ }
640
+ catch {
641
+ indexed = false;
642
+ }
643
+ }
631
644
  return {
632
645
  success: true,
633
646
  fact_id: factId,
@@ -636,6 +649,7 @@ async function executePinOperation(factId, targetStatus, deps, reason) {
636
649
  new_status: targetStatus,
637
650
  tx_hash: txHash,
638
651
  reason,
652
+ ...(indexed ? {} : { partial: true }),
639
653
  };
640
654
  }
641
655
  catch (err) {