@agentsignalnet/claude-plugin 0.2.88 → 0.2.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/scripts/dashboard.mjs +61 -1
- package/scripts/inbox-daemon.mjs +76 -0
- package/scripts/responder.mjs +379 -0
package/package.json
CHANGED
package/scripts/dashboard.mjs
CHANGED
|
@@ -667,6 +667,15 @@ const DEFAULT_SETTINGS = {
|
|
|
667
667
|
// a machine does not accumulate a year of other people's messages nobody
|
|
668
668
|
// decided to keep. 0 means keep nothing beyond what is on screen.
|
|
669
669
|
history_days: 7,
|
|
670
|
+
// Whether this machine answers when no session is live. Off, and it must
|
|
671
|
+
// stay off through an update: this is the one setting here that spends money
|
|
672
|
+
// and acts while nobody is watching, so it can only become anything else by
|
|
673
|
+
// somebody choosing it on this page.
|
|
674
|
+
//
|
|
675
|
+
// off nothing happens
|
|
676
|
+
// answer may reply and notify. No shell, no files.
|
|
677
|
+
// act may also read, search, edit and run commands.
|
|
678
|
+
responder: 'off',
|
|
670
679
|
};
|
|
671
680
|
|
|
672
681
|
function settings() {
|
|
@@ -2576,6 +2585,28 @@ const PAGE = `<!doctype html>
|
|
|
2576
2585
|
'value="' +
|
|
2577
2586
|
esc(String(LIMITS.history_days)) +
|
|
2578
2587
|
'" /> days of chat</label>' +
|
|
2588
|
+
// ANSWERING WHILE NOBODY IS HERE. Worded as what it does rather than
|
|
2589
|
+
// as a feature name, because "responder: act" tells somebody nothing
|
|
2590
|
+
// about what they are agreeing to, and this is the control on this
|
|
2591
|
+
// page that can spend money on its own.
|
|
2592
|
+
'<select id="lresp">' +
|
|
2593
|
+
['off', 'answer', 'act']
|
|
2594
|
+
.map(
|
|
2595
|
+
(k) =>
|
|
2596
|
+
'<option value="' +
|
|
2597
|
+
k +
|
|
2598
|
+
'"' +
|
|
2599
|
+
((LIMITS.responder ?? 'off') === k ? ' selected' : '') +
|
|
2600
|
+
'>' +
|
|
2601
|
+
{
|
|
2602
|
+
off: 'nobody answers when you are away',
|
|
2603
|
+
answer: 'answer messages while you are away',
|
|
2604
|
+
act: 'answer AND do the work while you are away',
|
|
2605
|
+
}[k] +
|
|
2606
|
+
'</option>',
|
|
2607
|
+
)
|
|
2608
|
+
.join('') +
|
|
2609
|
+
'</select>' +
|
|
2579
2610
|
'<button type="submit">Save</button>' +
|
|
2580
2611
|
'<span class="meta" id="lmsg"></span></form>' +
|
|
2581
2612
|
'<div class="meta" id="storage">measuring…</div>'
|
|
@@ -2628,6 +2659,7 @@ const PAGE = `<!doctype html>
|
|
|
2628
2659
|
max_agents: Number(document.getElementById('lmax').value),
|
|
2629
2660
|
default_connection_type: document.getElementById('lkind').value,
|
|
2630
2661
|
history_days: Number(document.getElementById('ldays').value),
|
|
2662
|
+
responder: document.getElementById('lresp').value,
|
|
2631
2663
|
});
|
|
2632
2664
|
if (result.error) {
|
|
2633
2665
|
msg.textContent = result.error;
|
|
@@ -3403,7 +3435,35 @@ const server = createServer(async (req, res) => {
|
|
|
3403
3435
|
return;
|
|
3404
3436
|
}
|
|
3405
3437
|
|
|
3406
|
-
|
|
3438
|
+
/*
|
|
3439
|
+
Optional in the payload like retention, and for the same reason: a caller
|
|
3440
|
+
changing only the agent cap must not blank this by omission. A first
|
|
3441
|
+
draft defaulted an absent value to 'off', which would have quietly turned
|
|
3442
|
+
answering off every time somebody saved a different field -- a setting
|
|
3443
|
+
that switches itself off is as untrustworthy as one that switches itself
|
|
3444
|
+
on.
|
|
3445
|
+
|
|
3446
|
+
REFUSED rather than coerced when it is present and wrong. The daemon
|
|
3447
|
+
reads this back, and the failure direction of a typo has to be "nothing
|
|
3448
|
+
happens" -- but a stored value nobody can explain is worse than an error,
|
|
3449
|
+
so it does not silently become 'off' either.
|
|
3450
|
+
*/
|
|
3451
|
+
const responder =
|
|
3452
|
+
payload.responder === undefined ? current.responder ?? 'off' : String(payload.responder);
|
|
3453
|
+
if (!['off', 'answer', 'act'].includes(responder)) {
|
|
3454
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
3455
|
+
res.end(
|
|
3456
|
+
JSON.stringify({ error: 'Answering while away must be off, answer or act.' }),
|
|
3457
|
+
);
|
|
3458
|
+
return;
|
|
3459
|
+
}
|
|
3460
|
+
|
|
3461
|
+
const next = {
|
|
3462
|
+
max_agents: max,
|
|
3463
|
+
default_connection_type: kind,
|
|
3464
|
+
history_days: days,
|
|
3465
|
+
responder,
|
|
3466
|
+
};
|
|
3407
3467
|
try {
|
|
3408
3468
|
saveSettings(next);
|
|
3409
3469
|
} catch (error) {
|
package/scripts/inbox-daemon.mjs
CHANGED
|
@@ -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,379 @@
|
|
|
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, and asked in the one place a person already goes.
|
|
23
|
+
*
|
|
24
|
+
* The setting lives in ~/.agentsignal/settings.json beside the other answers to
|
|
25
|
+
* "what will this machine do without asking me" -- the agent cap, what new
|
|
26
|
+
* agents are, how long chat is kept -- and the dashboard's This machine page
|
|
27
|
+
* writes it. Nobody has to export anything, and turning it on is a control
|
|
28
|
+
* somebody clicked rather than a line in a shell profile that outlives the
|
|
29
|
+
* decision and gets copied to the next machine.
|
|
30
|
+
*
|
|
31
|
+
* off (default) nothing happens
|
|
32
|
+
* answer may talk: read the inbox, reply, notify. No shell, no files.
|
|
33
|
+
* act may also do the work: read, search, edit, run commands.
|
|
34
|
+
*
|
|
35
|
+
* It must never become anything but `off` because somebody updated the plugin.
|
|
36
|
+
* Consenting to an autonomous agent is not the kind of thing that arrives in a
|
|
37
|
+
* patch release.
|
|
38
|
+
*
|
|
39
|
+
* AGENTSIGNAL_RESPONDER still overrides the file, and is for tests and for
|
|
40
|
+
* running one deliberately from a script. It is not the way a person turns this
|
|
41
|
+
* on, and nothing tells them to.
|
|
42
|
+
*
|
|
43
|
+
* THE BRAKES, and what each is actually for:
|
|
44
|
+
*
|
|
45
|
+
* single flight one responder per machine. Without it a burst of five
|
|
46
|
+
* messages spawns five sessions against the same repo.
|
|
47
|
+
* rate cap an hourly and a daily ceiling. This is the one that bounds
|
|
48
|
+
* the bill when something goes wrong in a way nobody
|
|
49
|
+
* predicted, which is the only kind that matters.
|
|
50
|
+
* peer cooldown two responders can answer each other forever, each reply
|
|
51
|
+
* waking the other, and neither is doing anything wrong. One
|
|
52
|
+
* spawn per peer per cooldown breaks the cycle from either
|
|
53
|
+
* side without needing both to be well behaved.
|
|
54
|
+
* chain depth a message a responder produced is marked, and a marked
|
|
55
|
+
* message never spawns another. Belt to the cooldown's
|
|
56
|
+
* braces, because the cooldown is a timer and timers expire.
|
|
57
|
+
* grace period only spawn for a message no live session took. The evidence
|
|
58
|
+
* is the handled list: still unhandled after the grace means
|
|
59
|
+
* nothing was there to handle it.
|
|
60
|
+
*
|
|
61
|
+
* Every decision -- spawn or refuse -- is appended to responder-ledger.jsonl
|
|
62
|
+
* with its reason. A thing that runs unattended has to be legible afterwards or
|
|
63
|
+
* it cannot be trusted, and "it seemed quiet" is not evidence.
|
|
64
|
+
*/
|
|
65
|
+
import { createRequire } from 'node:module';
|
|
66
|
+
import { spawn } from 'node:child_process';
|
|
67
|
+
|
|
68
|
+
const require = createRequire(import.meta.url);
|
|
69
|
+
import {
|
|
70
|
+
appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync,
|
|
71
|
+
} from 'node:fs';
|
|
72
|
+
import { homedir } from 'node:os';
|
|
73
|
+
import { join } from 'node:path';
|
|
74
|
+
|
|
75
|
+
const HOME = process.env.HOME ?? homedir();
|
|
76
|
+
const ROOT = join(HOME, '.agentsignal');
|
|
77
|
+
const LEDGER = join(ROOT, 'responder-ledger.jsonl');
|
|
78
|
+
const LOCK = join(ROOT, 'responder.lock');
|
|
79
|
+
|
|
80
|
+
/** Defaults chosen to be boring. Every one can be overridden by env. */
|
|
81
|
+
export const DEFAULTS = {
|
|
82
|
+
mode: 'off',
|
|
83
|
+
gracePeriodMs: 45_000,
|
|
84
|
+
perHour: 6,
|
|
85
|
+
perDay: 30,
|
|
86
|
+
peerCooldownMs: 10 * 60_000,
|
|
87
|
+
// A held lock older than this is debris from a killed responder, not a peer.
|
|
88
|
+
staleLockMs: 20 * 60_000,
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** What the dashboard's This machine page wrote, if anything. */
|
|
92
|
+
export function stored(path = join(ROOT, 'settings.json')) {
|
|
93
|
+
try {
|
|
94
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
95
|
+
} catch {
|
|
96
|
+
return {};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function settings(env = process.env, file = undefined) {
|
|
101
|
+
const saved = stored(...(file ? [file] : []));
|
|
102
|
+
const num = (name, key, fallback) => {
|
|
103
|
+
const raw = env[name];
|
|
104
|
+
if (raw !== undefined && raw.trim() !== '') {
|
|
105
|
+
const n = Number(raw);
|
|
106
|
+
if (Number.isFinite(n) && n >= 0) return n;
|
|
107
|
+
}
|
|
108
|
+
const v = saved[key];
|
|
109
|
+
return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback;
|
|
110
|
+
};
|
|
111
|
+
const mode = (env.AGENTSIGNAL_RESPONDER ?? saved.responder ?? DEFAULTS.mode)
|
|
112
|
+
.toString()
|
|
113
|
+
.trim()
|
|
114
|
+
.toLowerCase();
|
|
115
|
+
return {
|
|
116
|
+
mode: ['off', 'answer', 'act'].includes(mode) ? mode : 'off',
|
|
117
|
+
gracePeriodMs: num('AGENTSIGNAL_RESPONDER_GRACE_MS', 'responder_grace_ms', DEFAULTS.gracePeriodMs),
|
|
118
|
+
perHour: num('AGENTSIGNAL_RESPONDER_PER_HOUR', 'responder_per_hour', DEFAULTS.perHour),
|
|
119
|
+
perDay: num('AGENTSIGNAL_RESPONDER_PER_DAY', 'responder_per_day', DEFAULTS.perDay),
|
|
120
|
+
peerCooldownMs: num('AGENTSIGNAL_RESPONDER_PEER_COOLDOWN_MS', 'responder_peer_cooldown_ms', DEFAULTS.peerCooldownMs),
|
|
121
|
+
staleLockMs: num('AGENTSIGNAL_RESPONDER_STALE_LOCK_MS', 'responder_stale_lock_ms', DEFAULTS.staleLockMs),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* What a spawned session is allowed to touch.
|
|
127
|
+
*
|
|
128
|
+
* `answer` cannot reach a shell or a file. It exists so somebody can turn this
|
|
129
|
+
* on and watch it for a week before deciding whether it should be able to act.
|
|
130
|
+
*/
|
|
131
|
+
export function toolsFor(mode) {
|
|
132
|
+
const talk = [
|
|
133
|
+
'mcp__plugin_agentsignal_agentsignal__read_inbox',
|
|
134
|
+
'mcp__plugin_agentsignal_agentsignal__respond_to_message',
|
|
135
|
+
'mcp__plugin_agentsignal_agentsignal__notify',
|
|
136
|
+
'mcp__plugin_agentsignal_agentsignal__list_agents',
|
|
137
|
+
];
|
|
138
|
+
if (mode !== 'act') return talk;
|
|
139
|
+
return [...talk, 'Read', 'Grep', 'Glob', 'Bash', 'Edit', 'Write'];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function readLedger(path = LEDGER) {
|
|
143
|
+
if (!existsSync(path)) return [];
|
|
144
|
+
return readFileSync(path, 'utf8')
|
|
145
|
+
.split('\n')
|
|
146
|
+
.filter(Boolean)
|
|
147
|
+
.map((line) => {
|
|
148
|
+
try {
|
|
149
|
+
return JSON.parse(line);
|
|
150
|
+
} catch {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
.filter(Boolean);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function record(entry, path = LEDGER) {
|
|
158
|
+
mkdirSync(ROOT, { recursive: true });
|
|
159
|
+
appendFileSync(path, `${JSON.stringify(entry)}\n`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* May this message spawn a responder?
|
|
164
|
+
*
|
|
165
|
+
* Pure, and takes the world as arguments, so the brakes can be tested without
|
|
166
|
+
* spawning anything. Every refusal names itself: a responder that declines
|
|
167
|
+
* silently is indistinguishable from one that is broken.
|
|
168
|
+
*/
|
|
169
|
+
export function mayRespond(message, world) {
|
|
170
|
+
const {
|
|
171
|
+
now, config, ledger = [], lockHeldBy = null, handled = new Set(),
|
|
172
|
+
} = world;
|
|
173
|
+
|
|
174
|
+
if (config.mode === 'off') return { ok: false, why: 'disabled' };
|
|
175
|
+
|
|
176
|
+
if (message.from_responder) return { ok: false, why: 'chain_depth' };
|
|
177
|
+
|
|
178
|
+
if (handled.has(message.delivery_id)) return { ok: false, why: 'already_handled' };
|
|
179
|
+
|
|
180
|
+
const spooledAt = Date.parse(message.spooled_at ?? '');
|
|
181
|
+
if (!Number.isFinite(spooledAt)) return { ok: false, why: 'no_spool_stamp' };
|
|
182
|
+
if (now - spooledAt < config.gracePeriodMs) return { ok: false, why: 'within_grace' };
|
|
183
|
+
|
|
184
|
+
if (lockHeldBy && now - lockHeldBy.at < config.staleLockMs) {
|
|
185
|
+
return { ok: false, why: 'another_responder_running' };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const spawns = ledger.filter((e) => e.event === 'spawn');
|
|
189
|
+
const lastHour = spawns.filter((e) => now - e.at < 3_600_000).length;
|
|
190
|
+
if (lastHour >= config.perHour) {
|
|
191
|
+
return { ok: false, why: 'hourly_cap', cap: config.perHour };
|
|
192
|
+
}
|
|
193
|
+
const lastDay = spawns.filter((e) => now - e.at < 86_400_000).length;
|
|
194
|
+
if (lastDay >= config.perDay) {
|
|
195
|
+
return { ok: false, why: 'daily_cap', cap: config.perDay };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const peer = message.from_recipient_key ?? message.from ?? null;
|
|
199
|
+
if (peer) {
|
|
200
|
+
const recent = spawns
|
|
201
|
+
.filter((e) => e.peer === peer)
|
|
202
|
+
.reduce((a, e) => Math.max(a, e.at), 0);
|
|
203
|
+
if (recent && now - recent < config.peerCooldownMs) {
|
|
204
|
+
return { ok: false, why: 'peer_cooldown', peer };
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return { ok: true, peer };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Exclusive-create, the same brake the watcher uses. `wx` fails if it exists. */
|
|
212
|
+
export function takeLock(path = LOCK, now = Date.now()) {
|
|
213
|
+
mkdirSync(ROOT, { recursive: true });
|
|
214
|
+
try {
|
|
215
|
+
writeFileSync(path, JSON.stringify({ pid: process.pid, at: now }), { flag: 'wx' });
|
|
216
|
+
return true;
|
|
217
|
+
} catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function releaseLock(path = LOCK) {
|
|
223
|
+
try {
|
|
224
|
+
unlinkSync(path);
|
|
225
|
+
} catch {
|
|
226
|
+
/* already gone */
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function heldBy(path = LOCK) {
|
|
231
|
+
try {
|
|
232
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
233
|
+
} catch {
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* What the spawned session is told.
|
|
240
|
+
*
|
|
241
|
+
* Deliberately narrow. It is answering ONE message, and the instruction not to
|
|
242
|
+
* start anything new is what keeps "act" from meaning "wander off".
|
|
243
|
+
*/
|
|
244
|
+
export function promptFor(message, mode) {
|
|
245
|
+
return [
|
|
246
|
+
'You are answering one message on behalf of an agent whose human is away.',
|
|
247
|
+
'',
|
|
248
|
+
`From: ${message.from_name ?? message.from_recipient_key ?? 'another agent'}`,
|
|
249
|
+
`Title: ${message.title ?? '(none)'}`,
|
|
250
|
+
`Body: ${message.body ?? '(none)'}`,
|
|
251
|
+
message.options?.length
|
|
252
|
+
? `Options, one of which you must pick: ${JSON.stringify(message.options)}`
|
|
253
|
+
: '',
|
|
254
|
+
'',
|
|
255
|
+
'Answer with respond_to_message, choosing one option and writing what you',
|
|
256
|
+
'actually found in the body. The option is what your answer means; the body',
|
|
257
|
+
'is what it says, and up to 4096 characters of it reach the sender.',
|
|
258
|
+
'',
|
|
259
|
+
mode === 'act'
|
|
260
|
+
? '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.'
|
|
261
|
+
: 'You may not run commands or read files. Answer from the message alone, and say plainly if it cannot be answered that way.',
|
|
262
|
+
'',
|
|
263
|
+
'Nobody is watching this run. If you are unsure, say so in the body rather',
|
|
264
|
+
'than guessing -- an honest "I could not tell" is worth more than a',
|
|
265
|
+
'confident answer nobody checked.',
|
|
266
|
+
]
|
|
267
|
+
.filter((line) => line !== '')
|
|
268
|
+
.join('\n');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function spawnResponder(message, config, cwd = process.cwd()) {
|
|
272
|
+
const args = [
|
|
273
|
+
'--print',
|
|
274
|
+
'--permission-mode', config.mode === 'act' ? 'acceptEdits' : 'dontAsk',
|
|
275
|
+
'--allowed-tools', ...toolsFor(config.mode),
|
|
276
|
+
promptFor(message, config.mode),
|
|
277
|
+
];
|
|
278
|
+
const child = spawn('claude', args, {
|
|
279
|
+
cwd,
|
|
280
|
+
env: { ...process.env, AGENTSIGNAL_FROM_RESPONDER: '1' },
|
|
281
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
282
|
+
detached: false,
|
|
283
|
+
});
|
|
284
|
+
return child;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
// Self-test: the brakes have to fail closed, and a brake nobody tested is not a
|
|
289
|
+
// brake. Same discipline as check-function-fields -- prove it refuses.
|
|
290
|
+
// ---------------------------------------------------------------------------
|
|
291
|
+
if (process.argv[2] === '--self-test') {
|
|
292
|
+
const failures = [];
|
|
293
|
+
const check = (what, passed) => {
|
|
294
|
+
if (!passed) failures.push(what);
|
|
295
|
+
};
|
|
296
|
+
const now = 1_000_000_000;
|
|
297
|
+
const base = { mode: 'act', gracePeriodMs: 1000, perHour: 2, perDay: 5, peerCooldownMs: 600_000, staleLockMs: 60_000 };
|
|
298
|
+
const msg = {
|
|
299
|
+
delivery_id: 'd1', spooled_at: new Date(now - 5000).toISOString(),
|
|
300
|
+
from_recipient_key: 'u_peer', title: 't', body: 'b', options: ['a', 'b'],
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
check('a clean message is allowed', mayRespond(msg, { now, config: base }).ok);
|
|
304
|
+
|
|
305
|
+
check('OFF refuses everything',
|
|
306
|
+
mayRespond(msg, { now, config: { ...base, mode: 'off' } }).why === 'disabled');
|
|
307
|
+
|
|
308
|
+
check('a responder-made message never spawns another',
|
|
309
|
+
mayRespond({ ...msg, from_responder: true }, { now, config: base }).why === 'chain_depth');
|
|
310
|
+
|
|
311
|
+
check('a message a live session took is left alone',
|
|
312
|
+
mayRespond(msg, { now, config: base, handled: new Set(['d1']) }).why === 'already_handled');
|
|
313
|
+
|
|
314
|
+
check('inside the grace period it waits for a real session',
|
|
315
|
+
mayRespond({ ...msg, spooled_at: new Date(now - 10).toISOString() },
|
|
316
|
+
{ now, config: base }).why === 'within_grace');
|
|
317
|
+
|
|
318
|
+
check('an unstamped message is refused rather than guessed at',
|
|
319
|
+
mayRespond({ ...msg, spooled_at: undefined }, { now, config: base }).why === 'no_spool_stamp');
|
|
320
|
+
|
|
321
|
+
const busy = { now, config: base, lockHeldBy: { pid: 1, at: now - 1000 } };
|
|
322
|
+
check('one responder at a time', mayRespond(msg, busy).why === 'another_responder_running');
|
|
323
|
+
check('a stale lock does not block forever',
|
|
324
|
+
mayRespond(msg, { now, config: base, lockHeldBy: { pid: 1, at: now - 120_000 } }).ok);
|
|
325
|
+
|
|
326
|
+
const hourly = [
|
|
327
|
+
{ event: 'spawn', at: now - 1000, peer: 'u_other' },
|
|
328
|
+
{ event: 'spawn', at: now - 2000, peer: 'u_other2' },
|
|
329
|
+
];
|
|
330
|
+
check('the hourly cap bites', mayRespond(msg, { now, config: base, ledger: hourly }).why === 'hourly_cap');
|
|
331
|
+
check('and refusals do not count toward it',
|
|
332
|
+
mayRespond(msg, { now, config: base,
|
|
333
|
+
ledger: [{ event: 'refused', at: now - 1000 }, ...hourly.slice(1)] }).ok);
|
|
334
|
+
|
|
335
|
+
check('the same peer cannot be answered twice in a row',
|
|
336
|
+
mayRespond(msg, { now, config: base,
|
|
337
|
+
ledger: [{ event: 'spawn', at: now - 1000, peer: 'u_peer' }] }).why === 'peer_cooldown');
|
|
338
|
+
check('and a different peer still can',
|
|
339
|
+
mayRespond({ ...msg, from_recipient_key: 'u_someone_else' },
|
|
340
|
+
{ now, config: base,
|
|
341
|
+
ledger: [{ event: 'spawn', at: now - 1000, peer: 'u_peer' }] }).ok);
|
|
342
|
+
|
|
343
|
+
// The settings file is the front door now, so it gets the same treatment as
|
|
344
|
+
// the brakes: prove it opens, prove it stays shut, and prove a typo in it
|
|
345
|
+
// fails to OFF rather than to something.
|
|
346
|
+
{
|
|
347
|
+
const os = require('node:os');
|
|
348
|
+
const fsx = require('node:fs');
|
|
349
|
+
const dir = fsx.mkdtempSync(join(os.tmpdir(), 'responder-settings-'));
|
|
350
|
+
const file = join(dir, 'settings.json');
|
|
351
|
+
|
|
352
|
+
fsx.writeFileSync(file, JSON.stringify({ responder: 'act', responder_per_hour: 2 }));
|
|
353
|
+
check('the machine settings file turns it on', settings({}, file).mode === 'act');
|
|
354
|
+
check('and its numbers are read too', settings({}, file).perHour === 2);
|
|
355
|
+
|
|
356
|
+
fsx.writeFileSync(file, JSON.stringify({ responder: 'sure, why not' }));
|
|
357
|
+
check('a value that is not a mode is OFF, not on', settings({}, file).mode === 'off');
|
|
358
|
+
|
|
359
|
+
fsx.writeFileSync(file, JSON.stringify({ responder: 'act' }));
|
|
360
|
+
check('env still overrides the file, for tests and scripts',
|
|
361
|
+
settings({ AGENTSIGNAL_RESPONDER: 'off' }, file).mode === 'off');
|
|
362
|
+
|
|
363
|
+
fsx.writeFileSync(file, '{ not json');
|
|
364
|
+
check('an unreadable settings file is OFF rather than a crash',
|
|
365
|
+
settings({}, file).mode === 'off');
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
check('answer mode cannot reach a shell', !toolsFor('answer').includes('Bash'));
|
|
369
|
+
check('act mode can', toolsFor('act').includes('Bash'));
|
|
370
|
+
check('an unknown mode is off, not on', settings({ AGENTSIGNAL_RESPONDER: 'yes' }).mode === 'off');
|
|
371
|
+
check('unset is off', settings({}).mode === 'off');
|
|
372
|
+
|
|
373
|
+
if (failures.length) {
|
|
374
|
+
console.error('\nResponder self-test FAILED -- the brakes cannot be trusted:\n');
|
|
375
|
+
for (const f of failures) console.error(` x ${f}`);
|
|
376
|
+
process.exit(1);
|
|
377
|
+
}
|
|
378
|
+
console.log(`Responder self-test: ${21} checks passed (every brake fails closed).`);
|
|
379
|
+
}
|