sideby 0.39.0 → 0.40.1

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 (41) hide show
  1. package/README.md +2 -2
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +34 -3
  4. package/dist/src/cli/json-schemas.js +9 -2
  5. package/dist/src/cli/main.js +10 -2
  6. package/dist/src/core/cli-commands.js +12 -0
  7. package/dist/src/core/config.d.ts +1 -0
  8. package/dist/src/core/config.js +3 -0
  9. package/dist/src/core/handoff-run.js +192 -175
  10. package/dist/src/core/progress-state.d.ts +21 -7
  11. package/dist/src/core/progress-state.js +32 -8
  12. package/dist/src/core/search-catalog.js +18 -0
  13. package/dist/src/core/session-hooks.d.ts +7 -0
  14. package/dist/src/core/session-hooks.js +27 -0
  15. package/dist/src/core/unattended-pending.d.ts +14 -2
  16. package/dist/src/core/unattended-pending.js +27 -3
  17. package/dist/src/core/unattended-state.d.ts +19 -1
  18. package/dist/src/core/unattended-state.js +31 -5
  19. package/dist/src/core/unattended-wait.d.ts +86 -0
  20. package/dist/src/core/unattended-wait.js +125 -0
  21. package/dist/src/core/unattended.d.ts +19 -0
  22. package/dist/src/core/unattended.js +37 -4
  23. package/dist/src/families/claude/handoff.js +3 -1
  24. package/dist/src/panel/handler.js +16 -1
  25. package/dist/src/panel/i18n.d.ts +9 -0
  26. package/dist/src/panel/i18n.js +26 -8
  27. package/dist/src/panel/page-script.js +51 -2
  28. package/dist/src/panel/page-styles.js +7 -0
  29. package/dist/src/progress/hook.d.ts +7 -0
  30. package/dist/src/progress/hook.js +18 -11
  31. package/dist/src/types.d.ts +5 -0
  32. package/dist/src/unattended/hook.d.ts +21 -6
  33. package/dist/src/unattended/hook.js +261 -19
  34. package/package.json +2 -2
  35. package/schemas/config.json +14 -0
  36. package/schemas/unattended-defer.json +5 -0
  37. package/schemas/unattended-pending.json +5 -0
  38. package/schemas/unattended.json +16 -2
  39. package/skills/sideby/SKILL.md +3 -2
  40. package/skills/sideby/references/progress.md +3 -3
  41. package/skills/sideby/references/unattended.md +16 -2
@@ -4,7 +4,7 @@ export declare const PROGRESS_ENV = "SIDEBY_PROGRESS_EVERY";
4
4
  export declare const PROGRESS_MIN = 1;
5
5
  export declare const PROGRESS_MAX = 240;
6
6
  /** What turning it on picks when no interval is given. */
7
- export declare const PROGRESS_DEFAULT = 10;
7
+ export declare const PROGRESS_DEFAULT = 30;
8
8
  /** The intervals the Panel offers. */
9
9
  export declare const PROGRESS_CHOICES: readonly number[];
10
10
  /** The `timeout` of the `Stop` entry, in seconds (the same as Auto Handoff's IdleWatch). */
