@agentsignalnet/claude-plugin 0.2.136 → 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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agentsignal",
3
3
  "displayName": "AgentSignal",
4
- "version": "0.2.136",
4
+ "version": "0.2.138",
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.136",
3
+ "version": "0.2.138",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -19,10 +19,11 @@
19
19
  * Above the self-test it never writes, logs, prints or sends any of it, and
20
20
  * the self-test checks that structurally.
21
21
  */
22
- import { openSync, readSync, closeSync, readdirSync, existsSync } from 'node:fs';
22
+ import { openSync, readSync, closeSync, readdirSync, existsSync, statSync } from 'node:fs';
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, ownedHintKey, hintSessionId } from './watchers.mjs';
26
27
 
27
28
  export const QUIET_MS = 2000;
28
29
  export const END_GRACE_MS = 15_000;
@@ -177,6 +178,41 @@ export function findTranscript(sessionId, env = process.env) {
177
178
  return null;
178
179
  }
179
180
 
181
+ /**
182
+ * THIS SESSION, NOW. `cache` is the caller's object, kept across calls: the
183
+ * tail is re-read only when the transcript's size or mtime moved. Any failure
184
+ * is busy, so priority 0 waits for the Stop hook rather than interjecting.
185
+ */
186
+ export function sessionBusy({ env = process.env, now = Date.now(), cache = {}, ppid = process.ppid } = {}) {
187
+ try {
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;
204
+ if (!path) return classify([], { now, mtimeMs: null, hintAt });
205
+ const { size, mtimeMs } = statSync(path);
206
+ if (cache.path !== path || cache.size !== size || cache.mtimeMs !== mtimeMs) {
207
+ // The whole {entries, complete} snapshot, so a hit keeps a miss's verdict.
208
+ Object.assign(cache, { path, size, mtimeMs, tail: readTail(path, size) });
209
+ }
210
+ return classify(cache.tail, { now, mtimeMs, hintAt });
211
+ } catch {
212
+ return verdict(true, 'unknown');
213
+ }
214
+ }
215
+
180
216
  // ----- SELF-TEST: everything below this line is test code -----
