sideby 0.38.1 → 0.40.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.
Files changed (51) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +6 -0
  3. package/dist/src/cli/commands.js +120 -1
  4. package/dist/src/cli/json-schemas.js +44 -2
  5. package/dist/src/cli/main.js +37 -0
  6. package/dist/src/core/cli-commands.js +26 -2
  7. package/dist/src/core/config.d.ts +14 -0
  8. package/dist/src/core/config.js +21 -0
  9. package/dist/src/core/launch.d.ts +5 -0
  10. package/dist/src/core/launch.js +11 -1
  11. package/dist/src/core/progress-state.d.ts +94 -0
  12. package/dist/src/core/progress-state.js +240 -0
  13. package/dist/src/core/progress.d.ts +36 -0
  14. package/dist/src/core/progress.js +77 -0
  15. package/dist/src/core/prompt-origin.d.ts +40 -0
  16. package/dist/src/core/prompt-origin.js +98 -0
  17. package/dist/src/core/search-catalog.js +43 -0
  18. package/dist/src/core/unattended-attended.d.ts +109 -0
  19. package/dist/src/core/unattended-attended.js +337 -0
  20. package/dist/src/core/unattended-pending.d.ts +14 -2
  21. package/dist/src/core/unattended-pending.js +27 -3
  22. package/dist/src/core/unattended-state.d.ts +19 -1
  23. package/dist/src/core/unattended-state.js +31 -5
  24. package/dist/src/core/unattended-wait.d.ts +86 -0
  25. package/dist/src/core/unattended-wait.js +125 -0
  26. package/dist/src/core/unattended.d.ts +29 -2
  27. package/dist/src/core/unattended.js +48 -6
  28. package/dist/src/handoff/hook.js +19 -4
  29. package/dist/src/network/hook.js +4 -8
  30. package/dist/src/panel/handler.d.ts +3 -0
  31. package/dist/src/panel/handler.js +31 -1
  32. package/dist/src/panel/i18n.d.ts +27 -0
  33. package/dist/src/panel/i18n.js +56 -2
  34. package/dist/src/panel/page-script.js +118 -4
  35. package/dist/src/panel/page-styles.js +21 -0
  36. package/dist/src/progress/hook.d.ts +57 -0
  37. package/dist/src/progress/hook.js +258 -0
  38. package/dist/src/runtime.d.ts +9 -0
  39. package/dist/src/runtime.js +45 -2
  40. package/dist/src/types.d.ts +5 -0
  41. package/dist/src/unattended/hook.d.ts +26 -6
  42. package/dist/src/unattended/hook.js +361 -25
  43. package/package.json +1 -1
  44. package/schemas/config.json +27 -0
  45. package/schemas/progress.json +137 -0
  46. package/schemas/unattended-defer.json +5 -0
  47. package/schemas/unattended-pending.json +5 -0
  48. package/schemas/unattended.json +54 -2
  49. package/skills/sideby/SKILL.md +4 -1
  50. package/skills/sideby/references/progress.md +25 -0
  51. package/skills/sideby/references/unattended.md +25 -3
@@ -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
+ }
@@ -17,6 +17,11 @@ export interface PendingDecision {
17
17
  agentType?: string;
18
18
  /** The question and its options, the tool and what it was to do, or the deferred text; at most 4000 characters. */
19
19
  text: string;
20
+ /**
21
+ * Minutes the question or confirmation was on screen with nobody answering before the session went on without an
22
+ * answer (Answer Wait, ADR-0077). Absent when it was never shown.
23
+ */
24
+ waited?: number;
20
25
  /** When the user marked it done (ISO). */
21
26
  doneAt?: string;
22
27
  }
@@ -28,12 +33,19 @@ export declare const pendingDir: (stateDir: string) => string;
28
33
  /** At most `PENDING_TEXT_MAX` characters (whole characters, never half of one), ending in `…` when cut. */
29
34
  export declare function clipPendingText(text: string): string;
30
35
  /**
31
- * Keeps one Pending Decision and returns it. With `dedupe`, an open one of the same kind, session and text is
32
- * returned instead of a second copy (a model that asks the same question twice leaves one).
36
+ * Keeps one Pending Decision and returns it. With `dedupe`, an open one of the same kind, session and text (and both
37
+ * having waited on screen, or neither) is returned instead of a second copy (a model that asks the same question twice
38
+ * leaves one).
33
39
  */
34
40
  export declare function addPendingDecision(stateDir: string, input: PendingInput, at?: Date, opts?: {
35
41
  dedupe?: boolean;
36
42
  }): Promise<PendingDecision>;
