@agentsignalnet/claude-plugin 0.2.136 → 0.2.137

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.137",
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.137",
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 } from './watchers.mjs';
26
27
 
27
28
  export const QUIET_MS = 2000;
28
29
  export const END_GRACE_MS = 15_000;
@@ -177,6 +178,30 @@ 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 = {} } = {}) {
187
+ try {
188
+ const key = sessionKey(env);
189
+ // Transcripts are named by the session id; the HOST_ id a host may set is
190
+ // the hint key only, so it is the fallback here, never the first choice.
191
+ const path = key ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env) ?? findTranscript(key, env) : null;
192
+ const hintAt = key ? busyHintAt(env) : null;
193
+ if (!path) return classify([], { now, mtimeMs: null, hintAt });
194
+ const { size, mtimeMs } = statSync(path);
195
+ if (cache.path !== path || cache.size !== size || cache.mtimeMs !== mtimeMs) {
196
+ // The whole {entries, complete} snapshot, so a hit keeps a miss's verdict.
197
+ Object.assign(cache, { path, size, mtimeMs, tail: readTail(path, size) });
198
+ }
199
+ return classify(cache.tail, { now, mtimeMs, hintAt });
200
+ } catch {
201
+ return verdict(true, 'unknown');
202
+ }
203
+ }
204
+
180
205
  // ----- SELF-TEST: everything below this line is test code -----
