@agentsignalnet/claude-plugin 0.2.137 → 0.2.138
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/session-state.mjs +81 -8
- package/scripts/watchers.mjs +87 -6
package/package.json
CHANGED
|
@@ -23,7 +23,7 @@ import { openSync, readSync, closeSync, readdirSync, existsSync, statSync } from
|
|
|
23
23
|
import { homedir } from 'node:os';
|
|
24
24
|
import { join } from 'node:path';
|
|
25
25
|
import { fileURLToPath } from 'node:url';
|
|
26
|
-
import { sessionKey, busyHintAt } from './watchers.mjs';
|
|
26
|
+
import { sessionKey, busyHintAt, ownedHintKey, hintSessionId } from './watchers.mjs';
|
|
27
27
|
|
|
28
28
|
export const QUIET_MS = 2000;
|
|
29
29
|
export const END_GRACE_MS = 15_000;
|
|
@@ -183,13 +183,24 @@ export function findTranscript(sessionId, env = process.env) {
|
|
|
183
183
|
* tail is re-read only when the transcript's size or mtime moved. Any failure
|
|
184
184
|
* is busy, so priority 0 waits for the Stop hook rather than interjecting.
|
|
185
185
|
*/
|
|
186
|
-
export function sessionBusy({ env = process.env, now = Date.now(), cache = {} } = {}) {
|
|
186
|
+
export function sessionBusy({ env = process.env, now = Date.now(), cache = {}, ppid = process.ppid } = {}) {
|
|
187
187
|
try {
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
188
|
+
const own = sessionKey(env);
|
|
189
|
+
let owned = ownedHintKey(env, ppid);
|
|
190
|
+
if (owned && owned !== own) {
|
|
191
|
+
// A hint of another session is followed only if it is newer than
|
|
192
|
+
// anything this env's own session did: a dead claude's hint, found
|
|
193
|
+
// again through a reused pid, never redirects a live session.
|
|
194
|
+
const envPath = findTranscript(env.CLAUDE_CODE_SESSION_ID, env) ?? (own ? findTranscript(own, env) : null);
|
|
195
|
+
const envAt = Math.max(envPath ? statSync(envPath).mtimeMs : -Infinity, own ? (busyHintAt(env, own) ?? -Infinity) : -Infinity);
|
|
196
|
+
if (!((busyHintAt(env, owned) ?? -Infinity) > envAt)) owned = null;
|
|
197
|
+
}
|
|
198
|
+
const key = owned ?? own;
|
|
199
|
+
// Transcripts are named by the session id. A followed hint names its own;
|
|
200
|
+
// otherwise the env's. The key (possibly a HOST_ id) is only the fallback.
|
|
201
|
+
const id = owned ? hintSessionId(env, owned) : env.CLAUDE_CODE_SESSION_ID;
|
|
202
|
+
const path = key ? findTranscript(id, env) ?? findTranscript(key, env) : null;
|
|
203
|
+
const hintAt = key ? busyHintAt(env, key) : null;
|
|
193
204
|
if (!path) return classify([], { now, mtimeMs: null, hintAt });
|
|
194
205
|
const { size, mtimeMs } = statSync(path);
|
|
195
206
|
if (cache.path !== path || cache.size !== size || cache.mtimeMs !== mtimeMs) {
|
|
@@ -383,6 +394,68 @@ async function selfTest() {
|
|
|
383
394
|
const hostEnv = { ...env, CLAUDE_CODE_HOST_SESSION_ID: 'host-other-id' };
|
|
384
395
|
put([P(), A(TXT('answer'), 'end_turn'), SYS('turn_duration')], bigAt - 5000);
|
|
385
396
|
is('r3 qa#4 a differing HOST_ id still reads the session transcript', sessionBusy({ env: hostEnv, now: bigAt }), false, 'ended');
|
|
397
|
+
|
|
398
|
+
ok('the env session id is the key when the host id is unset', sessionKey({ CLAUDE_CODE_SESSION_ID: 'sess-env' }) === 'sess-env' &&
|
|
399
|
+
sessionKey({ CLAUDE_CODE_HOST_SESSION_ID: '', CLAUDE_CODE_SESSION_ID: 'sess-env' }) === 'sess-env');
|
|
400
|
+
|
|
401
|
+
// /clear: the monitor keeps the OLD id; the next prompt's hook names the NEW one.
|
|
402
|
+
const oldT = join(project, 'sess-old.jsonl');
|
|
403
|
+
const newT = join(project, 'sess-new.jsonl');
|
|
404
|
+
const stamp = (path, entries, mtimeMs) => {
|
|
405
|
+
fs.writeFileSync(path, entries.map((e) => `${JSON.stringify(e)}\n`).join(''));
|
|
406
|
+
fs.utimesSync(path, mtimeMs / 1000, mtimeMs / 1000);
|
|
407
|
+
};
|
|
408
|
+
const clearEnv = { ...env, CLAUDE_CODE_SESSION_ID: 'sess-old' };
|
|
409
|
+
spawnSync(process.execPath, [hook, 'start'], { env: { ...hookEnv, CLAUDE_CODE_SESSION_ID: 'sess-new' }, stdio: 'ignore', timeout: 10_000 });
|
|
410
|
+
const newHint = JSON.parse(fs.readFileSync(join(env.AGENTSIGNAL_STATE_DIR, 'busy', 'sess-new.json'), 'utf8'));
|
|
411
|
+
ok('the hook records its owner process', newHint.ownerPid === process.pid, newHint.ownerPid);
|
|
412
|
+
// The new turn's prompt and tool call land after the hint; the old transcript ended a minute before.
|
|
413
|
+
stamp(oldT, ended, newHint.at - 60_000);
|
|
414
|
+
stamp(newT, [P(), TU('a')], newHint.at + 1);
|
|
415
|
+
const later = newHint.at + 5000;
|
|
416
|
+
is('after /clear, the new session the owner hinted decides', sessionBusy({ env: clearEnv, now: later, ppid: process.pid }), true, 'open-tool');
|
|
417
|
+
is('a hint from another owner is not followed', sessionBusy({ env: clearEnv, now: later, ppid: process.pid + 1 }), false, 'ended');
|
|
418
|
+
// r3: an owned hint OLDER than the env session's own transcript (a dead
|
|
419
|
+
// claude's, through a reused pid) is not followed, though it is the newest owned.
|
|
420
|
+
const stalePid = process.pid + 2;
|
|
421
|
+
fs.writeFileSync(join(env.AGENTSIGNAL_STATE_DIR, 'busy', 'sess-stale.json'), JSON.stringify({ at: newHint.at - 120_000, ownerPid: stalePid, sessionId: 'sess-new' }));
|
|
422
|
+
is('r3 a stale owned hint does not redirect the session', sessionBusy({ env: clearEnv, now: later, ppid: stalePid }), false, 'ended');
|
|
423
|
+
// r3: a hint file whose name no sessionKey could produce is never followed.
|
|
424
|
+
fs.writeFileSync(join(env.AGENTSIGNAL_STATE_DIR, 'busy', 'a.b.json'), JSON.stringify({ at: newHint.at + 90_000, ownerPid: process.pid + 3 }));
|
|
425
|
+
ok('r3 a hint named outside [A-Za-z0-9_-] is ignored', ownedHintKey(env, process.pid + 3) === null, ownedHintKey(env, process.pid + 3));
|
|
426
|
+
// r3: the owner walk keeps the last pid it resolved, and stays in budget.
|
|
427
|
+
const { ownerPidWalk } = await import('./watchers.mjs');
|
|
428
|
+
const rows = { 100: '50 bash' };
|
|
429
|
+
ok('r3 a ps failure after a shell keeps the pid resolved so far', ownerPidWalk(100, { run: (pid) => { if (!rows[pid]) throw new Error('ps failed'); return rows[pid]; } }) === 50);
|
|
430
|
+
let fake = 0;
|
|
431
|
+
let calls = 0;
|
|
432
|
+
ownerPidWalk(100, { budgetMs: 2000, clock: () => fake, run: (pid, timeout) => { calls += 1; fake += Math.min(700, timeout); return `${pid - 1} sh`; } });
|
|
433
|
+
ok('r3 the owner walk stops at its total time budget', calls === 3, calls);
|
|
434
|
+
|
|
435
|
+
// Two hints of ONE owner (the env id's and the new one's): the newer decides,
|
|
436
|
+
// whichever it is, so neither directory order nor "first owned" can pass.
|
|
437
|
+
const hintAt = (key, at, ownerPid = process.pid) =>
|
|
438
|
+
fs.writeFileSync(join(env.AGENTSIGNAL_STATE_DIR, 'busy', `${key}.json`), JSON.stringify({ at, ownerPid }));
|
|
439
|
+
hintAt('sess-old', newHint.at - 30_000);
|
|
440
|
+
is('two owned hints: the newer one (sess-new) decides', sessionBusy({ env: clearEnv, now: later, ppid: process.pid }), true, 'open-tool');
|
|
441
|
+
ok('... ownedHintKey names sess-new', ownedHintKey(env, process.pid) === 'sess-new', ownedHintKey(env, process.pid));
|
|
442
|
+
hintAt('sess-old', newHint.at + 30_000);
|
|
443
|
+
is('two owned hints: once sess-old is newer, it decides', sessionBusy({ env: clearEnv, now: newHint.at + 30_000 + HINT_MAX_MS + 1, ppid: process.pid }), false, 'ended');
|
|
444
|
+
ok('... ownedHintKey names sess-old', ownedHintKey(env, process.pid) === 'sess-old', ownedHintKey(env, process.pid));
|
|
445
|
+
// A newer hint of ANOTHER owner never wins over this owner's own.
|
|
446
|
+
hintAt('sess-foreign', newHint.at + 60_000, process.pid + 1);
|
|
447
|
+
ok('a newer hint from another owner loses to the owned one', ownedHintKey(env, process.pid) === 'sess-old', ownedHintKey(env, process.pid));
|
|
448
|
+
ok('... and is that owner\'s own', ownedHintKey(env, process.pid + 1) === 'sess-foreign', ownedHintKey(env, process.pid + 1));
|
|
449
|
+
|
|
450
|
+
// r3: a hint keyed by a HOST_ id leads to the transcript of the session id
|
|
451
|
+
// it recorded, not to a file named after the HOST_ id.
|
|
452
|
+
spawnSync(process.execPath, [hook, 'start'], { env: { ...hookEnv, CLAUDE_CODE_HOST_SESSION_ID: 'host-latest', CLAUDE_CODE_SESSION_ID: 'sess-new' }, stdio: 'ignore', timeout: 10_000 });
|
|
453
|
+
const hostHint = JSON.parse(fs.readFileSync(join(env.AGENTSIGNAL_STATE_DIR, 'busy', 'host-latest.json'), 'utf8'));
|
|
454
|
+
// Newer than everything stamped above (some of it is in the future).
|
|
455
|
+
hostHint.at = newHint.at + 120_000;
|
|
456
|
+
fs.writeFileSync(join(env.AGENTSIGNAL_STATE_DIR, 'busy', 'host-latest.json'), JSON.stringify(hostHint));
|
|
457
|
+
ok('r3 the hint records the session id beside a HOST_ key', hostHint.sessionId === 'sess-new' && ownedHintKey(env, process.pid) === 'host-latest', hostHint);
|
|
458
|
+
is('r3 ... and the followed hint reads that session transcript', sessionBusy({ env: clearEnv, now: hostHint.at + HINT_MAX_MS + 1, ppid: process.pid }), true, 'open-tool');
|
|
386
459
|
} finally {
|
|
387
460
|
fs.rmSync(scratch, { recursive: true, force: true });
|
|
388
461
|
}
|
|
@@ -401,7 +474,7 @@ async function selfTest() {
|
|
|
401
474
|
'node:fs': ['openSync', 'readSync', 'closeSync', 'readdirSync', 'existsSync', 'statSync'],
|
|
402
475
|
'node:os': ['homedir'], 'node:path': ['join'], 'node:url': ['fileURLToPath'],
|
|
403
476
|
// watchers.mjs can write (writeSmall); only these two readers may come in.
|
|
404
|
-
'./watchers.mjs': ['sessionKey', 'busyHintAt'],
|
|
477
|
+
'./watchers.mjs': ['sessionKey', 'busyHintAt', 'ownedHintKey', 'hintSessionId'],
|
|
405
478
|
};
|
|
406
479
|
const imports = [...body.matchAll(/import\s*\{([^}]*)\}\s*from\s*'([^']+)'/g)].map(([, names, from]) => [from, names.split(',').map((n) => n.trim()).filter(Boolean)]);
|
|
407
480
|
const stray = imports.filter(([from, names]) => !ALLOWED[from] || names.some((n) => !ALLOWED[from].includes(n)));
|
package/scripts/watchers.mjs
CHANGED
|
@@ -12,10 +12,10 @@
|
|
|
12
12
|
* So the registry reader is one function, imported by both, and disagreeing
|
|
13
13
|
* takes an edit rather than an omission.
|
|
14
14
|
*/
|
|
15
|
-
import { readFileSync, writeFileSync, readdirSync, unlinkSync, mkdirSync, renameSync, statSync } from 'node:fs';
|
|
16
|
-
import { spawn } from 'node:child_process';
|
|
15
|
+
import { readFileSync, writeFileSync, readdirSync, unlinkSync, mkdirSync, renameSync, statSync, existsSync } from 'node:fs';
|
|
16
|
+
import { spawn, execFileSync } from 'node:child_process';
|
|
17
17
|
import { homedir } from 'node:os';
|
|
18
|
-
import { dirname, join } from 'node:path';
|
|
18
|
+
import { basename, dirname, join } from 'node:path';
|
|
19
19
|
import { identities as storedIdentities } from './state.mjs';
|
|
20
20
|
|
|
21
21
|
/**
|
|
@@ -210,6 +210,48 @@ export function sessionKey(env = process.env) {
|
|
|
210
210
|
return (env.CLAUDE_CODE_HOST_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || '').replace(/[^A-Za-z0-9_-]/g, '_');
|
|
211
211
|
}
|
|
212
212
|
|
|
213
|
+
/**
|
|
214
|
+
* THE CLAUDE PROCESS THAT RAN THIS HOOK: the parent, skipping the shells that
|
|
215
|
+
* wrap a hook command and exit with it. Without `ps`, the direct parent.
|
|
216
|
+
*/
|
|
217
|
+
// An absolute ps, never one looked up on an inherited PATH; none means no walk.
|
|
218
|
+
const PS = ['/bin/ps', '/usr/bin/ps'].find((path) => existsSync(path)) ?? null;
|
|
219
|
+
function psRow(pid, timeout) {
|
|
220
|
+
if (!PS) throw new Error('no ps');
|
|
221
|
+
return execFileSync(PS, ['-o', 'ppid=', '-o', 'comm=', '-p', String(pid)], {
|
|
222
|
+
encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout,
|
|
223
|
+
}).trim();
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The whole walk fits well inside the 10 s UserPromptSubmit budget. */
|
|
227
|
+
export const OWNER_WALK_MS = 2000;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Up from `start` past wrapper shells. Bounded in total time, not per call,
|
|
231
|
+
* and a failure keeps the last pid resolved rather than restarting at `start`.
|
|
232
|
+
*/
|
|
233
|
+
export function ownerPidWalk(start = process.ppid, { run = psRow, budgetMs = OWNER_WALK_MS, clock = Date.now } = {}) {
|
|
234
|
+
let pid = start;
|
|
235
|
+
const deadline = clock() + budgetMs;
|
|
236
|
+
try {
|
|
237
|
+
for (let depth = 0; pid > 1 && depth < 16; depth += 1) {
|
|
238
|
+
const left = deadline - clock();
|
|
239
|
+
if (left <= 0) return pid;
|
|
240
|
+
const match = /^(\d+)\s+(.+)$/.exec(run(pid, Math.min(1000, left)));
|
|
241
|
+
if (!match) return pid;
|
|
242
|
+
if (!/^(?:sh|bash|dash|zsh|ksh|fish)$/.test(basename(match[2]).replace(/^-/, ''))) return pid;
|
|
243
|
+
pid = Number(match[1]);
|
|
244
|
+
}
|
|
245
|
+
} catch {
|
|
246
|
+
return pid;
|
|
247
|
+
}
|
|
248
|
+
return pid;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function sessionOwnerPid() {
|
|
252
|
+
return ownerPidWalk(process.ppid);
|
|
253
|
+
}
|
|
254
|
+
|
|
213
255
|
/**
|
|
214
256
|
* A BUSY HINT, written at UserPromptSubmit. It covers only the moment between
|
|
215
257
|
* Enter and the prompt line reaching the transcript: session-state.mjs counts
|
|
@@ -263,15 +305,27 @@ export function markBusy(env = process.env, now = Date.now()) {
|
|
|
263
305
|
if (!key) return false;
|
|
264
306
|
try {
|
|
265
307
|
pruneHints(env, now);
|
|
266
|
-
|
|
308
|
+
// The session id too: a host may key hints by a HOST_ id, and transcripts
|
|
309
|
+
// are named by the session id, which a followed hint must lead to.
|
|
310
|
+
writeSmall(hintFile(env, key), { at: now, ownerPid: sessionOwnerPid(), sessionId: env.CLAUDE_CODE_SESSION_ID || null });
|
|
267
311
|
return true;
|
|
268
312
|
} catch {
|
|
269
313
|
return false;
|
|
270
314
|
}
|
|
271
315
|
}
|
|
272
316
|
|
|
273
|
-
|
|
274
|
-
|
|
317
|
+
/** The session id the hint under `key` was written for, or null. */
|
|
318
|
+
export function hintSessionId(env = process.env, key = sessionKey(env)) {
|
|
319
|
+
if (!key) return null;
|
|
320
|
+
try {
|
|
321
|
+
const id = JSON.parse(readFileSync(hintFile(env, key), 'utf8'))?.sessionId;
|
|
322
|
+
return typeof id === 'string' && id !== '' ? id : null;
|
|
323
|
+
} catch {
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export function busyHintAt(env = process.env, key = sessionKey(env)) {
|
|
275
329
|
if (!key) return null;
|
|
276
330
|
try {
|
|
277
331
|
const at = JSON.parse(readFileSync(hintFile(env, key), 'utf8'))?.at;
|
|
@@ -280,3 +334,30 @@ export function busyHintAt(env = process.env) {
|
|
|
280
334
|
return null;
|
|
281
335
|
}
|
|
282
336
|
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* THE SESSION A PROCESS OF `ownerPid` IS IN NOW. /clear keeps the monitor
|
|
340
|
+
* (same pid, the OLD session id in its environment) while the next turn
|
|
341
|
+
* writes a NEW transcript; its UserPromptSubmit hint names the new session.
|
|
342
|
+
* So the newest hint left by this monitor's own parent wins over the env id.
|
|
343
|
+
*/
|
|
344
|
+
export function ownedHintKey(env = process.env, ownerPid = process.ppid) {
|
|
345
|
+
let best = null;
|
|
346
|
+
try {
|
|
347
|
+
for (const name of readdirSync(join(lockDir(env), 'busy'))) {
|
|
348
|
+
// Only names a sessionKey could have produced; the key goes on to name files.
|
|
349
|
+
if (!/^[A-Za-z0-9_-]+\.json$/.test(name)) continue;
|
|
350
|
+
try {
|
|
351
|
+
const hint = JSON.parse(readFileSync(join(lockDir(env), 'busy', name), 'utf8'));
|
|
352
|
+
if (hint?.ownerPid === ownerPid && Number.isFinite(hint.at) && (!best || hint.at > best.at)) {
|
|
353
|
+
best = { key: name.slice(0, -'.json'.length), at: hint.at };
|
|
354
|
+
}
|
|
355
|
+
} catch {
|
|
356
|
+
/* torn or foreign: skip */
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
} catch {
|
|
360
|
+
/* no hints yet */
|
|
361
|
+
}
|
|
362
|
+
return best?.key ?? null;
|
|
363
|
+
}
|