sideby 0.38.1 → 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.
Files changed (42) 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 +88 -0
  4. package/dist/src/cli/json-schemas.js +35 -0
  5. package/dist/src/cli/main.js +29 -0
  6. package/dist/src/core/cli-commands.js +14 -2
  7. package/dist/src/core/config.d.ts +13 -0
  8. package/dist/src/core/config.js +18 -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 +80 -0
  12. package/dist/src/core/progress-state.js +216 -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 +25 -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.d.ts +10 -2
  21. package/dist/src/core/unattended.js +11 -2
  22. package/dist/src/handoff/hook.js +19 -4
  23. package/dist/src/network/hook.js +4 -8
  24. package/dist/src/panel/handler.d.ts +3 -0
  25. package/dist/src/panel/handler.js +15 -0
  26. package/dist/src/panel/i18n.d.ts +18 -0
  27. package/dist/src/panel/i18n.js +36 -0
  28. package/dist/src/panel/page-script.js +67 -2
  29. package/dist/src/panel/page-styles.js +14 -0
  30. package/dist/src/progress/hook.d.ts +50 -0
  31. package/dist/src/progress/hook.js +251 -0
  32. package/dist/src/runtime.d.ts +9 -0
  33. package/dist/src/runtime.js +45 -2
  34. package/dist/src/unattended/hook.d.ts +5 -0
  35. package/dist/src/unattended/hook.js +103 -9
  36. package/package.json +1 -1
  37. package/schemas/config.json +13 -0
  38. package/schemas/progress.json +137 -0
  39. package/schemas/unattended.json +38 -0
  40. package/skills/sideby/SKILL.md +3 -1
  41. package/skills/sideby/references/progress.md +25 -0
  42. 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`), and every turn that failed on an API error (`StopFailure`, in the background with `asyncRewake`, so its exit 2 wakes the session: Turn Retry,
136
- * ADR-0067). Codex has no such events for them; its own approval prompts and failed turns are not covered.
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`), and every turn that failed on an API error (`StopFailure`, in the background with `asyncRewake`, so its exit 2 wakes the session: Turn Retry,
296
- * ADR-0067). Codex has no such events for them; its own approval prompts and failed turns are not covered.
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')}}`],
@@ -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
- if (windows)
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
- else if (!st.stopBlocked && input.stop_hook_active !== true && input.stopHookActive !== true) {
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
- return { output: blockOutput(thresholdMessage(usable.brief, crossed)) };
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
  }
@@ -12,6 +12,7 @@ import { setTimeout as delay } from 'node:timers/promises';
12
12
  import { blockMessage, inCi, judge, NETWORK_ENV, prefersChinese, readNetworkConfig, refresh, verdict, } from '../core/egress.js';
13
13
  import { ownedFolder, readSmallFile, sha256, writeFileAtomic } from '../core/fs-safe.js';
14
14
  import { resolvePaths } from '../core/paths.js';
15
+ import { HELD_CLOSE, HELD_OPEN, hookWakeUp, hostMade } from '../core/prompt-origin.js';
15
16
  export const NETWORK_HOOK_COMMAND = 'sideby network-hook';
16
17
  /** The Host events this entry answers, and when each happens; `Refresh` is its own detached refresh. */
17
18
  const MOMENTS = { UserPromptSubmit: 'prompt', PreToolUse: 'tool' };
@@ -19,10 +20,6 @@ const MOMENTS = { UserPromptSubmit: 'prompt', PreToolUse: 'tool' };
19
20
  const STDIN_MAX = 1024 * 1024;
20
21
  /** Input that has not ended after this long is not waited for: the hook then decides as if it were given nothing. */
21
22
  const STDIN_WAIT_MS = 5000;
