@agentsignalnet/claude-plugin 0.2.120 → 0.2.122

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agentsignal",
3
3
  "displayName": "AgentSignal",
4
- "version": "0.2.120",
4
+ "version": "0.2.122",
5
5
  "description": "Page a human from inside Claude Code, or become an addressable agent that other agents can reach.",
6
6
  "author": {
7
7
  "name": "Data Group AI",
package/.mcp.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "mcpServers": {
3
3
  "agentsignal": {
4
4
  "command": "npx",
5
- "args": ["-y", "@agentsignalnet/mcp@0.2.70"],
5
+ "args": ["-y", "@agentsignalnet/mcp@0.2.71"],
6
6
  "env": {
7
7
  "AGENTSIGNAL_API_KEY": "${user_config.api_key}",
8
8
  "AGENTSIGNAL_JOIN_TOKEN": "${user_config.join_token}",
package/README.md CHANGED
@@ -55,7 +55,7 @@ before you mint your first invite.
55
55
  claude mcp add agentsignal -e AGENTSIGNAL_JOIN_TOKEN=<the token> -- npx -y @agentsignalnet/mcp
56
56
  ```
57
57
 
58
- That is the line `/agentsignal:invite` prints. It is the tools and nothing
58
+ That is the line `/agentsignal-invite` prints. It is the tools and nothing
59
59
  else: no commands, no coordination skill, no hooks, and no inbox watcher — so
60
60
  an urgent message waits for somebody to call `read_inbox` rather than
61
61
  interrupting the session it lands during.
@@ -102,6 +102,15 @@ in the API key tier, not the join token tier. An agent holding only a join
102
102
  token can answer a question but cannot ask one and wait. If you want one side
103
103
  to be able to block on the other, that side needs an API key.
104
104
 
105
+ ## Commands
106
+
107
+ Every slash command is named `agentsignal-*` so it cannot collide with a host
108
+ builtin (`/dashboard`, `/join`, `/update`): `/agentsignal-join`,
109
+ `/agentsignal-inbox`, `/agentsignal-fleet`, `/agentsignal-invite`,
110
+ `/agentsignal-spawn`, `/agentsignal-work`, `/agentsignal-update`,
111
+ `/agentsignal-dashboard`, `/agentsignal-website`. Claude Code still namespaces
112
+ by plugin, so the same files also appear as `/agentsignal:agentsignal-join`.
113
+
105
114
  ## Two agents, start to finish
106
115
 
107
116
  On the first machine, with an API key configured, ask Claude to make a channel
@@ -118,7 +127,7 @@ Put that token into the plugin's config on the second machine. Then:
118
127
 
119
128
  > Register yourself as `rerank-bot`, then tell me your recipient key.
120
129
 
121
- Back on the first machine, send to that key. On the second, `/agentsignal:inbox`
130
+ Back on the first machine, send to that key. On the second, `/agentsignal-inbox`
122
131
  reads it and replies.
123
132
 
124
133
  ## Restarts are free, and that took a fix
@@ -141,7 +150,7 @@ and the error names that as the reason.
141
150
 
142
151
  ## More than two
143
152
 
144
- `/agentsignal:fleet` announces this Claude to the others and says who leads.
153
+ `/agentsignal-fleet` announces this Claude to the others and says who leads.
145
154
  The rules it follows are in the `agent-coordination` skill, which loads on its
146
155
  own whenever a session is about to act as one of several agents.
147
156
 
@@ -159,7 +168,7 @@ It is not consensus. Two agents can briefly both believe they lead, and there is
159
168
  no fencing token, so decide *who does the work* with it and not anything that
160
169
  must happen exactly once. The skill spells out the failure modes.
161
170
 
162
- `/agentsignal:spawn` starts a subagent underneath this one. A subagent is only
171
+ `/agentsignal-spawn` starts a subagent underneath this one. A subagent is only
163
172
  yours if it joined on a token you minted — `connection_type: 'subagent'`
164
173
  records the sponsor at redemption, and that is what puts it beneath you in the
165
174
  fleet tree rather than beside you as another root. The machinery has been there
@@ -171,8 +180,8 @@ without remembering the sequence.
171
180
  `read_inbox` is a pull. A Claude that is not running is not polling, and there
172
181
  is no inbound path into a session. Pick one:
173
182
 
174
- 1. `/agentsignal:inbox` when you want to look.
175
- 2. `/loop 5m /agentsignal:inbox` to keep looking.
183
+ 1. `/agentsignal-inbox` when you want to look.
184
+ 2. `/loop 5m /agentsignal-inbox` to keep looking.
176
185
  3. The sending side calls `ask_agent` and blocks, holding its own turn open
177
186
  until the answer arrives. Needs an API key on the sender.
178
187
  4. Register the agent *with* an `endpoint` and take signed webhooks instead —
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-dashboard
2
3
  description: Open the dashboard in a browser and keep it running
3
4
  argument-hint: "[an agent's handle, to show only its side]"
4
5
  ---
@@ -6,7 +7,7 @@ argument-hint: "[an agent's handle, to show only its side]"
6
7
  The delivery log as a conversation, in a browser, refreshing itself. Useful when
7
8
  several agents are working and you want to watch rather than ask.
8
9
 
9
- The command is `/agentsignal:dashboard` and the script is `dashboard.mjs`. Both
10
+ The command is `/agentsignal-dashboard` and the script is `dashboard.mjs`. Both
10
11
  were called chat, which named the content rather than the thing: it is a control
11
12
  surface -- it sends, answers, invites and registers -- and "chat" undersold what
12
13
  a link to it hands somebody.
@@ -94,7 +95,7 @@ WHAT IT NEEDS, and what to say when it is missing. The dashboard reads the whole
94
95
  channel, so it wants an API KEY — a device credential reads one agent's inbox,
95
96
  which is one side of a conversation rather than the whole of it. An agent
96
97
  holding only a join token cannot run this and should use `read_inbox`, or
97
- `/agentsignal:inbox`, instead. Say that plainly rather than starting a server
98
+ `/agentsignal-inbox`, instead. Say that plainly rather than starting a server
98
99
  that will fail.
99
100
 
100
101
  The key never reaches the page. The browser talks to this local server and the
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-fleet
2
3
  description: Announce yourself to the other agents, and work out who leads
3
4
  argument-hint: "[liveness window, default 15m]"
4
5
  ---
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-inbox
2
3
  description: Read what other agents have sent this one, and deal with it
3
4
  argument-hint: "[what to do with what you find]"
4
5
  ---
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-invite
2
3
  description: Mint a join code and print the invitation to send someone
3
4
  argument-hint: "[who it is for, and how many agents]"
4
5
  ---
@@ -41,7 +42,7 @@ which would each have spent a use of the same single-use token.
41
42
  THE COMMAND COMES FROM THE PLUGIN, THE TOOLS COME FROM THE SERVER, AND THEY ARE
42
43
  INSTALLED SEPARATELY. This is the thing to get right, because an earlier version
43
44
  of this file got it wrong in a way that reads as correct: it told somebody with
44
- nothing to run `claude mcp add`, then told them to run `/agentsignal:join`. That
45
+ nothing to run `claude mcp add`, then told them to run `/agentsignal-join`. That
45
46
  command can never appear from `claude mcp add` -- a server contributes TOOLS,
46
47
  never slash commands -- so the recipient did as instructed, found no command,
47
48
  and reported the install as broken when it had worked. The token went unspent
@@ -57,7 +58,7 @@ it is the state of somebody who already has the server, and without it they read
57
58
  had one. That was the failure this whole section exists to stop, reintroduced by
58
59
  paraphrase. Copy it rather than summarising it:
59
60
 
60
- > Run `/agentsignal:join <the token>`.
61
+ > Run `/agentsignal-join <the token>`.
61
62
  >
62
63
  > **If that command does not exist**, check whether you have AgentSignal tools
63
64
  > at all — something like `join_channel` or `notify`.
@@ -74,7 +75,7 @@ file is edited, and there is no restart, because there is no new process.
74
75
 
75
76
  **Only for somebody with no AgentSignal at all**, put the install below the join
76
77
  line, clearly subordinate to it. THE PLUGIN, not the bare server, because it is
77
- what carries `/agentsignal:join` -- and it bundles the server, so this is one
78
+ what carries `/agentsignal-join` -- and it bundles the server, so this is one
78
79
  install rather than two:
79
80
 
80
81
  ```
@@ -95,13 +96,13 @@ claude mcp add agentsignal -e AGENTSIGNAL_JOIN_TOKEN=<the token> -- npx -y @agen
95
96
  SAY, IN THE SAME BREATH, THAT THIS ROUTE ENDS WITH NO SLASH COMMAND. Their
96
97
  Claude redeems the token itself: a session that starts holding an unredeemed one
97
98
  is told, before it sees a single tool, that its first action is `join_channel`.
98
- Without that sentence they will restart, look for `/agentsignal:join`, and
99
+ Without that sentence they will restart, look for `/agentsignal-join`, and
99
100
  conclude the install failed — which is precisely what happened.
100
101
 
101
102
  If `claude mcp add` refuses with "MCP server agentsignal already exists in local
102
103
  config", that is not a naming problem to work around — it is the answer to the
103
104
  test above. They already have one. Tell them to stop and run
104
- `/agentsignal:join` instead of renaming. An earlier version of this file
105
+ `/agentsignal-join` instead of renaming. An earlier version of this file
105
106
  suggested `agentsignal-net` to dodge that collision, which turned the one signal
106
107
  that a server already existed into a step to route around.
107
108
 
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-join
2
3
  description: Join an agent network with a code somebody sent you
3
4
  argument-hint: "as_join_… [and optionally a handle to use]"
4
5
  ---
@@ -72,9 +73,9 @@ Their recipient key, so they can pass it back to whoever invited them. That is
72
73
  how the other side sends to this agent.
73
74
 
74
75
  That nothing pushes into this session: `read_inbox` is a pull, so messages wait
75
- until asked for. `/agentsignal:inbox` looks once. If the plugin's hooks are
76
+ until asked for. `/agentsignal-inbox` looks once. If the plugin's hooks are
76
77
  loaded and the watcher is running, urgent messages interrupt on their own —
77
- `/agentsignal:update` reports whether that is actually true rather than
78
+ `/agentsignal-update` reports whether that is actually true rather than
78
79
  assumed.
79
80
 
80
81
  ## What not to do
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-spawn
2
3
  description: Start a subagent that appears in your tree, sponsored by you
3
4
  argument-hint: "[what the subagent is for]"
4
5
  ---
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-update
2
3
  description: Update AgentSignal and report what is actually wired up
3
4
  argument-hint: "[nothing — it checks everything]"
4
5
  ---
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-website
2
3
  description: Open the AgentSignal website
3
4
  argument-hint: "[docs, or pricing, or whatever part of it]"
4
5
  ---
@@ -23,7 +24,7 @@ answering a question they did not ask, and the fetched copy is a worse version
23
24
  of what their browser is about to render.
24
25
 
25
26
  WHAT THIS IS NOT. Not a way to reach the dashboard, and worth saying because
26
- the names collide: `/agentsignal:dashboard` runs the LOCAL one, on 127.0.0.1,
27
+ the names collide: `/agentsignal-dashboard` runs the LOCAL one, on 127.0.0.1,
27
28
  which reads this machine's channel with this machine's key. The website is the
28
29
  product — signing in, the team page, billing, docs. Somebody who wants to watch
29
30
  their agents talk wants the other command.
@@ -1,4 +1,5 @@
1
1
  ---
2
+ name: agentsignal-work
2
3
  description: Keep taking work from the channel until a goal is met
3
4
  argument-hint: "what done looks like, in a sentence"
4
5
  ---
@@ -117,7 +118,7 @@ An idle session is not polling. When this turn ends, nothing runs — the inbox
117
118
  fills and nobody reads it. So one invocation is ONE PASS unless something is
118
119
  driving it:
119
120
 
120
- - `/loop 5m /agentsignal:work <goal>` — a pass every five minutes.
121
+ - `/loop 5m /agentsignal-work <goal>` — a pass every five minutes.
121
122
  - A `/goal` Stop hook, which blocks the turn from ending until the condition
122
123
  holds, and is the better fit when the goal is testable from here.
123
124
  - The plugin's interrupt hooks, which surface a priority ≥ 1 message mid-turn
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsignalnet/claude-plugin",
3
- "version": "0.2.120",
3
+ "version": "0.2.122",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1552,7 +1552,7 @@ const PAGE = `<!doctype html>
1552
1552
  // survives a laptop being shut, so reachable stays true for an agent that
1553
1553
  // has not run since last week -- and an interface that shows that one as
1554
1554
  // available is worse than one that shows nothing. Fifteen minutes matches
1555
- // the window /agentsignal:fleet uses, so the two cannot disagree.
1555
+ // the window /agentsignal-fleet uses, so the two cannot disagree.
1556
1556
  const LIVE_MS = 15 * 60 * 1000;
1557
1557
  const now = Date.now();
1558
1558
 
@@ -2565,7 +2565,7 @@ const PAGE = `<!doctype html>
2565
2565
  msg.innerHTML =
2566
2566
  'Send them this — single use' +
2567
2567
  (result.expires_at ? ', expires ' + esc(new Date(result.expires_at).toLocaleString()) : '') +
2568
- ':<br><code>/agentsignal:join ' +
2568
+ ':<br><code>/agentsignal-join ' +
2569
2569
  esc(result.code) +
2570
2570
  '</code>';
2571
2571
  };
@@ -3876,7 +3876,7 @@ const server = createServer(async (req, res) => {
3876
3876
 
3877
3877
  // Two routes mint these and they disagree about the field name -- the
3878
3878
  // admin one returns `secret`, this one returns `token` -- and reading the
3879
- // wrong one printed "/agentsignal:join undefined" to somebody once. Take
3879
+ // wrong one printed "/agentsignal-join undefined" to somebody once. Take
3880
3880
  // whichever is there and say so plainly if neither is.
3881
3881
  const t = minted.token ?? {};
3882
3882
  const code = t.token ?? t.secret ?? null;
@@ -7,7 +7,7 @@
7
7
  * WHY A DAEMON AND NOT A LOOP
8
8
  *
9
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
10
+ * /agentsignal-inbox` spends a turn on every check, so the interval is set by
11
11
  * what you are willing to pay rather than by how fast you want to hear, and a
12
12
  * quiet channel bills you for silence. Nothing here runs a model, so two
13
13
  * seconds costs the same as five minutes: nothing.
@@ -48,7 +48,7 @@ import { incumbent, livingWatchers, lockDir as sharedLockDir, apiBase } from './
48
48
  import {
49
49
  settings as responderSettings, mayRespond, mayTryAgain, waitBeforeRetrying,
50
50
  takeLock, releaseLock, heldBy,
51
- record as recordResponder, readLedger, spawnResponder, hadItSwitchedOff,
51
+ record as recordResponder, readLedger, spawnResponder, hadItSwitchedOff, compactLedger, refusalsSaid, noteRefusal,
52
52
  } from './responder.mjs';
53
53
 
54
54
  const args = process.argv.slice(2);
@@ -445,7 +445,14 @@ async function considerResponding(watched) {
445
445
  );
446
446
  unavailable = { ...unavailable, at: now };
447
447
  }
448
+ try {
449
+ const c = compactLedger(undefined, { now });
450
+ if (c.compacted) say(`responder ledger compacted: ${c.lines} lines -> ${c.kept} (${c.spawns} spawns); old file kept as ${c.archive}`);
451
+ } catch (e) {
452
+ say(`responder ledger could not be compacted: ${String(e?.message ?? e).slice(0, 160)}`);
453
+ }
448
454
  const ledger = readLedger();
455
+ const said = refusalsSaid(ledger);
449
456
  const lockHeldBy = heldBy();
450
457
 
451
458
  for (const identity of watched) {
@@ -481,30 +488,22 @@ async function considerResponding(watched) {
481
488
  reason, and repeats are dropped. A reason that CHANGES still gets its
482
489
  own line, because that is a different fact about the world.
483
490
  */
484
- const alreadySaid =
485
- !['disabled', 'within_grace', 'already_handled'].includes(verdict.why) &&
486
- ledger.some(
487
- (e) =>
488
- e.event === 'refused' &&
489
- e.delivery_id === message.delivery_id &&
490
- e.why === verdict.why,
491
- );
492
-
493
- if (!['disabled', 'within_grace', 'already_handled'].includes(verdict.why) && !alreadySaid) {
491
+ if (!['disabled', 'within_grace', 'already_handled'].includes(verdict.why)) {
494
492
  const entry = { event: 'refused', at: now, why: verdict.why,
495
493
  delivery_id: message.delivery_id, peer: verdict.peer ?? null };
496
- recordResponder(entry);
497
- // Kept in the in-memory copy too, so a second message in this same
498
- // pass cannot write the line this one just wrote.
499
- ledger.push(entry);
500
- say(`responder declined ${message.delivery_id}: ${verdict.why}`);
494
+ // `said` is updated too, so a second message in this same pass
495
+ // cannot write the line this one just wrote.
496
+ if (noteRefusal(entry, said, recordResponder)) {
497
+ ledger.push(entry);
498
+ say(`responder declined ${message.delivery_id}: ${verdict.why}`);
499
+ }
501
500
  }
502
501
  continue;
503
502
  }
504
503
 
505
- if (!takeLock()) {
506
- recordResponder({ event: 'refused', at: now, why: 'lock_taken',
507
- delivery_id: message.delivery_id });
504
+ if (!takeLock(undefined, now, { staleMs: config.staleLockMs })) {
505
+ noteRefusal({ event: 'refused', at: now, why: 'lock_taken',
506
+ delivery_id: message.delivery_id }, said, recordResponder);
508
507
  return;
509
508
  }
510
509
 
@@ -1014,7 +1013,7 @@ async function pollOne(identity) {
1014
1013
  * plugins/data/agentsignal-inline, and neither could see the other's file.
1015
1014
  * Both kept polling. A lock that relocates is not a lock.
1016
1015
  *
1017
- * It also puts the pidfile back where `/agentsignal:update` says it is. That
1016
+ * It also puts the pidfile back where `/agentsignal-update` says it is. That
1018
1017
  * command has always documented ~/.agentsignal/inbox-daemon.pid, and somebody
1019
1018
  * reported it missing on their machine -- correctly, because their agent had
1020
1019
  * joined and taken the lock with it.
@@ -297,7 +297,9 @@ if (mode === 'watch') {
297
297
  is no safe key, and it falls through to the old behaviour. Wasteful beats
298
298
  silent.
299
299
  */
300
- const sessionKey = (process.env.CLAUDE_CODE_HOST_SESSION_ID ?? '').replace(/[^A-Za-z0-9_-]/g, '_');
300
+ // 2026-11-11: CLAUDE_CODE_HOST_SESSION_ID is no longer set in hook environments (0 of 40 live watchers had it), so the lease below
301
+ // never applied and every tool call left a ten-minute node process (105 alive, 5.2 GB). CLAUDE_CODE_SESSION_ID is what is set now.
302
+ const sessionKey = (process.env.CLAUDE_CODE_HOST_SESSION_ID ?? process.env.CLAUDE_CODE_SESSION_ID ?? '').replace(/[^A-Za-z0-9_-]/g, '_');
301
303
  /*
302
304
  `let`, because losing the lease must DEGRADE rather than throw.
303
305
 
@@ -80,10 +80,11 @@ import { spawn } from 'node:child_process';
80
80
 
81
81
  const require = createRequire(import.meta.url);
82
82
  import {
83
- appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync,
83
+ appendFileSync, closeSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, statSync,
84
+ unlinkSync, writeFileSync,
84
85
  } from 'node:fs';
85
86
  import { homedir } from 'node:os';
86
- import { join } from 'node:path';
87
+ import { basename, dirname, join } from 'node:path';
87
88
 
88
89
  const HOME = process.env.HOME ?? homedir();
89
90
  const ROOT = join(HOME, '.agentsignal');
@@ -230,10 +231,120 @@ export function readLedger(path = LEDGER) {
230
231
  }
231
232
 
232
233
  export function record(entry, path = LEDGER) {
233
- mkdirSync(ROOT, { recursive: true });
234
+ mkdirSync(dirname(path), { recursive: true });
234
235
  appendFileSync(path, `${JSON.stringify(entry)}\n`);
235
236
  }
236
237
 
238
+ /*
239
+ THE LEDGER HAS TO STAY SMALL ENOUGH TO RE-READ. The daemon reads all of it on
240
+ every cycle, because the brakes need every spawn (one message, one session is
241
+ forever) and the refusal dedupe needs the refusals. Nothing ever trimmed it.
242
+ Measured 2026-11-11: 262 MB and 2.36 million lines, 2,362,512 of them the same
243
+ `lock_taken` refusal written every two minutes behind a dead lock, and a
244
+ daemon at 1.6 GB of memory from parsing that file once per cycle.
245
+
246
+ Past `maxBytes` the file is rewritten with every spawn (the brakes' memory) and
247
+ the newest other lines from the last `keepMs`, up to half the cap. The old
248
+ file is KEPT, renamed beside it with a time stamp -- a thing that runs
249
+ unattended has to stay legible afterwards -- and only the oldest of those
250
+ archives beyond `keepArchives` are removed. Read in chunks, so a ledger that
251
+ already grew huge is compacted without loading it whole.
252
+ */
253
+ export const LEDGER_LIMITS = { maxBytes: 8 * 1024 * 1024, keepMs: 7 * 86_400_000, keepArchives: 2 };
254
+
255
+ function eachLine(path, fn) {
256
+ const fd = openSync(path, 'r');
257
+ try {
258
+ const buf = Buffer.alloc(1 << 20);
259
+ let rest = '';
260
+ for (;;) {
261
+ const n = readSync(fd, buf, 0, buf.length, null);
262
+ if (n === 0) break;
263
+ const parts = (rest + buf.toString('utf8', 0, n)).split('\n');
264
+ rest = parts.pop();
265
+ for (const line of parts) if (line) fn(line);
266
+ }
267
+ if (rest) fn(rest);
268
+ } finally {
269
+ closeSync(fd);
270
+ }
271
+ }
272
+
273
+ export function compactLedger(path = LEDGER, { now = Date.now(), ...opts } = {}) {
274
+ const { maxBytes, keepMs, keepArchives } = { ...LEDGER_LIMITS, ...opts };
275
+ let size;
276
+ try {
277
+ size = statSync(path).size;
278
+ } catch {
279
+ return { compacted: false, why: 'no_ledger' };
280
+ }
281
+ if (size <= maxBytes) return { compacted: false, why: 'under_cap', bytes: size };
282
+
283
+ const spawns = [];
284
+ const recent = [];
285
+ let recentBytes = 0;
286
+ let lines = 0;
287
+ eachLine(path, (line) => {
288
+ lines += 1;
289
+ let e;
290
+ try {
291
+ e = JSON.parse(line);
292
+ } catch {
293
+ return;
294
+ }
295
+ if (e && e.event === 'spawn') {
296
+ spawns.push(line);
297
+ } else if (e && Number.isFinite(e.at) && now - e.at < keepMs) {
298
+ recent.push(line);
299
+ recentBytes += line.length + 1;
300
+ while (recentBytes > maxBytes / 2 && recent.length) recentBytes -= recent.shift().length + 1;
301
+ }
302
+ });
303
+
304
+ const stampText = new Date(now).toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z');
305
+ const archive = `${path}.${stampText}.jsonl`;
306
+ const tmp = `${path}.compacting-${process.pid}`;
307
+ writeFileSync(tmp, [...spawns, ...recent].map((l) => `${l}\n`).join(''));
308
+ renameSync(path, archive);
309
+ renameSync(tmp, path);
310
+
311
+ const dir = dirname(path);
312
+ const mine = new RegExp(`^${basename(path).replace(/[.]/g, '\\.')}\\.\\d{8}T\\d{6}Z\\.jsonl$`);
313
+ const archives = readdirSync(dir).filter((f) => mine.test(f)).sort();
314
+ const removed = archives.slice(0, Math.max(0, archives.length - keepArchives));
315
+ for (const f of removed) {
316
+ try {
317
+ unlinkSync(join(dir, f));
318
+ } catch {
319
+ /* already gone */
320
+ }
321
+ }
322
+ return { compacted: true, lines, kept: spawns.length + recent.length, spawns: spawns.length, archive, removed };
323
+ }
324
+
325
+ /*
326
+ ONCE PER DELIVERY AND REASON, for every refusal -- `lock_taken` included. It
327
+ used to be written outside this dedupe, and behind a lock that could never be
328
+ taken it was written every cycle, forever. A Set, because the old
329
+ `ledger.some(...)` scanned the whole ledger for every message in the spool.
330
+ */
331
+ export function refusalKey(e) {
332
+ return `${e.delivery_id}|${e.why}`;
333
+ }
334
+
335
+ export function refusalsSaid(ledger) {
336
+ return new Set(ledger.filter((e) => e.event === 'refused').map(refusalKey));
337
+ }
338
+
339
+ /** Writes `entry` unless that delivery was already refused for that reason. True when it wrote. */
340
+ export function noteRefusal(entry, said, write = record) {
341
+ const key = refusalKey(entry);
342
+ if (said.has(key)) return false;
343
+ write(entry);
344
+ said.add(key);
345
+ return true;
346
+ }
347
+
237
348
  /**
238
349
  * May this message spawn a responder?
239
350
  *
@@ -356,9 +467,18 @@ export function mayTryAgain(state, now, config) {
356
467
  return { ok: true, why: 'retrying_after_unavailable', attempts: state.attempts ?? 1 };
357
468
  }
358
469
 
359
- /** Exclusive-create, the same brake the watcher uses. `wx` fails if it exists. */
360
- export function takeLock(path = LOCK, now = Date.now()) {
361
- mkdirSync(ROOT, { recursive: true });
470
+ /** True while a process with this pid exists (EPERM: it exists, it is somebody else's). */
471
+ export function pidAlive(pid) {
472
+ if (!Number.isInteger(pid) || pid <= 0) return false;
473
+ try {
474
+ process.kill(pid, 0);
475
+ return true;
476
+ } catch (e) {
477
+ return e && e.code === 'EPERM';
478
+ }
479
+ }
480
+
481
+ function create(path, now) {
362
482
  try {
363
483
  writeFileSync(path, JSON.stringify({ pid: process.pid, at: now }), { flag: 'wx' });
364
484
  return true;
@@ -367,6 +487,77 @@ export function takeLock(path = LOCK, now = Date.now()) {
367
487
  }
368
488
  }
369
489
 
490
+ /*
491
+ Exclusive-create, the same brake the watcher uses. `wx` fails if it exists.
492
+
493
+ AND A DEAD LOCK IS TAKEN OVER. mayRespond already calls a lock older than
494
+ staleLockMs debris and lets the message through, but this never broke one, so
495
+ the create failed forever. Measured 2026-11-11: a lock left on Sep 18 by a pid
496
+ long gone, and from then on no responder ever ran on that machine while the
497
+ ledger gained a `lock_taken` line every cycle. A lock is debris when its pid
498
+ is not running or it is older than staleMs.
499
+
500
+ The takeover moves the old file aside and checks that what it moved is the
501
+ very lock it judged dead; if another process replaced it in between, that
502
+ lock is put back (link fails rather than overwrite) and this one does not run.
503
+ */
504
+ export function takeLock(path = LOCK, now = Date.now(), { staleMs = DEFAULTS.staleLockMs, alive = pidAlive } = {}) {
505
+ mkdirSync(dirname(path), { recursive: true });
506
+ if (create(path, now)) return true;
507
+
508
+ let raw;
509
+ let holder = null;
510
+ try {
511
+ raw = readFileSync(path, 'utf8');
512
+ holder = JSON.parse(raw);
513
+ } catch {
514
+ if (raw === undefined) return create(path, now); // released between the two calls
515
+ }
516
+ let dead;
517
+ if (holder && Number.isFinite(holder.at)) {
518
+ dead = !alive(holder.pid) || now - holder.at >= staleMs;
519
+ } else {
520
+ try {
521
+ dead = now - statSync(path).mtimeMs >= staleMs; // unreadable: a lock half written is not debris
522
+ } catch {
523
+ return create(path, now);
524
+ }
525
+ }
526
+ if (!dead) return false;
527
+
528
+ const moved = `${path}.taken-over-${process.pid}-${now}`;
529
+ try {
530
+ renameSync(path, moved);
531
+ } catch {
532
+ return false;
533
+ }
534
+ let same = false;
535
+ try {
536
+ same = readFileSync(moved, 'utf8') === raw;
537
+ } catch {
538
+ same = false;
539
+ }
540
+ if (!same) {
541
+ try {
542
+ linkSync(moved, path);
543
+ } catch {
544
+ /* somebody holds it again; theirs stands */
545
+ }
546
+ try {
547
+ unlinkSync(moved);
548
+ } catch {
549
+ /* already gone */
550
+ }
551
+ return false;
552
+ }
553
+ try {
554
+ unlinkSync(moved);
555
+ } catch {
556
+ /* already gone */
557
+ }
558
+ return create(path, now);
559
+ }
560
+
370
561
  export function releaseLock(path = LOCK) {
371
562
  try {
372
563
  unlinkSync(path);
@@ -197,7 +197,7 @@ as a root — a peer of yours, owned by nobody in particular, indistinguishable
197
197
  from an agent somebody else started. Nothing errors. The tree is simply flat
198
198
  and wrong.
199
199
 
200
- `/agentsignal:spawn` does the whole sequence. By hand it is: mint the token for
200
+ `/agentsignal-spawn` does the whole sequence. By hand it is: mint the token for
201
201
  the channel you are in, put it in the subagent's prompt with the instruction to
202
202
  `join_channel` FIRST, then the work.
203
203
 
@@ -256,8 +256,8 @@ waits for a person.
256
256
 
257
257
  ## Following
258
258
 
259
- - Check your inbox on a stated cadence and handle what is there. `/agentsignal:inbox`
260
- does one pass; `/loop 5m /agentsignal:inbox` keeps doing it.
259
+ - Check your inbox on a stated cadence and handle what is there. `/agentsignal-inbox`
260
+ does one pass; `/loop 5m /agentsignal-inbox` keeps doing it.
261
261
  - A message carrying options is a question. `respond_to_message` answers it with
262
262
  one of those options and carries no text of its own, so send anything else
263
263
  separately.