@agentsignalnet/claude-plugin 0.2.135 → 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.
- package/.claude-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/scripts/session-state.mjs +418 -0
- package/scripts/task-hook.mjs +42 -1
- package/scripts/watchers.mjs +80 -1
package/package.json
CHANGED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* IS THE PARENT SESSION IN A TURN? Decided from its own transcript.
|
|
4
|
+
*
|
|
5
|
+
* node session-state.mjs --self-test
|
|
6
|
+
*
|
|
7
|
+
* The inbox monitor holds a priority-0 message while a turn runs and wakes the
|
|
8
|
+
* session with it once the session is idle. Hooks cannot say "idle": Esc
|
|
9
|
+
* during generation fires no hook at all, and `idle_prompt` means "no turn",
|
|
10
|
+
* not "no tool" (spike 0, CC 2.1.326). So the transcript is the authority and
|
|
11
|
+
* a UserPromptSubmit hint can only ADD busy, for the moment before the prompt
|
|
12
|
+
* line is written.
|
|
13
|
+
*
|
|
14
|
+
* Line ORDER is causal, timestamps are not, so rules read entries in file
|
|
15
|
+
* order and take time only from the file's mtime. An open foreground tool is
|
|
16
|
+
* busy for as long as it runs; a backgrounded tool whose turn ended is idle.
|
|
17
|
+
*
|
|
18
|
+
* PRIVACY: this module reads transcript lines into memory to classify them.
|
|
19
|
+
* Above the self-test it never writes, logs, prints or sends any of it, and
|
|
20
|
+
* the self-test checks that structurally.
|
|
21
|
+
*/
|
|
22
|
+
import { openSync, readSync, closeSync, readdirSync, existsSync, statSync } from 'node:fs';
|
|
23
|
+
import { homedir } from 'node:os';
|
|
24
|
+
import { join } from 'node:path';
|
|
25
|
+
import { fileURLToPath } from 'node:url';
|
|
26
|
+
import { sessionKey, busyHintAt } from './watchers.mjs';
|
|
27
|
+
|
|
28
|
+
export const QUIET_MS = 2000;
|
|
29
|
+
export const END_GRACE_MS = 15_000;
|
|
30
|
+
export const MODEL_STALL_MS = 600_000;
|
|
31
|
+
export const HINT_MAX_MS = 30_000;
|
|
32
|
+
export const TAIL_START = 256 * 1024;
|
|
33
|
+
export const TAIL_MAX = 4 * 1024 * 1024;
|
|
34
|
+
|
|
35
|
+
// No environment override: an inherited variable must not change when priority
|
|
36
|
+
// 0 may interrupt. Tests pass `stallMs` to classify directly.
|
|
37
|
+
|
|
38
|
+
// An ALLOW-list, not the deny-list of metadata types: new metadata lines keep
|
|
39
|
+
// appearing (ai-title, continued-in, ...) and are written after a turn ends,
|
|
40
|
+
// so an unknown type must never read as a turn in flight.
|
|
41
|
+
const CONVERSATION = new Set(['user', 'assistant', 'system', 'queue-operation']);
|
|
42
|
+
const blocks = (e) => (Array.isArray(e.message?.content) ? e.message.content : []);
|
|
43
|
+
const textOf = (e) =>
|
|
44
|
+
typeof e.message?.content === 'string'
|
|
45
|
+
? e.message.content
|
|
46
|
+
: blocks(e).filter((b) => b?.type === 'text').map((b) => String(b.text ?? '')).join('');
|
|
47
|
+
const isInterrupt = (e) => e.type === 'user' && textOf(e).startsWith('[Request interrupted by user');
|
|
48
|
+
const isPrompt = (e) =>
|
|
49
|
+
e.type === 'user' && !e.isMeta && !isInterrupt(e) &&
|
|
50
|
+
!blocks(e).some((b) => b?.type === 'tool_result') &&
|
|
51
|
+
(typeof e.message?.content === 'string' || blocks(e).length > 0);
|
|
52
|
+
const isTurnEnd = (e) => e.type === 'system' && (e.subtype === 'turn_duration' || e.subtype === 'stop_hook_summary');
|
|
53
|
+
// Only the two subtypes above end a turn. Any other system line (local_command,
|
|
54
|
+
// an unfamiliar subtype, ...) after the end is the last entry and reaches the
|
|
55
|
+
// in-flight/stall rule, so it never releases priority 0 early. Queue operations
|
|
56
|
+
// are conversation entries too: a trailing dequeue (or any other queue line)
|
|
57
|
+
// is the last entry, so it holds busy in-flight until a prompt or the stall.
|
|
58
|
+
const STOPS = new Set(['end_turn', 'stop_sequence', 'max_tokens', 'refusal']);
|
|
59
|
+
const verdict = (busy, reason) => ({ busy, reason });
|
|
60
|
+
|
|
61
|
+
/** JSONL to entries. A tail read starts mid-line, so its first line is dropped. */
|
|
62
|
+
export function parseLines(text, fromStart) {
|
|
63
|
+
const lines = String(text).split('\n');
|
|
64
|
+
if (!fromStart) lines.shift();
|
|
65
|
+
const entries = [];
|
|
66
|
+
for (const line of lines) {
|
|
67
|
+
if (!line.trim()) continue;
|
|
68
|
+
try {
|
|
69
|
+
const entry = JSON.parse(line);
|
|
70
|
+
if (entry && typeof entry === 'object') entries.push(entry);
|
|
71
|
+
} catch {
|
|
72
|
+
/* a torn or foreign line: skip it */
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return entries;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The rules of the re-plan (§3), in order. `mtimeMs` null means no transcript.
|
|
80
|
+
* `tail` is readTail's `{entries, complete}` snapshot, or an array a caller
|
|
81
|
+
* knows to be the whole history.
|
|
82
|
+
*/
|
|
83
|
+
export function classify(tail, { now = Date.now(), mtimeMs = null, hintAt = null, stallMs = MODEL_STALL_MS } = {}) {
|
|
84
|
+
if (hintAt != null && hintAt > (mtimeMs ?? -Infinity) && now - hintAt < HINT_MAX_MS) return verdict(true, 'hint');
|
|
85
|
+
if (mtimeMs == null) return verdict(true, 'unknown');
|
|
86
|
+
const quietFor = now - mtimeMs;
|
|
87
|
+
if (quietFor < QUIET_MS) return verdict(true, 'quiet');
|
|
88
|
+
const known = tail == null || Array.isArray(tail);
|
|
89
|
+
// A window that neither reached byte zero nor holds a prompt may have lost a
|
|
90
|
+
// tool_use whose result never came: it cannot prove no tool is open, so the
|
|
91
|
+
// stall rule may not release it. A turn end, an interrupt or a stop still
|
|
92
|
+
// can, because a window with no prompt lies inside one turn and those end it.
|
|
93
|
+
const partial = !known && tail.complete !== true;
|
|
94
|
+
const entries = known ? tail : tail.entries;
|
|
95
|
+
const conv = (Array.isArray(entries) ? entries : []).filter((e) => e && typeof e === 'object' && CONVERSATION.has(e.type));
|
|
96
|
+
if (conv.length === 0) return verdict(true, 'unknown');
|
|
97
|
+
const stalled = quietFor >= stallMs;
|
|
98
|
+
const unsettled = () => (partial ? verdict(true, 'unknown') : stalled ? verdict(false, 'stalled') : verdict(true, 'in-flight'));
|
|
99
|
+
|
|
100
|
+
let start = 0;
|
|
101
|
+
for (let i = conv.length - 1; i >= 0; i -= 1) {
|
|
102
|
+
if (isPrompt(conv[i])) { start = i; break; }
|
|
103
|
+
}
|
|
104
|
+
const turn = conv.slice(start);
|
|
105
|
+
const open = new Set();
|
|
106
|
+
for (const e of turn) {
|
|
107
|
+
for (const b of blocks(e)) {
|
|
108
|
+
if (b?.type === 'tool_use' && b.id) open.add(b.id);
|
|
109
|
+
else if (b?.type === 'tool_result') open.delete(b.tool_use_id);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (open.size) return verdict(true, 'open-tool');
|
|
113
|
+
|
|
114
|
+
let lastEnd = -1;
|
|
115
|
+
let lastQueue = -1;
|
|
116
|
+
conv.forEach((e, i) => {
|
|
117
|
+
if (isTurnEnd(e)) lastEnd = i;
|
|
118
|
+
if (e.type === 'queue-operation') lastQueue = i;
|
|
119
|
+
});
|
|
120
|
+
if (lastQueue > lastEnd && conv[lastQueue].operation === 'enqueue') {
|
|
121
|
+
return stalled && !partial ? verdict(false, 'stalled') : verdict(true, 'queued');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const last = conv[conv.length - 1];
|
|
125
|
+
if (isTurnEnd(last)) return verdict(false, 'ended');
|
|
126
|
+
if (isInterrupt(last)) return verdict(false, 'interrupted');
|
|
127
|
+
if (last.type === 'assistant' && (STOPS.has(last.message?.stop_reason) || last.isApiErrorMessage)) {
|
|
128
|
+
return quietFor >= END_GRACE_MS ? verdict(false, 'ended') : verdict(true, 'ending');
|
|
129
|
+
}
|
|
130
|
+
return unsettled();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The tail of a transcript, doubling the window until it holds a prompt, as
|
|
135
|
+
* `{entries, complete}`. `complete` means the read reached byte zero or holds
|
|
136
|
+
* a real prompt; hitting `max` or the round limit alone leaves it false.
|
|
137
|
+
*/
|
|
138
|
+
export function readTail(path, size, { start = TAIL_START, max = TAIL_MAX } = {}) {
|
|
139
|
+
const fd = openSync(path, 'r');
|
|
140
|
+
try {
|
|
141
|
+
let entries = [];
|
|
142
|
+
let complete = false;
|
|
143
|
+
for (let want = start, round = 0; round < 16; want *= 2, round += 1) {
|
|
144
|
+
const len = Math.min(size, want, max);
|
|
145
|
+
// One byte more before the window: if it is a newline, the window starts
|
|
146
|
+
// on a line boundary and its first line is whole, so it is kept.
|
|
147
|
+
const extra = len < size ? 1 : 0;
|
|
148
|
+
const buffer = Buffer.alloc(len + extra);
|
|
149
|
+
const got = readSync(fd, buffer, 0, len + extra, size - len - extra);
|
|
150
|
+
const whole = extra === 0 || buffer[0] === 0x0a;
|
|
151
|
+
entries = parseLines(buffer.subarray(extra, got).toString('utf8'), whole);
|
|
152
|
+
complete = len === size || entries.some(isPrompt);
|
|
153
|
+
if (complete || len >= max) break;
|
|
154
|
+
}
|
|
155
|
+
return { entries, complete };
|
|
156
|
+
} finally {
|
|
157
|
+
closeSync(fd);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** `<config>/projects/*\/<id>.jsonl`, or null. The id cannot name a path. */
|
|
162
|
+
export function findTranscript(sessionId, env = process.env) {
|
|
163
|
+
// Refused, not sanitized: two ids differing only in other characters must
|
|
164
|
+
// never name the same file.
|
|
165
|
+
const id = String(sessionId ?? '');
|
|
166
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id)) return null;
|
|
167
|
+
const root = join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'projects');
|
|
168
|
+
let dirs = [];
|
|
169
|
+
try {
|
|
170
|
+
dirs = readdirSync(root, { withFileTypes: true });
|
|
171
|
+
} catch {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
for (const dir of dirs) {
|
|
175
|
+
const path = join(root, dir.name, `${id}.jsonl`);
|
|
176
|
+
if (dir.isDirectory() && existsSync(path)) return path;
|
|
177
|
+
}
|
|
178
|
+
return null;
|
|
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
|
+
|
|
205
|
+
// ----- SELF-TEST: everything below this line is test code -----
|
|
206
|
+
async function selfTest() {
|
|
207
|
+
const fs = await import('node:fs');
|
|
208
|
+
const { tmpdir } = await import('node:os');
|
|
209
|
+
const checks = [];
|
|
210
|
+
const ok = (what, passed, detail = '') => checks.push([what, Boolean(passed), detail]);
|
|
211
|
+
const P = (text = 'do the thing') => ({ type: 'user', message: { role: 'user', content: text } });
|
|
212
|
+
const A = (content, stop = null, extra = {}) => ({ type: 'assistant', message: { role: 'assistant', content, stop_reason: stop }, ...extra });
|
|
213
|
+
const TXT = (text) => [{ type: 'text', text }];
|
|
214
|
+
const TU = (...ids) => A(ids.map((id) => ({ type: 'tool_use', id, name: 'Bash', input: {} })), 'tool_use');
|
|
215
|
+
const TR = (id, extra = {}, result = {}) => ({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, ...extra }] }, toolUseResult: result });
|
|
216
|
+
const INT = (suffix = '') => ({ type: 'user', message: { role: 'user', content: TXT(`[Request interrupted by user${suffix}]`) } });
|
|
217
|
+
const SYS = (subtype) => ({ type: 'system', subtype });
|
|
218
|
+
const Q = (operation) => ({ type: 'queue-operation', operation });
|
|
219
|
+
const T = 1_000_000_000;
|
|
220
|
+
const at = (entries, dt, hintAt = null) => classify(entries, { now: T + dt, mtimeMs: T, hintAt, stallMs: MODEL_STALL_MS });
|
|
221
|
+
const is = (what, got, busy, reason) => ok(what, got.busy === busy && (!reason || got.reason === reason), got);
|
|
222
|
+
const MIN = 60_000;
|
|
223
|
+
|
|
224
|
+
const t1 = [P(), A([{ type: 'thinking', thinking: '' }]), A(TXT('partial')), INT()];
|
|
225
|
+
is('T1 Esc mid-generation, no hook: idle at +2s', at(t1, 2000), false, 'interrupted');
|
|
226
|
+
const t2 = [P(), TU('a'), TR('a', { is_error: true }), INT(' for tool use')];
|
|
227
|
+
is('T2 Esc mid-tool: busy quiet at +1s', at(t2, 1000), true, 'quiet');
|
|
228
|
+
is('T2 Esc mid-tool: idle at +2s', at(t2, 2000), false, 'interrupted');
|
|
229
|
+
const t3 = [P(), TU('a')];
|
|
230
|
+
for (const dt of [63_000, 11 * MIN, 120 * MIN]) is(`T3 a running foreground tool is busy at +${dt}ms`, at(t3, dt), true, 'open-tool');
|
|
231
|
+
const ended = [P(), TU('a'), TR('a', {}, { backgroundTaskId: 'bg-fake-1' }), A(TXT('started'), 'end_turn'), SYS('stop_hook_summary'), SYS('turn_duration')];
|
|
232
|
+
is('T4 a backgrounded tool whose turn ended is idle', at(ended, 20_000), false, 'ended');
|
|
233
|
+
is('T4 an enqueue not yet dequeued is busy', at([...ended, Q('enqueue')], 20_000), true, 'queued');
|
|
234
|
+
is('T4 dequeued, and the new turn ended: idle', at([...ended, Q('enqueue'), Q('dequeue'), P('<task-notification/>'), A(TXT('done'), 'end_turn'), SYS('turn_duration')], 20_000), false, 'ended');
|
|
235
|
+
is('T5 prompt only: busy in-flight at +5min', at([P()], 5 * MIN), true, 'in-flight');
|
|
236
|
+
is('T5 prompt only: idle stalled at +10min+1', at([P()], 10 * MIN + 1), false, 'stalled');
|
|
237
|
+
is('T6 parallel tools with one still open: busy at +2h', at([P(), TU('a', 'b'), TR('a')], 120 * MIN), true, 'open-tool');
|
|
238
|
+
const t7 = [P(), A(TXT('answer'), 'end_turn')];
|
|
239
|
+
is('T7 end_turn without turn_duration: busy ending at +10s', at(t7, 10_000), true, 'ending');
|
|
240
|
+
is('T7 end_turn without turn_duration: idle at +15s', at(t7, 15_000), false, 'ended');
|
|
241
|
+
is('T8 an API error is idle at +15s', at([P(), A(TXT('API Error'), null, { isApiErrorMessage: true })], 15_000), false, 'ended');
|
|
242
|
+
is('T9a a hint newer than the transcript and 5s old is busy', at(ended, 20_000, T + 15_000), true, 'hint');
|
|
243
|
+
is('T9b a hint older than the transcript does not make busy', at(ended, 20_000, T - 1000), false, 'ended');
|
|
244
|
+
is('T9c a hint 31s old does not make busy', at(ended, 32_000, T + 1000), false, 'ended');
|
|
245
|
+
is('T10 no transcript is busy unknown', classify([], { now: T, mtimeMs: null }), true, 'unknown');
|
|
246
|
+
is('T10 metadata only is busy unknown', at([{ type: 'attachment' }, { type: 'api-request' }, { type: 'mode' }], 20_000), true, 'unknown');
|
|
247
|
+
const torn = parseLines(`${ended.map((e) => JSON.stringify(e)).join('\nnot json {\n')}\n`, true);
|
|
248
|
+
ok('T10 a garbage line in the middle is skipped', torn.length === ended.length && at(torn, 20_000).reason === 'ended', torn.length);
|
|
249
|
+
for (const sub of ['local_command', 'novel_subtype_fake']) {
|
|
250
|
+
const after = [...ended, SYS(sub)];
|
|
251
|
+
is(`qa#1 end then system/${sub}: busy in-flight at +2s`, at(after, 2000), true, 'in-flight');
|
|
252
|
+
is(`qa#1 end then system/${sub}: busy in-flight at stall-1`, at(after, MODEL_STALL_MS - 1), true, 'in-flight');
|
|
253
|
+
is(`qa#1 end then system/${sub}: idle stalled at stall`, at(after, MODEL_STALL_MS), false, 'stalled');
|
|
254
|
+
is(`qa#1 end, system/${sub}, then a genuine end: idle`, at([...after, SYS('turn_duration')], 2000), false, 'ended');
|
|
255
|
+
}
|
|
256
|
+
const dq = [...ended, Q('enqueue'), Q('dequeue')];
|
|
257
|
+
// A dequeue with its prompt not written yet is the last entry: busy in-flight
|
|
258
|
+
// until the stall limit, never idle after a grace (r4 qa#1).
|
|
259
|
+
is('r4 a trailing dequeue after an end is busy in-flight at +5s', at(dq, 5000), true, 'in-flight');
|
|
260
|
+
is('r4 ... still busy past the end grace', at(dq, END_GRACE_MS + 1), true, 'in-flight');
|
|
261
|
+
is('r4 ... and released only at the stall limit', at(dq, MODEL_STALL_MS), false, 'stalled');
|
|
262
|
+
is('r4 end_turn with no turn_duration, then enqueue and dequeue: busy at +20s', at([P(), A(TXT('ok'), 'end_turn'), Q('enqueue'), Q('dequeue')], 20_000), true, 'in-flight');
|
|
263
|
+
is('r4 any other queue line after an end is the last entry: busy', at([...ended, Q('remove')], 20_000), true, 'in-flight');
|
|
264
|
+
is('logic#1 r2 queue operations alone are in-flight, not unknown', at([Q('enqueue'), Q('dequeue')], 5 * MIN), true, 'in-flight');
|
|
265
|
+
is('logic#1 r2 ... and reach the stall release', at([Q('enqueue'), Q('dequeue')], 10 * MIN + 1), false, 'stalled');
|
|
266
|
+
is('metadata types written after a turn ends do not make it busy', at([...ended, { type: 'ai-title' }, { type: 'continued-in' }, { type: 'last-prompt' }], 20_000), false, 'ended');
|
|
267
|
+
|
|
268
|
+
const dir = fs.mkdtempSync(join(tmpdir(), 'agentsignal-session-selftest-'));
|
|
269
|
+
try {
|
|
270
|
+
const big = join(dir, 'big.jsonl');
|
|
271
|
+
fs.writeFileSync(big, `${JSON.stringify(P())}\n${JSON.stringify(A(TXT('x'.repeat(300 * 1024)), 'end_turn'))}\n`);
|
|
272
|
+
const size = fs.statSync(big).size;
|
|
273
|
+
is('T11 a 300 KiB final end_turn line still classifies idle', classify(readTail(big, size), { now: T + 20_000, mtimeMs: T }), false, 'ended');
|
|
274
|
+
|
|
275
|
+
// logic#1: a capped window that holds no prompt cannot establish the open tools.
|
|
276
|
+
const jsonl = (es) => es.map((e) => `${JSON.stringify(e)}\n`).join('');
|
|
277
|
+
const PAD = { type: 'progress', pad: 'x'.repeat(4096) };
|
|
278
|
+
const tail = (name, text, cap) => {
|
|
279
|
+
const path = join(dir, name);
|
|
280
|
+
fs.writeFileSync(path, text);
|
|
281
|
+
return readTail(path, fs.statSync(path).size, { start: 64, max: cap });
|
|
282
|
+
};
|
|
283
|
+
const at2 = (snap, dt) => classify(snap, { now: T + dt, mtimeMs: T, stallMs: MODEL_STALL_MS });
|
|
284
|
+
const parallel = jsonl([P(), TU('A', 'B'), PAD, TR('A')]);
|
|
285
|
+
is('logic#1 capped window, B use outside, A result inside: busy unknown at +2h', at2(tail('par.jsonl', parallel, 1024), 120 * MIN), true, 'unknown');
|
|
286
|
+
is('logic#1 the complete fixture: busy open-tool for B at +2h', at2(tail('par-full.jsonl', parallel, TAIL_MAX), 120 * MIN), true, 'open-tool');
|
|
287
|
+
const suffixEnd = jsonl([P(), TU('A', 'B'), PAD, TR('A'), A(TXT('done'), 'end_turn'), SYS('turn_duration')]);
|
|
288
|
+
is('logic#1 r2 a turn end in an incomplete window releases: idle ended', at2(tail('end.jsonl', suffixEnd, 1024), 20_000), false, 'ended');
|
|
289
|
+
const suffixInt = jsonl([P(), TU('A', 'B'), PAD, TR('A'), INT()]);
|
|
290
|
+
is('logic#1 r2 an interrupt in an incomplete window releases: idle', at2(tail('int.jsonl', suffixInt, 1024), 20_000), false, 'interrupted');
|
|
291
|
+
const suffixStop = jsonl([P(), TU('A', 'B'), PAD, TR('A'), A(TXT('done'), 'end_turn')]);
|
|
292
|
+
is('logic#1 r2 a stop in an incomplete window: ending, then ended after the grace', at2(tail('stop.jsonl', suffixStop, 1024), 10_000).reason === 'ending' ? at2(tail('stop.jsonl', suffixStop, 1024), 20_000) : { busy: null }, false, 'ended');
|
|
293
|
+
const promptIn = jsonl([P(), TU('A', 'B'), PAD, TR('A'), TR('B'), P('next'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')]);
|
|
294
|
+
is('logic#1 a real prompt inside a capped window: idle ended', at2(tail('prompt.jsonl', promptIn, 1024), 20_000), false, 'ended');
|
|
295
|
+
const exact = jsonl([TR('A'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')]);
|
|
296
|
+
is('logic#1 a file exactly at the cap is read from byte zero: idle ended', at2(tail('exact.jsonl', exact, Buffer.byteLength(exact)), 20_000), false, 'ended');
|
|
297
|
+
is('logic#1 a known-complete array still classifies', at2([TR('A'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')], 20_000), false, 'ended');
|
|
298
|
+
|
|
299
|
+
const config = join(dir, 'config');
|
|
300
|
+
fs.mkdirSync(join(config, 'projects', '-fake-project'), { recursive: true });
|
|
301
|
+
fs.writeFileSync(join(config, 'projects', '-fake-project', 'sess-fake-1.jsonl'), '');
|
|
302
|
+
fs.writeFileSync(join(config, 'projects', 'x.jsonl'), '');
|
|
303
|
+
const env = { CLAUDE_CONFIG_DIR: config };
|
|
304
|
+
ok('T12 findTranscript finds <id>.jsonl', findTranscript('sess-fake-1', env) === join(config, 'projects', '-fake-project', 'sess-fake-1.jsonl'));
|
|
305
|
+
ok('T12 an unknown id is null', findTranscript('sess-none', env) === null && findTranscript('', env) === null);
|
|
306
|
+
ok('T12 ../x cannot leave projects/', findTranscript('../x', env) === null);
|
|
307
|
+
// r3 security#3: an id that would need sanitizing is refused, even when the
|
|
308
|
+
// sanitized name exists.
|
|
309
|
+
fs.writeFileSync(join(config, 'projects', '-fake-project', 'a_b.jsonl'), '');
|
|
310
|
+
ok('r3 security#3 a/b and a.b are refused, not read as a_b', findTranscript('a/b', env) === null && findTranscript('a.b', env) === null &&
|
|
311
|
+
findTranscript('a_b', env) === join(config, 'projects', '-fake-project', 'a_b.jsonl'));
|
|
312
|
+
|
|
313
|
+
// r3 logic#4: a window that starts exactly on a line boundary keeps that line.
|
|
314
|
+
const boundary = join(dir, 'boundary.jsonl');
|
|
315
|
+
const lead = `${JSON.stringify({ type: 'progress', pad: 'y'.repeat(200) })}\n`;
|
|
316
|
+
const own = jsonl([P('the real prompt'), A(TXT('ok'), 'end_turn'), SYS('turn_duration')]);
|
|
317
|
+
fs.writeFileSync(boundary, lead + own);
|
|
318
|
+
const cut = Buffer.byteLength(own);
|
|
319
|
+
const snap = readTail(boundary, fs.statSync(boundary).size, { start: cut, max: cut });
|
|
320
|
+
ok('r3 logic#4 a prompt that starts the window exactly is kept, so the window is complete', snap.complete === true && snap.entries.length === 3, snap.entries.length);
|
|
321
|
+
const mid = readTail(boundary, fs.statSync(boundary).size, { start: cut - 5, max: cut - 5 });
|
|
322
|
+
ok('r3 logic#4 ... and a torn first line is still dropped', mid.complete === false && mid.entries.length === 2, mid.entries.length);
|
|
323
|
+
} finally {
|
|
324
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
325
|
+
}
|
|
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
|
+
|
|
391
|
+
const source = fs.readFileSync(fileURLToPath(import.meta.url), 'utf8');
|
|
392
|
+
// Everything before the self-test function, comments stripped, so neither a
|
|
393
|
+
// marker string nor a comment can shrink or pad what is scanned.
|
|
394
|
+
const body = source.slice(0, source.indexOf(['async function', 'selfTest('].join(' '))).replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
|
|
395
|
+
const leaks = ['writeFileSync', 'appendFileSync', 'writeSync', 'createWriteStream', 'fs.write', 'fetch(', 'console.', 'process.std',
|
|
396
|
+
'require(', 'import(', 'child_process', 'node:http', 'node:https', 'node:net', 'node:dgram', 'node:tls'].filter((s) => body.includes(s));
|
|
397
|
+
ok('T13 nothing above the self-test writes, sends or prints', body.length > 1000 && leaks.length === 0, leaks);
|
|
398
|
+
// r3 security#2: the module may import only these names, so a writing or
|
|
399
|
+
// sending helper cannot arrive through an import either.
|
|
400
|
+
const ALLOWED = {
|
|
401
|
+
'node:fs': ['openSync', 'readSync', 'closeSync', 'readdirSync', 'existsSync', 'statSync'],
|
|
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'],
|
|
405
|
+
};
|
|
406
|
+
const imports = [...body.matchAll(/import\s*\{([^}]*)\}\s*from\s*'([^']+)'/g)].map(([, names, from]) => [from, names.split(',').map((n) => n.trim()).filter(Boolean)]);
|
|
407
|
+
const stray = imports.filter(([from, names]) => !ALLOWED[from] || names.some((n) => !ALLOWED[from].includes(n)));
|
|
408
|
+
const bare = (body.match(/^\s*import\b/gm) ?? []).length;
|
|
409
|
+
ok('r3 security#2 T13 imports only the allowed names', imports.length >= 5 && stray.length === 0 && bare === imports.length, { stray, bare });
|
|
410
|
+
ok('r3 security#4 no AGENTSIGNAL_ setting is read from the environment', !/AGENTSIGNAL_/.test(body));
|
|
411
|
+
|
|
412
|
+
const failed = checks.filter(([, passed]) => !passed);
|
|
413
|
+
for (const [what, , detail] of failed) console.error(` x ${what}: ${JSON.stringify(detail)}`);
|
|
414
|
+
console.log(failed.length === 0 ? `Session state: ${checks.length} checks passed.` : `Session state: ${failed.length} of ${checks.length} FAILED.`);
|
|
415
|
+
process.exit(failed.length === 0 ? 0 : 1);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === '--self-test') await selfTest();
|
package/scripts/task-hook.mjs
CHANGED
|
@@ -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) {
|
package/scripts/watchers.mjs
CHANGED
|
@@ -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
|
+
}
|