22
- /** A wake-up Claude Code makes from a background hook's exit 2 starts like this; only such a prompt carries a held message. */
23
- const WAKE_UP = /^<task-notification>\s*<summary>Stop hook feedback<\/summary>/;
24
- /** A prompt Claude Code made itself starts with this (a background task's notification, a hook's wake-up). */
25
- const HOST_MADE = '<task-notification>';
26
23
  /** `Held` asks again after these waits, then every `HELD_EVERY_MS`: one request each time. */
27
24
  export const HELD_DELAYS_MS = [15_000, 30_000];
28
25
  export const HELD_EVERY_MS = 60_000;
@@ -38,8 +35,6 @@ const DECISION_POLL_MS = 200;
38
35
  const DECISION_KEPT_MS = 3600_000;
39
36
  /** The most of a held message that is handed over. */
40
37
  const HELD_MAX_CHARS = 8000;
41
- const HELD_OPEN = '<sideby-held-message>';
42
- const HELD_CLOSE = '</sideby-held-message>';
43
38
  async function readInput(input) {
44
39
  if (input === undefined)
45
40
  return '';
@@ -81,7 +76,7 @@ async function hostMadePrompt(input) {
81
76
  const v = JSON.parse(await readInput(input));
82
77
  if (!v || typeof v.prompt !== 'string' || typeof v.prompt_id !== 'string' || !v.prompt_id)
83
78
  return undefined;
84
- return v.prompt.trimStart().startsWith(HOST_MADE) ? { id: v.prompt_id, prompt: v.prompt } : undefined;
79
+ return hostMade(v.prompt) ? { id: v.prompt_id, prompt: v.prompt } : undefined;
85
80
  }
86
81
  catch {
87
82
  return undefined;
@@ -129,7 +124,8 @@ function heldMessage(prompt, zh) {
129
124
  // A wake-up that was blocked again carries the first message inside the tags: hand over that one alone.
130
125
  const from = prompt.indexOf(HELD_OPEN);
131
126
  const to = prompt.lastIndexOf(HELD_CLOSE);
132
- const inner = WAKE_UP.test(prompt.trimStart()) && from !== -1 && to > from;
127
+ // Only a wake-up Claude Code made from a background hook's exit 2 carries a held message.
128
+ const inner = hookWakeUp(prompt) && from !== -1 && to > from;
133
129
  const whole = (inner ? prompt.slice(from + HELD_OPEN.length, to) : prompt).trim();
134
130
  const text = whole.slice(0, HELD_MAX_CHARS);
135
131
  const cut = whole.length > HELD_MAX_CHARS
@@ -9,6 +9,7 @@ import { type LiveSession, type LiveSessionsResult, sessionCopyText } from '../c
9
9
  import { listMessages, type MessageReceipt, sendMessage } from '../core/messages.ts';
10
10
  import { type AccountModel } from '../core/model-choice.ts';
11
11
  import { type NetworkOverview } from '../core/network.ts';
12
+ import { type ProgressView } from '../core/progress.ts';
12
13
  import { type RemoteControlGroup } from '../core/remote-control.ts';
13
14
  import { type UnattendedStatus } from '../core/unattended.ts';
14
15
  import { type PendingDecision } from '../core/unattended-pending.ts';
@@ -301,6 +302,8 @@ export interface PanelState {
301
302
  network?: NetworkOverview;
302
303
  /** Unattended Mode (spec §3.37): whether it is on for the computer, why, until when, the Schedule; absent when unreadable. */
303
304
  unattended?: PanelUnattendedStatus;
305
+ /** Progress Reminders (spec §3.42): on or off, how often, and the choices; absent without Claude Accounts. */
306
+ progress?: ProgressView;
304
307
  }
305
308
  /** One Pending Decision as the Panel's Unattended page lists it, with the way back to its Session. */
306
309
  export interface PanelPendingDecision extends PendingDecision {
@@ -25,6 +25,8 @@ import { listMessages, sendMessage } from '../core/messages.js';
25
25
  import { accountModel, setAccountModel } from '../core/model-choice.js';
26
26
  import { GUARDED_FAMILIES, setNetwork } from '../core/network.js';
27
27
  import { tildify } from '../core/paths.js';
28
+ import { PROGRESS_FAMILIES } from '../core/progress.js';
29
+ import { validEvery } from '../core/progress-state.js';
28
30
  import { quotaAsking } from '../core/quota-fetch.js';
29
31
  import { takeoverLimits } from '../core/quota-levels.js';
30
32
  import { remoteControlTodo } from '../core/remote-control.js';
@@ -647,6 +649,7 @@ async function buildState(rt, opts) {
647
649
  .then((st) => withPendingIds(st, rt.paths.stateDir))
648
650
  .catch(() => undefined);
649
651
  const showBrowser = browser && (browser.families.matched.length || browser.families.openOnly.length);
652
+ const progress = accounts.some((a) => PROGRESS_FAMILIES.includes(a.family)) ? rt.progressView() : undefined;
650
653
  const permissions = aiTaskPermissions(rt.config);
651
654
  return {
652
655
  schemaVersion: 1,
@@ -694,6 +697,7 @@ async function buildState(rt, opts) {
694
697
  ...(rt.config.panel && Object.keys(rt.config.panel).length ? { panel: rt.config.panel } : {}),
695
698
  ...(network ? { network } : {}),
696
699
  ...(unattended ? { unattended } : {}),
700
+ ...(progress ? { progress } : {}),
697
701
  };
698
702
  }
699
703
  const SHELL_SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/;
@@ -2299,6 +2303,17 @@ export function createPanelHandler(opts) {
2299
2303
  return { family, ...(await rt.setQuotaCheck(family, body.on)) };
2300
2304
  },
2301
2305
  },
2306
+ // Progress Reminders on with `every` minutes, or off with null: config `progress` (spec §3.42).
2307
+ '/api/progress': {
2308
+ async run(body) {
2309
+ const every = body.every;
2310
+ if (every !== null && !validEvery(every))
2311
+ throw new HttpError(400, '"every" must be whole minutes from 1 to 240, or null to turn it off');
2312
+ const rt = await getRuntime();
2313
+ const r = await rt.setProgress(validEvery(every) ? every : undefined);
2314
+ return { changed: r.changed, ...(r.after === undefined ? {} : { every: r.after }) };
2315
+ },
2316
+ },
2302
2317
  // The Panel's theme and language (spec §3.29): config `panel.theme` and `panel.language`; null removes one.
2303
2318
  '/api/panel/settings': {
2304
2319
  async run(body) {
@@ -1714,6 +1714,10 @@ declare const en: {
1714
1714
  'ua.overnight': string;
1715
1715
  'ua.allDay': string;
1716
1716
  'ua.remove': string;
1717
+ 'ua.here': string;
1718
+ 'ua.hereNote': string;
1719
+ 'ua.hereHint': string;
1720
+ 'ua.hereSession': string;
1717
1721
  'ua.pending': string;
1718
1722
  'ua.pendingNote': string;
1719
1723
  'ua.pendingEmpty': string;
@@ -1747,6 +1751,20 @@ declare const en: {
1747
1751
  'ua.problem': string;
1748
1752
  'ua.unreadable': string;
1749
1753
  'ai.ask.unattended': string;
1754
+ 'ai.ask.progress': string;
1755
+ 'pr.title': string;
1756
+ 'pr.hint': string;
1757
+ 'pr.switch': string;
1758
+ 'pr.every': string;
1759
+ 'pr.minutes': string;
1760
+ 'pr.everyLong': string;
1761
+ 'pr.cost': string;
1762
+ 'pr.scope': string;
1763
+ 'pr.codex': string;
1764
+ 'pr.onToast': string;
1765
+ 'pr.everyToast': string;
1766
+ 'pr.offToast': string;
1767
+ 'pr.failed': string;
1750
1768
  };
1751
1769
  export type MessageKey = keyof typeof en;
1752
1770
  export declare const MESSAGES: Record<PanelLang, Record<string, string>>;