@agentsignalnet/claude-plugin 0.2.88 → 0.2.89

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.88",
4
+ "version": "0.2.89",
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsignalnet/claude-plugin",
3
- "version": "0.2.88",
3
+ "version": "0.2.89",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -43,6 +43,12 @@ import { stateDirs, writeDir, identities as storedIdentities } from './state.mjs
43
43
  // One copy, shared with the hook -- which has to ask the same question the
44
44
  // moment a join creates a credential. See the note at the top of that file.
45
45
  import { incumbent, livingWatchers, lockDir as sharedLockDir, apiBase } from './watchers.mjs';
46
+ // Answering when nobody is home. Off unless AGENTSIGNAL_RESPONDER says
47
+ // otherwise, so importing it costs nothing and changes nothing.
48
+ import {
49
+ settings as responderSettings, mayRespond, takeLock, releaseLock, heldBy,
50
+ record as recordResponder, readLedger, spawnResponder,
51
+ } from './responder.mjs';
46
52
 
47
53
  const args = process.argv.slice(2);
48
54
  function flag(name, fallback) {
@@ -261,6 +267,76 @@ async function tick() {
261
267
  // each is one small request, and a burst of parallel fetches off a laptop
262
268
  // waking from sleep is a worse neighbour than a few hundred milliseconds.
263
269
  for (const identity of watched) await pollOne(identity);
270
+
271
+ // AFTER polling, not during: the question is "did a live session take this",
272
+ // and the grace period has to elapse before that has an answer.
273
+ await considerResponding(watched);
274
+ }
275
+
276
+ /**
277
+ * Spawn a headless session for a message nothing else took.
278
+ *
279
+ * Returns immediately when the responder is off, which is the default and the
280
+ * common case -- this must cost nothing at all for the people who never turn it
281
+ * on. Every refusal past that point is written to the ledger, because a thing
282
+ * that declines silently cannot be told from a thing that is broken.
283
+ */
284
+ async function considerResponding(watched) {
285
+ const config = responderSettings();
286
+ if (config.mode === 'off') return;
287
+
288
+ const now = Date.now();
289
+ const ledger = readLedger();
290
+ const lockHeldBy = heldBy();
291
+
292
+ for (const identity of watched) {
293
+ let spool;
294
+ let handled;
295
+ try {
296
+ spool = JSON.parse(readFileSync(identity.spool, 'utf8'));
297
+ handled = new Set(readHandled(identity.dir));
298
+ } catch {
299
+ continue;
300
+ }
301
+
302
+ for (const message of spool.messages ?? []) {
303
+ const verdict = mayRespond(message, { now, config, ledger, lockHeldBy, handled });
304
+ if (!verdict.ok) {
305
+ // Only the interesting refusals. "within_grace" and "already_handled"
306
+ // are the system working and would drown the ledger they share with the
307
+ // decisions somebody actually needs to read.
308
+ if (!['disabled', 'within_grace', 'already_handled'].includes(verdict.why)) {
309
+ recordResponder({ event: 'refused', at: now, why: verdict.why,
310
+ delivery_id: message.delivery_id, peer: verdict.peer ?? null });
311
+ say(`responder declined ${message.delivery_id}: ${verdict.why}`);
312
+ }
313
+ continue;
314
+ }
315
+
316
+ if (!takeLock()) {
317
+ recordResponder({ event: 'refused', at: now, why: 'lock_taken',
318
+ delivery_id: message.delivery_id });
319
+ return;
320
+ }
321
+
322
+ recordResponder({ event: 'spawn', at: now, mode: config.mode,
323
+ delivery_id: message.delivery_id, peer: verdict.peer ?? null,
324
+ title: message.title ?? null });
325
+ say(`responder answering ${message.delivery_id} (${config.mode}) from ${verdict.peer ?? 'unknown'}`);
326
+
327
+ const child = spawnResponder(message, config, identity.dir);
328
+ child.on('exit', (code) => {
329
+ releaseLock();
330
+ recordResponder({ event: 'finished', at: Date.now(),
331
+ delivery_id: message.delivery_id, exit_code: code });
332
+ say(`responder finished ${message.delivery_id} with code ${code}`);
333
+ });
334
+
335
+ // One per pass. The lock enforces this anyway; returning makes it true
336
+ // without depending on the lock being right.
337
+ return;
338
+ }
339
+ }
264
340
  }
265
341
 
266
342
  async function pollOne(identity) {
@@ -0,0 +1,323 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Answer when nobody is home.
4
+ *
5
+ * node responder.mjs --self-test # prove the brakes work
6
+ *
7
+ * A message reaches this machine in under two seconds and then waits for the
8
+ * session to do something, because hooks only fire at the boundary between two
9
+ * tool calls. A session sitting at the prompt has no boundaries, so a question
10
+ * can wait indefinitely -- measured, twice: 90s and 120s with no reply, the
11
+ * second one explicitly asking for an instant answer.
12
+ *
13
+ * That is not a transport problem and no amount of realtime fixes it. What
14
+ * fixes it is something being awake. This spawns a headless session to handle a
15
+ * message that no live session took.
16
+ *
17
+ * WHAT THIS IS. A standing delegation that spends money and acts while nobody
18
+ * is watching. Everything below is written on the assumption that it will one
19
+ * day misfire at 4am, and that the person reading the log afterwards will be
20
+ * trying to work out what it did and why.
21
+ *
22
+ * SO: OFF UNLESS ASKED. AGENTSIGNAL_RESPONDER is unset by default and this does
23
+ * nothing. It must never become true because somebody updated the plugin --
24
+ * consenting to an autonomous agent is not the kind of thing that should arrive
25
+ * in a patch release.
26
+ *
27
+ * off (default) nothing happens
28
+ * answer may talk: read the inbox, reply, notify. No shell, no files.
29
+ * act may also do the work: read, search, edit, run commands.
30
+ *
31
+ * THE BRAKES, and what each is actually for:
32
+ *
33
+ * single flight one responder per machine. Without it a burst of five
34
+ * messages spawns five sessions against the same repo.
35
+ * rate cap an hourly and a daily ceiling. This is the one that bounds
36
+ * the bill when something goes wrong in a way nobody
37
+ * predicted, which is the only kind that matters.
38
+ * peer cooldown two responders can answer each other forever, each reply
39
+ * waking the other, and neither is doing anything wrong. One
40
+ * spawn per peer per cooldown breaks the cycle from either
41
+ * side without needing both to be well behaved.
42
+ * chain depth a message a responder produced is marked, and a marked
43
+ * message never spawns another. Belt to the cooldown's
44
+ * braces, because the cooldown is a timer and timers expire.
45
+ * grace period only spawn for a message no live session took. The evidence
46
+ * is the handled list: still unhandled after the grace means
47
+ * nothing was there to handle it.
48
+ *
49
+ * Every decision -- spawn or refuse -- is appended to responder-ledger.jsonl
50
+ * with its reason. A thing that runs unattended has to be legible afterwards or
51
+ * it cannot be trusted, and "it seemed quiet" is not evidence.
52
+ */
53
+ import { spawn } from 'node:child_process';
54
+ import {
55
+ appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync,
56
+ } from 'node:fs';
57
+ import { homedir } from 'node:os';
58
+ import { join } from 'node:path';
59
+
60
+ const HOME = process.env.HOME ?? homedir();
61
+ const ROOT = join(HOME, '.agentsignal');
62
+ const LEDGER = join(ROOT, 'responder-ledger.jsonl');
63
+ const LOCK = join(ROOT, 'responder.lock');
64
+
65
+ /** Defaults chosen to be boring. Every one can be overridden by env. */
66
+ export const DEFAULTS = {
67
+ mode: 'off',
68
+ gracePeriodMs: 45_000,
69
+ perHour: 6,
70
+ perDay: 30,
71
+ peerCooldownMs: 10 * 60_000,
72
+ // A held lock older than this is debris from a killed responder, not a peer.
73
+ staleLockMs: 20 * 60_000,
74
+ };
75
+
76
+ export function settings(env = process.env) {
77
+ const num = (name, fallback) => {
78
+ const raw = env[name];
79
+ if (raw === undefined || raw.trim() === '') return fallback;
80
+ const n = Number(raw);
81
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
82
+ };
83
+ const mode = (env.AGENTSIGNAL_RESPONDER ?? DEFAULTS.mode).trim().toLowerCase();
84
+ return {
85
+ mode: ['off', 'answer', 'act'].includes(mode) ? mode : 'off',
86
+ gracePeriodMs: num('AGENTSIGNAL_RESPONDER_GRACE_MS', DEFAULTS.gracePeriodMs),
87
+ perHour: num('AGENTSIGNAL_RESPONDER_PER_HOUR', DEFAULTS.perHour),
88
+ perDay: num('AGENTSIGNAL_RESPONDER_PER_DAY', DEFAULTS.perDay),
89
+ peerCooldownMs: num('AGENTSIGNAL_RESPONDER_PEER_COOLDOWN_MS', DEFAULTS.peerCooldownMs),
90
+ staleLockMs: num('AGENTSIGNAL_RESPONDER_STALE_LOCK_MS', DEFAULTS.staleLockMs),
91
+ };
92
+ }
93
+
94
+ /**
95
+ * What a spawned session is allowed to touch.
96
+ *
97
+ * `answer` cannot reach a shell or a file. It exists so somebody can turn this
98
+ * on and watch it for a week before deciding whether it should be able to act.
99
+ */
100
+ export function toolsFor(mode) {
101
+ const talk = [
102
+ 'mcp__plugin_agentsignal_agentsignal__read_inbox',
103
+ 'mcp__plugin_agentsignal_agentsignal__respond_to_message',
104
+ 'mcp__plugin_agentsignal_agentsignal__notify',
105
+ 'mcp__plugin_agentsignal_agentsignal__list_agents',
106
+ ];
107
+ if (mode !== 'act') return talk;
108
+ return [...talk, 'Read', 'Grep', 'Glob', 'Bash', 'Edit', 'Write'];
109
+ }
110
+
111
+ export function readLedger(path = LEDGER) {
112
+ if (!existsSync(path)) return [];
113
+ return readFileSync(path, 'utf8')
114
+ .split('\n')
115
+ .filter(Boolean)
116
+ .map((line) => {
117
+ try {
118
+ return JSON.parse(line);
119
+ } catch {
120
+ return null;
121
+ }
122
+ })
123
+ .filter(Boolean);
124
+ }
125
+
126
+ export function record(entry, path = LEDGER) {
127
+ mkdirSync(ROOT, { recursive: true });
128
+ appendFileSync(path, `${JSON.stringify(entry)}\n`);
129
+ }
130
+
131
+ /**
132
+ * May this message spawn a responder?
133
+ *
134
+ * Pure, and takes the world as arguments, so the brakes can be tested without
135
+ * spawning anything. Every refusal names itself: a responder that declines
136
+ * silently is indistinguishable from one that is broken.
137
+ */
138
+ export function mayRespond(message, world) {
139
+ const {
140
+ now, config, ledger = [], lockHeldBy = null, handled = new Set(),
141
+ } = world;
142
+
143
+ if (config.mode === 'off') return { ok: false, why: 'disabled' };
144
+
145
+ if (message.from_responder) return { ok: false, why: 'chain_depth' };
146
+
147
+ if (handled.has(message.delivery_id)) return { ok: false, why: 'already_handled' };
148
+
149
+ const spooledAt = Date.parse(message.spooled_at ?? '');
150
+ if (!Number.isFinite(spooledAt)) return { ok: false, why: 'no_spool_stamp' };
151
+ if (now - spooledAt < config.gracePeriodMs) return { ok: false, why: 'within_grace' };
152
+
153
+ if (lockHeldBy && now - lockHeldBy.at < config.staleLockMs) {
154
+ return { ok: false, why: 'another_responder_running' };
155
+ }
156
+
157
+ const spawns = ledger.filter((e) => e.event === 'spawn');
158
+ const lastHour = spawns.filter((e) => now - e.at < 3_600_000).length;
159
+ if (lastHour >= config.perHour) {
160
+ return { ok: false, why: 'hourly_cap', cap: config.perHour };
161
+ }
162
+ const lastDay = spawns.filter((e) => now - e.at < 86_400_000).length;
163
+ if (lastDay >= config.perDay) {
164
+ return { ok: false, why: 'daily_cap', cap: config.perDay };
165
+ }
166
+
167
+ const peer = message.from_recipient_key ?? message.from ?? null;
168
+ if (peer) {
169
+ const recent = spawns
170
+ .filter((e) => e.peer === peer)
171
+ .reduce((a, e) => Math.max(a, e.at), 0);
172
+ if (recent && now - recent < config.peerCooldownMs) {
173
+ return { ok: false, why: 'peer_cooldown', peer };
174
+ }
175
+ }
176
+
177
+ return { ok: true, peer };
178
+ }
179
+
180
+ /** Exclusive-create, the same brake the watcher uses. `wx` fails if it exists. */
181
+ export function takeLock(path = LOCK, now = Date.now()) {
182
+ mkdirSync(ROOT, { recursive: true });
183
+ try {
184
+ writeFileSync(path, JSON.stringify({ pid: process.pid, at: now }), { flag: 'wx' });
185
+ return true;
186
+ } catch {
187
+ return false;
188
+ }
189
+ }
190
+
191
+ export function releaseLock(path = LOCK) {
192
+ try {
193
+ unlinkSync(path);
194
+ } catch {
195
+ /* already gone */
196
+ }
197
+ }
198
+
199
+ export function heldBy(path = LOCK) {
200
+ try {
201
+ return JSON.parse(readFileSync(path, 'utf8'));
202
+ } catch {
203
+ return null;
204
+ }
205
+ }
206
+
207
+ /**
208
+ * What the spawned session is told.
209
+ *
210
+ * Deliberately narrow. It is answering ONE message, and the instruction not to
211
+ * start anything new is what keeps "act" from meaning "wander off".
212
+ */
213
+ export function promptFor(message, mode) {
214
+ return [
215
+ 'You are answering one message on behalf of an agent whose human is away.',
216
+ '',
217
+ `From: ${message.from_name ?? message.from_recipient_key ?? 'another agent'}`,
218
+ `Title: ${message.title ?? '(none)'}`,
219
+ `Body: ${message.body ?? '(none)'}`,
220
+ message.options?.length
221
+ ? `Options, one of which you must pick: ${JSON.stringify(message.options)}`
222
+ : '',
223
+ '',
224
+ 'Answer with respond_to_message, choosing one option and writing what you',
225
+ 'actually found in the body. The option is what your answer means; the body',
226
+ 'is what it says, and up to 4096 characters of it reach the sender.',
227
+ '',
228
+ mode === 'act'
229
+ ? 'You may read, search and run commands to establish the answer. Do the smallest thing that answers this message and stop. Do not start work nobody asked for, and do not send messages to anybody else.'
230
+ : 'You may not run commands or read files. Answer from the message alone, and say plainly if it cannot be answered that way.',
231
+ '',
232
+ 'Nobody is watching this run. If you are unsure, say so in the body rather',
233
+ 'than guessing -- an honest "I could not tell" is worth more than a',
234
+ 'confident answer nobody checked.',
235
+ ]
236
+ .filter((line) => line !== '')
237
+ .join('\n');
238
+ }
239
+
240
+ export function spawnResponder(message, config, cwd = process.cwd()) {
241
+ const args = [
242
+ '--print',
243
+ '--permission-mode', config.mode === 'act' ? 'acceptEdits' : 'dontAsk',
244
+ '--allowed-tools', ...toolsFor(config.mode),
245
+ promptFor(message, config.mode),
246
+ ];
247
+ const child = spawn('claude', args, {
248
+ cwd,
249
+ env: { ...process.env, AGENTSIGNAL_FROM_RESPONDER: '1' },
250
+ stdio: ['ignore', 'pipe', 'pipe'],
251
+ detached: false,
252
+ });
253
+ return child;
254
+ }
255
+
256
+ // ---------------------------------------------------------------------------
257
+ // Self-test: the brakes have to fail closed, and a brake nobody tested is not a
258
+ // brake. Same discipline as check-function-fields -- prove it refuses.
259
+ // ---------------------------------------------------------------------------
260
+ if (process.argv[2] === '--self-test') {
261
+ const failures = [];
262
+ const check = (what, passed) => {
263
+ if (!passed) failures.push(what);
264
+ };
265
+ const now = 1_000_000_000;
266
+ const base = { mode: 'act', gracePeriodMs: 1000, perHour: 2, perDay: 5, peerCooldownMs: 600_000, staleLockMs: 60_000 };
267
+ const msg = {
268
+ delivery_id: 'd1', spooled_at: new Date(now - 5000).toISOString(),
269
+ from_recipient_key: 'u_peer', title: 't', body: 'b', options: ['a', 'b'],
270
+ };
271
+
272
+ check('a clean message is allowed', mayRespond(msg, { now, config: base }).ok);
273
+
274
+ check('OFF refuses everything',
275
+ mayRespond(msg, { now, config: { ...base, mode: 'off' } }).why === 'disabled');
276
+
277
+ check('a responder-made message never spawns another',
278
+ mayRespond({ ...msg, from_responder: true }, { now, config: base }).why === 'chain_depth');
279
+
280
+ check('a message a live session took is left alone',
281
+ mayRespond(msg, { now, config: base, handled: new Set(['d1']) }).why === 'already_handled');
282
+
283
+ check('inside the grace period it waits for a real session',
284
+ mayRespond({ ...msg, spooled_at: new Date(now - 10).toISOString() },
285
+ { now, config: base }).why === 'within_grace');
286
+
287
+ check('an unstamped message is refused rather than guessed at',
288
+ mayRespond({ ...msg, spooled_at: undefined }, { now, config: base }).why === 'no_spool_stamp');
289
+
290
+ const busy = { now, config: base, lockHeldBy: { pid: 1, at: now - 1000 } };
291
+ check('one responder at a time', mayRespond(msg, busy).why === 'another_responder_running');
292
+ check('a stale lock does not block forever',
293
+ mayRespond(msg, { now, config: base, lockHeldBy: { pid: 1, at: now - 120_000 } }).ok);
294
+
295
+ const hourly = [
296
+ { event: 'spawn', at: now - 1000, peer: 'u_other' },
297
+ { event: 'spawn', at: now - 2000, peer: 'u_other2' },
298
+ ];
299
+ check('the hourly cap bites', mayRespond(msg, { now, config: base, ledger: hourly }).why === 'hourly_cap');
300
+ check('and refusals do not count toward it',
301
+ mayRespond(msg, { now, config: base,
302
+ ledger: [{ event: 'refused', at: now - 1000 }, ...hourly.slice(1)] }).ok);
303
+
304
+ check('the same peer cannot be answered twice in a row',
305
+ mayRespond(msg, { now, config: base,
306
+ ledger: [{ event: 'spawn', at: now - 1000, peer: 'u_peer' }] }).why === 'peer_cooldown');
307
+ check('and a different peer still can',
308
+ mayRespond({ ...msg, from_recipient_key: 'u_someone_else' },
309
+ { now, config: base,
310
+ ledger: [{ event: 'spawn', at: now - 1000, peer: 'u_peer' }] }).ok);
311
+
312
+ check('answer mode cannot reach a shell', !toolsFor('answer').includes('Bash'));
313
+ check('act mode can', toolsFor('act').includes('Bash'));
314
+ check('an unknown mode is off, not on', settings({ AGENTSIGNAL_RESPONDER: 'yes' }).mode === 'off');
315
+ check('unset is off', settings({}).mode === 'off');
316
+
317
+ if (failures.length) {
318
+ console.error('\nResponder self-test FAILED -- the brakes cannot be trusted:\n');
319
+ for (const f of failures) console.error(` x ${f}`);
320
+ process.exit(1);
321
+ }
322
+ console.log(`Responder self-test: ${16} checks passed (every brake fails closed).`);
323
+ }