43
+ /**
44
+ * Takes back a Pending Decision the caller has just kept, when what it was about ended while it was being kept (Answer
45
+ * Wait: a person answered meanwhile). Only that exact one: the id it got back, still open and kept at `at`; an older
46
+ * one the dedupe returned is left alone. Best effort.
47
+ */
48
+ export declare function withdrawPendingDecision(stateDir: string, kept: PendingDecision, at: Date): Promise<void>;
37
49
  /**
38
50
  * The Pending Decisions, oldest first: open ones, or with `all` the done ones too. Deletes the files of those done
39
51
  * more than 30 days ago.
@@ -45,6 +45,7 @@ function parse(value) {
45
45
  return undefined;
46
46
  const opt = (k) => typeof v[k] === 'string' && v[k] ? { [k]: v[k].slice(0, 4096) } : {};
47
47
  const done = typeof v.doneAt === 'string' && Number.isFinite(Date.parse(v.doneAt)) ? { doneAt: v.doneAt } : {};
48
+ const waited = validWaited(v.waited) ? { waited: v.waited } : {};
48
49
  return {
49
50
  id: v.id,
50
51
  at: v.at,
@@ -56,6 +57,7 @@ function parse(value) {
56
57
  ...opt('agentId'),
57
58
  ...opt('agentType'),
58
59
  text: clipPendingText(v.text),
60
+ ...waited,
59
61
  ...done,
60
62
  };
61
63
  }
@@ -87,15 +89,23 @@ async function readAll(stateDir) {
87
89
  .filter((d) => d !== undefined)
88
90
  .sort((a, b) => Date.parse(a.at) - Date.parse(b.at) || a.id.localeCompare(b.id));
89
91
  }
92
+ /** Whole minutes, at most a week. */
93
+ const validWaited = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 7 * 24 * 60;
90
94
  const fileOf = (stateDir, id) => join(pendingDir(stateDir), `${id}.json`);
91
95
  /**
92
- * Keeps one Pending Decision and returns it. With `dedupe`, an open one of the same kind, session and text is
93
- * returned instead of a second copy (a model that asks the same question twice leaves one).
96
+ * Keeps one Pending Decision and returns it. With `dedupe`, an open one of the same kind, session and text (and both
97
+ * having waited on screen, or neither) is returned instead of a second copy (a model that asks the same question twice
98
+ * leaves one).
94
99
  */
95
100
  export async function addPendingDecision(stateDir, input, at = new Date(), opts = {}) {
96
101
  const text = clipPendingText(input.text);
97
102
  if (opts.dedupe) {
98
- const same = (await readAll(stateDir)).find((d) => !d.doneAt && d.kind === input.kind && d.sessionId === input.sessionId && d.text === text);
103
+ const same = (await readAll(stateDir)).find((d) => !d.doneAt &&
104
+ d.kind === input.kind &&
105
+ d.sessionId === input.sessionId &&
106
+ d.text === text &&
107
+ // One refused at once and one that went on after a wait are two things the user should see.
108
+ Boolean(d.waited) === Boolean(input.waited));
99
109
  if (same)
100
110
  return same;
101
111
  }
@@ -111,10 +121,24 @@ export async function addPendingDecision(stateDir, input, at = new Date(), opts
111
121
  ...(input.agentId ? { agentId: input.agentId } : {}),
112
122
  ...(input.agentType ? { agentType: input.agentType } : {}),
113
123
  text,
124
+ ...(validWaited(input.waited) ? { waited: input.waited } : {}),
114
125
  };
115
126
  await writeFileAtomic(join(dir, `${decision.id}.json`), `${JSON.stringify(decision)}\n`, 0o600);
116
127
  return decision;
117
128
  }
129
+ /**
130
+ * Takes back a Pending Decision the caller has just kept, when what it was about ended while it was being kept (Answer
131
+ * Wait: a person answered meanwhile). Only that exact one: the id it got back, still open and kept at `at`; an older
132
+ * one the dedupe returned is left alone. Best effort.
133
+ */
134
+ export async function withdrawPendingDecision(stateDir, kept, at) {
135
+ if (kept.at !== at.toISOString() || kept.doneAt)
136
+ return;
137
+ const dir = await existingDir(stateDir);
138
+ if (!dir || !ID.test(kept.id))
139
+ return;
140
+ await rm(join(dir, `${kept.id}.json`), { force: true }).catch(() => { });
141
+ }
118
142
  /**
119
143
  * The Pending Decisions, oldest first: open ones, or with `all` the done ones too. Deletes the files of those done
120
144
  * more than 30 days ago.
@@ -105,10 +105,28 @@ export declare function unattendedState(input: {
105
105
  }): UnattendedState;
106
106
  /** Reads a small JSON file that must be a plain file (opened without following a link); undefined otherwise. */
107
107
  export declare function readSmallJson(file: string, max?: number): Promise<unknown>;
