sideby 0.38.0 → 0.39.0
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/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +6 -0
- package/dist/src/cli/commands.js +88 -0
- package/dist/src/cli/json-schemas.js +35 -0
- package/dist/src/cli/main.js +32 -1
- package/dist/src/core/cli-commands.js +14 -2
- package/dist/src/core/config.d.ts +13 -0
- package/dist/src/core/config.js +18 -0
- package/dist/src/core/launch.d.ts +5 -0
- package/dist/src/core/launch.js +11 -1
- package/dist/src/core/network.d.ts +11 -1
- package/dist/src/core/network.js +21 -1
- package/dist/src/core/progress-state.d.ts +80 -0
- package/dist/src/core/progress-state.js +216 -0
- package/dist/src/core/progress.d.ts +36 -0
- package/dist/src/core/progress.js +77 -0
- package/dist/src/core/prompt-origin.d.ts +40 -0
- package/dist/src/core/prompt-origin.js +98 -0
- package/dist/src/core/search-catalog.js +25 -0
- package/dist/src/core/unattended-attended.d.ts +109 -0
- package/dist/src/core/unattended-attended.js +337 -0
- package/dist/src/core/unattended.d.ts +10 -2
- package/dist/src/core/unattended.js +11 -2
- package/dist/src/handoff/hook.js +19 -4
- package/dist/src/menubar/script.js +9 -3
- package/dist/src/network/hook.d.ts +9 -0
- package/dist/src/network/hook.js +186 -4
- package/dist/src/panel/handler.d.ts +3 -0
- package/dist/src/panel/handler.js +15 -0
- package/dist/src/panel/i18n.d.ts +18 -0
- package/dist/src/panel/i18n.js +36 -0
- package/dist/src/panel/page-script.js +67 -2
- package/dist/src/panel/page-styles.js +14 -0
- package/dist/src/progress/hook.d.ts +50 -0
- package/dist/src/progress/hook.js +251 -0
- package/dist/src/runtime.d.ts +9 -0
- package/dist/src/runtime.js +45 -2
- package/dist/src/unattended/hook.d.ts +5 -0
- package/dist/src/unattended/hook.js +103 -9
- package/package.json +1 -1
- package/schemas/config.json +13 -0
- package/schemas/progress.json +137 -0
- package/schemas/unattended.json +38 -0
- package/skills/sideby/SKILL.md +3 -1
- package/skills/sideby/references/network.md +1 -1
- package/skills/sideby/references/progress.md +25 -0
- package/skills/sideby/references/unattended.md +9 -1
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
// Attended Sessions (spec §3.37 "有人在的会话", ADR-0075): a Claude session someone typed into within the last 30 minutes
|
|
2
|
+
// asks as usual while Unattended Mode stays on for every other session. A leaf module (Node built-ins and leaf modules
|
|
3
|
+
// only): `unattended-hook` imports it.
|
|
4
|
+
//
|
|
5
|
+
// Only `unattended-hook`'s background `UserPromptSubmit` entry writes a record, and only after the session's own
|
|
6
|
+
// transcript (`ownTranscript`) said the prompt was typed by a person (`promptOrigin`). One file per session under `<state>/unattended/attended/`,
|
|
7
|
+
// named by a hash of the session id; every level must be a real folder of the user that nobody else can write to
|
|
8
|
+
// (`ownedFolder`, as for Pending Decisions). Nothing of the prompt is kept. A record is read and written back under a lock
|
|
9
|
+
// of its own (`<hash>.lock` beside it), so a told mark never puts back an older `at` a prompt has just renewed.
|
|
10
|
+
import { constants } from 'node:fs';
|
|
11
|
+
import { open, readdir, realpath, rm } from 'node:fs/promises';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
14
|
+
import { ownedFolder, readSmallFile, sha256, writeFileAtomic } from './fs-safe.js';
|
|
15
|
+
import { takeFileLock } from './lock.js';
|
|
16
|
+
import { readUnattendedConfig, readUnattendedOverride, unattendedState, } from './unattended-state.js';
|
|
17
|
+
/** How long a session counts as attended after each prompt someone typed into it. */
|
|
18
|
+
export const ATTENDED_MS = 30 * 60_000;
|
|
19
|
+
/** The `timeout` of the hook entry: the longest wait for the transcript (`ORIGIN_WAIT_MS`) with room to spare. */
|
|
20
|
+
export const ATTENDED_HOOK_TIMEOUT_S = 30;
|
|
21
|
+
/** How long the hook waits for Claude Code to write the prompt into the transcript (70–180 ms with Claude Code 2.1.325). */
|
|
22
|
+
export const ORIGIN_WAIT_MS = 10_000;
|
|
23
|
+
const ORIGIN_POLL_MS = 50;
|
|
24
|
+
/**
|
|
25
|
+
* How far before the transcript's end at the start the prompt's line is looked for (a queued prompt is written early).
|
|
26
|
+
* Reading starts at the beginning of the line that holds this point, so a line longer than it (a prompt with a
|
|
27
|
+
* picture) is read whole.
|
|
28
|
+
*/
|
|
29
|
+
const ORIGIN_BACK_BYTES = 256 * 1024;
|
|
30
|
+
/** The most of a transcript read while waiting, and the longest line held: past either, the prompt does not count. */
|
|
31
|
+
const ORIGIN_READ_MAX = 32 * 1024 * 1024;
|
|
32
|
+
const LINE_MAX = 8 * 1024 * 1024;
|
|
33
|
+
/** A record that ran out more than this long ago is removed. */
|
|
34
|
+
const KEEP_EXPIRED_MS = 60 * 60_000;
|
|
35
|
+
const PARTS = ['unattended', 'attended'];
|
|
36
|
+
const fileName = (sessionId) => `${sha256(sessionId).slice(0, 32)}.json`;
|
|
37
|
+
const lockName = (sessionId) => `${sha256(sessionId).slice(0, 32)}.lock`;
|
|
38
|
+
/** One session's record is read and written back by one caller at a time; a holder that died frees it after `staleMs`. */
|
|
39
|
+
const LOCK = { staleMs: 15_000, beatMs: 5_000 };
|
|
40
|
+
const LOCK_WAIT = { timeoutMs: 5_000, pollMs: 25 };
|
|
41
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
42
|
+
function parse(text) {
|
|
43
|
+
if (!text)
|
|
44
|
+
return undefined;
|
|
45
|
+
try {
|
|
46
|
+
const v = JSON.parse(text);
|
|
47
|
+
const str = (x) => (typeof x === 'string' && x ? x : undefined);
|
|
48
|
+
const sessionId = str(v.sessionId);
|
|
49
|
+
const family = str(v.family);
|
|
50
|
+
const at = str(v.at);
|
|
51
|
+
const since = str(v.since);
|
|
52
|
+
if (!sessionId || !family || !at || !since)
|
|
53
|
+
return undefined;
|
|
54
|
+
if (!Number.isFinite(Date.parse(at)) || !Number.isFinite(Date.parse(since)))
|
|
55
|
+
return undefined;
|
|
56
|
+
const account = str(v.account);
|
|
57
|
+
const cwd = str(v.cwd);
|
|
58
|
+
const toldAt = str(v.toldAt);
|
|
59
|
+
return {
|
|
60
|
+
sessionId,
|
|
61
|
+
family,
|
|
62
|
+
...(account ? { account } : {}),
|
|
63
|
+
...(cwd ? { cwd } : {}),
|
|
64
|
+
at,
|
|
65
|
+
since,
|
|
66
|
+
...(toldAt && Number.isFinite(Date.parse(toldAt)) ? { toldAt } : {}),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** When the record stops counting, in ms; it counts while this is later than now. */
|
|
74
|
+
export const attendedEnd = (r) => Date.parse(r.at) + ATTENDED_MS;
|
|
75
|
+
/** The session's record while it still counts at `now`; undefined otherwise or when the folder is not safe. */
|
|
76
|
+
export async function readAttended(stateDir, sessionId, now) {
|
|
77
|
+
const dir = await ownedFolder(stateDir, PARTS, { create: false }).catch(() => null);
|
|
78
|
+
if (!dir)
|
|
79
|
+
return undefined;
|
|
80
|
+
const r = parse(await readSmallFile(join(dir, fileName(sessionId)), 8192));
|
|
81
|
+
const t = now.getTime();
|
|
82
|
+
return r && r.sessionId === sessionId && Date.parse(r.at) <= t && t < attendedEnd(r) ? r : undefined;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Notes a prompt someone typed into the session at `at`: it counts as attended for `ATTENDED_MS` from then. A stretch
|
|
86
|
+
* that was still running goes on (its `since` and `toldAt` are kept); otherwise a new one starts. A prompt no later than
|
|
87
|
+
* the one already noted changes nothing. Removes records that ran out over an hour ago. Throws when the folder is not
|
|
88
|
+
* safe to use, or when the session's record stays locked for 5 seconds.
|
|
89
|
+
*/
|
|
90
|
+
export async function markAttended(stateDir, who, at) {
|
|
91
|
+
const dir = (await ownedFolder(stateDir, PARTS, { create: true, private: true }));
|
|
92
|
+
const file = join(dir, fileName(who.sessionId));
|
|
93
|
+
const t = at.getTime();
|
|
94
|
+
const release = await takeFileLock(join(dir, lockName(who.sessionId)), { ...LOCK, wait: LOCK_WAIT });
|
|
95
|
+
if (!release)
|
|
96
|
+
throw new Error(`the Attended Session record ${file} stayed locked; the next prompt notes it again`);
|
|
97
|
+
let record;
|
|
98
|
+
try {
|
|
99
|
+
const old = parse(await readSmallFile(file, 8192));
|
|
100
|
+
// A prompt no later than the one already noted (an old prompt's id handed in again, or two hooks out of order)
|
|
101
|
+
// changes nothing.
|
|
102
|
+
if (old && old.sessionId === who.sessionId && t <= Date.parse(old.at) && t < attendedEnd(old))
|
|
103
|
+
return old;
|
|
104
|
+
const running = old && old.sessionId === who.sessionId && t < attendedEnd(old) && Date.parse(old.at) <= t;
|
|
105
|
+
record = {
|
|
106
|
+
sessionId: who.sessionId,
|
|
107
|
+
family: who.family,
|
|
108
|
+
...(who.account ? { account: who.account } : {}),
|
|
109
|
+
...(who.cwd ? { cwd: who.cwd } : {}),
|
|
110
|
+
at: iso(t),
|
|
111
|
+
since: running ? old.since : iso(t),
|
|
112
|
+
...(running && old.toldAt ? { toldAt: old.toldAt } : {}),
|
|
113
|
+
};
|
|
114
|
+
await writeFileAtomic(file, `${JSON.stringify(record)}\n`, 0o600);
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
await release();
|
|
118
|
+
}
|
|
119
|
+
await pruneAttended(dir, t);
|
|
120
|
+
return record;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Notes that the user was told in the session during the stretch that began at `since`. Best effort: a record that
|
|
124
|
+
* stays locked is left as it is. `beforeWrite` runs between the read and the write (for tests).
|
|
125
|
+
*/
|
|
126
|
+
export async function markTold(stateDir, sessionId, since, now, deps = {}) {
|
|
127
|
+
const dir = await ownedFolder(stateDir, PARTS, { create: false }).catch(() => null);
|
|
128
|
+
if (!dir)
|
|
129
|
+
return;
|
|
130
|
+
const file = join(dir, fileName(sessionId));
|
|
131
|
+
const release = await takeFileLock(join(dir, lockName(sessionId)), { ...LOCK, wait: LOCK_WAIT }).catch(() => null);
|
|
132
|
+
if (!release)
|
|
133
|
+
return;
|
|
134
|
+
try {
|
|
135
|
+
const r = parse(await readSmallFile(file, 8192));
|
|
136
|
+
if (!r || r.sessionId !== sessionId || r.since !== since)
|
|
137
|
+
return;
|
|
138
|
+
await deps.beforeWrite?.();
|
|
139
|
+
await writeFileAtomic(file, `${JSON.stringify({ ...r, toldAt: now.toISOString() })}\n`, 0o600);
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
await release();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Removes records that ran out over an hour ago, or cannot be read. Each one is read again and removed under its
|
|
147
|
+
* session's lock, so a prompt that renews it meanwhile is never lost; a record whose lock is held is left for the next
|
|
148
|
+
* time. `beforeRemove` runs between the first read and taking the lock (for tests).
|
|
149
|
+
*/
|
|
150
|
+
async function pruneAttended(dir, t, deps = {}) {
|
|
151
|
+
const gone = (r) => !r || attendedEnd(r) + KEEP_EXPIRED_MS < t;
|
|
152
|
+
for (const name of await readdir(dir).catch(() => [])) {
|
|
153
|
+
if (!name.endsWith('.json'))
|
|
154
|
+
continue;
|
|
155
|
+
const file = join(dir, name);
|
|
156
|
+
if (!gone(parse(await readSmallFile(file, 8192))))
|
|
157
|
+
continue;
|
|
158
|
+
await deps.beforeRemove?.();
|
|
159
|
+
// The lock beside a record has the record's name (`fileName`, `lockName`).
|
|
160
|
+
const release = await takeFileLock(join(dir, `${name.slice(0, -'.json'.length)}.lock`), LOCK).catch(() => null);
|
|
161
|
+
if (!release)
|
|
162
|
+
continue;
|
|
163
|
+
try {
|
|
164
|
+
if (gone(parse(await readSmallFile(file, 8192))))
|
|
165
|
+
await rm(file, { force: true }).catch(() => { });
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
await release();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Every session that counts as attended at `now`, latest end first. `prune` also removes long-expired records;
|
|
174
|
+
* `beforeRemove` runs before each removal takes its lock (for tests).
|
|
175
|
+
*/
|
|
176
|
+
export async function listAttended(stateDir, now, opts = {}) {
|
|
177
|
+
const dir = await ownedFolder(stateDir, PARTS, { create: false }).catch(() => null);
|
|
178
|
+
if (!dir)
|
|
179
|
+
return [];
|
|
180
|
+
const t = now.getTime();
|
|
181
|
+
const out = [];
|
|
182
|
+
for (const name of await readdir(dir).catch(() => [])) {
|
|
183
|
+
if (!name.endsWith('.json'))
|
|
184
|
+
continue;
|
|
185
|
+
const r = parse(await readSmallFile(join(dir, name), 8192));
|
|
186
|
+
if (!r || name !== fileName(r.sessionId) || Date.parse(r.at) > t || attendedEnd(r) <= t)
|
|
187
|
+
continue;
|
|
188
|
+
out.push({
|
|
189
|
+
sessionId: r.sessionId,
|
|
190
|
+
family: r.family,
|
|
191
|
+
...(r.account ? { account: r.account } : {}),
|
|
192
|
+
...(r.cwd ? { cwd: r.cwd } : {}),
|
|
193
|
+
since: r.since,
|
|
194
|
+
until: iso(attendedEnd(r)),
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
if (opts.prune)
|
|
198
|
+
await pruneAttended(dir, t, opts.beforeRemove ? { beforeRemove: opts.beforeRemove } : {});
|
|
199
|
+
return out.sort((a, b) => Date.parse(b.until) - Date.parse(a.until) || a.sessionId.localeCompare(b.sessionId));
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Whether `transcript` is the file where Claude Code keeps session `sessionId`'s transcript:
|
|
203
|
+
* `<config dir>/projects/<folder>/<session id>.jsonl`, the config dir being `CLAUDE_CONFIG_DIR` or `~/.claude`, compared
|
|
204
|
+
* after resolving links. A hook input that names any other file is not believed, so a made-up transcript elsewhere marks
|
|
205
|
+
* nothing.
|
|
206
|
+
*/
|
|
207
|
+
export async function ownTranscript(transcript, sessionId, env) {
|
|
208
|
+
const config = env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), '.claude');
|
|
209
|
+
if (!isAbsolute(transcript) || !isAbsolute(config) || basename(transcript) !== `${sessionId}.jsonl`)
|
|
210
|
+
return false;
|
|
211
|
+
const [got, want] = await Promise.all([
|
|
212
|
+
realpath(dirname(dirname(transcript))).catch(() => undefined),
|
|
213
|
+
realpath(join(config, 'projects')).catch(() => undefined),
|
|
214
|
+
]);
|
|
215
|
+
return got !== undefined && got === want;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* The transcript line of prompt `promptId`: Claude Code writes a `user` line with the prompt's `promptId`, its text, a
|
|
219
|
+
* `timestamp` and an `origin` (`human` for a typed prompt; `task-notification`, `peer` for a Message from another
|
|
220
|
+
* process or session; none under `-p`; checked with Claude Code 2.1.325). The line is written shortly after the hook
|
|
221
|
+
* starts, so the transcript is read from the start of the line `ORIGIN_BACK_BYTES` before its end at the start, then every `ORIGIN_POLL_MS` what
|
|
222
|
+
* was added, for at most `ORIGIN_WAIT_MS`. Only lines holding the prompt id are parsed, and of them only `type`,
|
|
223
|
+
* `promptId`, `origin.kind`, `timestamp` and the message's text are looked at. Undefined when it cannot tell.
|
|
224
|
+
*/
|
|
225
|
+
export async function promptOrigin(transcript, promptId, deps = {}) {
|
|
226
|
+
if (!isAbsolute(transcript) || !transcript.endsWith('.jsonl') || !promptId)
|
|
227
|
+
return undefined;
|
|
228
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
229
|
+
const clock = deps.clock ?? Date.now;
|
|
230
|
+
const start = clock();
|
|
231
|
+
let offset;
|
|
232
|
+
let rest = '';
|
|
233
|
+
let read = 0;
|
|
234
|
+
for (;;) {
|
|
235
|
+
const fh = await open(transcript, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(() => undefined);
|
|
236
|
+
if (fh) {
|
|
237
|
+
try {
|
|
238
|
+
const st = await fh.stat();
|
|
239
|
+
if (!st.isFile())
|
|
240
|
+
return undefined;
|
|
241
|
+
// A transcript that did not exist yet when the hook started (a new session's first prompt) is read whole.
|
|
242
|
+
if (offset === undefined)
|
|
243
|
+
offset = await lineStart(fh, Math.max(0, st.size - ORIGIN_BACK_BYTES));
|
|
244
|
+
if (st.size < offset)
|
|
245
|
+
[offset, rest] = [0, ''];
|
|
246
|
+
while (offset < st.size) {
|
|
247
|
+
const len = Math.min(st.size - offset, 1024 * 1024);
|
|
248
|
+
const buf = Buffer.alloc(len);
|
|
249
|
+
const { bytesRead } = await fh.read(buf, 0, len, offset);
|
|
250
|
+
if (!bytesRead)
|
|
251
|
+
break;
|
|
252
|
+
offset += bytesRead;
|
|
253
|
+
read += bytesRead;
|
|
254
|
+
const lines = (rest + buf.subarray(0, bytesRead).toString('utf8')).split('\n');
|
|
255
|
+
rest = lines.pop() ?? '';
|
|
256
|
+
for (const line of lines) {
|
|
257
|
+
const found = originOf(line, promptId);
|
|
258
|
+
if (found)
|
|
259
|
+
return found;
|
|
260
|
+
}
|
|
261
|
+
if (read > ORIGIN_READ_MAX || rest.length > LINE_MAX)
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
finally {
|
|
266
|
+
await fh.close().catch(() => { });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
else
|
|
270
|
+
offset ??= 0;
|
|
271
|
+
if (clock() - start >= ORIGIN_WAIT_MS)
|
|
272
|
+
return undefined;
|
|
273
|
+
await sleep(ORIGIN_POLL_MS);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Where the line that holds byte `at` starts: just after the last newline before it, looked for at most `LINE_MAX`
|
|
278
|
+
* back. A line longer than that is not held anyway, so `at` itself is kept.
|
|
279
|
+
*/
|
|
280
|
+
async function lineStart(fh, at) {
|
|
281
|
+
const stop = Math.max(0, at - LINE_MAX);
|
|
282
|
+
let end = at;
|
|
283
|
+
while (end > stop) {
|
|
284
|
+
const len = Math.min(end - stop, 64 * 1024);
|
|
285
|
+
const buf = Buffer.alloc(len);
|
|
286
|
+
const { bytesRead } = await fh.read(buf, 0, len, end - len);
|
|
287
|
+
if (bytesRead < len)
|
|
288
|
+
return at;
|
|
289
|
+
const nl = buf.lastIndexOf(0x0a);
|
|
290
|
+
if (nl >= 0)
|
|
291
|
+
return end - len + nl + 1;
|
|
292
|
+
end -= len;
|
|
293
|
+
}
|
|
294
|
+
return stop === 0 ? 0 : at;
|
|
295
|
+
}
|
|
296
|
+
function originOf(line, promptId) {
|
|
297
|
+
if (!line.includes(promptId) || !line.includes('"origin"'))
|
|
298
|
+
return undefined;
|
|
299
|
+
try {
|
|
300
|
+
const r = JSON.parse(line);
|
|
301
|
+
if (r.type !== 'user' || r.promptId !== promptId || !r.origin || typeof r.origin !== 'object')
|
|
302
|
+
return undefined;
|
|
303
|
+
const at = typeof r.timestamp === 'string' ? Date.parse(r.timestamp) : Number.NaN;
|
|
304
|
+
const text = textOf(r.message?.content);
|
|
305
|
+
return {
|
|
306
|
+
origin: r.origin.kind === 'human' ? 'human' : 'other',
|
|
307
|
+
...(Number.isFinite(at) ? { at } : {}),
|
|
308
|
+
...(text !== undefined ? { text } : {}),
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return undefined;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function textOf(content) {
|
|
316
|
+
if (typeof content === 'string')
|
|
317
|
+
return content;
|
|
318
|
+
if (!Array.isArray(content))
|
|
319
|
+
return undefined;
|
|
320
|
+
const parts = [];
|
|
321
|
+
for (const b of content)
|
|
322
|
+
if (b && b.type === 'text' && typeof b.text === 'string')
|
|
323
|
+
parts.push(b.text);
|
|
324
|
+
return parts.join('\n');
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Whether one session is unattended right now: Unattended Mode is on (the Schedule, the manual state and the session
|
|
328
|
+
* flag, read fresh) and the session is not an Attended Session. `attended` is its record while it counts. Hooks and
|
|
329
|
+
* later features that must stay quiet in an unattended session ask this.
|
|
330
|
+
*/
|
|
331
|
+
export async function sessionUnattended(opts) {
|
|
332
|
+
const { schedule } = await readUnattendedConfig(opts.configFile);
|
|
333
|
+
const override = await readUnattendedOverride(opts.stateDir);
|
|
334
|
+
const state = unattendedState({ schedule, override, now: opts.now, session: opts.session });
|
|
335
|
+
const attended = opts.sessionId ? await readAttended(opts.stateDir, opts.sessionId, opts.now) : undefined;
|
|
336
|
+
return { on: state.on && !attended, state, ...(attended ? { attended } : {}) };
|
|
337
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Env } from '../types.ts';
|
|
2
2
|
import type { Paths } from './paths.ts';
|
|
3
3
|
import { type SessionHookPart } from './session-hooks.ts';
|
|
4
|
+
import { type AttendedSession } from './unattended-attended.ts';
|
|
4
5
|
import { type UnattendedOverride, type UnattendedSlot, type UnattendedState } from './unattended-state.ts';
|
|
5
6
|
/** Families whose sessions Unattended Mode covers in v1. */
|
|
6
7
|
export declare const UNATTENDED_FAMILIES: readonly string[];
|
|
@@ -16,6 +17,11 @@ export interface UnattendedStatus extends UnattendedState {
|
|
|
16
17
|
schedule: UnattendedSlot[];
|
|
17
18
|
/** Open Pending Decisions. */
|
|
18
19
|
pending: number;
|
|
20
|
+
/**
|
|
21
|
+
* Attended Sessions (ADR-0075): Claude sessions someone typed into within the last 30 minutes, which ask as usual
|
|
22
|
+
* while the mode stays on for the rest. Latest end first.
|
|
23
|
+
*/
|
|
24
|
+
attended: AttendedSession[];
|
|
19
25
|
coverage: Record<string, UnattendedCoverage>;
|
|
20
26
|
/** When `on --slot-end` would end: the end of the current or next Slot, when that is within 72 hours. */
|
|
21
27
|
slotEnd?: string;
|
|
@@ -132,8 +138,10 @@ export declare const unattendedClock: (iso: string, now: Date, zh?: boolean) =>
|
|
|
132
138
|
/**
|
|
133
139
|
* Unattended Mode's session hooks: before the ask tool and when the model ends its turn (`Stop`, which keeps a turn
|
|
134
140
|
* that ended on a question going once) in Claude and Codex; and in Claude on every permission request Claude Code is
|
|
135
|
-
* about to show, every MCP server form (`Elicitation`),
|
|
136
|
-
*
|
|
141
|
+
* about to show, every MCP server form (`Elicitation`), every turn that failed on an API error (`StopFailure`, in the
|
|
142
|
+
* background with `asyncRewake`, so its exit 2 wakes the session: Turn Retry, ADR-0067), and every prompt
|
|
143
|
+
* (`UserPromptSubmit`, in the background with `async`, so it never holds a prompt back: Attended Sessions, ADR-0075).
|
|
144
|
+
* Codex has no such events for them; its own approval prompts and failed turns are not covered.
|
|
137
145
|
*/
|
|
138
146
|
export declare function unattendedHookPart(): SessionHookPart;
|
|
139
147
|
/** The line a Claude Launch prints when the user's own `--settings` leaves no room for the hook. */
|
|
@@ -8,6 +8,7 @@ import { editConfigUnattended } from './config.js';
|
|
|
8
8
|
import { UserError } from './errors.js';
|
|
9
9
|
import { ownedFolder, writeFileAtomic } from './fs-safe.js';
|
|
10
10
|
import { sidebyHookCommand } from './session-hooks.js';
|
|
11
|
+
import { ATTENDED_HOOK_TIMEOUT_S, listAttended } from './unattended-attended.js';
|
|
11
12
|
import { listPendingDecisions } from './unattended-pending.js';
|
|
12
13
|
import { RETRY_HOOK_TIMEOUT_S } from './unattended-retry.js';
|
|
13
14
|
import { clearUnattendedOverride, clockText, ensureUnattendedDir, MAX_MANUAL_MS, parseClock, parseDays, parseSlot, readUnattendedConfig, readUnattendedOverride, scheduleStretchAt, slotEnd, UNATTENDED_ENV, unattendedState, writeUnattendedOverride, } from './unattended-state.js';
|
|
@@ -60,6 +61,7 @@ export async function unattendedStatus(opts) {
|
|
|
60
61
|
configured,
|
|
61
62
|
schedule,
|
|
62
63
|
pending: (await listPendingDecisions(opts.paths.stateDir, { now, prune: !opts.readOnly })).length,
|
|
64
|
+
attended: await listAttended(opts.paths.stateDir, now, { prune: !opts.readOnly }),
|
|
63
65
|
coverage: coverageOf(opts.families, configured),
|
|
64
66
|
...(end !== undefined && end - now.getTime() <= MAX_MANUAL_MS
|
|
65
67
|
? { slotEnd: new Date(end).toISOString() }
|
|
@@ -292,8 +294,10 @@ export const unattendedClock = (iso, now, zh = false) => clockText(Date.parse(is
|
|
|
292
294
|
/**
|
|
293
295
|
* Unattended Mode's session hooks: before the ask tool and when the model ends its turn (`Stop`, which keeps a turn
|
|
294
296
|
* that ended on a question going once) in Claude and Codex; and in Claude on every permission request Claude Code is
|
|
295
|
-
* about to show, every MCP server form (`Elicitation`),
|
|
296
|
-
*
|
|
297
|
+
* about to show, every MCP server form (`Elicitation`), every turn that failed on an API error (`StopFailure`, in the
|
|
298
|
+
* background with `asyncRewake`, so its exit 2 wakes the session: Turn Retry, ADR-0067), and every prompt
|
|
299
|
+
* (`UserPromptSubmit`, in the background with `async`, so it never holds a prompt back: Attended Sessions, ADR-0075).
|
|
300
|
+
* Codex has no such events for them; its own approval prompts and failed turns are not covered.
|
|
297
301
|
*/
|
|
298
302
|
export function unattendedHookPart() {
|
|
299
303
|
const command = (family, event = 'PreToolUse') => sidebyHookCommand('unattended-hook', family, event);
|
|
@@ -313,6 +317,11 @@ export function unattendedHookPart() {
|
|
|
313
317
|
hooks: [{ ...claude('StopFailure')[0], asyncRewake: true, timeout: RETRY_HOOK_TIMEOUT_S }],
|
|
314
318
|
},
|
|
315
319
|
],
|
|
320
|
+
// Waits up to 10 seconds for the prompt's transcript line; `async`, so the prompt goes on at once and nothing
|
|
321
|
+
// the hook prints or returns reaches the session.
|
|
322
|
+
UserPromptSubmit: [
|
|
323
|
+
{ hooks: [{ ...claude('UserPromptSubmit')[0], async: true, timeout: ATTENDED_HOOK_TIMEOUT_S }] },
|
|
324
|
+
],
|
|
316
325
|
},
|
|
317
326
|
codex: {
|
|
318
327
|
PreToolUse: [`{matcher="^request_user_input$",${codex('PreToolUse')}}`],
|
package/dist/src/handoff/hook.js
CHANGED
|
@@ -6,6 +6,8 @@ import { randomBytes } from 'node:crypto';
|
|
|
6
6
|
import { readFile, rm, stat } from 'node:fs/promises';
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import { BRIEF_DONE, FILES, HANDOFF_ENV, readJsonFile, writeJsonFile, } from '../core/handoff-chain.js';
|
|
9
|
+
import { resolvePaths } from '../core/paths.js';
|
|
10
|
+
import { progressReminderTurn } from '../core/progress-state.js';
|
|
9
11
|
import { claudeHookReader } from '../families/claude/handoff-hook.js';
|
|
10
12
|
import { codexHookReader } from '../families/codex/handoff-hook.js';
|
|
11
13
|
import { grokHookReader } from '../families/grok/handoff-hook.js';
|
|
@@ -121,6 +123,10 @@ export async function decide(opts) {
|
|
|
121
123
|
const reason = field(input, 'reason');
|
|
122
124
|
if (reason && reason !== 'end_turn')
|
|
123
125
|
return {};
|
|
126
|
+
// A turn a Progress Reminder started while the session waits on background work (spec §3.42, ADR-0076): handled so
|
|
127
|
+
// that handing over goes as it would without the reminder. A record that is missing or late says no: an ordinary turn.
|
|
128
|
+
const reminder = family === 'claude' &&
|
|
129
|
+
(await progressReminderTurn(resolvePaths(env).stateDir, sessionId, field(input, 'prompt_id', 'promptId')));
|
|
124
130
|
// A finished turn means a Host kept at its limit has continued: a later `handoff ready` waits for the turn again.
|
|
125
131
|
const waitingFile = join(dir, FILES.waiting);
|
|
126
132
|
const held = await readJsonFile(waitingFile);
|
|
@@ -134,8 +140,10 @@ export async function decide(opts) {
|
|
|
134
140
|
}
|
|
135
141
|
if (!usable)
|
|
136
142
|
return {};
|
|
137
|
-
// The turn that just ended joins the window's recent turns before anything is judged (ADR-0032).
|
|
138
|
-
|
|
143
|
+
// The turn that just ended joins the window's recent turns before anything is judged (ADR-0032). A reminder's turn
|
|
144
|
+
// does not: what the wait used counts toward the next real turn, as without reminders, so one wait is not cut into
|
|
145
|
+
// small turns that would move the adaptive level later.
|
|
146
|
+
if (windows && !reminder)
|
|
139
147
|
await keep(recordTurn(st, windows));
|
|
140
148
|
const notice = await waitOutput();
|
|
141
149
|
if (notice)
|
|
@@ -148,7 +156,10 @@ export async function decide(opts) {
|
|
|
148
156
|
if (st.thresholdSentAt) {
|
|
149
157
|
if (await briefFinished(usable.brief, Date.parse(st.thresholdSentAt)))
|
|
150
158
|
await ready({ trigger: 'threshold', brief: usable.brief, briefSource: 'agent', ...window });
|
|
151
|
-
|
|
159
|
+
// A reminder's turn always has `stop_hook_active` (a hook woke it), but nobody asked it for the Brief yet: hold
|
|
160
|
+
// it once like an ordinary turn instead of handing over without the agent's Brief.
|
|
161
|
+
else if (!st.stopBlocked &&
|
|
162
|
+
(reminder || (input.stop_hook_active !== true && input.stopHookActive !== true))) {
|
|
152
163
|
await keep({ ...st, stopBlocked: true });
|
|
153
164
|
return { output: blockOutput(stopMessage(usable.brief)) };
|
|
154
165
|
}
|
|
@@ -164,7 +175,11 @@ export async function decide(opts) {
|
|
|
164
175
|
return {};
|
|
165
176
|
}
|
|
166
177
|
await keep({ ...st, thresholdSentAt: now.toISOString(), thresholdWindow: crossed, stopBlocked: true });
|
|
167
|
-
|
|
178
|
+
// A reminder's turn ends while background work runs: the message IdleWatch would have sent.
|
|
179
|
+
const text = reminder
|
|
180
|
+
? idleThresholdMessage(usable.brief, crossed)
|
|
181
|
+
: thresholdMessage(usable.brief, crossed);
|
|
182
|
+
return { output: blockOutput(text) };
|
|
168
183
|
}
|
|
169
184
|
return {};
|
|
170
185
|
}
|
|
@@ -212,13 +212,19 @@ function run(argv) {
|
|
|
212
212
|
if (seen && seen === iconSeen) iconStable = seen;
|
|
213
213
|
iconSeen = seen;
|
|
214
214
|
}
|
|
215
|
-
// Drops the menu from the icon when it shows
|
|
216
|
-
//
|
|
215
|
+
// Drops the menu from the icon when it shows. When the icon is hidden, such as by a full menu bar or under the
|
|
216
|
+
// notch, clicking it would drop the menu in the screen's top left corner, so the menu drops below the right end of
|
|
217
|
+
// the menu bar instead, where the icon would be, on the screen the user is typing in.
|
|
217
218
|
function openMenu() {
|
|
218
219
|
var w = item.button.window;
|
|
219
220
|
if (w && !w.isNil() && (w.occlusionState & $.NSWindowOcclusionStateVisible)) { item.button.performClick(null); return; }
|
|
221
|
+
var screen = $.NSScreen.mainScreen;
|
|
222
|
+
if (!screen || screen.isNil()) screen = $.NSScreen.screens.firstObject;
|
|
223
|
+
var v = screen.visibleFrame;
|
|
224
|
+
var at = $.NSMakePoint(Math.max(v.origin.x, v.origin.x + v.size.width - Number(item.menu.size.width) - 8), v.origin.y + v.size.height);
|
|
220
225
|
app.activateIgnoringOtherApps(true);
|
|
221
|
-
|
|
226
|
+
// nil, not null: the bridge turns null into NSNull, which AppKit asks for its window and throws.
|
|
227
|
+
item.menu.popUpMenuPositioningItemAtLocationInView($(), at, $());
|
|
222
228
|
app.deactivate;
|
|
223
229
|
}
|
|
224
230
|
function registerHotkey() {
|
|
@@ -9,7 +9,16 @@ export interface NetworkHookDeps {
|
|
|
9
9
|
sleep?: Sleep;
|
|
10
10
|
/** Starts the detached refresh; tests replace it. */
|
|
11
11
|
background?: (family: string, env: Env) => void;
|
|
12
|
+
/** What the Host hands the hook on stdin; without it the hook decides as if it were given nothing. */
|
|
13
|
+
input?: AsyncIterable<string | Uint8Array> | string;
|
|
14
|
+
/** Whether the Host that started the hook is gone (`ppid` 1 by default): nothing is left to wake. */
|
|
15
|
+
parentGone?: () => boolean;
|
|
12
16
|
}
|
|
17
|
+
/** `Held` asks again after these waits, then every `HELD_EVERY_MS`: one request each time. */
|
|
18
|
+
export declare const HELD_DELAYS_MS: readonly [15000, 30000];
|
|
19
|
+
export declare const HELD_EVERY_MS = 60000;
|
|
20
|
+
/** `Held` ends by itself after this long, two minutes before the 5 hours Claude Code gives it (core/network.ts). */
|
|
21
|
+
export declare const HELD_BUDGET_MS: number;
|
|
13
22
|
/** Returns the exit code: 0 lets the Host go on, 2 blocks (the reason is written to `err`). */
|
|
14
23
|
export declare function runNetworkHook(argv: readonly string[], env: Env, err: {
|
|
15
24
|
write(s: string): unknown;
|