@agentsignalnet/claude-plugin 0.2.56

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.
@@ -0,0 +1,677 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Watch this agent's inbox so the model does not have to.
4
+ *
5
+ * node inbox-daemon.mjs [--interval 2] [--spool <path>]
6
+ *
7
+ * WHY A DAEMON AND NOT A LOOP
8
+ *
9
+ * Polling was never the problem; polling WITH A MODEL was. `/loop 5m
10
+ * /agentsignal:inbox` spends a turn on every check, so the interval is set by
11
+ * what you are willing to pay rather than by how fast you want to hear, and a
12
+ * quiet channel bills you for silence. Nothing here runs a model, so two
13
+ * seconds costs the same as five minutes: nothing.
14
+ *
15
+ * That is the whole trick. It buys latency that looked like it needed webhooks.
16
+ *
17
+ * WHAT IT DOES NOT DO
18
+ *
19
+ * It does not interrupt anything. It writes a file; the hooks in
20
+ * `hooks/` decide what that means, because they are the only things
21
+ * that run at a moment a model can act on. Keeping the two apart means the
22
+ * poller can be restarted, moved, or replaced with a webhook receiver without
23
+ * touching the interruption logic.
24
+ *
25
+ * THE SPOOL
26
+ *
27
+ * One JSON file, rewritten whole on every change. Not appended: a hook reads
28
+ * it on every tool call, and a file that only grows is a file that gets slower
29
+ * for as long as the session lasts. Messages leave it when a hook marks them
30
+ * handled, so it holds what is OUTSTANDING rather than what has ever arrived.
31
+ *
32
+ * Written to a temporary name and renamed over the real one, because a hook
33
+ * reading it half-written would see truncated JSON and conclude, wrongly, that
34
+ * there is nothing waiting. Rename is atomic on the same filesystem.
35
+ */
36
+ import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, statSync, unlinkSync } from 'node:fs';
37
+ import { fileURLToPath } from 'node:url';
38
+ import { join, dirname } from 'node:path';
39
+ import { stateDirs, writeDir, identities as storedIdentities } from './state.mjs';
40
+ // One copy, shared with the hook -- which has to ask the same question the
41
+ // moment a join creates a credential. See the note at the top of that file.
42
+ import { incumbent, livingWatchers, lockDir as sharedLockDir, apiBase } from './watchers.mjs';
43
+
44
+ const args = process.argv.slice(2);
45
+ function flag(name, fallback) {
46
+ const i = args.indexOf(`--${name}`);
47
+ return i === -1 ? fallback : args[i + 1];
48
+ }
49
+
50
+ /**
51
+ * Everything this prints is stamped, because the log is read after the fact.
52
+ *
53
+ * Started from a SessionStart hook, nothing is watching stdout -- it goes to a
54
+ * file somebody opens hours later, wondering why a message never arrived. An
55
+ * unstamped line cannot answer that: "poll failed" is a different story
56
+ * depending on whether it happened once at boot or has been happening since.
57
+ */
58
+ function stamp(...parts) {
59
+ return [new Date().toISOString(), ...parts].join(' ');
60
+ }
61
+ const say = (...parts) => console.log(stamp(...parts));
62
+ const complain = (...parts) => console.error(stamp('ERROR', ...parts));
63
+
64
+ const baseUrl = apiBase();
65
+ const intervalMs = Math.max(1, Number(flag('interval', '2'))) * 1000;
66
+
67
+ /**
68
+ * Where the identity lives -- ALL the places, matching the MCP server exactly.
69
+ *
70
+ * This list and the one in packages/mcp/src/index.ts have to stay identical.
71
+ * They are the two halves of one agent: the server registers and writes the
72
+ * credential, this reads it and watches that agent's inbox. Disagreeing about
73
+ * which directory means watching a different agent than the session is, and
74
+ * that failure is silent -- a watcher with no credential looks exactly like a
75
+ * channel with nothing on it.
76
+ *
77
+ * More than one directory is not a choice. Started from a plugin hook,
78
+ * CLAUDE_PLUGIN_DATA is set and points at the plugin's own data; started by
79
+ * hand or from a `claude mcp add` server, it is not and the home directory is
80
+ * where things are. One machine has both, because the plugin and a hand-added
81
+ * server are two ways of running the same thing. So: read from any, and let
82
+ * the base-URL check decide what belongs.
83
+ */
84
+ /**
85
+ * The credential, and the directory it came from.
86
+ *
87
+ * The spool goes NEXT TO THE CREDENTIAL rather than in whichever directory
88
+ * happened to be first. That is what keeps this and the hooks pointed at the
89
+ * same file: they both find the identity the same way, so they both land in
90
+ * the same place, whether this was started from a plugin hook or by hand.
91
+ * Choosing a directory independently is how the two came apart before.
92
+ */
93
+ function credential() {
94
+ for (const dir of stateDirs()) {
95
+ try {
96
+ const stored = JSON.parse(readFileSync(join(dir, 'agent.json'), 'utf8'));
97
+ // Keyed on base URL for the same reason the MCP server is: a production
98
+ // credential must not be reused against localhost, or the reverse. It is
99
+ // also what makes looking in several directories safe.
100
+ if (stored?.credential && stored.base_url === baseUrl) return { secret: stored.credential, dir };
101
+ } catch {
102
+ /* absent or unreadable is a normal first run, not an error */
103
+ }
104
+ }
105
+ // An explicit secret has no directory of its own, so it falls back to the
106
+ // one the server would have written to -- the same one the hooks fall back
107
+ // to.
108
+ if (process.env.AGENTSIGNAL_DEVICE_SECRET) {
109
+ return { secret: process.env.AGENTSIGNAL_DEVICE_SECRET, dir: writeDir() };
110
+ }
111
+ return null;
112
+ }
113
+
114
+ /**
115
+ * Where state goes when no credential was found to sit beside.
116
+ *
117
+ * Deliberately NOT `stateDirs()[0]`: that list now includes neighbouring
118
+ * directories, and falling back to one of those would scatter this agent's
119
+ * spool and pidfile into some other server's data directory. Mirrors
120
+ * writeDir() in packages/mcp/src/index.ts, which these two halves have to
121
+ * agree on for the same reason stateDirs() does.
122
+ */
123
+ const found = credential();
124
+ const secret = found?.secret ?? null;
125
+
126
+ /** Where the spool and pidfile go: beside the credential in use. */
127
+ const stateDir = flag('state-dir', found?.dir ?? writeDir());
128
+
129
+ const spoolPath = flag('spool', join(stateDir, 'inbox-spool.json'));
130
+
131
+ /**
132
+ * EVERY identity on this machine, not just the first.
133
+ *
134
+ * An identity is per-checkout now, so a laptop with two projects on it has two
135
+ * agents in two accounts -- and one watcher following only the first means the
136
+ * second is registered, addressable, and never interrupts anybody. Its
137
+ * messages sit in an inbox nothing is reading, which looks exactly like a
138
+ * quiet channel.
139
+ *
140
+ * Still ONE daemon. The lock stays machine-wide, because the thing that must
141
+ * not happen twice is a message being delivered twice, and that is a property
142
+ * of the process rather than of the credential. So: one process, N inboxes,
143
+ * each with its spool beside its own credential where the hooks already look.
144
+ *
145
+ * Re-read on every tick rather than once at startup. Registering happens
146
+ * mid-session -- that is the whole point of a join code -- and the daemon is
147
+ * not restarted when it does, because a hook that finds one running stands
148
+ * down. A new checkout would otherwise never be watched until something
149
+ * unrelated killed this process. The cost is a readdir of a few directories
150
+ * beside an HTTPS request, which is nothing.
151
+ */
152
+ function identities() {
153
+ // An explicitly named spool means one inbox and that inbox only: it is the
154
+ // by-hand invocation, and quietly watching several while writing one file
155
+ // would be worse than the limitation.
156
+ if (flag('spool', null) || process.env.AGENTSIGNAL_DEVICE_SECRET) {
157
+ return secret ? [{ secret, dir: stateDir, spool: spoolPath }] : [];
158
+ }
159
+
160
+ const seen = new Map();
161
+ for (const dir of stateDirs()) {
162
+ try {
163
+ const stored = JSON.parse(readFileSync(join(dir, 'agent.json'), 'utf8'));
164
+ if (!stored?.credential || stored.base_url !== baseUrl) continue;
165
+ // Keyed on the credential, not the directory: the same identity found
166
+ // through a plugin directory and through a sibling is one agent, and
167
+ // polling it twice would deliver everything to it twice.
168
+ if (!seen.has(stored.credential)) {
169
+ seen.set(stored.credential, {
170
+ secret: stored.credential,
171
+ dir,
172
+ spool: join(dir, 'inbox-spool.json'),
173
+ handle: stored.handle ?? null,
174
+ });
175
+ }
176
+ } catch {
177
+ /* no identity in this directory, which is the ordinary case */
178
+ }
179
+ }
180
+ return [...seen.values()];
181
+ }
182
+
183
+ if (!secret) {
184
+ // Naming the directories, because "no credential" with nowhere named is a
185
+ // message you cannot act on -- and the whole bug this replaces was two
186
+ // halves looking in different places without either of them saying where.
187
+ complain(
188
+ `No device credential for ${baseUrl}. Looked in: ${stateDirs().join(', ')}\n` +
189
+ 'This watches ONE agent’s inbox, so it needs that agent’s credential --\n' +
190
+ 'register with join_channel first, or set AGENTSIGNAL_DEVICE_SECRET.',
191
+ );
192
+ process.exit(1);
193
+ }
194
+
195
+ /** Read one identity's spool, tolerating every way it can be missing or broken. */
196
+ function readSpool(path) {
197
+ try {
198
+ const spool = JSON.parse(readFileSync(path, 'utf8'));
199
+ return {
200
+ since: typeof spool.since === 'string' ? spool.since : null,
201
+ messages: Array.isArray(spool.messages) ? spool.messages : [],
202
+ };
203
+ } catch {
204
+ return { since: null, messages: [] };
205
+ }
206
+ }
207
+
208
+ /** Delivery ids a hook has already shown the model. Written only by hooks. */
209
+ function readHandled(dir) {
210
+ try {
211
+ return JSON.parse(readFileSync(join(dir, 'inbox-handled.json'), 'utf8')).delivery_ids ?? [];
212
+ } catch {
213
+ return [];
214
+ }
215
+ }
216
+
217
+ function writeSpool(path, spool) {
218
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
219
+ const temporary = `${path}.${process.pid}.tmp`;
220
+ writeFileSync(temporary, JSON.stringify(spool, null, 2), { mode: 0o600 });
221
+ renameSync(temporary, path);
222
+ }
223
+
224
+ /**
225
+ * What a message is allowed to interrupt.
226
+ *
227
+ * AgentSignal's priority runs -2 to 2 and already means what we need. The
228
+ * mapping is deliberately coarse, because there are only two moments a model
229
+ * can act on anything: between tool calls, and at the end of a turn. A third
230
+ * urgency would have nowhere to happen.
231
+ */
232
+ function urgency(priority) {
233
+ if (priority >= 1) return 'interrupt';
234
+ return 'finish';
235
+ }
236
+
237
+ /**
238
+ * Consecutive poll failures, PER IDENTITY.
239
+ *
240
+ * Shared across all of them, one identity behind a revoked key or an
241
+ * unreachable host would keep resetting the count and the "recovered" line
242
+ * would be about somebody else's poll.
243
+ */
244
+ const failures = new Map();
245
+
246
+ /** Identities whose credential the server has rejected outright. */
247
+ const rejected = new Set();
248
+
249
+ async function tick() {
250
+ const watched = identities().filter((i) => !rejected.has(i.secret));
251
+
252
+ if (watched.length === 0) {
253
+ complain('No identity left to watch; every credential was rejected. Stopping.');
254
+ process.exit(1);
255
+ }
256
+
257
+ // Sequential rather than concurrent. There are a handful of these at most,
258
+ // each is one small request, and a burst of parallel fetches off a laptop
259
+ // waking from sleep is a worse neighbour than a few hundred milliseconds.
260
+ for (const identity of watched) await pollOne(identity);
261
+ }
262
+
263
+ async function pollOne(identity) {
264
+ const { secret, dir, spool: spoolFile } = identity;
265
+ const who = identity.handle ? `${identity.handle}: ` : '';
266
+ const spool = readSpool(spoolFile);
267
+
268
+ const query = new URLSearchParams({ limit: '50' });
269
+ if (spool.since) query.set('since', spool.since);
270
+
271
+ let fetched;
272
+ try {
273
+ const response = await fetch(`${baseUrl}/v1/devices/me/messages?${query}`, {
274
+ headers: { Authorization: `Device ${secret}` },
275
+ });
276
+ if (!response.ok) {
277
+ // 401 will not fix itself: the credential was revoked or the agent was
278
+ // deleted. Say so once and stop, rather than making the same rejected
279
+ // request every two seconds until somebody notices the log.
280
+ if (response.status === 401) {
281
+ // Drop THIS identity, not the process. On a machine watching several,
282
+ // one agent being deleted must not take the others' interruptions with
283
+ // it -- and the others would have no way to report that they had gone
284
+ // quiet, because going quiet is what it looks like.
285
+ complain(
286
+ `${who}credential rejected (401). The agent was probably removed. ` +
287
+ 'No longer watching it; other identities continue.',
288
+ );
289
+ rejected.add(secret);
290
+ return;
291
+ }
292
+ throw new Error(`${response.status}`);
293
+ }
294
+ fetched = (await response.json()).messages ?? [];
295
+ // Say when it comes back, not only when it breaks. A log that records the
296
+ // start of an outage and never its end cannot tell you whether the thing
297
+ // is working now, which is the only question anyone reads it to answer.
298
+ const before = failures.get(secret) ?? 0;
299
+ if (before > 0) say(`${who}polling recovered after ${before} failure(s)`);
300
+ failures.set(secret, 0);
301
+ } catch (error) {
302
+ // A network blip is not news. Report the first one and then go quiet, so a
303
+ // laptop that slept overnight does not produce a screenful of identical
304
+ // lines to scroll past in the morning.
305
+ const count = (failures.get(secret) ?? 0) + 1;
306
+ failures.set(secret, count);
307
+ if (count === 1) {
308
+ complain(`${who}poll failed (${error.message}). Retrying quietly; will say so when it recovers.`);
309
+ }
310
+ return;
311
+ }
312
+
313
+ // Drop what a hook has already put in front of the model. This is the only
314
+ // place the spool shrinks: the hooks append to `inbox-handled.json` and never
315
+ // touch the spool, so each file has exactly one writer and a hook firing
316
+ // mid-poll cannot lose a message between them.
317
+ const handled = new Set(readHandled(dir));
318
+ const outstanding = spool.messages.filter((m) => !handled.has(m.delivery_id));
319
+ if (outstanding.length !== spool.messages.length) {
320
+ spool.messages = outstanding;
321
+ writeSpool(spoolFile, spool);
322
+ }
323
+
324
+ if (fetched.length === 0) return;
325
+
326
+ const seen = new Set(spool.messages.map((m) => m.delivery_id));
327
+ const arrived = fetched
328
+ .filter((m) => !seen.has(m.delivery_id))
329
+ .map((m) => ({
330
+ delivery_id: m.delivery_id,
331
+ message_id: m.message_id,
332
+ title: m.title,
333
+ body: m.body,
334
+ priority: m.priority,
335
+ options: m.options,
336
+ created_at: m.created_at,
337
+ urgency: urgency(m.priority),
338
+ }));
339
+
340
+ if (arrived.length === 0) return;
341
+
342
+ // `since` moves to the newest thing SEEN, not the newest thing outstanding.
343
+ // Moving it to the oldest unhandled message would re-fetch it forever.
344
+ const newest = fetched
345
+ .map((m) => m.created_at)
346
+ .reduce((a, b) => (a > b ? a : b), spool.since ?? '');
347
+
348
+ writeSpool(spoolFile, { since: newest, messages: [...spool.messages, ...arrived] });
349
+
350
+ for (const m of arrived) {
351
+ say(`${who}received priority ${m.priority} (${m.urgency}) — ${m.title ?? '(no title)'}`);
352
+ }
353
+ }
354
+
355
+ /**
356
+ * ONE DAEMON, GUARDED HERE RATHER THAN BY THE CALLER.
357
+ *
358
+ * Started from a SessionStart hook, so it is launched again on every session
359
+ * and several sessions can open at once. Two pollers against one inbox is not
360
+ * merely wasteful: both fetch the same message, both append it, and the spool
361
+ * grows a duplicate of everything.
362
+ *
363
+ * The obvious guard -- `pgrep -f inbox-daemon.mjs || start` -- does not work,
364
+ * and fails in the direction that hides itself. The shell running that check
365
+ * has "inbox-daemon.mjs" in its own command line, so pgrep matches the checker,
366
+ * concludes a daemon is already up, and never starts one. Nothing appears to be
367
+ * wrong; messages simply never arrive.
368
+ *
369
+ * So: a pidfile, and a liveness test that asks the kernel rather than a string.
370
+ * Signal 0 delivers nothing and only reports whether the process is there.
371
+ *
372
+ * AND IT HAS TO HAND OVER, which the first version of this did not.
373
+ *
374
+ * A daemon outlives the session that started it -- that is the point of it --
375
+ * so restarting Claude does not replace it, and updating the plugin only
376
+ * changes files on disk. The guard above then works against itself: the FIRST
377
+ * daemon to claim the pidfile keeps it forever, so a fix can be published,
378
+ * installed and restarted into, and the process actually doing the work is
379
+ * still the old one. Observed exactly that: a daemon from 01:38 was still
380
+ * running at 01:51 while two newer ones started, read the pidfile, and
381
+ * politely stood down.
382
+ *
383
+ * Nobody should have to know a pidfile exists to receive a bug fix. So a
384
+ * sidecar records WHICH SCRIPT is running and when that file was last
385
+ * modified, and a newer one asks the older to leave. Two of the same version
386
+ * still refuse to run together -- that is what the guard was always for.
387
+ *
388
+ * THE PIDFILE STAYS A BARE NUMBER, and the extra goes in a separate file.
389
+ *
390
+ * The first attempt put the metadata in the pidfile as JSON, which broke the
391
+ * one moment it was written for. During an upgrade both versions exist, and an
392
+ * older daemon reading that pidfile does Number('{"pid":…}'), gets NaN,
393
+ * concludes nothing is running, and starts a SECOND watcher -- then stamps its
394
+ * own bare pid over the file. Two pollers on one inbox, every message fetched
395
+ * twice, caused by the change meant to prevent exactly that.
396
+ *
397
+ * Backward compatibility has to run in both directions when the old code is
398
+ * the code you are replacing. So the format every version already understands
399
+ * is left alone, and the new information goes somewhere old versions never
400
+ * look. The sidecar is trusted only when its pid matches the pidfile, so a
401
+ * leftover from a dead daemon cannot describe a live one.
402
+ */
403
+ /**
404
+ * THE LOCK IS MACHINE-WIDE. The spool is not, and that difference is the point.
405
+ *
406
+ * The spool belongs beside the credential, because the hooks find it the same
407
+ * way and the two have to land on the same file. The lock answers a different
408
+ * question -- is anything already watching on this machine -- and keying it on
409
+ * the credential is what let three daemons run at once.
410
+ *
411
+ * A credential appears the moment an agent joins, which is now the ordinary
412
+ * case rather than a rare one: the whole point of a join code is that it works
413
+ * mid-session. Before it appears `stateDir` is the fallback directory; after,
414
+ * it is wherever the credential was written. So the daemon started at 19:57
415
+ * took its lock in ~/.agentsignal, the one started at 20:04 took a lock in
416
+ * plugins/data/agentsignal-inline, and neither could see the other's file.
417
+ * Both kept polling. A lock that relocates is not a lock.
418
+ *
419
+ * It also puts the pidfile back where `/agentsignal:update` says it is. That
420
+ * command has always documented ~/.agentsignal/inbox-daemon.pid, and somebody
421
+ * reported it missing on their machine -- correctly, because their agent had
422
+ * joined and taken the lock with it.
423
+ */
424
+ function lockDir() {
425
+ // A named directory is EXCLUSIVE, exactly as it is for credentials: a
426
+ // fixture pointed somewhere of its own must not be able to stand down the
427
+ // real watcher, or take it over. Isolation has to cover the lock too, or
428
+ // running the tests kills the daemon the developer is using.
429
+ // `||` rather than `??`, because an environment variable set to the empty
430
+ // string is how a caller unsets one it cannot delete -- and `?? ''` would
431
+ // take that literally and put the lock in the current directory.
432
+ // The flag is this script's alone; the rest of the rule is shared, so the
433
+ // hook cannot start looking somewhere else.
434
+ return flag('state-dir', undefined) || sharedLockDir();
435
+ }
436
+
437
+ const lockRoot = lockDir();
438
+ const pidPath = join(lockRoot, 'inbox-daemon.pid');
439
+ const metaPath = join(lockRoot, 'inbox-daemon.meta.json');
440
+
441
+ /**
442
+ * ONE FILE PER WATCHER, because a pidfile holds one pid and the bug is plural.
443
+ *
444
+ * A pidfile names a single rival, so a starting daemon can stand down at most
445
+ * one thing. That is enough when duplication cannot already exist -- and it can
446
+ * already exist, on every machine that ran a version predating the lock. A
447
+ * report from one of them: three watchers, two of them from the same directory.
448
+ * The second of those two overwrote the first's pidfile when it started, so the
449
+ * first became unfindable by anything reading that file, including the fix
450
+ * written to sweep it. A newer daemon started beside all three, swept the one
451
+ * it could see, and left the rest polling.
452
+ *
453
+ * It is worth being exact about why that is bad rather than untidy: two
454
+ * watchers on one inbox fetch every message twice, and an urgent one interrupts
455
+ * twice off a single send. The person on the other end sees a duplicate they
456
+ * cannot explain and no error anywhere.
457
+ *
458
+ * A directory of `<pid>.json` makes the count honest. Every live watcher is a
459
+ * file, so the sweep sees all of them and the mtime rule -- still a total order
460
+ * -- picks exactly one winner out of any number of rivals rather than out of
461
+ * two.
462
+ *
463
+ * NOT THE PROCESS TABLE, which is the fix that suggests itself and is wrong.
464
+ * Walking `ps` finds watchers this one must not touch: the tests isolate by
465
+ * HOME, a fixture isolates by `--state-dir`, and neither is visible in an
466
+ * argument list. A sweep keyed on argv cannot tell a developer's real daemon
467
+ * from a test's, so running the suite would kill the daemon they are using --
468
+ * the exact hazard the `--state-dir` comment above exists to prevent. Scoping
469
+ * the registry to the lock directory means isolation keeps working for free,
470
+ * because isolation is already expressed as a different lock directory.
471
+ *
472
+ * The pidfile is still written. An older daemon reads only that, and during an
473
+ * upgrade both versions exist -- dropping it would make this fix invisible to
474
+ * the very processes it has to negotiate with.
475
+ */
476
+ const watchersDir = join(lockRoot, 'watchers');
477
+ const myWatcherPath = join(watchersDir, `${process.pid}.json`);
478
+
479
+ /**
480
+ * Where 0.2.21 and earlier would have left a lock, so their orphans can be
481
+ * stood down instead of polling forever.
482
+ *
483
+ * Without this the fix cannot reach the daemons it is for. A machine that
484
+ * joined an agent under the old code has a watcher holding a pidfile beside
485
+ * its credential; the fixed daemon looks only at the canonical path, finds it
486
+ * free, and starts -- leaving the orphan running exactly as before. The bug
487
+ * outlives its own fix on every machine that already hit it.
488
+ *
489
+ * One release of sweeping is enough: after this, no version writes a lock
490
+ * anywhere else.
491
+ */
492
+ function legacyLocks() {
493
+ const dirs = new Set([...stateDirs(), writeDir(), stateDir]);
494
+ return [...dirs]
495
+ .map((dir) => join(dir, 'inbox-daemon.pid'))
496
+ .filter((path) => path !== pidPath);
497
+ }
498
+
499
+ /** This script, and its mtime, which is what "newer" is decided on. */
500
+ const me = {
501
+ pid: process.pid,
502
+ script: fileURLToPath(import.meta.url),
503
+ // A git checkout stamps files with the moment they were written, so a fix
504
+ // pulled five minutes ago is genuinely newer than a copy from this morning.
505
+ mtime: (() => {
506
+ try {
507
+ return statSync(fileURLToPath(import.meta.url)).mtimeMs;
508
+ } catch {
509
+ return 0;
510
+ }
511
+ })(),
512
+ };
513
+
514
+
515
+ /** Wait for a process to actually go, rather than assuming a signal worked. */
516
+ async function waitForExit(pid, ms) {
517
+ const deadline = Date.now() + ms;
518
+ while (Date.now() < deadline) {
519
+ try {
520
+ process.kill(pid, 0);
521
+ } catch {
522
+ return true;
523
+ }
524
+ await new Promise((r) => setTimeout(r, 100));
525
+ }
526
+ return false;
527
+ }
528
+
529
+
530
+ const rivals = livingWatchers(lockRoot);
531
+
532
+ if (rivals.length) {
533
+ /**
534
+ * MTIME DECIDES, and a different path on its own decides nothing.
535
+ *
536
+ * This used to also count `held.script !== me.script` as newer, which reads
537
+ * as "a different copy must be the update". It is symmetric, and that is
538
+ * fatal: each copy qualifies as newer than the other, so they take turns
539
+ * evicting each other for as long as both keep being started. Restarting
540
+ * does not clear it, because neither copy is wrong -- they are both doing
541
+ * what they were told.
542
+ *
543
+ * There is no single duplicate to remove, either. One machine here had FIVE
544
+ * roots run a daemon: three cache directories, a checkout, and a worktree of
545
+ * it. A marketplace sourced from a directory means a session inside that
546
+ * directory loads the plugin from there while a session anywhere else loads
547
+ * it from the cache, and every version leaves its own cache directory
548
+ * behind. Different paths are the normal state, not a misconfiguration.
549
+ *
550
+ * An mtime is a total order across all of them, so exactly one wins and the
551
+ * losers stay down. The case the path check was for still works: a freshly
552
+ * installed version is written now, so it is newer than what it replaces --
553
+ * which is the same argument the sidecar comment already makes for a git
554
+ * checkout being newer than this morning's copy.
555
+ *
556
+ * Equal mtimes stand down rather than fight. Two copies of one release do
557
+ * not need to argue about which of them runs.
558
+ *
559
+ * COMPARED AGAINST THE NEWEST RIVAL, not against each in turn. Standing down
560
+ * to the first one that outranks this process would be the same answer, but
561
+ * evicting them one at a time would not: a daemon that beats two rivals and
562
+ * loses to a third must kill neither, or it takes down watchers on its way
563
+ * to standing down and leaves the machine emptier than it found it.
564
+ */
565
+ const newest = rivals.reduce((best, rival) => (rival.mtime > best.mtime ? rival : best));
566
+
567
+ if (!(me.mtime > newest.mtime)) {
568
+ say(`already watching under pid ${newest.pid}; nothing to do`);
569
+ process.exit(0);
570
+ }
571
+
572
+ // Signalled in one pass and waited for in another, so a slow exit does not
573
+ // hold up the notice to the rest. They have no cleanup to do; the wait is
574
+ // only to be sure that "superseded" means gone rather than asked politely.
575
+ //
576
+ // SIGTERM, not SIGKILL: it has no cleanup to do, but a signal it could
577
+ // ignore is a signal worth sending politely first.
578
+ for (const rival of rivals) {
579
+ say(`superseding pid ${rival.pid} (${rival.script ?? 'unknown script'})`);
580
+ try {
581
+ process.kill(rival.pid, 'SIGTERM');
582
+ } catch {
583
+ /* it went on its own between the check and the signal */
584
+ }
585
+ }
586
+
587
+ for (const rival of rivals) {
588
+ if (!(await waitForExit(rival.pid, 5000))) {
589
+ // Refusing to start is the safe answer. Two pollers duplicate every
590
+ // message, and a duplicate urgent message is an interruption that fires
591
+ // twice -- worse than a fix arriving one restart late.
592
+ complain(`pid ${rival.pid} did not exit; leaving it alone rather than running two watchers`);
593
+ process.exit(1);
594
+ }
595
+ }
596
+ }
597
+
598
+ // Orphans from before the lock was machine-wide. Deliberately after the
599
+ // stand-down above: a daemon that has just agreed somebody else is in charge
600
+ // must not go around killing things on its way out.
601
+ //
602
+ // No vintage check here, unlike the incumbent. Holding a lock in one of these
603
+ // places is itself proof of an older build -- no version that writes the
604
+ // canonical lock also writes these -- and the sidecar beside a legacy pidfile
605
+ // describes a daemon whose mtime says nothing useful about which of us should
606
+ // win. The pidfile is left in place: whoever wrote it is gone, and an empty
607
+ // file at a path nothing reads any more is not worth a delete.
608
+ for (const path of legacyLocks()) {
609
+ const stale = incumbent(path);
610
+ if (!stale) continue;
611
+ say(`superseding pid ${stale.pid}, which holds an older lock at ${path}`);
612
+ try {
613
+ process.kill(stale.pid, 'SIGTERM');
614
+ } catch {
615
+ /* it went on its own between the check and the signal */
616
+ }
617
+ if (!(await waitForExit(stale.pid, 5000))) {
618
+ complain(`pid ${stale.pid} did not exit; leaving it alone rather than running two watchers`);
619
+ process.exit(1);
620
+ }
621
+ }
622
+
623
+ mkdirSync(lockRoot, { recursive: true, mode: 0o700 });
624
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
625
+ // Sidecar first: a daemon that appears in the pidfile before it is described
626
+ // is one an older version can still stand down against, which is the safe
627
+ // order. The reverse would leave a moment where the metadata points at a pid
628
+ // that is not yet claiming anything.
629
+ writeFileSync(metaPath, JSON.stringify(me), { mode: 0o600 });
630
+ writeFileSync(pidPath, String(process.pid), { mode: 0o600 });
631
+
632
+ // The registry entry last, for the same reason the sidecar goes first: until
633
+ // this process is described everywhere, it should be findable by the oldest
634
+ // reader rather than only by the newest.
635
+ mkdirSync(watchersDir, { recursive: true, mode: 0o700 });
636
+ writeFileSync(myWatcherPath, JSON.stringify(me), { mode: 0o600 });
637
+
638
+ // Best effort, and correctness does not depend on it -- a start that finds
639
+ // this entry checks the pid before believing it. It is here so an ordinary
640
+ // stop leaves nothing behind, rather than leaving the next start to reason
641
+ // about a file whose process is gone.
642
+ let departed = false;
643
+ function standDown() {
644
+ if (departed) return;
645
+ departed = true;
646
+ try {
647
+ unlinkSync(myWatcherPath);
648
+ } catch {
649
+ /* already gone, or never written */
650
+ }
651
+ }
652
+ process.on('exit', standDown);
653
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) {
654
+ process.on(signal, () => {
655
+ standDown();
656
+ process.exit(0);
657
+ });
658
+ }
659
+
660
+ const watching = identities();
661
+ say(
662
+ `started (pid ${process.pid}) watching ${baseUrl} every ${intervalMs / 1000}s; ` +
663
+ `${watching.length} identit${watching.length === 1 ? 'y' : 'ies'}: ` +
664
+ watching.map((i) => i.spool).join(', '),
665
+ );
666
+ // A spool for each identity, so a hook reading one before the first poll sees
667
+ // an empty file rather than nothing at all.
668
+ for (const identity of identities()) {
669
+ if (!existsSync(identity.spool)) {
670
+ writeSpool(identity.spool, { since: new Date().toISOString(), messages: [] });
671
+ }
672
+ }
673
+
674
+ await tick();
675
+ setInterval(() => {
676
+ tick().catch((error) => complain(`Unexpected: ${error.stack ?? error.message}`));
677
+ }, intervalMs);