108
- /** What the config file says about Unattended Mode, read by hand (no schema): whether it has the section, and its Schedule. */
108
+ /**
109
+ * Answer Wait (spec §3.37 item 7, ADR-0077): how many minutes a question or a confirmation shown in a Claude session
110
+ * waits for a person before, with Unattended Mode on, the session goes on without an answer. Config
111
+ * `unattended.answerWait`: whole minutes, or `false` for never.
112
+ */
113
+ export declare const ANSWER_WAIT_DEFAULT = 10;
114
+ export declare const ANSWER_WAIT_MIN = 1;
115
+ export declare const ANSWER_WAIT_MAX = 120;
116
+ /** The waits the Panel offers; any other one the CLI set is shown beside them. */
117
+ export declare const ANSWER_WAIT_CHOICES: readonly number[];
118
+ /** Whether `v` is a wait the config takes: whole minutes from 1 to 120. */
119
+ export declare const validAnswerWait: (v: unknown) => v is number;
120
+ /** The wait the config's `unattended.answerWait` value means: minutes, or null for never. Anything else is the default. */
121
+ export declare function parseAnswerWait(value: unknown): number | null;
122
+ /**
123
+ * What the config file says about Unattended Mode, read by hand (no schema): whether it has the section, its Schedule
124
+ * and its Answer Wait (minutes, or null for never).
125
+ */
109
126
  export declare function readUnattendedConfig(configFile: string): Promise<{
110
127
  configured: boolean;
111
128
  schedule: UnattendedSlot[];
129
+ answerWait: number | null;
112
130
  }>;
113
131
  /**
114
132
  * The manual state as the file holds it, expired or not; undefined when there is none, it is not one, or
@@ -307,21 +307,47 @@ export async function readSmallJson(file, max = 1024 * 1024) {
307
307
  return undefined;
308
308
  }
309
309
  }
310
- /** What the config file says about Unattended Mode, read by hand (no schema): whether it has the section, and its Schedule. */
310
+ /**
311
+ * Answer Wait (spec §3.37 item 7, ADR-0077): how many minutes a question or a confirmation shown in a Claude session
312
+ * waits for a person before, with Unattended Mode on, the session goes on without an answer. Config
313
+ * `unattended.answerWait`: whole minutes, or `false` for never.
314
+ */
315
+ export const ANSWER_WAIT_DEFAULT = 10;
316
+ export const ANSWER_WAIT_MIN = 1;
317
+ export const ANSWER_WAIT_MAX = 120;
318
+ /** The waits the Panel offers; any other one the CLI set is shown beside them. */
319
+ export const ANSWER_WAIT_CHOICES = [5, 10, 15, 30, 60];
320
+ /** Whether `v` is a wait the config takes: whole minutes from 1 to 120. */
321
+ export const validAnswerWait = (v) => typeof v === 'number' && Number.isInteger(v) && v >= ANSWER_WAIT_MIN && v <= ANSWER_WAIT_MAX;
322
+ /** The wait the config's `unattended.answerWait` value means: minutes, or null for never. Anything else is the default. */
323
+ export function parseAnswerWait(value) {
324
+ if (value === false)
325
+ return null;
326
+ return validAnswerWait(value) ? value : ANSWER_WAIT_DEFAULT;
327
+ }
328
+ /**
329
+ * What the config file says about Unattended Mode, read by hand (no schema): whether it has the section, its Schedule
330
+ * and its Answer Wait (minutes, or null for never).
331
+ */
311
332
  export async function readUnattendedConfig(configFile) {
333
+ const none = { configured: false, schedule: [], answerWait: ANSWER_WAIT_DEFAULT };
312
334
  // The config may be a link a dotfiles manager keeps; reading through it is fine.
313
335
  try {
314
336
  const text = await readFile(configFile, 'utf8');
315
337
  if (text.length > 4 * 1024 * 1024)
316
- return { configured: false, schedule: [] };
338
+ return none;
317
339
  const config = JSON.parse(text);
318
340
  const section = config && typeof config === 'object' ? config.unattended : undefined;
319
341
  if (!section || typeof section !== 'object')
320
- return { configured: false, schedule: [] };
321
- return { configured: true, schedule: parseSchedule(section.schedule) };
342
+ return none;
343
+ return {
344
+ configured: true,
345
+ schedule: parseSchedule(section.schedule),
346
+ answerWait: parseAnswerWait(section.answerWait),
347
+ };
322
348
  }
323
349
  catch {
324
- return { configured: false, schedule: [] };
350
+ return none;
325
351
  }
326
352
  }