181
217
  async function selfTest() {
182
218
  const fs = await import('node:fs');
@@ -299,6 +335,132 @@ async function selfTest() {
299
335
  fs.rmSync(dir, { recursive: true, force: true });
300
336
  }
301
337
 
338
+ // --- sessionBusy, end to end: a scratch config and state dir, real hook process
339
+ {
340
+ const { spawnSync } = await import('node:child_process');
341
+ const { markBusy } = await import('./watchers.mjs');
342
+ const scratch = fs.mkdtempSync(join(tmpdir(), 'agentsignal-session-selftest-'));
343
+ const config = join(scratch, 'config');
344
+ const project = join(config, 'projects', '-fake-project');
345
+ fs.mkdirSync(project, { recursive: true });
346
+ const env = { CLAUDE_CONFIG_DIR: config, AGENTSIGNAL_STATE_DIR: join(scratch, 'state'), CLAUDE_CODE_SESSION_ID: 's1' };
347
+ const transcript = join(project, 's1.jsonl');
348
+ const put = (entries, mtimeMs, append = false) => {
349
+ fs[append ? 'appendFileSync' : 'writeFileSync'](transcript, entries.map((e) => `${JSON.stringify(e)}\n`).join(''));
350
+ fs.utimesSync(transcript, mtimeMs / 1000, mtimeMs / 1000);
351
+ };
352
+ try {
353
+ const hook = join(fileURLToPath(new URL('.', import.meta.url)), 'task-hook.mjs');
354
+ const hookEnv = { ...process.env, ...env, AGENTSIGNAL_TASK: 'off' };
355
+ delete hookEnv.CLAUDE_CODE_HOST_SESSION_ID;
356
+ spawnSync(process.execPath, [hook, 'start'], { env: hookEnv, stdio: 'ignore', timeout: 10_000 });
357
+ const hinted = busyHintAt(env);
358
+ is('T14 the start hook with no transcript is busy hint', sessionBusy({ env, now: Date.now() }), true, 'hint');
359
+ is('T14 ... and unknown once the hint is 30s old', sessionBusy({ env, now: (hinted ?? 0) + HINT_MAX_MS + 1 }), true, 'unknown');
360
+
361
+ const now = Date.now();
362
+ put(t1, now - 5000);
363
+ markBusy(env, now - 10_000);
364
+ is('T15 an interrupted transcript with an older hint is idle', sessionBusy({ env, now }), false, 'interrupted');
365
+
366
+ const cache = {};
367
+ put([P(), A(TXT('answer'), 'end_turn')], now - 9000);
368
+ is('T16 end_turn alone is busy ending', sessionBusy({ env, now, cache }), true, 'ending');
369
+ put([SYS('turn_duration')], now - 5000, true);
370
+ is('T16 an appended turn_duration is re-read, not served from the cache', sessionBusy({ env, now, cache }), false, 'ended');
371
+
372
+ // A turn larger than TAIL_MAX whose open tool_use fell out of the window.
373
+ const bigAt = Date.now() + HINT_MAX_MS + 1;
374
+ const pad = { type: 'progress', pad: 'x'.repeat(1024 * 1024) };
375
+ const big = {};
376
+ put([P(), TU('A', 'B'), pad, pad, pad, pad, pad, TR('A')], bigAt - 120 * MIN);
377
+ is('T18 a >4 MiB incomplete turn on a cache miss is busy unknown', sessionBusy({ env, now: bigAt, cache: big }), true, 'unknown');
378
+ const missed = big.tail;
379
+ is('T18 ... and on the cache hit', sessionBusy({ env, now: bigAt, cache: big }), true, 'unknown');
380
+ ok('T18 ... which was a hit', missed && big.tail === missed);
381
+ put([P('next'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')], bigAt - 5000, true);
382
+ is('T18 a real prompt and end appended: idle ended', sessionBusy({ env, now: bigAt, cache: big }), false, 'ended');
383
+
384
+ const quiet = fs.mkdtempSync(join(tmpdir(), 'agentsignal-session-selftest-'));
385
+ try {
386
+ is('T17 no session id is busy unknown', sessionBusy({ env: { CLAUDE_CONFIG_DIR: config, AGENTSIGNAL_STATE_DIR: quiet }, now }), true, 'unknown');
387
+ ok('T17 ... and nothing is written', fs.readdirSync(quiet).length === 0);
388
+ } finally {
389
+ fs.rmSync(quiet, { recursive: true, force: true });
390
+ }
391
+
392
+ // r3 qa#4: a host that sets a HOST_ id different from the transcript's
393
+ // session id still finds the transcript by the session id.
394
+ const hostEnv = { ...env, CLAUDE_CODE_HOST_SESSION_ID: 'host-other-id' };
395
+ put([P(), A(TXT('answer'), 'end_turn'), SYS('turn_duration')], bigAt - 5000);
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');
459
+ } finally {
460
+ fs.rmSync(scratch, { recursive: true, force: true });
461
+ }
462
+ }
463
+
302
464
  const source = fs.readFileSync(fileURLToPath(import.meta.url), 'utf8');
303
465
  // Everything before the self-test function, comments stripped, so neither a
304
466
  // marker string nor a comment can shrink or pad what is scanned.
@@ -309,13 +471,15 @@ async function selfTest() {
309
471
  // r3 security#2: the module may import only these names, so a writing or
310
472
  // sending helper cannot arrive through an import either.
311
473
  const ALLOWED = {
312
- 'node:fs': ['openSync', 'readSync', 'closeSync', 'readdirSync', 'existsSync'],
474
+ 'node:fs': ['openSync', 'readSync', 'closeSync', 'readdirSync', 'existsSync', 'statSync'],
313
475
  'node:os': ['homedir'], 'node:path': ['join'], 'node:url': ['fileURLToPath'],
476
+ // watchers.mjs can write (writeSmall); only these two readers may come in.
477
+ './watchers.mjs': ['sessionKey', 'busyHintAt', 'ownedHintKey', 'hintSessionId'],
314
478
  };
315
479
  const imports = [...body.matchAll(/import\s*\{([^}]*)\}\s*from\s*'([^']+)'/g)].map(([, names, from]) => [from, names.split(',').map((n) => n.trim()).filter(Boolean)]);
316
480
  const stray = imports.filter(([from, names]) => !ALLOWED[from] || names.some((n) => !ALLOWED[from].includes(n)));
317
481
  const bare = (body.match(/^\s*import\b/gm) ?? []).length;
318
- ok('r3 security#2 T13 imports only the allowed names', imports.length >= 4 && stray.length === 0 && bare === imports.length, { stray, bare });
482
+ ok('r3 security#2 T13 imports only the allowed names', imports.length >= 5 && stray.length === 0 && bare === imports.length, { stray, bare });
319
483
  ok('r3 security#4 no AGENTSIGNAL_ setting is read from the environment', !/AGENTSIGNAL_/.test(body));
320
484
 
321
485
  const failed = checks.filter(([, passed]) => !passed);
@@ -38,8 +38,9 @@
38
38
  import { execFileSync } from 'node:child_process';
39
39
  import { readFileSync } from 'node:fs';
40
40
  import { basename } from 'node:path';
41
+ import { fileURLToPath } from 'node:url';
41
42
  import { identities, repoRoot } from './state.mjs';
42
- import { apiBase } from './watchers.mjs';
43
+ import { apiBase, markBusy, busyHintAt } from './watchers.mjs';
43
44
 
44
45
  const MAX = 120;
45
46
 
@@ -126,6 +127,9 @@ async function send(identity, base, task) {
126
127
 
127
128
  async function main() {
128
129
  const mode = process.argv[2] ?? 'start';
130
+ // Local, and before the reporting switch: the inbox monitor reads it to hold
131
+ // a priority-0 message while a turn starts. It says nothing to the network.
132
+ if (mode === 'start') markBusy();
129
133
  if (reportingDisabled()) return;
130
134
 
131
135
  const base = apiBase();
@@ -181,6 +185,43 @@ if (process.argv.includes('--self-test')) {
181
185
  ok('unset is on', reportingDisabled({}), false);
182
186
  ok('any other value is on', reportingDisabled({ AGENTSIGNAL_TASK: 'yes' }), false);
183
187
 
188
+ // UserPromptSubmit leaves a busy hint even with reporting switched off.
189
+ {
190
+ const { mkdtempSync, rmSync } = await import('node:fs');
191
+ const { tmpdir } = await import('node:os');
192
+ const { join } = await import('node:path');
193
+ const { spawnSync } = await import('node:child_process');
194
+ const { writeFileSync, symlinkSync, utimesSync, mkdirSync, existsSync } = await import('node:fs');
195
+ const dir = mkdtempSync(join(tmpdir(), 'agentsignal-task-selftest-'));
196
+ try {
197
+ const env = { ...process.env, AGENTSIGNAL_STATE_DIR: dir, AGENTSIGNAL_TASK: 'off', CLAUDE_CODE_SESSION_ID: 'sess-fake-task' };
198
+ delete env.CLAUDE_CODE_HOST_SESSION_ID;
199
+ const before = Date.now();
200
+ // fileURLToPath, not URL.pathname: a path with a space or % stays a path.
201
+ spawnSync(process.execPath, [fileURLToPath(import.meta.url), 'start'], { env, stdio: 'ignore', timeout: 10_000 });
202
+ const at = busyHintAt(env);
203
+ ok('start writes the busy hint with reporting off', at !== null && at >= before, true);
204
+ ok('r3 the hook names its own file by fileURLToPath', /import\.meta\.url\)\.pathname/.test(source), false);
205
+
206
+ // r3 security#3: a symlink planted at the temp name is replaced, not followed.
207
+ const busyDir = join(dir, 'busy');
208
+ const victim = join(dir, 'victim.txt');
209
+ writeFileSync(victim, 'keep me');
210
+ symlinkSync(victim, join(busyDir, `sess-fake-task.json.${process.pid}.tmp`));
211
+ ok('r3 markBusy writes the hint', markBusy(env, before + 1) === true && busyHintAt(env) === before + 1, true);
212
+ ok('r3 ... without writing through a planted temp symlink', readFileSync(victim, 'utf8'), 'keep me');
213
+ // r3 logic#6: a day-old hint of another session is pruned by the next mark.
214
+ mkdirSync(busyDir, { recursive: true });
215
+ const stale = join(busyDir, 'sess-gone.json');
216
+ writeFileSync(stale, JSON.stringify({ at: 1 }));
217
+ utimesSync(stale, 1, 1);
218
+ markBusy(env, Date.now());
219
+ ok('r3 a day-old hint is pruned', existsSync(stale), false);
220
+ } finally {
221
+ rmSync(dir, { recursive: true, force: true });
222
+ }
223
+ }
224
+
184
225
  let failed = 0;
185
226
  for (const [what, passed, got, want] of checks) {
186
227
  if (!passed) {
@@ -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 } 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
  /**
@@ -201,3 +201,163 @@ export function ensureWatcher({
201
201
 
202
202
  return { started: true, reason: 'nothing was watching' };
203
203
  }
204
+
205
+ /**
206
+ * THE SESSION A HOOK OR MONITOR BELONGS TO, as a safe file name, or ''.
207
+ * The HOST_ form is read first for hosts that set it.
208
+ */
209
+ export function sessionKey(env = process.env) {
210
+ return (env.CLAUDE_CODE_HOST_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || '').replace(/[^A-Za-z0-9_-]/g, '_');
211
+ }
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
+
255
+ /**
256
+ * A BUSY HINT, written at UserPromptSubmit. It covers only the moment between
257
+ * Enter and the prompt line reaching the transcript: session-state.mjs counts
258
+ * it as busy while it is newer than the transcript and under 30 s old, and
259
+ * never as idle. So it holds a time and nothing else -- no owner, no clear.
260
+ */
261
+ const hintFile = (env, key) => join(lockDir(env), 'busy', `${key}.json`);
262
+
263
+ function writeSmall(path, value) {
264
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
265
+ const temporary = `${path}.${process.pid}.tmp`;
266
+ // Whatever sits at the temp name (a leftover, or a planted symlink) is
267
+ // removed, and the new file is created exclusively, so no link is followed.
268
+ try {
269
+ unlinkSync(temporary);
270
+ } catch {
271
+ /* nothing there */
272
+ }
273
+ writeFileSync(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
274
+ try {
275
+ renameSync(temporary, path);
276
+ } catch (error) {
277
+ try {
278
+ unlinkSync(temporary);
279
+ } catch {
280
+ /* gone already */
281
+ }
282
+ throw error;
283
+ }
284
+ }
285
+
286
+ /** Busy hints a day old matter to nobody; one per session would otherwise pile up. */
287
+ export const HINT_PRUNE_MS = 24 * 3_600_000;
288
+ function pruneHints(env, now) {
289
+ const dir = join(lockDir(env), 'busy');
290
+ try {
291
+ for (const name of readdirSync(dir)) {
292
+ try {
293
+ if (now - statSync(join(dir, name)).mtimeMs > HINT_PRUNE_MS) unlinkSync(join(dir, name));
294
+ } catch {
295
+ /* gone already */
296
+ }
297
+ }
298
+ } catch {
299
+ /* no hints yet */
300
+ }
301
+ }
302
+
303
+ export function markBusy(env = process.env, now = Date.now()) {
304
+ const key = sessionKey(env);
305
+ if (!key) return false;
306
+ try {
307
+ pruneHints(env, now);
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 });
311
+ return true;
312
+ } catch {
313
+ return false;
314
+ }
315
+ }
316
+
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)) {
329
+ if (!key) return null;
330
+ try {
331
+ const at = JSON.parse(readFileSync(hintFile(env, key), 'utf8'))?.at;
332
+ return Number.isFinite(at) ? at : null;
333
+ } catch {
334
+ return null;
335
+ }
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
+ }