replywizard-whatsapp-mcp 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,133 @@
1
+ Required Notice: Copyright Palworks FZE LLC (https://replywizard.app)
2
+
3
+ # PolyForm Noncommercial License 1.0.0
4
+
5
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree
10
+ to them as both strict obligations and conditions to all
11
+ your licenses.
12
+
13
+ ## Copyright License
14
+
15
+ The licensor grants you a copyright license for the
16
+ software to do everything you might do with the software
17
+ that would otherwise infringe the licensor's copyright
18
+ in it for any permitted purpose. However, you may
19
+ only distribute the software according to [Distribution
20
+ License](#distribution-license) and make changes or new works
21
+ based on the software according to [Changes and New Works
22
+ License](#changes-and-new-works-license).
23
+
24
+ ## Distribution License
25
+
26
+ The licensor grants you an additional copyright license
27
+ to distribute copies of the software. Your license
28
+ to distribute covers distributing the software with
29
+ changes and new works permitted by [Changes and New Works
30
+ License](#changes-and-new-works-license).
31
+
32
+ ## Notices
33
+
34
+ You must ensure that anyone who gets a copy of any part of
35
+ the software from you also gets a copy of these terms or the
36
+ URL for them above, as well as copies of any plain-text lines
37
+ beginning with `Required Notice:` that the licensor provided
38
+ with the software. For example:
39
+
40
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
41
+
42
+ ## Changes and New Works License
43
+
44
+ The licensor grants you an additional copyright license to
45
+ make changes and new works based on the software for any
46
+ permitted purpose.
47
+
48
+ ## Patent License
49
+
50
+ The licensor grants you a patent license for the software that
51
+ covers patent claims the licensor can license, or becomes able
52
+ to license, that you would infringe by using the software.
53
+
54
+ ## Noncommercial Purposes
55
+
56
+ Any noncommercial purpose is a permitted purpose.
57
+
58
+ ## Personal Uses
59
+
60
+ Personal use for research, experiment, and testing for
61
+ the benefit of public knowledge, personal study, private
62
+ entertainment, hobby projects, amateur pursuits, or religious
63
+ observance, without any anticipated commercial application,
64
+ is use for a permitted purpose.
65
+
66
+ ## Noncommercial Organizations
67
+
68
+ Use by any charitable organization, educational institution,
69
+ public research organization, public safety or health
70
+ organization, environmental protection organization,
71
+ or government institution is use for a permitted purpose
72
+ regardless of the source of funding or obligations resulting
73
+ from the funding.
74
+
75
+ ## Fair Use
76
+
77
+ You may have "fair use" rights for the software under the
78
+ law. These terms do not limit them.
79
+
80
+ ## No Other Rights
81
+
82
+ These terms do not allow you to sublicense or transfer any of
83
+ your licenses to anyone else, or prevent the licensor from
84
+ granting licenses to anyone else. These terms do not imply
85
+ any other licenses.
86
+
87
+ ## Patent Defense
88
+
89
+ If you make any written claim that the software infringes or
90
+ contributes to infringement of any patent, your patent license
91
+ for the software granted under these terms ends immediately. If
92
+ your company makes such a claim, your patent license ends
93
+ immediately for work on behalf of your company.
94
+
95
+ ## Violations
96
+
97
+ The first time you are notified in writing that you have
98
+ violated any of these terms, or done anything with the software
99
+ not covered by your licenses, your licenses can nonetheless
100
+ continue if you come into full compliance with these terms,
101
+ and take practical steps to correct past violations, within
102
+ 32 days of receiving notice. Otherwise, all your licenses
103
+ end immediately.
104
+
105
+ ## No Liability
106
+
107
+ ***As far as the law allows, the software comes as is, without
108
+ any warranty or condition, and the licensor will not be liable
109
+ to you for any damages arising out of these terms or the use
110
+ or nature of the software, under any kind of legal claim.***
111
+
112
+ ## Definitions
113
+
114
+ The **licensor** is the individual or entity offering these
115
+ terms, and the **software** is the software the licensor makes
116
+ available under these terms.
117
+
118
+ **You** refers to the individual or entity agreeing to these
119
+ terms.
120
+
121
+ **Your company** is any legal entity, sole proprietorship,
122
+ or other kind of organization that you work for, plus all
123
+ organizations that have control over, are under the control of,
124
+ or are under common control with that organization. **Control**
125
+ means ownership of substantially all the assets of an entity,
126
+ or the power to direct its management and policies by vote,
127
+ contract, or otherwise. Control can be direct or indirect.
128
+
129
+ **Your licenses** are all the licenses granted to you for the
130
+ software under these terms.
131
+
132
+ **Use** means anything you do with the software requiring one
133
+ of your licenses.
package/README.md CHANGED
@@ -114,6 +114,8 @@ nothing the agent reads. The **Copy Antigravity config** button gives you the JS
114
114
  `--add-mcp` line is still printed on the tab, labelled for what it does, for anyone who wants
115
115
  the entry in the editor's own MCP panel as well.
116
116
 
117
+ **Staying connected (0.6.1, 0.6.2).** The daemon closes a session that has been quiet for 10 minutes and, with no browser connected, exits after 30. Up to 0.6.0 the connector your AI app launches kept one session for life, so the first request after a quiet spell answered "The Reply Wizard MCP daemon is not reachable" until you restarted the app's MCP server. From 0.6.1 the connector opens a new session, or starts the daemon again, and sends the request once more, with nothing for you to do; the daemon answers an unknown session with HTTP 404, as the MCP specification asks, so apps that connect over HTTP directly start a new session too; the daemon stays up while a paired browser is connected; and a freshly started daemon waits up to 40 seconds for the browser before answering "not connected", inside the request's own time budget. 0.6.2 fixes one case: a reconnect whose first message could not be sent used to end the connector process; it now fails that one request and the next request tries again.
118
+
117
119
  **Budgets (0.6.0).** `transcribe_voice_note` is allowed 160 seconds (voice capture inside the extension takes up to 130), and the host reports its real package version on the handshake and in `replywizard status`.
118
120
 
119
121
  **The bridge names its own version on the handshake** as of 0.3.1, so the extension can tell a
@@ -337,3 +339,17 @@ client. Printed, the two tell themselves apart.
337
339
 
338
340
  See [`../ARCHITECTURE.md`](../ARCHITECTURE.md) (MCP Integration) for the design, and
339
341
  [`../ROADMAP.md`](../ROADMAP.md) §3.4 for the open MCP items.
342
+
343
+ ## License
344
+
345
+ Copyright Palworks FZE LLC. From the first version published after 2026-10-24 this package is
346
+ licensed under the [PolyForm Noncommercial License 1.0.0](LICENSE): free for noncommercial use,
347
+ and every copy must keep the `Required Notice` line. Versions up to and including 0.6.0 were
348
+ published under the MIT License and stay under it.
349
+
350
+ **Reply Wizard users** (free or paid) have our additional permission to use this package with the
351
+ Reply Wizard extension for any purpose, including in their own business, under the
352
+ [Acceptable Use Policy](https://replywizard.app/acceptable-use) section 18.
353
+
354
+ Any other commercial use, such as embedding, redistributing, reselling or building a product on
355
+ this package, needs a commercial licence from Palworks FZE LLC: grievance@replywizard.app.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "replywizard-whatsapp-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Local MCP server and command line that expose WhatsApp Web (read + value tools) to AI clients via the Reply Wizard Chrome extension.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -46,5 +46,5 @@
46
46
  "@modelcontextprotocol/sdk": "^1.0.0",
47
47
  "ws": "^8.18.0"
48
48
  },
49
- "license": "MIT"
49
+ "license": "PolyForm-Noncommercial-1.0.0"
50
50
  }
package/src/connector.js CHANGED
@@ -146,18 +146,164 @@ export function spawnDetachedDaemon() {
146
146
  log('Started the Reply Wizard MCP daemon.');
147
147
  }
148
148
 
149
+ /**
150
+ * The daemon no longer holds our session: it reaped it after 10 quiet minutes, or it restarted.
151
+ * 404 is the MCP spec's answer; 400 with these words is what daemons up to 0.6.0 answered, and
152
+ * one of those may still be the daemon running when this connector starts.
153
+ */
154
+ const STALE_SESSION_TEXT = /No valid session|unknown Mcp-Session-Id/i;
155
+ export function isStaleSession(err) {
156
+ const code = err && err.code;
157
+ return code === 404 || (code === 400 && STALE_SESSION_TEXT.test(String((err && err.message) || '')));
158
+ }
159
+
160
+ /** Nothing is listening: the daemon exited (idle for 30 minutes, a crash, a reboot). */
161
+ export function isDaemonDown(err) {
162
+ if (!err) return false;
163
+ const text = `${err.message || ''} ${(err.cause && (err.cause.code || err.cause.message)) || ''}`;
164
+ return /fetch failed|ECONNREFUSED|ECONNRESET|socket hang up|other side closed/i.test(text);
165
+ }
166
+
167
+ /**
168
+ * A daemon-facing transport that survives the daemon forgetting us.
169
+ *
170
+ * WHY (measured 2026-11-08): the daemon reaps a session after 10 quiet minutes and exits after
171
+ * 30 minutes with none, both by design. The connector held ONE transport for its whole life, so
172
+ * the first tool call after any quiet spell longer than ten minutes was answered "daemon not
173
+ * reachable" while the daemon was up, and only restarting the AI app's MCP server cured it.
174
+ * That is the ordinary shape of a working day, not an edge case.
175
+ *
176
+ * So a send that fails because the session is gone, or because nothing is listening, is
177
+ * recovered here and the client never sees it: start the daemon again if it is down, open a
178
+ * new session, REPLAY the client's own `initialize` (its answer is swallowed, because the client
179
+ * already has one) and `notifications/initialized`, then send the original message again, once.
180
+ * Concurrent failures share one recovery. Anything else is thrown to the pump as before.
181
+ *
182
+ * Same surface as a transport (start/send/close/onmessage/onclose/onerror), so the pump is
183
+ * unchanged.
184
+ *
185
+ * @param {{makeTransport: () => object, revive: () => Promise<void>, replyTimeoutMs?: number}} deps
186
+ */
187
+ export function createDaemonLink({ makeTransport, revive, replyTimeoutMs = 15000 }) {
188
+ let current = null;
189
+ let initRequest = null;
190
+ let initialized = false;
191
+ let recovering = null;
192
+ let replays = 0;
193
+ let closed = false;
194
+ const internal = new Map(); // replayed initialize id -> resolve
195
+
196
+ const link = {
197
+ onmessage: null, onclose: null, onerror: null,
198
+ async start() { current = wire(makeTransport()); await current.start(); },
199
+ async send(msg) {
200
+ if (msg && msg.method === 'initialize' && msg.id !== undefined) initRequest = msg;
201
+ if (msg && msg.method === 'notifications/initialized') initialized = true;
202
+ const used = current;
203
+ try {
204
+ await used.send(msg);
205
+ } catch (err) {
206
+ if (closed) throw err;
207
+ // A call whose transport was REPLACED underneath it (another call's recovery closed it,
208
+ // which aborts whatever was in flight) is re-sent on the new one whatever its error was.
209
+ // Measured 2026-11-08: four parallel calls after a restart, one recovered and three
210
+ // failed with an abort that was not a "stale session" error.
211
+ const replaced = current !== used;
212
+ if (!replaced && !(isStaleSession(err) || isDaemonDown(err))) throw err;
213
+ if (msg && msg.method === 'initialize') throw err; // nothing to replay yet
214
+ if (!replaced) log(isDaemonDown(err) ? 'daemon is down; starting it again.' : 'daemon dropped our session; opening a new one.');
215
+ // Not replaced: this call leads the recovery. Replaced: wait for the one in progress, if
216
+ // any, and never start a second, which would close the session the first just opened.
217
+ if (!replaced || recovering) await recover(isDaemonDown(err));
218
+ await current.send(msg);
219
+ }
220
+ },
221
+ async close() { closed = true; const t = current; current = null; if (t) await t.close(); link.onclose && link.onclose(); },
222
+ };
223
+
224
+ function wire(t) {
225
+ t.onmessage = (m) => {
226
+ if (m && internal.has(m.id)) { const done = internal.get(m.id); internal.delete(m.id); done(m); return; }
227
+ link.onmessage && link.onmessage(m);
228
+ };
229
+ t.onerror = (e) => link.onerror && link.onerror(e);
230
+ t.onclose = () => {}; // a replaced transport closing is not the link closing
231
+ return t;
232
+ }
233
+
234
+ function recover(down) {
235
+ if (!recovering) {
236
+ recovering = (async () => {
237
+ if (down) await revive();
238
+ const old = current;
239
+ if (old) { old.onmessage = null; old.onerror = null; old.close().catch(() => {}); }
240
+ current = wire(makeTransport());
241
+ await current.start();
242
+ if (!initRequest) return;
243
+ const id = `rw-reconnect-${++replays}`;
244
+ let timer = null;
245
+ const answered = new Promise((resolve, reject) => {
246
+ internal.set(id, resolve);
247
+ timer = setTimeout(() => { if (internal.delete(id)) reject(new Error('the daemon did not answer the new session')); }, replyTimeoutMs);
248
+ timer.unref?.();
249
+ });
250
+ // If the replayed initialize cannot even be SENT, nothing awaits `answered`, and its timer
251
+ // rejecting later is an unhandled rejection, which ends this process: the AI app would lose
252
+ // the server on exactly the failure this recovery exists for (review 2026-11-08, finding A).
253
+ answered.catch(() => {});
254
+ let reply;
255
+ try {
256
+ await current.send({ ...initRequest, id });
257
+ reply = await answered;
258
+ } finally {
259
+ clearTimeout(timer);
260
+ internal.delete(id);
261
+ }
262
+ if (reply.error) throw new Error(`the daemon refused the new session: ${reply.error.message}`);
263
+ if (initialized) await current.send({ jsonrpc: '2.0', method: 'notifications/initialized' });
264
+ })().finally(() => { recovering = null; });
265
+ }
266
+ return recovering;
267
+ }
268
+
269
+ return link;
270
+ }
271
+
272
+ /**
273
+ * After the daemon is started again, the extension reconnects on its own backoff (up to 30s,
274
+ * plus a one-minute alarm). A call sent before it is back answers "browser not connected", so
275
+ * wait for it, briefly, and carry on regardless: the daemon's own answer is still correct.
276
+ */
277
+ export async function waitForBrowser(healthUrl, { timeout = 35000, interval = 500, fetchImpl = fetch, now = Date.now } = {}) {
278
+ const deadline = now() + timeout;
279
+ for (;;) {
280
+ try { const r = await fetchImpl(healthUrl); const b = await r.json(); if (b.extensionConnected && b.paired) return true; } catch { /* not yet */ }
281
+ if (now() >= deadline) return false;
282
+ await delay(interval);
283
+ }
284
+ }
285
+
149
286
  export async function main() {
150
287
  const httpPort = Number(process.env.RW_MCP_HTTP_PORT) || DEFAULT_HTTP_PORT;
151
288
  const base = `http://${HOST}:${httpPort}`;
289
+ const healthUrl = `${base}/healthz`;
152
290
 
153
- await ensureDaemon({ healthUrl: `${base}/healthz`, spawnDaemon: spawnDetachedDaemon });
291
+ await ensureDaemon({ healthUrl, spawnDaemon: spawnDetachedDaemon });
154
292
 
155
- // Read the daemon's auth token AFTER it is up (the daemon writes it at startup).
156
- const token = readToken();
157
- const opts = token ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : undefined;
293
+ // Read the daemon's auth token each time a transport is made: a restarted daemon writes it at
294
+ // startup (normally the same value, persisted in the state dir).
295
+ const makeTransport = () => {
296
+ const token = readToken();
297
+ const opts = token ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : undefined;
298
+ return new StreamableHTTPClientTransport(new URL(`${base}/mcp`), opts);
299
+ };
300
+ const revive = async () => {
301
+ const how = await ensureDaemon({ healthUrl, spawnDaemon: spawnDetachedDaemon });
302
+ if (how === 'spawned') await waitForBrowser(healthUrl);
303
+ };
158
304
 
159
305
  const clientFacing = new StdioServerTransport();
160
- const daemonFacing = new StreamableHTTPClientTransport(new URL(`${base}/mcp`), opts);
306
+ const daemonFacing = createDaemonLink({ makeTransport, revive });
161
307
  pumpTransports(clientFacing, daemonFacing);
162
308
 
163
309
  await daemonFacing.start();
package/src/daemon.js CHANGED
@@ -201,12 +201,17 @@ export function createDaemon({
201
201
  try { body = await readJsonBody(req); } catch (e) { rpcError(res, 400, (e && e.message) || 'Invalid body'); return; }
202
202
  if (existing) { await existing.transport.handleRequest(req, res, body); return; }
203
203
  if (!sessionId && isInitializeRequest(body)) { await newSession(req, res, body); return; }
204
+ // A session id we do not hold is 404, as the MCP spec requires, and that status is what
205
+ // tells a client to start a new session. It used to be 400, which no client reads that
206
+ // way: a session reaped after 10 quiet minutes, or lost to a daemon restart, left every
207
+ // connected AI app answering "daemon not reachable" until it was restarted by hand.
208
+ if (sessionId) { rpcError(res, 404, 'Unknown Mcp-Session-Id. Start a new session with initialize.'); return; }
204
209
  rpcError(res, 400, 'No valid session. Send an initialize request first (no Mcp-Session-Id).');
205
210
  return;
206
211
  }
207
212
 
208
213
  if (req.method === 'GET' || req.method === 'DELETE') {
209
- if (!existing) { rpcError(res, 400, 'Missing or unknown Mcp-Session-Id'); return; }
214
+ if (!existing) { rpcError(res, sessionId ? 404 : 400, 'Missing or unknown Mcp-Session-Id'); return; }
210
215
  await existing.transport.handleRequest(req, res);
211
216
  return;
212
217
  }
@@ -233,7 +238,12 @@ export function createDaemon({
233
238
  if (t - s.lastSeen > staleSessionMs) { closed++; try { s.transport.close(); } catch { /* onclose removes it */ } }
234
239
  }
235
240
  }
236
- if (idleMs > 0 && sessions.size === 0 && (t - lastActivityAt) > idleMs) { onIdle(); }
241
+ // A browser that is connected and paired keeps the daemon up (owner Table S1 item 4,
242
+ // 2026-11-08). Exiting under it cost the next AI request about 8 seconds while the extension
243
+ // found a new daemon on its backoff; staying up costs one idle Node process, and the daemon
244
+ // still exits once the browser has gone too.
245
+ const browserHere = !!(bridge && bridge.paired && bridge.socket && bridge.socket.readyState === 1);
246
+ if (idleMs > 0 && sessions.size === 0 && !browserHere && (t - lastActivityAt) > idleMs) { onIdle(); }
237
247
  return closed;
238
248
  }
239
249
 
package/src/wsServer.js CHANGED
@@ -205,6 +205,13 @@ export class ExtensionBridge {
205
205
  this.wss = null;
206
206
  this.socket = null; // the single connected extension socket
207
207
  this.paired = false;
208
+ // A daemon started on demand (the connector spawns it, or it was idle for 30 minutes and
209
+ // exited) is up before the extension is: the extension finds it on its own backoff, up to
210
+ // 30 seconds. A call in that window used to fail with "extension is not connected" on a
211
+ // machine where everything was fine. So for its first moments a daemon that HAS been paired
212
+ // before waits for the browser instead (measured 2026-11-08).
213
+ this.startedAt = Date.now();
214
+ this.reconnectGraceMs = opts.reconnectGraceMs ?? 40_000;
208
215
  this.pairingCode = null;
209
216
  this.pairingAttempts = 0; // wrong-code counter for the current code
210
217
  this.pairingCodeExpiresAt = 0; // absolute deadline; a reconnect reuses, never extends
@@ -485,7 +492,28 @@ export class ExtensionBridge {
485
492
  * (read vs value) with bounded concurrency + per-lane backpressure; the per-action
486
493
  * timeout covers queue wait + round-trip.
487
494
  */
488
- callAction(action, params = {}, { client = null } = {}) {
495
+ callAction(action, params = {}, opts = {}) {
496
+ if (!this.portConflict && !this._ready() && this._browserMayStillArrive()) {
497
+ // The wait is part of the call's budget, not on top of it: a send whose caller has given up
498
+ // must not later put a Send bar on screen (review 2026-11-08).
499
+ const started = Date.now();
500
+ return this._waitForBrowser().then(() => this._callNow(action, params, { ...opts, waitedMs: Date.now() - started }));
501
+ }
502
+ return this._callNow(action, params, opts);
503
+ }
504
+
505
+ _ready() { return !!this.socket && this.socket.readyState === this.socket.OPEN && this.paired; }
506
+
507
+ /** Only a machine paired before, and only while the daemon is young: otherwise answer now. */
508
+ _browserMayStillArrive() {
509
+ return this.reconnectGraceMs > 0 && this.sessionTokens.length > 0 && Date.now() - this.startedAt < this.reconnectGraceMs;
510
+ }
511
+
512
+ async _waitForBrowser() {
513
+ while (!this._ready() && this._browserMayStillArrive()) await new Promise((r) => setTimeout(r, 250));
514
+ }
515
+
516
+ _callNow(action, params = {}, { client = null, waitedMs = 0 } = {}) {
489
517
  if (this.portConflict) {
490
518
  return Promise.reject(new Error(`Another Reply Wizard hub is already using port ${this.port}. Close the duplicate MCP host (or set RW_MCP_PORT to a free port) and reconnect.`));
491
519
  }
@@ -501,7 +529,7 @@ export class ExtensionBridge {
501
529
  }
502
530
  return new Promise((resolve, reject) => {
503
531
  const entry = { action, params, client, resolve, reject, settled: false, id: null, timer: null };
504
- const timeoutMs = this._timeoutFor(action);
532
+ const timeoutMs = Math.max(1000, this._timeoutFor(action) - waitedMs);
505
533
  // When this call will be answered "timed out", queue wait included: a send keeps its Send
506
534
  // bar inside it, so nobody can send a message the assistant was told failed.
507
535
  entry.deadline = Date.now() + timeoutMs;