327
353
  /**
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The `timeout` of the hook entries that wait. A question shown at 18:00 with Unattended Mode off still goes on when a
3
+ * Slot begins at 23:00; Claude Code ends the hook after this and the question then simply stays on screen.
4
+ */
5
+ export declare const ANSWER_HOOK_TIMEOUT_S: number;
6
+ /** How often a waiting hook looks again: an answered question frees its hook within this. */
7
+ export declare const WATCH_POLL_MS = 3000;
8
+ /** What the session record says is on screen now. */
9
+ export interface ScreenMark {
10
+ status: string;
11
+ /** `statusUpdatedAt`: changes whenever the dialog or the wait ends or another one takes its place. */
12
+ at: number;
13
+ }
14
+ /** Claude Code's config folder for the session: `CLAUDE_CONFIG_DIR`, else `~/.claude`. */
15
+ export declare function claudeConfigDir(env: {
16
+ HOME?: string | undefined;
17
+ CLAUDE_CONFIG_DIR?: string | undefined;
18
+ }): string;
19
+ /**
20
+ * The status the record of process `pid` holds for session `sessionId`; undefined when it cannot be read, is a link,
21
+ * names another session, or lacks `status` or `statusUpdatedAt`.
22
+ */
23
+ export declare function readScreen(env: {
24
+ HOME?: string | undefined;
25
+ CLAUDE_CONFIG_DIR?: string | undefined;
26
+ }, pid: number, sessionId: string): Promise<ScreenMark | undefined>;
27
+ /** What a waiting hook reads afresh at every look: the wait (minutes, or null for never) and whether the mode is on. */
28
+ export interface WaitSettings {
29
+ wait: number | null;
30
+ on: boolean;
31
+ }
32
+ /**
33
+ * Waits while the session shows `expect` (`waiting`: a question or a permission prompt; `idle`: a turn ended and the
34
+ * session waits for a prompt). Returns the record's mark once the wait has passed since `startedAt` and Unattended
35
+ * Mode is on, so the caller can look once more just before it acts (`lastLook`), and undefined as soon as anything
36
+ * says a person (or anything else) moved on or it cannot tell: there is no record for the session, it does not show
37
+ * `expect` within 2 seconds, it shows a dialog put up after `shownBy` (the dialog this hook was started for was on
38
+ * screen before the hook began, so a later one is another dialog: the person answered this one meanwhile), it changes
39
+ * (another status or another `statusUpdatedAt`), it cannot be read, `moved` says so (a person typed after the turn
40
+ * the hook watches), the Host is gone, or the wait was set to never. While the mode is off past the wait it keeps
41
+ * waiting; Claude Code's `timeout` ends it in the end. With `from` it goes on watching that mark, without looking for it
42
+ * first.
43
+ */
44
+ export declare function watchScreen(opts: {
45
+ env: {
46
+ HOME?: string | undefined;
47
+ CLAUDE_CONFIG_DIR?: string | undefined;
48
+ };
49
+ pid: number;
50
+ sessionId: string;
51
+ expect: 'waiting' | 'idle';
52
+ startedAt: number;
53
+ clock: () => number;
54
+ sleep: (ms: number) => Promise<void>;
55
+ parentGone: () => boolean;
56
+ settings: () => Promise<WaitSettings>;
57
+ /** Whether something sideby noted says the session moved on since `startedAt`; checked at every look. */
58
+ moved?: () => Promise<boolean>;
59
+ /** The latest `statusUpdatedAt` the watched mark may have (when the hook began). */
60
+ shownBy?: number;
61
+ /** A mark already found: go on watching it. */
62
+ from?: ScreenMark;
63
+ }): Promise<ScreenMark | undefined>;
64
+ /**
65
+ * The last look before a waiting hook acts (and again after it kept the Pending Decision), with the wait and the mode
66
+ * read afresh: `act` while the Host is still there, the record still shows `mark`, nothing sideby noted says the
67
+ * session moved on, the wait (as set now) has passed and Unattended Mode is on; `wait` when all that holds but the
68
+ * wait was made longer and has not passed, or the mode went off: the hook goes on watching; `stop` for anything else,
69
+ * the wait set to never, or anything it cannot read: the hook then lets it be.
70
+ */
71
+ export declare function lastLook(opts: {
72
+ env: {
73
+ HOME?: string | undefined;
74
+ CLAUDE_CONFIG_DIR?: string | undefined;
75
+ };
76
+ pid: number;
77
+ sessionId: string;
78
+ mark: ScreenMark;
79
+ startedAt: number;
80
+ clock: () => number;
81
+ parentGone: () => boolean;
82
+ settings: () => Promise<WaitSettings>;
83
+ moved?: () => Promise<boolean>;
84
+ }): Promise<'act' | 'wait' | 'stop'>;
85
+ /** Whole minutes from `startedAt` to `now`, at least 1: how long the question waited, as the user reads it. */
86
+ export declare const waitedMinutes: (startedAt: number, now: number) => number;