@@ -26,7 +26,7 @@ export interface WatchRecord {
26
26
  id: string;
27
27
  /** When the session began waiting: kept across reminder turns. */
28
28
  since: string;
29
- /** When the `Stop` that started this watch came. */
29
+ /** When the hook of the `Stop` that started this watch began, before reading its input: the order of the Stops. */
30
30
  at: string;
31
31
  /** When this watch woke the session. */
32
32
  wokeAt?: string;
@@ -49,17 +49,31 @@ export interface LockWait {
49
49
  export declare function readWatch(stateDir: string, sessionId: string): Promise<WatchRecord | undefined>;
50
50
  /**
51
51
  * Replaces the session's watch (file 600, atomically) under the session's lock, so it never lands between another
52
- * watch's last check and its `wokeAt`. False when the lock stays held: then nothing is written and the caller must not
53
- * act as the session's watch. Throws when the folder is not safe to use.
52
+ * watch's last check and its `wokeAt`, unless the record holds the watch of a later `Stop` (its `at` is later): a
53
+ * `Stop` whose hook got its input or the lock late never ends the watch of the turn after it. False when the lock
54
+ * stays held or a later watch is kept: then nothing is written and the caller must not act as the session's watch.
55
+ * Throws when the folder is not safe to use.
54
56
  */
55
57
  export declare function writeWatch(stateDir: string, sessionId: string, record: WatchRecord, opts?: LockWait): Promise<boolean>;
56
58
  /**
57
- * Marks the watch `id` woken at `at`, only while the session's record is still that watch: the check and the write
58
- * hold the session's lock, so a later `Stop` replaces the record before or after, never in between. False when the
59
- * record is another watch's, is missing, or the lock stays held (`beforeWrite` runs inside the lock, for tests).
59
+ * Whether the session's latest prompt is not the one the watching `Stop` ended, so a turn began after it: compared by
60
+ * the prompt's id (`own`, hashed), never by time, because the next prompt's record can be written before the watch
61
+ * starts. Only a `Stop` without an id falls back to whether the record came after it (`stopAt`).
62
+ */
63
+ export declare function newerPrompt(p: PromptRecord | undefined, own: string | undefined, stopAt: number): boolean;
64
+ /**
65
+ * Marks the watch `id` woken at `at`, only while the session's record is still that watch and, with `turn`, no
66
+ * prompt came after the turn the watch's `Stop` ended (`newerPrompt`): a reminder sent then would only queue behind
67
+ * that turn and cost a model call of its own. The checks and the write hold the session's lock, so a later `Stop`
68
+ * replaces the record, or a prompt is noted, before or after, never in between. False when the record is another
69
+ * watch's, is missing, a newer prompt is noted, or the lock stays held (`beforeWrite` runs inside the lock, for tests).
60
70
  */
61
71
  export declare function markWatchWoken(stateDir: string, sessionId: string, id: string, at: Date, deps?: {
62
72
  beforeWrite?: () => Promise<void>;
73
+ turn?: {
74
+ prompt?: string;
75
+ stopAt: number;
76
+ };
63
77
  }): Promise<boolean>;
64
78
  export declare function readPromptRecord(stateDir: string, sessionId: string): Promise<PromptRecord | undefined>;
65
79
  /**
@@ -14,7 +14,7 @@ export const PROGRESS_ENV = 'SIDEBY_PROGRESS_EVERY';
14
14
  export const PROGRESS_MIN = 1;
15
15
  export const PROGRESS_MAX = 240;
16
16
  /** What turning it on picks when no interval is given. */
17
- export const PROGRESS_DEFAULT = 10;
17
+ export const PROGRESS_DEFAULT = 30;
18
18
  /** The intervals the Panel offers. */
19
19
  export const PROGRESS_CHOICES = [5, 10, 15, 30, 60];
20
20
  /** The `timeout` of the `Stop` entry, in seconds (the same as Auto Handoff's IdleWatch). */
@@ -122,18 +122,37 @@ export async function readWatch(stateDir, sessionId) {
122
122
  }
123
123
  /**
124
124
  * Replaces the session's watch (file 600, atomically) under the session's lock, so it never lands between another
125
- * watch's last check and its `wokeAt`. False when the lock stays held: then nothing is written and the caller must not
126
- * act as the session's watch. Throws when the folder is not safe to use.
125
+ * watch's last check and its `wokeAt`, unless the record holds the watch of a later `Stop` (its `at` is later): a
126
+ * `Stop` whose hook got its input or the lock late never ends the watch of the turn after it. False when the lock
127
+ * stays held or a later watch is kept: then nothing is written and the caller must not act as the session's watch.
128
+ * Throws when the folder is not safe to use.
127
129
  */
128
130
  export async function writeWatch(stateDir, sessionId, record, opts = {}) {
129
131
  const dir = (await folder(stateDir, true));
130
- const done = await underLock(dir, hashOf(sessionId), opts.lockWait ?? LOCK_WAIT, () => writeFileAtomic(join(dir, watchName(sessionId)), `${JSON.stringify(record)}\n`, 0o600));
131
- return done !== undefined;
132
+ const done = await underLock(dir, hashOf(sessionId), opts.lockWait ?? LOCK_WAIT, async () => {
133
+ const file = join(dir, watchName(sessionId));
134
+ const old = parseWatch(await readSmallFile(file, RECORD_MAX));
135
+ if (old && Date.parse(old.at) > Date.parse(record.at))
136
+ return false;
137
+ await writeFileAtomic(file, `${JSON.stringify(record)}\n`, 0o600);
138
+ return true;
139
+ });
140
+ return done?.value === true;
141
+ }
142
+ /**
143
+ * Whether the session's latest prompt is not the one the watching `Stop` ended, so a turn began after it: compared by
144
+ * the prompt's id (`own`, hashed), never by time, because the next prompt's record can be written before the watch
145
+ * starts. Only a `Stop` without an id falls back to whether the record came after it (`stopAt`).
146
+ */
147
+ export function newerPrompt(p, own, stopAt) {
148
+ return Boolean(p && (own ? p.prompt !== own : Date.parse(p.at) > stopAt));
132
149
  }
133
150
  /**
134
- * Marks the watch `id` woken at `at`, only while the session's record is still that watch: the check and the write
135
- * hold the session's lock, so a later `Stop` replaces the record before or after, never in between. False when the
136
- * record is another watch's, is missing, or the lock stays held (`beforeWrite` runs inside the lock, for tests).
151
+ * Marks the watch `id` woken at `at`, only while the session's record is still that watch and, with `turn`, no
152
+ * prompt came after the turn the watch's `Stop` ended (`newerPrompt`): a reminder sent then would only queue behind
153
+ * that turn and cost a model call of its own. The checks and the write hold the session's lock, so a later `Stop`
154
+ * replaces the record, or a prompt is noted, before or after, never in between. False when the record is another
155
+ * watch's, is missing, a newer prompt is noted, or the lock stays held (`beforeWrite` runs inside the lock, for tests).
137
156
  */
138
157
  export async function markWatchWoken(stateDir, sessionId, id, at, deps = {}) {
139
158
  const dir = await folder(stateDir, false);
@@ -144,6 +163,11 @@ export async function markWatchWoken(stateDir, sessionId, id, at, deps = {}) {
144
163
  const fresh = parseWatch(await readSmallFile(file, RECORD_MAX));
145
164
  if (fresh?.id !== id)
146
165
  return false;
166
+ if (deps.turn) {
167
+ const p = parsePrompt(await readSmallFile(join(dir, promptName(sessionId)), RECORD_MAX));
168
+ if (newerPrompt(p, deps.turn.prompt, deps.turn.stopAt))
169
+ return false;
170
+ }
147
171
  await deps.beforeWrite?.();
148
172
  await writeFileAtomic(file, `${JSON.stringify({ ...fresh, wokeAt: at.toISOString() })}\n`, 0o600);
149
173
  return true;
@@ -348,6 +348,24 @@ const ENTRIES = [
348
348
  target: { action: 'unattended-add-slot', write: true },
349
349
  cliCommand: 'sideby unattended schedule add',
350
350
  },
351
+ {
352
+ id: 'action.unattended-wait',
353
+ kind: 'action',
354
+ title: { en: 'Choose how long a question waits for you', zh: '设置提问等你多久' },
355
+ synonyms: [
356
+ 'answer wait',
357
+ 'question timeout',
358
+ 'nobody answers',
359
+ 'go on without me',
360
+ '没人回答',
361
+ '问题没人回',
362
+ '自动按推荐继续',
363
+ '等多久',
364
+ ],
365
+ panel: at({ en: 'Unattended page', zh: '无人值守页' }, { en: 'If nobody answers', zh: '没人回答时' }),
366
+ target: { action: 'unattended-wait', write: true },
367
+ cliCommand: 'sideby unattended wait <minutes>|off',
368
+ },
351
369
  {
352
370
  id: 'action.network-guard',
353
371
  kind: 'action',
@@ -31,6 +31,13 @@ export declare function sessionHookArgs(family: string, stateDir: string, parts:
31
31
  * Code takes one `--settings`). Auto Handoff's own hooks and options come first and are kept as they are.
32
32
  */
33
33
  export declare function withClaudeHooks(hookArgs: readonly string[], extra: ClaudeHooks, out: string): Promise<string[]>;
34
+ /**
35
+ * Claude `--settings` arguments with `dirs` added to the file's `permissions.additionalDirectories`, written as `out`.
36
+ * Claude Code 2.1.326 asks the user to trust every `--add-dir` folder it has not seen before the session starts, and
37
+ * exits on "No"; a folder from `--settings` becomes a working directory without that question (tried with Claude Code
38
+ * 2.1.326 on 2026-11-17). Each folder is listed as given and, when a link leads to it, by its real path too.
39
+ */
40
+ export declare function withClaudeDirs(args: readonly string[], dirs: readonly string[], out: string): Promise<string[]>;
34
41
  /**
35
42
  * Auto Handoff's Claude hook arguments with the session's own sideby hooks (`sessionArgs`, from `sessionHookArgs`)
36
43
  * merged into one `--settings` file, written next to the session's file with `-handoff` added to its name.
@@ -92,6 +92,33 @@ export async function withClaudeHooks(hookArgs, extra, out) {
92
92
  const at = hookArgs.indexOf('--settings');
93
93
  return at === -1 ? [...hookArgs, '--settings', out] : hookArgs.map((a, i) => (i === at + 1 ? out : a));
94
94
  }
95
+ /**
96
+ * Claude `--settings` arguments with `dirs` added to the file's `permissions.additionalDirectories`, written as `out`.
97
+ * Claude Code 2.1.326 asks the user to trust every `--add-dir` folder it has not seen before the session starts, and
98
+ * exits on "No"; a folder from `--settings` becomes a working directory without that question (tried with Claude Code
99
+ * 2.1.326 on 2026-11-17). Each folder is listed as given and, when a link leads to it, by its real path too.
100
+ */
101
+ export async function withClaudeDirs(args, dirs, out) {
102
+ const settings = await settingsOf(args);
103
+ const permissions = settings.permissions && typeof settings.permissions === 'object' && !Array.isArray(settings.permissions)
104
+ ? settings.permissions
105
+ : {};
106
+ const had = Array.isArray(permissions.additionalDirectories) ? permissions.additionalDirectories : [];
107
+ const add = dirs.flatMap((d) => {
108
+ try {
109
+ const real = realpathSync(d);
110
+ return real === d ? [d] : [d, real];
111
+ }
112
+ catch {
113
+ return [d];
114
+ }
115
+ });
116
+ const additionalDirectories = [...new Set([...had, ...add])];
117
+ await mkdir(dirname(out), { recursive: true, mode: 0o700 });
118
+ await writeFileAtomic(out, `${JSON.stringify({ ...settings, permissions: { ...permissions, additionalDirectories } }, null, 2)}\n`, 0o600);
119
+ const at = args.indexOf('--settings');
120
+ return at === -1 ? [...args, '--settings', out] : args.map((a, i) => (i === at + 1 ? out : a));
121
+ }
95
122
  /**
96
123
  * Auto Handoff's Claude hook arguments with the session's own sideby hooks (`sessionArgs`, from `sessionHookArgs`)
97
124
  * merged into one `--settings` file, written next to the session's file with `-handoff` added to its name.
@@ -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;
@@ -0,0 +1,125 @@
1
+ // Answer Wait (spec §3.37 item 7, ADR-0077): a question or a confirmation Claude Code shows in a session sideby started
2
+ // waits for a person; once it has waited `unattended.answerWait` minutes and Unattended Mode is on, `unattended-hook`
3
+ // lets the session go on without an answer. A leaf module (Node built-ins and core/fs-safe.ts only): the hook imports it.
4
+ //
5
+ // What is on screen is read from Claude Code's own session record, `<config dir>/sessions/<pid>.json`, the pid being the
6
+ // hook's parent (the Host): its `sessionId`, `status` and `statusUpdatedAt`, nothing else. Tried with Claude Code
7
+ // 2.1.325 on 2026-11-16: `status` is `waiting` while a question or a permission prompt is on screen and `idle` while the
8
+ // session waits for a prompt, and `statusUpdatedAt` changes when either ends or another dialog takes its place (it
9
+ // stayed the same for 11 minutes while one prompt waited). The record is written before the hook starts.
10
+ import { homedir } from 'node:os';
11
+ import { join } from 'node:path';
12
+ import { readSmallFile } from './fs-safe.js';
13
+ /**
14
+ * The `timeout` of the hook entries that wait. A question shown at 18:00 with Unattended Mode off still goes on when a
15
+ * Slot begins at 23:00; Claude Code ends the hook after this and the question then simply stays on screen.
16
+ */
17
+ export const ANSWER_HOOK_TIMEOUT_S = 12 * 60 * 60;
18
+ /** How long a hook looks for the record to show what it waits on before it gives up (it is written before the hook). */
19
+ const SHOWN_WAIT_MS = 2000;
20
+ const SHOWN_POLL_MS = 100;
21
+ /** How often a waiting hook looks again: an answered question frees its hook within this. */
22
+ export const WATCH_POLL_MS = 3000;
23
+ /** Claude Code's config folder for the session: `CLAUDE_CONFIG_DIR`, else `~/.claude`. */
24
+ export function claudeConfigDir(env) {
25
+ return env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), '.claude');
26
+ }
27
+ /**
28
+ * The status the record of process `pid` holds for session `sessionId`; undefined when it cannot be read, is a link,
29
+ * names another session, or lacks `status` or `statusUpdatedAt`.
30
+ */
31
+ export async function readScreen(env, pid, sessionId) {
32
+ if (!Number.isInteger(pid) || pid <= 1)
33
+ return undefined;
34
+ const text = await readSmallFile(join(claudeConfigDir(env), 'sessions', `${pid}.json`), 64 * 1024);
35
+ if (text === undefined)
36
+ return undefined;
37
+ try {
38
+ const v = JSON.parse(text);
39
+ if (!v || v.sessionId !== sessionId)
40
+ return undefined;
41
+ if (typeof v.status !== 'string' || typeof v.statusUpdatedAt !== 'number')
42
+ return undefined;
43
+ return { status: v.status, at: v.statusUpdatedAt };
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ /**
50
+ * Waits while the session shows `expect` (`waiting`: a question or a permission prompt; `idle`: a turn ended and the
51
+ * session waits for a prompt). Returns the record's mark once the wait has passed since `startedAt` and Unattended
52
+ * Mode is on, so the caller can look once more just before it acts (`lastLook`), and undefined as soon as anything
53
+ * says a person (or anything else) moved on or it cannot tell: there is no record for the session, it does not show
54
+ * `expect` within 2 seconds, it shows a dialog put up after `shownBy` (the dialog this hook was started for was on
55
+ * screen before the hook began, so a later one is another dialog: the person answered this one meanwhile), it changes
56
+ * (another status or another `statusUpdatedAt`), it cannot be read, `moved` says so (a person typed after the turn
57
+ * the hook watches), the Host is gone, or the wait was set to never. While the mode is off past the wait it keeps
58
+ * waiting; Claude Code's `timeout` ends it in the end. With `from` it goes on watching that mark, without looking for it
59
+ * first.
60
+ */
61
+ export async function watchScreen(opts) {
62
+ let mark = opts.from;
63
+ if (!mark) {
64
+ // No record for this session at all: nothing is shown in a terminal that sideby can watch.
65
+ mark = await readScreen(opts.env, opts.pid, opts.sessionId);
66
+ if (!mark)
67
+ return undefined;
68
+ for (let waited = 0; mark?.status !== opts.expect; waited += SHOWN_POLL_MS) {
69
+ if (waited >= SHOWN_WAIT_MS)
70
+ return undefined;
71
+ await opts.sleep(SHOWN_POLL_MS);
72
+ mark = await readScreen(opts.env, opts.pid, opts.sessionId);
73
+ }
74
+ if (opts.shownBy !== undefined && mark.at > opts.shownBy)
75
+ return undefined;
76
+ if (await opts.moved?.())
77
+ return undefined;
78
+ }
79
+ for (;;) {
80
+ await opts.sleep(WATCH_POLL_MS);
81
+ if (opts.parentGone())
82
+ return undefined;
83
+ const m = await readScreen(opts.env, opts.pid, opts.sessionId);
84
+ if (!sameMark(m, mark))
85
+ return undefined;
86
+ if (await opts.moved?.())
87
+ return undefined;
88
+ const d = await due(opts.settings, opts.clock, opts.startedAt);
89
+ if (d === 'stop')
90
+ return undefined;
91
+ if (d === 'act')
92
+ return mark;
93
+ }
94
+ }
95
+ const sameMark = (a, b) => a !== undefined && a.status === b.status && a.at === b.at;
96
+ /** With the wait and the mode as they are now: act, keep waiting (not due yet, or the mode is off), or stop (never). */
97
+ async function due(settings, clock, startedAt) {
98
+ const s = await settings();
99
+ if (s.wait === null)
100
+ return 'stop';
101
+ return clock() - startedAt >= s.wait * 60_000 && s.on ? 'act' : 'wait';
102
+ }
103
+ /**
104
+ * The last look before a waiting hook acts (and again after it kept the Pending Decision), with the wait and the mode
105
+ * read afresh: `act` while the Host is still there, the record still shows `mark`, nothing sideby noted says the
106
+ * session moved on, the wait (as set now) has passed and Unattended Mode is on; `wait` when all that holds but the
107
+ * wait was made longer and has not passed, or the mode went off: the hook goes on watching; `stop` for anything else,
108
+ * the wait set to never, or anything it cannot read: the hook then lets it be.
109
+ */
110
+ export async function lastLook(opts) {
111
+ try {
112
+ if (opts.parentGone())
113
+ return 'stop';
114
+ if (!sameMark(await readScreen(opts.env, opts.pid, opts.sessionId), opts.mark))
115
+ return 'stop';
116
+ if (await opts.moved?.())
117
+ return 'stop';
118
+ return await due(opts.settings, opts.clock, opts.startedAt);
119
+ }
120
+ catch {
121
+ return 'stop';
122
+ }
123
+ }
124
+ /** Whole minutes from `startedAt` to `now`, at least 1: how long the question waited, as the user reads it. */
125
+ export const waitedMinutes = (startedAt, now) => Math.max(1, Math.round((now - startedAt) / 60_000));
@@ -15,6 +15,11 @@ export interface UnattendedStatus extends UnattendedState {
15
15
  /** The config has an `unattended` section, so sessions sideby starts get the hook. */
16
16
  configured: boolean;
17
17
  schedule: UnattendedSlot[];
18
+ /**
19
+ * Answer Wait (ADR-0077): minutes a question or permission prompt shown in a Claude session waits for a person
20
+ * before, with the mode on, the session goes on without an answer; null: never. 10 when not set.
21
+ */
22
+ answerWait: number | null;
18
23
  /** Open Pending Decisions. */
19
24
  pending: number;
20
25
  /**
@@ -122,6 +127,18 @@ export declare function setUnattendedSchedule(opts: {
122
127
  }): Promise<UnattendedChange & {
123
128
  previous: UnattendedSlot[];
124
129
  }>;
130
+ /**
131
+ * Sets the Answer Wait (ADR-0077): whole minutes from 1 to 120, or null for never, creating the config section. It
132
+ * reaches running sessions at once (their hooks read it at every look). Throws a UserError for any other value.
133
+ */
134
+ export declare function setAnswerWait(opts: {
135
+ paths: Paths;
136
+ families: readonly string[];
137
+ minutes: number | null;
138
+ now?: Date;
139
+ }): Promise<UnattendedChange & {
140
+ before: number | null;
141
+ }>;
125
142
  /** The preset names `schedule preset` takes, with what each adds. */
126
143
  export declare const UNATTENDED_PRESETS: Readonly<Record<string, UnattendedSlot>>;
127
144
  /** The Slot `schedule add` was given, or why it cannot be one (the message says what to do). */
@@ -141,6 +158,8 @@ export declare const unattendedClock: (iso: string, now: Date, zh?: boolean) =>
141
158
  * about to show, every MCP server form (`Elicitation`), every turn that failed on an API error (`StopFailure`, in the
142
159
  * background with `asyncRewake`, so its exit 2 wakes the session: Turn Retry, ADR-0067), and every prompt
143
160
  * (`UserPromptSubmit`, in the background with `async`, so it never holds a prompt back: Attended Sessions, ADR-0075).
161
+ * For Answer Wait (ADR-0077) the `PermissionRequest` entry may wait while its prompt is on screen, so it has a long
162
+ * `timeout`, and a second `Stop` entry waits in the background (`asyncRewake`) after a turn that ended on a question.
144
163
  * Codex has no such events for them; its own approval prompts and failed turns are not covered.
145
164
  */
146
165
  export declare function unattendedHookPart(): SessionHookPart;