181
206
  async function selfTest() {
182
207
  const fs = await import('node:fs');
@@ -299,6 +324,70 @@ async function selfTest() {
299
324
  fs.rmSync(dir, { recursive: true, force: true });
300
325
  }
301
326
 
327
+ // --- sessionBusy, end to end: a scratch config and state dir, real hook process
328
+ {
329
+ const { spawnSync } = await import('node:child_process');
330
+ const { markBusy } = await import('./watchers.mjs');
331
+ const scratch = fs.mkdtempSync(join(tmpdir(), 'agentsignal-session-selftest-'));
332
+ const config = join(scratch, 'config');
333
+ const project = join(config, 'projects', '-fake-project');
334
+ fs.mkdirSync(project, { recursive: true });
335
+ const env = { CLAUDE_CONFIG_DIR: config, AGENTSIGNAL_STATE_DIR: join(scratch, 'state'), CLAUDE_CODE_SESSION_ID: 's1' };
336
+ const transcript = join(project, 's1.jsonl');
337
+ const put = (entries, mtimeMs, append = false) => {
338
+ fs[append ? 'appendFileSync' : 'writeFileSync'](transcript, entries.map((e) => `${JSON.stringify(e)}\n`).join(''));
339
+ fs.utimesSync(transcript, mtimeMs / 1000, mtimeMs / 1000);
340
+ };
341
+ try {
342
+ const hook = join(fileURLToPath(new URL('.', import.meta.url)), 'task-hook.mjs');
343
+ const hookEnv = { ...process.env, ...env, AGENTSIGNAL_TASK: 'off' };
344
+ delete hookEnv.CLAUDE_CODE_HOST_SESSION_ID;
345
+ spawnSync(process.execPath, [hook, 'start'], { env: hookEnv, stdio: 'ignore', timeout: 10_000 });
346
+ const hinted = busyHintAt(env);
347
+ is('T14 the start hook with no transcript is busy hint', sessionBusy({ env, now: Date.now() }), true, 'hint');
348
+ is('T14 ... and unknown once the hint is 30s old', sessionBusy({ env, now: (hinted ?? 0) + HINT_MAX_MS + 1 }), true, 'unknown');
349
+
350
+ const now = Date.now();
351
+ put(t1, now - 5000);
352
+ markBusy(env, now - 10_000);
353
+ is('T15 an interrupted transcript with an older hint is idle', sessionBusy({ env, now }), false, 'interrupted');
354
+
355
+ const cache = {};
356
+ put([P(), A(TXT('answer'), 'end_turn')], now - 9000);
357
+ is('T16 end_turn alone is busy ending', sessionBusy({ env, now, cache }), true, 'ending');
358
+ put([SYS('turn_duration')], now - 5000, true);
359
+ is('T16 an appended turn_duration is re-read, not served from the cache', sessionBusy({ env, now, cache }), false, 'ended');
360
+
361
+ // A turn larger than TAIL_MAX whose open tool_use fell out of the window.
362
+ const bigAt = Date.now() + HINT_MAX_MS + 1;
363
+ const pad = { type: 'progress', pad: 'x'.repeat(1024 * 1024) };
364
+ const big = {};
365
+ put([P(), TU('A', 'B'), pad, pad, pad, pad, pad, TR('A')], bigAt - 120 * MIN);
366
+ is('T18 a >4 MiB incomplete turn on a cache miss is busy unknown', sessionBusy({ env, now: bigAt, cache: big }), true, 'unknown');
367
+ const missed = big.tail;
368
+ is('T18 ... and on the cache hit', sessionBusy({ env, now: bigAt, cache: big }), true, 'unknown');
369
+ ok('T18 ... which was a hit', missed && big.tail === missed);
370
+ put([P('next'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')], bigAt - 5000, true);
371
+ is('T18 a real prompt and end appended: idle ended', sessionBusy({ env, now: bigAt, cache: big }), false, 'ended');
372
+
373
+ const quiet = fs.mkdtempSync(join(tmpdir(), 'agentsignal-session-selftest-'));
374
+ try {
375
+ is('T17 no session id is busy unknown', sessionBusy({ env: { CLAUDE_CONFIG_DIR: config, AGENTSIGNAL_STATE_DIR: quiet }, now }), true, 'unknown');
376
+ ok('T17 ... and nothing is written', fs.readdirSync(quiet).length === 0);
377
+ } finally {
378
+ fs.rmSync(quiet, { recursive: true, force: true });
379
+ }
380
+
381
+ // r3 qa#4: a host that sets a HOST_ id different from the transcript's
382
+ // session id still finds the transcript by the session id.
383
+ const hostEnv = { ...env, CLAUDE_CODE_HOST_SESSION_ID: 'host-other-id' };
384
+ put([P(), A(TXT('answer'), 'end_turn'), SYS('turn_duration')], bigAt - 5000);
385
+ is('r3 qa#4 a differing HOST_ id still reads the session transcript', sessionBusy({ env: hostEnv, now: bigAt }), false, 'ended');
386
+ } finally {
387
+ fs.rmSync(scratch, { recursive: true, force: true });
388
+ }
389
+ }
390
+
302
391
  const source = fs.readFileSync(fileURLToPath(import.meta.url), 'utf8');
303
392
  // Everything before the self-test function, comments stripped, so neither a
304
393
  // marker string nor a comment can shrink or pad what is scanned.
@@ -309,13 +398,15 @@ async function selfTest() {
309
398
  // r3 security#2: the module may import only these names, so a writing or
310
399
  // sending helper cannot arrive through an import either.
311
400
  const ALLOWED = {
312
- 'node:fs': ['openSync', 'readSync', 'closeSync', 'readdirSync', 'existsSync'],
401
+ 'node:fs': ['openSync', 'readSync', 'closeSync', 'readdirSync', 'existsSync', 'statSync'],
313
402
  'node:os': ['homedir'], 'node:path': ['join'], 'node:url': ['fileURLToPath'],
403
+ // watchers.mjs can write (writeSmall); only these two readers may come in.
404
+ './watchers.mjs': ['sessionKey', 'busyHintAt'],
314
405
  };
315
406
  const imports = [...body.matchAll(/import\s*\{([^}]*)\}\s*from\s*'([^']+)'/g)].map(([, names, from]) => [from, names.split(',').map((n) => n.trim()).filter(Boolean)]);
316
407
  const stray = imports.filter(([from, names]) => !ALLOWED[from] || names.some((n) => !ALLOWED[from].includes(n)));
317
408
  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 });
409
+ ok('r3 security#2 T13 imports only the allowed names', imports.length >= 5 && stray.length === 0 && bare === imports.length, { stray, bare });
319
410
  ok('r3 security#4 no AGENTSIGNAL_ setting is read from the environment', !/AGENTSIGNAL_/.test(body));
320
411
 
321
412
  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,7 +12,7 @@
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';
15
+ import { readFileSync, writeFileSync, readdirSync, unlinkSync, mkdirSync, renameSync, statSync } from 'node:fs';
16
16
  import { spawn } from 'node:child_process';
17
17
  import { homedir } from 'node:os';
18
18
  import { dirname, join } from 'node:path';
@@ -201,3 +201,82 @@ 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
+ * A BUSY HINT, written at UserPromptSubmit. It covers only the moment between
215
+ * Enter and the prompt line reaching the transcript: session-state.mjs counts
216
+ * it as busy while it is newer than the transcript and under 30 s old, and
217
+ * never as idle. So it holds a time and nothing else -- no owner, no clear.
218
+ */
219
+ const hintFile = (env, key) => join(lockDir(env), 'busy', `${key}.json`);
220
+
221
+ function writeSmall(path, value) {
222
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
223
+ const temporary = `${path}.${process.pid}.tmp`;
224
+ // Whatever sits at the temp name (a leftover, or a planted symlink) is
225
+ // removed, and the new file is created exclusively, so no link is followed.
226
+ try {
227
+ unlinkSync(temporary);
228
+ } catch {
229
+ /* nothing there */
230
+ }
231
+ writeFileSync(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
232
+ try {
233
+ renameSync(temporary, path);
234
+ } catch (error) {
235
+ try {
236
+ unlinkSync(temporary);
237
+ } catch {
238
+ /* gone already */
239
+ }
240
+ throw error;
241
+ }
242
+ }
243
+
244
+ /** Busy hints a day old matter to nobody; one per session would otherwise pile up. */
245
+ export const HINT_PRUNE_MS = 24 * 3_600_000;
246
+ function pruneHints(env, now) {
247
+ const dir = join(lockDir(env), 'busy');
248
+ try {
249
+ for (const name of readdirSync(dir)) {
250
+ try {
251
+ if (now - statSync(join(dir, name)).mtimeMs > HINT_PRUNE_MS) unlinkSync(join(dir, name));
252
+ } catch {
253
+ /* gone already */
254
+ }
255
+ }
256
+ } catch {
257
+ /* no hints yet */
258
+ }
259
+ }
260
+
261
+ export function markBusy(env = process.env, now = Date.now()) {
262
+ const key = sessionKey(env);
263
+ if (!key) return false;
264
+ try {
265
+ pruneHints(env, now);
266
+ writeSmall(hintFile(env, key), { at: now });
267
+ return true;
268
+ } catch {
269
+ return false;
270
+ }
271
+ }
272
+
273
+ export function busyHintAt(env = process.env) {
274
+ const key = sessionKey(env);
275
+ if (!key) return null;
276
+ try {
277
+ const at = JSON.parse(readFileSync(hintFile(env, key), 'utf8'))?.at;
278
+ return Number.isFinite(at) ? at : null;
279
+ } catch {
280
+ return null;
281
+ }
282
+ }