sideby 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261031T154831-0045dd"}
1
+ {"id":"20261101T024154-fb1cda"}
@@ -3057,6 +3057,17 @@ const SESSION_STATUS = {
3057
3057
  idle: 'idle',
3058
3058
  unknown: '—',
3059
3059
  };
3060
+ /** What the user does for a Session that needs them, when it is not the Host itself asking (spec §3.32 step 1). */
3061
+ const NEEDS_YOU_FOR = {
3062
+ 'pending-decision': 'a decision',
3063
+ 'message-to-approve': 'approve a message',
3064
+ 'message-to-paste': 'paste a message',
3065
+ };
3066
+ function sessionStatusText(s) {
3067
+ const why = s.reason ? NEEDS_YOU_FOR[s.reason] : undefined;
3068
+ const text = SESSION_STATUS[s.status] ?? SESSION_STATUS.unknown;
3069
+ return s.status === 'needs-you' ? c.yellow(why ? `${text}: ${why}` : text) : text;
3070
+ }
3060
3071
  /** The language of a copied Session Reference: `--lang`, else the user's locale. */
3061
3072
  function copyLang(a, env) {
3062
3073
  const flag = a.flags.get('lang');
@@ -3107,7 +3118,7 @@ export async function cmdSessions(a, io, runtime) {
3107
3118
  const anyRun = sessions.some((s) => s.run);
3108
3119
  const rows = sessions.map((s) => [
3109
3120
  c.bold(sessionLabel(s.accountLabel, truncate(s.title, 40), s.sessionId)),
3110
- s.status === 'needs-you' ? c.yellow(SESSION_STATUS[s.status]) : SESSION_STATUS[s.status],
3121
+ sessionStatusText(s),
3111
3122
  s.cwd ? tildify(s.cwd, home) : '',
3112
3123
  s.startedAt ? clock(s.startedAt, now) : '',
3113
3124
  ...(anyRun
@@ -3126,6 +3137,10 @@ export async function cmdSessions(a, io, runtime) {
3126
3137
  io.out(c.dim(`Run: ${title} ${tildify(board, home)}`));
3127
3138
  if (boards.size)
3128
3139
  io.out(c.dim('Open its run report: sideby sessions open-run <account|session-id>'));
3140
+ if (sessions.some((s) => s.reason === 'pending-decision'))
3141
+ io.out(c.dim('See the decisions waiting for you: sideby unattended pending'));
3142
+ if (sessions.some((s) => s.reason === 'message-to-paste' || s.reason === 'message-to-approve'))
3143
+ io.out(c.dim('See the messages waiting for you, with the line to paste: sideby messages'));
3129
3144
  io.out(c.dim('Copy one for another AI: sideby sessions copy <account|session-id>'));
3130
3145
  return 0;
3131
3146
  }
@@ -4052,12 +4067,12 @@ function unattendedLine(s, now) {
4052
4067
  const at = (iso) => clock2(iso, now);
4053
4068
  const slot = s.slot ? ` · Slot "${s.slot}"` : '';
4054
4069
  if (s.reason === 'slot' || s.reason === 'manual')
4055
- return `${c.green('on')}${s.reason === 'manual' ? ' · turned on by hand' : slot}${s.until ? ` · until ${at(s.until)}` : ' · no end: the Schedule covers every hour'}`;
4070
+ return `${c.green('on')}${s.until ? ` · until ${at(s.until)}` : ' · no end: the Schedule covers every hour'}${s.reason === 'manual' ? ' · turned on by hand' : slot}`;
4056
4071
  if (s.reason === 'session')
4057
4072
  return `${c.green('on')} for this session only (started with --unattended)`;
4058
4073
  if (s.reason === 'paused')
4059
- return `${c.yellow('paused')}${slot}${s.until ? ` · until ${at(s.until)}, then the Schedule goes on` : ' · until you turn it on (`sideby unattended on`)'}`;
4060
- return `${c.dim('off')}${s.next ? ` · next ${at(s.next.at)}${s.next.slot ? ` (${s.next.slot})` : ''}` : ''}`;
4074
+ return `${c.yellow('paused')}${s.until ? ` · back on at ${at(s.until)}` : ' · until you turn it on (`sideby unattended on`)'}${slot}`;
4075
+ return `${c.dim('off')}${s.next ? ` · turns on at ${at(s.next.at)}${s.next.slot ? ` (Slot "${s.next.slot}")` : ''}` : ''}`;
4061
4076
  }
4062
4077
  const clock2 = (iso, now) => clockText(Date.parse(iso), now.getTime());
4063
4078
  function printSchedule(io, schedule) {
@@ -1002,8 +1002,11 @@ export const OUTPUT_SCHEMAS = {
1002
1002
  description: 'The Session Label: `<accountLabel> · <title> · <first 8 of sessionId>`.',
1003
1003
  }),
1004
1004
  status: Type.Union(['needs-you', 'busy', 'idle', 'unknown'].map((k) => Type.Literal(k)), {
1005
- description: '`needs-you`: it waits for the user (a permission or a question); `unknown` where the host does not say.',
1005
+ description: "`needs-you`: the user has to act on it (`reason` says why); `busy` and `idle` as the host says; `unknown` where the host does not say. The first matching row of spec §3.32 step 1's status table.",
1006
1006
  }),
1007
+ reason: Type.Optional(Type.Union(['host-waits', 'pending-decision', 'message-to-approve', 'message-to-paste'].map((k) => Type.Literal(k)), {
1008
+ description: 'Only with `needs-you`: the host waits for a permission or an answer; an open Pending Decision names the session (`sideby unattended pending`); a Message to it waits for the user to approve it in its terminal; or a Message to it waits to be pasted (`sideby messages`). New values may be added.',
1009
+ })),
1007
1010
  cwd: Type.Optional(Str),
1008
1011
  pid: Type.Optional(Type.Integer({ description: 'The host process running it.' })),
1009
1012
  startedAt: Type.Optional(Str),
@@ -338,7 +338,9 @@ a Claude or Codex session sideby started is not allowed to ask a question: the m
338
338
  where it can be undone, and skips anything hard to undo (deleting, sending, publishing, deploying, paying). Each
339
339
  question it could not ask, and each thing it skipped (\`defer\`), is kept as a Pending Decision for when you are back.
340
340
  In Claude sessions, a permission prompt Claude Code is about to show (a command it wants a person to confirm, also in
341
- a subagent) is answered with "no" and how to do it without one, and kept as a Pending Decision too. Codex's own
341
+ a subagent) is answered with "no" and how to do it without one, and kept as a Pending Decision too. A Claude turn
342
+ that failed for a passing reason (an overloaded server, a dropped connection, a rate limit that is not a used-up
343
+ Quota) is started again after 1, 2, then 4 minutes; after three it is kept as a Pending Decision. Codex's own
342
344
  approval prompts are not covered.
343
345
 
344
346
  When it is on: during a Slot of the Schedule (local days and times; an end before the start is the next day), from
@@ -3,6 +3,7 @@ import type { Runtime } from '../runtime.ts';
3
3
  import type { Account } from '../types.ts';
4
4
  import { type LiveSessionDeps } from './live-sessions-procs.ts';
5
5
  import type { SessionRun } from './run-link.ts';
6
+ import { type NeedsYouReason } from './session-status.ts';
6
7
  export type LiveSessionStatus = 'needs-you' | 'busy' | 'idle' | 'unknown';
7
8
  export interface LiveSession {
8
9
  /** The Account ref, for example `claude:002`. */
@@ -15,7 +16,10 @@ export interface LiveSession {
15
16
  title: string;
16
17
  /** `<accountLabel> · <title> · <first 8 of sessionId>`. */
17
18
  label: string;
19
+ /** The first matching row of the status table (spec §3.32 step 1, `STATUS_RULES` in session-status.ts). */
18
20
  status: LiveSessionStatus;
21
+ /** Why the Session needs the user; only with status `needs-you`. */
22
+ reason?: NeedsYouReason;
19
23
  cwd?: string;
20
24
  pid?: number;
21
25
  startedAt?: string;
@@ -5,6 +5,7 @@ import { liveSessionReader } from '../families/live-sessions.js';
5
5
  import { aliasesByAccount } from './accounts.js';
6
6
  import { aliasArgs, aliasRefs } from './config.js';
7
7
  import { processView, systemDeps } from './live-sessions-procs.js';
8
+ import { MESSAGES_LOOKED_AT, readAttention, withStatus, } from './session-status.js';
8
9
  export const shortId = (id) => id.slice(0, 8);
9
10
  /** `<accountLabel> · <title> · <first 8 of id>`; a Session without a title leaves its part out. */
10
11
  export const sessionLabel = (accountLabel, title, id) => [accountLabel, title, shortId(id)].filter(Boolean).join(' · ');
@@ -87,6 +88,13 @@ export async function listLiveSessions(rt, opts = {}, deps) {
87
88
  const readable = accounts.filter((a) => liveSessionReader(a.family));
88
89
  if (!readable.length)
89
90
  return { sessions: [], problems };
91
+ // What sideby keeps for Sessions (Pending Decisions, Messages) is read beside the Hosts' files. The Messages module
92
+ // reaches back here to pick a target, so it is loaded only when needed.
93
+ const kept = readAttention(rt.readContext().stateDir, async () => (await import('./messages.js')).listMessages(rt, { limit: MESSAGES_LOOKED_AT, persist: false }), problems);
94
+ let keptNow;
95
+ const keptRead = kept.then((k) => {
96
+ keptNow = k;
97
+ });
90
98
  const ctl = new AbortController();
91
99
  const procs = processView(deps ?? systemDeps(rt.env), ctl.signal);
92
100
  const found = [];
@@ -122,13 +130,19 @@ export async function listLiveSessions(rt, opts = {}, deps) {
122
130
  const late = new Promise((resolve) => {
123
131
  timer = setTimeout(() => resolve('late'), deadlineMs);
124
132
  });
125
- if ((await Promise.race([work.then(() => 'done'), late])) === 'late') {
133
+ const done = Promise.all([work, keptRead]).then(() => 'done');
134
+ if ((await Promise.race([done, late])) === 'late') {
126
135
  ctl.abort();
127
- problems.push(`stopped looking after ${deadlineMs / 1000} s; ${[...pending].join(', ') || 'some accounts'} may run sessions that are not shown; run \`sideby sessions\` again`);
136
+ if (pending.size || !keptNow)
137
+ problems.push(pending.size
138
+ ? `stopped looking after ${deadlineMs / 1000} s; ${[...pending].join(', ')} may run sessions that are not shown; run \`sideby sessions\` again`
139
+ : `stopped looking after ${deadlineMs / 1000} s; a session waiting on a decision or a message may not show as needing you; run \`sideby sessions\` again`);
128
140
  }
129
141
  clearTimeout(timer);
142
+ // Past the deadline, what sideby keeps counts only if it was read in time.
143
+ const sessions = withStatus(found, keptNow ?? { decisions: [], receipts: [] });
130
144
  // One unreadable process is met by every Account of its Family: say it once.
131
- return { sessions: sortSessions([...found]), problems: [...new Set(problems)] };
145
+ return { sessions: sortSessions(sessions), problems: [...new Set(problems)] };
132
146
  }
133
147
  export function referenceText(s, lang) {
134
148
  const id = shortId(s.sessionId);
@@ -57,7 +57,16 @@ export interface MessageDeps {
57
57
  timeoutMs?: number;
58
58
  /** How `codex <args>` runs for Codex delivery; resolves to its exit code. */
59
59
  runCodex?: (args: readonly string[], env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<number>;
60
+ /** The wait between delivery tries; a real timer when left out. */
61
+ sleep?: (ms: number) => Promise<void>;
60
62
  }
63
+ /** How many times a delivery whose channel failed in a way that may pass is tried, the first time included. */
64
+ export declare const DELIVERY_TRIES = 3;
65
+ /** The wait before the second try; each next one waits twice as long, at most `DELIVERY_RETRY_MAX_MS`. */
66
+ export declare const DELIVERY_RETRY_FIRST_MS = 2000;
67
+ export declare const DELIVERY_RETRY_MAX_MS = 60000;
68
+ /** The wait before try `n` (2-based: the first try does not wait). */
69
+ export declare const deliveryRetryDelay: (n: number) => number;
61
70
  /** The largest screenshot sideby copies. */
62
71
  export declare const MAX_IMAGE_BYTES: number;
63
72
  /** The image type of a file's first bytes (`png`, `jpg`, `gif`, `webp`), or null. */
@@ -11,6 +11,13 @@ import { UserError } from './errors.js';
11
11
  import { ownedFolder, UnsafeFolderError, writeFileAtomic } from './fs-safe.js';
12
12
  import { processView, systemDeps } from './live-sessions-procs.js';
13
13
  import { selectSession } from './session-select.js';
14
+ /** How many times a delivery whose channel failed in a way that may pass is tried, the first time included. */
15
+ export const DELIVERY_TRIES = 3;
16
+ /** The wait before the second try; each next one waits twice as long, at most `DELIVERY_RETRY_MAX_MS`. */
17
+ export const DELIVERY_RETRY_FIRST_MS = 2_000;
18
+ export const DELIVERY_RETRY_MAX_MS = 60_000;
19
+ /** The wait before try `n` (2-based: the first try does not wait). */
20
+ export const deliveryRetryDelay = (n) => Math.min(DELIVERY_RETRY_MAX_MS, DELIVERY_RETRY_FIRST_MS * 2 ** Math.max(0, n - 2));
14
21
  /** The largest screenshot sideby copies. */
15
22
  export const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
16
23
  const IMAGE_TYPES = [
@@ -253,7 +260,7 @@ async function sendOpened(rt, target, opts, deps) {
253
260
  let result;
254
261
  try {
255
262
  const acct = (await rt.accounts()).find((a) => a.ref === to.account);
256
- result = await deliver(rt, to, acct, receipt, text, reply, procDeps, deps);
263
+ result = await deliverWithRetry(() => deliver(rt, to, acct, receipt, text, reply, procDeps, deps), to, procDeps, deps);
257
264
  }
258
265
  catch (err) {
259
266
  result = {
@@ -261,7 +268,8 @@ async function sendOpened(rt, target, opts, deps) {
261
268
  note: `sideby could not deliver it (${err.code ?? err.message}); paste the line into its tab`,
262
269
  };
263
270
  }
264
- Object.assign(receipt, result);
271
+ const { retry: _retry, ...outcome } = result;
272
+ Object.assign(receipt, outcome);
265
273
  try {
266
274
  await saveReceipt(receipt);
267
275
  }
@@ -275,6 +283,32 @@ async function sendOpened(rt, target, opts, deps) {
275
283
  }
276
284
  return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
277
285
  }
286
+ /**
287
+ * Delivers, and tries again while the channel failed in a way that may pass and took nothing (`retry`, never after a
288
+ * write that may have reached the session, ADR-0065): up to `DELIVERY_TRIES` times, 2 s, then 4 s apart, and not once
289
+ * the target's process is gone. Every try runs every check again (settings, session record, socket owner and folder).
290
+ * The last failure is the result, its note saying how many tries were made.
291
+ */
292
+ async function deliverWithRetry(once, to, procDeps, deps) {
293
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
294
+ let result = await once();
295
+ let tries = 1;
296
+ while (result.retry && result.status === 'paste-needed' && tries < DELIVERY_TRIES) {
297
+ if (to.pid === undefined)
298
+ break;
299
+ const gone = await processView(procDeps)
300
+ .get(to.pid)
301
+ .then((p) => !p, () => false);
302
+ if (gone)
303
+ break;
304
+ tries++;
305
+ await sleep(deliveryRetryDelay(tries));
306
+ result = await once();
307
+ }
308
+ if (result.retry && result.status === 'paste-needed' && tries > 1 && result.note)
309
+ result = { ...result, note: result.note.replace(/\); paste /, `; tried ${tries} times); paste `) };
310
+ return result;
311
+ }
278
312
  async function deliver(rt, to, acct, r, text, reply, procDeps, deps) {
279
313
  if (to.guessed)
280
314
  return {
@@ -0,0 +1,55 @@
1
+ import type { LiveSessionStatus } from './live-sessions.ts';
2
+ import type { MessageReceipt } from './messages.ts';
3
+ import { type PendingDecision } from './unattended-pending.ts';
4
+ /** Why a Session needs the user: the row of `STATUS_RULES` that matched. Set only with status `needs-you`. */
5
+ export type NeedsYouReason = 'host-waits' | 'pending-decision' | 'message-to-approve' | 'message-to-paste';
6
+ /** What the table looks at for one Session. */
7
+ export interface StatusSignals {
8
+ /** What the Host's own files say (a Family reader's status). */
9
+ host: LiveSessionStatus;
10
+ /** Open Pending Decisions kept for this Session. */
11
+ pendingDecisions: number;
12
+ /** Messages delivered to it that it shows only once the user approves them in its terminal (ADR-0045). */
13
+ messagesToApprove: number;
14
+ /** Messages to it that wait for the user to paste them (`paste-needed`) and its record does not show yet. */
15
+ messagesToPaste: number;
16
+ }
17
+ export interface StatusRule {
18
+ status: LiveSessionStatus;
19
+ reason?: NeedsYouReason;
20
+ when: (s: StatusSignals) => boolean;
21
+ }
22
+ /** The table of spec §3.32 step 1, in order; the first row whose `when` holds gives the status. */
23
+ export declare const STATUS_RULES: readonly StatusRule[];
24
+ /** The status the first matching row of `STATUS_RULES` gives, and its reason when it is `needs-you`. */
25
+ export declare function sessionStatus(s: StatusSignals): {
26
+ status: LiveSessionStatus;
27
+ reason?: NeedsYouReason;
28
+ };
29
+ /** The fields of a Live Session the table needs. */
30
+ export interface StatusTarget {
31
+ account: string;
32
+ family: string;
33
+ sessionId: string;
34
+ status: LiveSessionStatus;
35
+ transcript?: string;
36
+ }
37
+ /** What sideby keeps for Sessions, read once per listing. */
38
+ export interface SessionAttention {
39
+ decisions: readonly PendingDecision[];
40
+ receipts: readonly MessageReceipt[];
41
+ }
42
+ /** The signals of one Session, from its Host status and what sideby keeps for it. */
43
+ export declare function signalsOf(s: StatusTarget, kept: SessionAttention): StatusSignals;
44
+ /** Each Session with the status the table gives it; `reason` is set only on `needs-you`, and dropped otherwise. */
45
+ export declare function withStatus<T extends StatusTarget & {
46
+ reason?: NeedsYouReason;
47
+ }>(sessions: readonly T[], kept: SessionAttention): T[];
48
+ /** How many of the newest Messages are looked at: each may read the end of its target's record. */
49
+ export declare const MESSAGES_LOOKED_AT = 50;
50
+ /**
51
+ * Reads what sideby keeps for Sessions: open Pending Decisions and the newest Messages, both without writing (an old
52
+ * done Decision is not deleted, a Message found read is not saved). A store that cannot be read adds a problem line
53
+ * and counts as empty.
54
+ */
55
+ export declare function readAttention(stateDir: string, messages: () => Promise<readonly MessageReceipt[]>, problems: string[]): Promise<SessionAttention>;
@@ -0,0 +1,59 @@
1
+ import { listPendingDecisions } from './unattended-pending.js';
2
+ /** The table of spec §3.32 step 1, in order; the first row whose `when` holds gives the status. */
3
+ export const STATUS_RULES = [
4
+ { status: 'needs-you', reason: 'host-waits', when: (s) => s.host === 'needs-you' },
5
+ { status: 'needs-you', reason: 'pending-decision', when: (s) => s.pendingDecisions > 0 },
6
+ { status: 'needs-you', reason: 'message-to-approve', when: (s) => s.messagesToApprove > 0 },
7
+ { status: 'needs-you', reason: 'message-to-paste', when: (s) => s.messagesToPaste > 0 },
8
+ { status: 'busy', when: (s) => s.host === 'busy' },
9
+ { status: 'idle', when: (s) => s.host === 'idle' },
10
+ { status: 'unknown', when: () => true },
11
+ ];
12
+ /** The status the first matching row of `STATUS_RULES` gives, and its reason when it is `needs-you`. */
13
+ export function sessionStatus(s) {
14
+ const row = STATUS_RULES.find((r) => r.when(s));
15
+ return row.reason ? { status: row.status, reason: row.reason } : { status: row.status };
16
+ }
17
+ /** The signals of one Session, from its Host status and what sideby keeps for it. */
18
+ export function signalsOf(s, kept) {
19
+ const pendingDecisions = kept.decisions.filter((d) => !d.doneAt &&
20
+ d.sessionId === s.sessionId &&
21
+ d.family === s.family &&
22
+ (!d.account || d.account === s.account)).length;
23
+ const mine = kept.receipts.filter((r) => r.toSessionId === s.sessionId && r.toAccount === s.account);
24
+ return {
25
+ host: s.status,
26
+ pendingDecisions,
27
+ messagesToApprove: mine.filter((r) => r.status === 'delivered' && r.needsApproval).length,
28
+ // Only where sideby can see the Session's record: a paste shows there and clears the row; without one it never would.
29
+ messagesToPaste: s.transcript ? mine.filter((r) => r.status === 'paste-needed').length : 0,
30
+ };
31
+ }
32
+ /** Each Session with the status the table gives it; `reason` is set only on `needs-you`, and dropped otherwise. */
33
+ export function withStatus(sessions, kept) {
34
+ return sessions.map((s) => {
35
+ const { reason: _old, ...rest } = s;
36
+ const r = sessionStatus(signalsOf(s, kept));
37
+ return { ...rest, status: r.status, ...(r.reason ? { reason: r.reason } : {}) };
38
+ });
39
+ }
40
+ /** How many of the newest Messages are looked at: each may read the end of its target's record. */
41
+ export const MESSAGES_LOOKED_AT = 50;
42
+ /**
43
+ * Reads what sideby keeps for Sessions: open Pending Decisions and the newest Messages, both without writing (an old
44
+ * done Decision is not deleted, a Message found read is not saved). A store that cannot be read adds a problem line
45
+ * and counts as empty.
46
+ */
47
+ export async function readAttention(stateDir, messages, problems) {
48
+ const [decisions, receipts] = await Promise.all([
49
+ listPendingDecisions(stateDir, { prune: false }).catch((err) => {
50
+ problems.push(`could not read Pending Decisions (${err.code ?? err.message}); sessions waiting on one are not marked; run \`sideby unattended pending\` to see why`);
51
+ return [];
52
+ }),
53
+ messages().catch((err) => {
54
+ problems.push(`could not read sent messages (${err.code ?? err.message}); sessions with a message to paste are not marked; run \`sideby messages\` to see why`);
55
+ return [];
56
+ }),
57
+ ]);
58
+ return { decisions, receipts };
59
+ }
@@ -0,0 +1,39 @@
1
+ /** How many times in a row one session's failed turn is started again before it is left for the user. */
2
+ export declare const RETRY_LIMIT = 3;
3
+ /** The wait before the first retry; each next one waits twice as long (1, 2 and 4 minutes). */
4
+ export declare const RETRY_FIRST_MS = 60000;
5
+ /** A streak older than this starts again from one (a failure the next night is not the fourth of last night's). */
6
+ export declare const RETRY_FRESH_MS: number;
7
+ /** The `timeout` of the hook entry: the longest wait (4 minutes) with room to spare. */
8
+ export declare const RETRY_HOOK_TIMEOUT_S = 600;
9
+ /** The wait before retry `n` (1-based). */
10
+ export declare const retryDelay: (n: number) => number;
11
+ /** The `StopFailure` error types (Claude Code's hook `error` field) that can be a passing failure. */
12
+ export declare const PASSING_ERRORS: readonly string[];
13
+ /**
14
+ * Whether a failed turn's error is a passing one, from the hook input's `error` type and its text
15
+ * (`last_assistant_message`, `error_details`). Checked with Claude Code 2.1.316 against a local server: HTTP 500 and
16
+ * a refused connection come as `server_error`, 429 as `rate_limit`, 408 as `unknown`.
17
+ */
18
+ export declare function passingFailure(error: string | undefined, text: string): boolean;
19
+ /** One session's run of failed turns that were started again. */
20
+ export interface RetryStreak {
21
+ /** How many failures in a row, this one included. */
22
+ count: number;
23
+ /** The wait this failure's hook owns; a later failure or a finished turn replaces or removes it. */
24
+ token: string;
25
+ at: string;
26
+ }
27
+ /** The session's streak, or undefined when there is none or its folder is not safe to read. */
28
+ export declare function readRetryStreak(stateDir: string, sessionId: string): Promise<RetryStreak | undefined>;
29
+ /**
30
+ * Counts one more failure for the session and returns the streak with a new token. A streak older than
31
+ * `RETRY_FRESH_MS` starts again from one. Throws when the folder is not safe to use (the caller then retries nothing).
32
+ */
33
+ export declare function countFailure(stateDir: string, sessionId: string, now: Date): Promise<RetryStreak>;
34
+ /** Ends the session's streak: its turn finished, or it was left for the user. */
35
+ export declare function clearRetryStreak(stateDir: string, sessionId: string): Promise<void>;
36
+ /** What the model reads when its session is woken to go on after a passing failure. */
37
+ export declare function retryMessage(error: string, text: string, count: number, zh: boolean): string;
38
+ /** What the user reads in the morning when the retries ran out: kept as a Pending Decision. */
39
+ export declare function retryGaveUpText(error: string, text: string): string;
@@ -0,0 +1,107 @@
1
+ // Turn Retry (spec §3.37 item 6, ADR-0067): while Unattended Mode is on, a Claude turn that ended on a passing failure
2
+ // (an overloaded or failing server, a rate limit that is not a used-up Quota, a dropped or refused connection) is
3
+ // started again by `unattended-hook`'s background `StopFailure` entry, at most `RETRY_LIMIT` times in a row per
4
+ // session, each after a longer wait. A leaf module (Node built-ins and core/fs-safe.ts only): the hook imports it.
5
+ //
6
+ // The streak of one session is a file under `<state>/unattended/retries/`, named by a hash of the session id, so a
7
+ // session id never becomes a path. Both folders must be real folders of the user that nobody else can write to
8
+ // (`ownedFolder`, as for Pending Decisions); when one is not, nothing is read or written there and no turn is retried.
9
+ import { randomBytes } from 'node:crypto';
10
+ import { rm } from 'node:fs/promises';
11
+ import { join } from 'node:path';
12
+ import { ownedFolder, readSmallFile, sha256, writeFileAtomic } from './fs-safe.js';
13
+ /** How many times in a row one session's failed turn is started again before it is left for the user. */
14
+ export const RETRY_LIMIT = 3;
15
+ /** The wait before the first retry; each next one waits twice as long (1, 2 and 4 minutes). */
16
+ export const RETRY_FIRST_MS = 60_000;
17
+ /** A streak older than this starts again from one (a failure the next night is not the fourth of last night's). */
18
+ export const RETRY_FRESH_MS = 6 * 60 * 60_000;
19
+ /** The `timeout` of the hook entry: the longest wait (4 minutes) with room to spare. */
20
+ export const RETRY_HOOK_TIMEOUT_S = 600;
21
+ /** The wait before retry `n` (1-based). */
22
+ export const retryDelay = (n) => RETRY_FIRST_MS * 2 ** (Math.max(1, n) - 1);
23
+ /** The `StopFailure` error types (Claude Code's hook `error` field) that can be a passing failure. */
24
+ export const PASSING_ERRORS = ['rate_limit', 'overloaded', 'server_error', 'unknown'];
25
+ /**
26
+ * Claude Code's wording when a Quota, a plan limit, a spend cap or credits are used up (its error reference: "You've
27
+ * hit your session limit", "Fable limit reached", "monthly spend limit", "Credit balance is too low", "Usage credits
28
+ * required"). Waiting minutes does not help those: Auto Handoff or `autoContinueAtUsageLimit` takes them. A plain
29
+ * "Rate limit reached" is a throttle, not a used-up Quota.
30
+ */
31
+ const USED_UP = /hit your|usage limit|out of (?:extra )?usage|spend limit|spending limit|credit balance|usage credits|(?<!rate )limit reached/i;
32
+ /** What an `unknown` error must say to count as passing: a timeout or overload status, or a dropped connection. */
33
+ const PASSING_TEXT = /\b(?:408|429|5\d\d)\b|timed? ?out|timeout|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|EPIPE|socket hang up|connection (?:refused|reset|error|closed)|network|overloaded|temporarily/i;
34
+ /**
35
+ * Whether a failed turn's error is a passing one, from the hook input's `error` type and its text
36
+ * (`last_assistant_message`, `error_details`). Checked with Claude Code 2.1.316 against a local server: HTTP 500 and
37
+ * a refused connection come as `server_error`, 429 as `rate_limit`, 408 as `unknown`.
38
+ */
39
+ export function passingFailure(error, text) {
40
+ if (!error || !PASSING_ERRORS.includes(error) || USED_UP.test(text))
41
+ return false;
42
+ return error !== 'unknown' || PASSING_TEXT.test(text);
43
+ }
44
+ const PARTS = ['unattended', 'retries'];
45
+ const fileName = (sessionId) => `${sha256(sessionId).slice(0, 32)}.json`;
46
+ function parse(text) {
47
+ if (!text)
48
+ return undefined;
49
+ try {
50
+ const v = JSON.parse(text);
51
+ if (typeof v.count !== 'number' || !Number.isInteger(v.count) || v.count < 1)
52
+ return undefined;
53
+ if (typeof v.token !== 'string' || typeof v.at !== 'string' || !Number.isFinite(Date.parse(v.at)))
54
+ return undefined;
55
+ return { count: v.count, token: v.token, at: v.at };
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
61
+ /** The session's streak, or undefined when there is none or its folder is not safe to read. */
62
+ export async function readRetryStreak(stateDir, sessionId) {
63
+ const dir = await ownedFolder(stateDir, PARTS, { create: false }).catch(() => null);
64
+ if (!dir)
65
+ return undefined;
66
+ return parse(await readSmallFile(join(dir, fileName(sessionId)), 4096));
67
+ }
68
+ /**
69
+ * Counts one more failure for the session and returns the streak with a new token. A streak older than
70
+ * `RETRY_FRESH_MS` starts again from one. Throws when the folder is not safe to use (the caller then retries nothing).
71
+ */
72
+ export async function countFailure(stateDir, sessionId, now) {
73
+ const dir = (await ownedFolder(stateDir, PARTS, { create: true, private: true }));
74
+ const file = join(dir, fileName(sessionId));
75
+ const old = parse(await readSmallFile(file, 4096));
76
+ const fresh = old && now.getTime() - Date.parse(old.at) < RETRY_FRESH_MS;
77
+ const streak = {
78
+ count: fresh ? old.count + 1 : 1,
79
+ token: randomBytes(8).toString('hex'),
80
+ at: now.toISOString(),
81
+ };
82
+ await writeFileAtomic(file, `${JSON.stringify(streak)}\n`, 0o600);
83
+ return streak;
84
+ }
85
+ /** Ends the session's streak: its turn finished, or it was left for the user. */
86
+ export async function clearRetryStreak(stateDir, sessionId) {
87
+ const dir = await ownedFolder(stateDir, PARTS, { create: false }).catch(() => null);
88
+ if (dir)
89
+ await rm(join(dir, fileName(sessionId)), { force: true });
90
+ }
91
+ const clip = (s, max) => {
92
+ const one = s.replace(/\s+/g, ' ').trim();
93
+ return one.length <= max ? one : `${one.slice(0, max - 1)}…`;
94
+ };
95
+ /** What the model reads when its session is woken to go on after a passing failure. */
96
+ export function retryMessage(error, text, count, zh) {
97
+ const why = clip(`${error}${text ? `: ${text}` : ''}`, 200);
98
+ if (zh)
99
+ return `sideby 无人值守:你上一个回合因为暂时性的错误中断了(${why}),没人在,sideby 让会话接着做(第 ${count} 次,最多 ${RETRY_LIMIT} 次)。先看看已经做完了什么,不要重做,从中断的地方继续完成任务。`;
100
+ return `sideby's Unattended Mode: your last turn failed for a passing reason (${why}), and nobody is here to start it again, so sideby did (retry ${count} of ${RETRY_LIMIT}). Check what is already done, do not redo it, and continue the task where it stopped.`;
101
+ }
102
+ /** What the user reads in the morning when the retries ran out: kept as a Pending Decision. */
103
+ export function retryGaveUpText(error, text) {
104
+ const why = clip(`${error}${text ? `: ${text}` : ''}`, 300);
105
+ const waits = Array.from({ length: RETRY_LIMIT }, (_, i) => retryDelay(i + 1) / 60_000).join(', ');
106
+ return `The session stopped: its turn kept failing for a passing reason (${why}). sideby started it again ${RETRY_LIMIT} times (after ${waits} minutes) and then left it. Continue the session when you are back.`;
107
+ }
@@ -132,8 +132,8 @@ export declare const unattendedClock: (iso: string, now: Date, zh?: boolean) =>
132
132
  /**
133
133
  * Unattended Mode's session hooks: before the ask tool and when the model ends its turn (`Stop`, which keeps a turn
134
134
  * 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 and every MCP server form (`Elicitation`). Codex has no such events for them; its own approval
136
- * prompts are not covered.
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.
137
137
  */
138
138
  export declare function unattendedHookPart(): SessionHookPart;
139
139
  /** The line a Claude Launch prints when the user's own `--settings` leaves no room for the hook. */
@@ -9,6 +9,7 @@ import { UserError } from './errors.js';
9
9
  import { ownedFolder, writeFileAtomic } from './fs-safe.js';
10
10
  import { sidebyHookCommand } from './session-hooks.js';
11
11
  import { listPendingDecisions } from './unattended-pending.js';
12
+ import { RETRY_HOOK_TIMEOUT_S } from './unattended-retry.js';
12
13
  import { clearUnattendedOverride, clockText, ensureUnattendedDir, MAX_MANUAL_MS, parseClock, parseDays, parseSlot, readUnattendedConfig, readUnattendedOverride, scheduleStretchAt, slotEnd, UNATTENDED_ENV, unattendedState, writeUnattendedOverride, } from './unattended-state.js';
13
14
  /** Families whose sessions Unattended Mode covers in v1. */
14
15
  export const UNATTENDED_FAMILIES = ['claude', 'codex'];
@@ -291,8 +292,8 @@ export const unattendedClock = (iso, now, zh = false) => clockText(Date.parse(is
291
292
  /**
292
293
  * Unattended Mode's session hooks: before the ask tool and when the model ends its turn (`Stop`, which keeps a turn
293
294
  * that ended on a question going once) in Claude and Codex; and in Claude on every permission request Claude Code is
294
- * about to show and every MCP server form (`Elicitation`). Codex has no such events for them; its own approval
295
- * prompts are not covered.
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.
296
297
  */
297
298
  export function unattendedHookPart() {
298
299
  const command = (family, event = 'PreToolUse') => sidebyHookCommand('unattended-hook', family, event);
@@ -305,6 +306,13 @@ export function unattendedHookPart() {
305
306
  PermissionRequest: [{ matcher: '*', hooks: claude('PermissionRequest') }],
306
307
  Stop: [{ hooks: claude('Stop') }],
307
308
  Elicitation: [{ matcher: '*', hooks: claude('Elicitation') }],
309
+ // Waits up to 4 minutes before it wakes the session; Claude Code still enforces `timeout` on `asyncRewake`.
310
+ // No matcher: every failed turn reaches it, so a later failure that is not retried still ends an earlier wait.
311
+ StopFailure: [
312
+ {
313
+ hooks: [{ ...claude('StopFailure')[0], asyncRewake: true, timeout: RETRY_HOOK_TIMEOUT_S }],
314
+ },
315
+ ],
308
316
  },
309
317
  codex: {
310
318
  PreToolUse: [`{matcher="^request_user_input$",${codex('PreToolUse')}}`],
@@ -3,7 +3,7 @@
3
3
  // back as a paste with the reason; nothing here reads a key file or a token.
4
4
  import { inboundGroups } from '../../core/inbound.js';
5
5
  import { hostArgs } from '../../core/live-sessions-procs.js';
6
- import { checkSocket, claudeSocketOf, DELIVER_TIMEOUT_MS, messageLine, sessionBypass, socketChanged, socketRoots, UnconfirmedWrite, writeToSocket, } from './messaging.js';
6
+ import { checkSocket, claudeSocketOf, DELIVER_TIMEOUT_MS, messageLine, PassingWriteError, sessionBypass, socketChanged, socketRoots, UnconfirmedWrite, writeToSocket, } from './messaging.js';
7
7
  export async function deliverClaude(req) {
8
8
  const { rt, to, acct, pid, procs, deps } = req;
9
9
  const paste = (note) => ({ status: 'paste-needed', note });
@@ -35,7 +35,11 @@ export async function deliverClaude(req) {
35
35
  note: `sideby wrote it to ${to.label} but could not confirm it arrived (${err.message}).${ended ? ' The session has ended since.' : ''} It may still show up; check the session before you send it again`,
36
36
  };
37
37
  }
38
- return paste(`sideby could not reach ${to.label} (${err.message}); paste the line into its tab`);
38
+ // Nothing was written: a failure that may pass is tried again (core/messages.ts), any other is a paste.
39
+ return {
40
+ ...paste(`sideby could not reach ${to.label} (${err.message}); paste the line into its tab`),
41
+ ...(err instanceof PassingWriteError ? { retry: true } : {}),
42
+ };
39
43
  }
40
44
  if (inbound === 'accept')
41
45
  return { status: 'delivered' };
@@ -60,10 +60,17 @@ export declare const messageLine: (text: string) => string;
60
60
  */
61
61
  export declare class UnconfirmedWrite extends Error {
62
62
  }
63
+ /**
64
+ * Nothing was written, and the failure may pass: the session refused or dropped the connection, its queue was full,
65
+ * or it did not answer in time. Sending again cannot deliver the line twice, so the delivery is tried again.
66
+ */
67
+ export declare class PassingWriteError extends Error {
68
+ }
63
69
  /**
64
70
  * Connects to `path`, runs `verify` (a reason rejects before anything is written), writes `line`, and closes the
65
71
  * connection as soon as the line is flushed, also when the peer keeps its end open. Rejects on a refused connection
66
- * or after `timeoutMs`; with `UnconfirmedWrite` once the line was written and the flush did not come.
72
+ * or after `timeoutMs` (with `PassingWriteError` when nothing was written and it may pass); with `UnconfirmedWrite`
73
+ * once the line was written and the flush did not come.
67
74
  */
68
75
  export declare function writeToSocket(path: string, line: string, timeoutMs?: number, verify?: () => Promise<string | null>): Promise<void>;
69
76
  /** Whether Host arguments start Claude Code in bypass permission mode. */
@@ -111,10 +111,19 @@ export const messageLine = (text) => `${JSON.stringify({ type: 'user', message:
111
111
  */
112
112
  export class UnconfirmedWrite extends Error {
113
113
  }
114
+ /**
115
+ * Nothing was written, and the failure may pass: the session refused or dropped the connection, its queue was full,
116
+ * or it did not answer in time. Sending again cannot deliver the line twice, so the delivery is tried again.
117
+ */
118
+ export class PassingWriteError extends Error {
119
+ }
120
+ /** Socket errors before anything is written that a session that is busy for a moment gives. */
121
+ const PASSING_CODES = new Set(['ECONNREFUSED', 'ECONNRESET', 'EAGAIN', 'ETIMEDOUT', 'EPIPE']);
114
122
  /**
115
123
  * Connects to `path`, runs `verify` (a reason rejects before anything is written), writes `line`, and closes the
116
124
  * connection as soon as the line is flushed, also when the peer keeps its end open. Rejects on a refused connection
117
- * or after `timeoutMs`; with `UnconfirmedWrite` once the line was written and the flush did not come.
125
+ * or after `timeoutMs` (with `PassingWriteError` when nothing was written and it may pass); with `UnconfirmedWrite`
126
+ * once the line was written and the flush did not come.
118
127
  */
119
128
  export function writeToSocket(path, line, timeoutMs = DELIVER_TIMEOUT_MS, verify) {
120
129
  return new Promise((resolve, reject) => {
@@ -132,7 +141,7 @@ export function writeToSocket(path, line, timeoutMs = DELIVER_TIMEOUT_MS, verify
132
141
  else
133
142
  resolve();
134
143
  };
135
- const timer = setTimeout(() => finish(new Error(`it did not answer within ${timeoutMs / 1000} s`)), timeoutMs);
144
+ const timer = setTimeout(() => finish(new PassingWriteError(`it did not answer within ${timeoutMs / 1000} s`)), timeoutMs);
136
145
  sock.once('connect', async () => {
137
146
  const changed = verify ? await verify().catch((e) => e.message) : null;
138
147
  if (changed)
@@ -142,7 +151,10 @@ export function writeToSocket(path, line, timeoutMs = DELIVER_TIMEOUT_MS, verify
142
151
  written = true;
143
152
  sock.end(line, () => finish(null));
144
153
  });
145
- sock.once('error', (err) => finish(new Error(err.code === 'ECONNREFUSED' ? 'it refused the connection' : (err.code ?? err.message))));
154
+ sock.once('error', (err) => {
155
+ const why = err.code === 'ECONNREFUSED' ? 'it refused the connection' : (err.code ?? err.message);
156
+ finish(err.code && PASSING_CODES.has(err.code) ? new PassingWriteError(why) : new Error(why));
157
+ });
146
158
  });
147
159
  }
148
160
  /** Whether Host arguments start Claude Code in bypass permission mode. */
@@ -28,5 +28,11 @@ export interface Delivery {
28
28
  note?: string;
29
29
  /** The Host took it but shows it only after the user approves it in the target's terminal (ADR-0045). */
30
30
  needsApproval?: boolean;
31
+ /**
32
+ * A `paste-needed` whose channel took nothing and failed in a way that may pass (a refused connection, no answer
33
+ * before writing): sending again cannot deliver it twice, so `core/messages.ts` tries again after a wait. Never
34
+ * kept in a receipt.
35
+ */
36
+ retry?: boolean;
31
37
  }
32
38
  export declare const DELIVERERS: Readonly<Record<string, (req: DeliveryRequest) => Promise<Delivery>>>;
@@ -52,7 +52,7 @@ const WHY = {
52
52
  };
53
53
  /** The next session's first prompt: the Brief's path only, never its text (it would show in a process list). */
54
54
  export function firstPrompt(fromRef, brief, trigger) {
55
- return `This task was handed over from ${fromRef} by sideby because ${WHY[trigger]}. Read ${brief} first, then continue the task it describes. If the user asks to move the task to another account (back to ${fromRef}, say), run \`sideby handoff ready --to <account>\` and end your turn.`;
55
+ return `This task was handed over from ${fromRef} by sideby because ${WHY[trigger]}. Read ${brief} first, then continue the task it describes. The previous session may have stopped mid-step: check the working tree, git history and any remote state before you repeat an outside action such as a push, a message or a pull request, and do not repeat one that already happened. If the user asks to move the task to another account (back to ${fromRef}, say), run \`sideby handoff ready --to <account>\` and end your turn.`;
56
56
  }
57
57
  const clock = (iso) => new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
58
58
  /** For the user, not the model (ADR-0018): this session will wait for the reset, and how to move on now instead. */
@@ -935,6 +935,12 @@ declare const en: {
935
935
  'spage.status.busy': string;
936
936
  'spage.status.idle': string;
937
937
  'spage.status.unknown': string;
938
+ 'spage.why.host-waits': string;
939
+ 'spage.why.pending-decision': string;
940
+ 'spage.why.message-to-approve': string;
941
+ 'spage.why.message-to-paste': string;
942
+ 'spage.decision': string;
943
+ 'spage.decisionTip': string;
938
944
  'spage.guessed': string;
939
945
  'spage.guessedTip': string;
940
946
  'spage.run': string;
@@ -937,6 +937,12 @@ const en = {
937
937
  'spage.status.busy': 'Working',
938
938
  'spage.status.idle': 'Idle',
939
939
  'spage.status.unknown': 'Running',
940
+ 'spage.why.host-waits': 'It waits in its terminal for your answer or your approval.',
941
+ 'spage.why.pending-decision': 'It asked something while you were away, and the answer is still yours to give. See it under Unattended.',
942
+ 'spage.why.message-to-approve': 'A message sent to it shows only once you approve it in its terminal.',
943
+ 'spage.why.message-to-paste': 'A message sent to it is waiting for you to paste it into its tab.',
944
+ 'spage.decision': 'Decision waiting',
945
+ 'spage.decisionTip': 'Open Unattended to see what it asked and mark it done.',
940
946
  'spage.guessed': 'newest session (guessed)',
941
947
  'spage.guessedTip': 'sideby could not tell which session this account is running, so it shows the newest one.',
942
948
  'spage.run': 'Task: {title}',
@@ -1512,13 +1518,13 @@ const en = {
1512
1518
  'ua.untilDay': 'until {day} {time}',
1513
1519
  'ua.backToday': 'back on at {time}',
1514
1520
  'ua.backDay': 'back on {day} {time}',
1515
- 'ua.nextToday': 'next: {time}',
1516
- 'ua.nextDay': 'next: {day} {time}',
1521
+ 'ua.nextToday': 'turns on at {time}',
1522
+ 'ua.nextDay': 'turns on {day} {time}',
1517
1523
  'ua.today': 'today',
1518
1524
  'ua.tomorrow': 'tomorrow',
1519
1525
  'ua.noEnd': 'stays on: your Schedule covers every hour',
1520
1526
  'ua.pausedOpen': 'until you turn it on again',
1521
- 'ua.onNote': 'Sessions sideby starts do not stop to wait for you. Questions go on with the recommended choice; a step Claude Code wants you to confirm is refused, and the session finds another way or skips it. What they skipped is listed below.',
1527
+ 'ua.onNote': 'Sessions sideby starts do not stop to wait for you. Questions go on with the recommended choice; a step Claude Code wants you to confirm is refused, and the session finds another way or skips it; a Claude turn cut off by a passing server or network error is started again, up to 3 times. What they skipped is listed below.',
1522
1528
  'ua.offNote': 'When it is on, sessions sideby starts do not stop to wait for you: no questions, and no prompts asking you to confirm a step.',
1523
1529
  'ua.pausedNote': 'Until then, sessions ask you as usual. Turn it on now to go back.',
1524
1530
  'ua.turnOn': 'Turn on now',
@@ -2532,6 +2538,12 @@ const zh = {
2532
2538
  'spage.status.busy': '运行中',
2533
2539
  'spage.status.idle': '空闲',
2534
2540
  'spage.status.unknown': '在运行',
2541
+ 'spage.why.host-waits': '它在终端里等你回答或批准。',
2542
+ 'spage.why.pending-decision': '你不在时它问过一件事,还等你决定。在「无人值守」页能看到。',
2543
+ 'spage.why.message-to-approve': '发给它的消息要你在它的终端里批准后才显示。',
2544
+ 'spage.why.message-to-paste': '发给它的消息还等你粘贴到它的标签页里。',
2545
+ 'spage.decision': '有事待你决定',
2546
+ 'spage.decisionTip': '打开「无人值守」页,看它问了什么,处理完标为已完成。',
2535
2547
  'spage.guessed': '最新会话(推测)',
2536
2548
  'spage.guessedTip': 'sideby 没法确定这个账号正在跑哪个会话,先显示它最新的一个。',
2537
2549
  'spage.run': '任务:{title}',
@@ -3104,16 +3116,16 @@ const zh = {
3104
3116
  'ua.slotQuoted': '时段『{name}』',
3105
3117
  'ua.slotN': '时段 {n}',
3106
3118
  'ua.untilToday': '到 {time}',
3107
- 'ua.untilDay': '到{day} {time}',
3108
- 'ua.backToday': '到 {time} 后恢复',
3109
- 'ua.backDay': '到{day} {time} 后恢复',
3110
- 'ua.nextToday': '下一次 {time}',
3111
- 'ua.nextDay': '下一次 {day} {time}',
3119
+ 'ua.untilDay': '到 {day} {time}',
3120
+ 'ua.backToday': '{time} 自动恢复',
3121
+ 'ua.backDay': '{day} {time} 自动恢复',
3122
+ 'ua.nextToday': '{time} 自动开启',
3123
+ 'ua.nextDay': '{day} {time} 自动开启',
3112
3124
  'ua.today': '今天',
3113
3125
  'ua.tomorrow': '明天',
3114
3126
  'ua.noEnd': '一直开着:时间表覆盖了每个小时',
3115
3127
  'ua.pausedOpen': '等你再打开',
3116
- 'ua.onNote': 'sideby 启动的会话不会停下来等你:提问按推荐继续;Claude Code 要你确认的操作直接拒绝,会话换个做法或跳过。跳过的记在下面。',
3128
+ 'ua.onNote': 'sideby 启动的会话不会停下来等你:提问按推荐继续;Claude Code 要你确认的操作直接拒绝,会话换个做法或跳过;Claude 回合因为服务器或网络的暂时问题中断时,自动接着跑,最多 3 次。跳过的记在下面。',
3117
3129
  'ua.offNote': '开着时,sideby 启动的会话不停下来等你:不提问,也不弹要你确认的框。',
3118
3130
  'ua.pausedNote': '在那之前,会话照常问你。现在开就恢复。',
3119
3131
  'ua.turnOn': '现在开',
@@ -402,6 +402,22 @@ export declare function sortSessions<T extends LogicSession>(list: readonly T[])
402
402
  * shown before comes ahead of the shown ones, in `sortSessions` order.
403
403
  */
404
404
  export declare function steadyOrder<T extends LogicSession>(shown: readonly string[], list: readonly T[]): T[];
405
+ /**
406
+ * Everything a Sessions row shows except its age, as plain values: the page redraws a row only when this changes.
407
+ * `reason` is in it, so a Session that keeps `needs-you` for another reason (a decision instead of its Host asking)
408
+ * gets its button and its hint redrawn.
409
+ */
410
+ export declare function sessionRowShape(s: LogicSession & {
411
+ family?: string;
412
+ reason?: string;
413
+ guessed?: boolean;
414
+ copy?: unknown;
415
+ orca?: unknown;
416
+ run?: unknown;
417
+ }, msg?: {
418
+ status: string;
419
+ needsApproval?: boolean;
420
+ }): unknown[];
405
421
  /** How long ago a Session was last active, as a message key and count; null when it has no time at all. */
406
422
  export declare function sessionAge(s: LogicSession, now: number): {
407
423
  key: string;
@@ -801,6 +801,29 @@ export function steadyOrder(shown, list) {
801
801
  rank.sort((a, b) => needs(a.s) - needs(b.s) || a.seen - b.seen || a.at - b.at);
802
802
  return rank.map((x) => x.s);
803
803
  }
804
+ /**
805
+ * Everything a Sessions row shows except its age, as plain values: the page redraws a row only when this changes.
806
+ * `reason` is in it, so a Session that keeps `needs-you` for another reason (a decision instead of its Host asking)
807
+ * gets its button and its hint redrawn.
808
+ */
809
+ export function sessionRowShape(s, msg) {
810
+ return [
811
+ s.sessionId,
812
+ s.account,
813
+ s.accountLabel,
814
+ s.family,
815
+ s.title,
816
+ s.label,
817
+ s.status,
818
+ s.reason || '',
819
+ s.cwd,
820
+ s.guessed,
821
+ s.copy,
822
+ Boolean(s.orca),
823
+ s.run || null,
824
+ msg ? msg.status + (msg.needsApproval ? '+approve' : '') : '',
825
+ ];
826
+ }
804
827
  /** How long ago a Session was last active, as a message key and count; null when it has no time at all. */
805
828
  export function sessionAge(s, now) {
806
829
  const ts = Date.parse(s.updatedAt || s.startedAt || '');
@@ -5,7 +5,7 @@ import { groupsToAccept } from '../core/inbound.js';
5
5
  import { quotaIsStale } from '../core/quota-levels.js';
6
6
  import { remoteControlTodo } from '../core/remote-control.js';
7
7
  import { catalogMatchLevel, catalogNorm, searchCatalog } from '../core/search-catalog.js';
8
- import { aiTaskAccounts, aliasArgsOf, aliasIssue, askBridge, askBridged, askCopy, attentionReasons, attentionWhy, autostartNote, bindingWindow, cacheHitRate, canLeaveLocal, categoryOrder, codeSwapOutcome, dotsKeepKeyboard, enableOutcome, fileSize, fixPrompt, foldSkips, foldToolCalls, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, hiddenIn, highlightParts, histFilters, historyEmpty, historyWhen, hotkeyFromKey, hotkeyPressKind, inDisplayOrder, loginClusters, loginKey, longWindow, maskEmail, matchesQuery, mdBlocks, mdInline, menuPlacement, mergeDaily, mergeUsage, messageChip, messageNews, messageToCheck, networkTaskFacts, newAccountDir, nextReset, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, quotaAskable, quotaHighLevel, quotaPressure, radioStep, reloadForBuild, remoteControlSummary, reorder, resetWhen, rowBadge, runCodeSwap, saveHandoffChange, sendBlock, sendFileProblem, sendResultView, sessionAge, sessionLabelParts, shortCwd, shortSessionLabel, sortAccounts, sortSessions, steadyOrder, stripSecrets, suggestAlias, suggestName, switchFailure, tailInView, taskFindings, uaDayRuns, uaGroupPending, uaOnChoices, uaParseClock, uaPickTime, uaSameSlot, uaShouldRead, uaSlotNight, uaStatusParts, uaStepClock, uaToggleDay, uaWaitingCount, uaWhen, updatedAge, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
8
+ import { aiTaskAccounts, aliasArgsOf, aliasIssue, askBridge, askBridged, askCopy, attentionReasons, attentionWhy, autostartNote, bindingWindow, cacheHitRate, canLeaveLocal, categoryOrder, codeSwapOutcome, dotsKeepKeyboard, enableOutcome, fileSize, fixPrompt, foldSkips, foldToolCalls, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, hiddenIn, highlightParts, histFilters, historyEmpty, historyWhen, hotkeyFromKey, hotkeyPressKind, inDisplayOrder, loginClusters, loginKey, longWindow, maskEmail, matchesQuery, mdBlocks, mdInline, menuPlacement, mergeDaily, mergeUsage, messageChip, messageNews, messageToCheck, networkTaskFacts, newAccountDir, nextReset, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, quotaAskable, quotaHighLevel, quotaPressure, radioStep, reloadForBuild, remoteControlSummary, reorder, resetWhen, rowBadge, runCodeSwap, saveHandoffChange, sendBlock, sendFileProblem, sendResultView, sessionAge, sessionLabelParts, sessionRowShape, shortCwd, shortSessionLabel, sortAccounts, sortSessions, steadyOrder, stripSecrets, suggestAlias, suggestName, switchFailure, tailInView, taskFindings, uaDayRuns, uaGroupPending, uaOnChoices, uaParseClock, uaPickTime, uaSameSlot, uaShouldRead, uaSlotNight, uaStatusParts, uaStepClock, uaToggleDay, uaWaitingCount, uaWhen, updatedAge, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
9
9
  const LOGIC = [
10
10
  quotaIsStale,
11
11
  catalogNorm,
@@ -82,6 +82,7 @@ const LOGIC = [
82
82
  sendResultView,
83
83
  sessionAge,
84
84
  sessionLabelParts,
85
+ sessionRowShape,
85
86
  shortCwd,
86
87
  shortSessionLabel,
87
88
  sortAccounts,
@@ -3590,7 +3591,8 @@ const MAIN = String.raw `
3590
3591
  p.title ? h('span', { class: 'sess-title' }, p.title) : null,
3591
3592
  h('span', { class: 'mono sess-id' }, p.id)),
3592
3593
  h('div', { class: 'sess-sub muted small' },
3593
- h('span', { class: 'sess-status' }, h('span', { class: 'dot sess-dot', 'aria-hidden': 'true' }), t('spage.status.' + status)),
3594
+ sessStatus(s, status),
3595
+ s.reason === 'pending-decision' && status === 'needs-you' ? h('button', { class: 'chip chip-sm chip-warn chip-btn sess-decision', type: 'button', 'data-key': 'sess-decision-' + s.sessionId, 'data-tip': t('spage.decisionTip'), onclick: () => setPage('unattended') }, t('spage.decision'), icon('chevron')) : null,
3594
3596
  chip ? msgChip(chip, msg, s) : null,
3595
3597
  s.guessed ? h('span', { class: 'chip sess-guessed', tabindex: '0', 'data-tip': t('spage.guessedTip') }, t('spage.guessed')) : null,
3596
3598
  runChip(s),
@@ -3598,6 +3600,11 @@ const MAIN = String.raw `
3598
3600
  h('span', { class: 'sess-age', 'data-age': s.sessionId }, sessAgeText(s)))),
3599
3601
  h('div', { class: 'sess-actions' }, copyBtn, sendBtn, more)), liveMenu)
3600
3602
  }
3603
+ // The status, and why a Session needs the user when sideby knows (spec §3.32 step 1's table).
3604
+ function sessStatus(s, status) {
3605
+ const why = status === 'needs-you' && ['host-waits', 'pending-decision', 'message-to-approve', 'message-to-paste'].includes(s.reason) ? t('spage.why.' + s.reason) : null
3606
+ return h('span', { class: 'sess-status', tabindex: why ? '0' : null, 'data-tip': why }, h('span', { class: 'dot sess-dot', 'aria-hidden': 'true' }), t('spage.status.' + status))
3607
+ }
3601
3608
  // The latest Message's state on a row. One that waits for a paste opens what to paste and why, so the line is never
3602
3609
  // only in the dialog that sent it.
3603
3610
  function msgChip(chip, msg, s) {
@@ -3651,7 +3658,7 @@ const MAIN = String.raw `
3651
3658
  sp.order = list.map((s) => s.sessionId)
3652
3659
  // Everything a row shows except its age, which renderSessionAges keeps current in place.
3653
3660
  const shape = JSON.stringify([lang, hs.opening, !d && !sp.error, sp.error ? sp.error.message : '', d ? d.problems : [],
3654
- list.map((s) => [s.sessionId, s.account, s.accountLabel, s.family, s.title, s.label, s.status, s.cwd, s.guessed, s.copy, Boolean(s.orca), s.run || null, sp.msgs[s.sessionId] ? sp.msgs[s.sessionId].status + (sp.msgs[s.sessionId].needsApproval ? '+approve' : '') : '']), inboundShape()])
3661
+ list.map((s) => sessionRowShape(s, sp.msgs[s.sessionId])), inboundShape()])
3655
3662
  if (shape === sp.drawn) { sp.pending = false; renderSessionAges(); revealSession(); return }
3656
3663
  if (sessionsMenuOpen()) { sp.pending = true; return }
3657
3664
  sp.pending = false
@@ -5796,7 +5803,8 @@ const MAIN = String.raw `
5796
5803
  const p = uaStatusParts(st)
5797
5804
  const schedule = st.schedule || []
5798
5805
  const slotWord = p.slot !== null && schedule[p.slot] ? uaSlotWord(schedule[p.slot], p.slot) : null
5799
- if (p.state === 'on') return [t('ua.on'), p.byHand ? t('ua.byHand') : slotWord, p.noEnd ? t('ua.noEnd') : uaAt('until', p.until)]
5806
+ // State first, then the one time that matters (until when, or when it comes on), then why.
5807
+ if (p.state === 'on') return [t('ua.on'), p.noEnd ? t('ua.noEnd') : uaAt('until', p.until), p.byHand ? t('ua.byHand') : slotWord]
5800
5808
  if (p.state === 'paused') return [t('ua.paused'), p.noEnd ? t('ua.pausedOpen') : uaAt('back', p.until)]
5801
5809
  return [t('ua.off'), p.next ? uaAt('next', p.next.at) : null]
5802
5810
  }
@@ -5,6 +5,10 @@ export declare const ASK_TOOLS: Readonly<Record<string, string>>;
5
5
  type Env = Record<string, string | undefined>;
6
6
  export interface UnattendedHookDeps {
7
7
  now?: () => Date;
8
+ /** Turn Retry's wait; a real timer by default. */
9
+ sleep?: (ms: number) => Promise<void>;
10
+ /** Whether the Host that started the hook is gone (`ppid` 1 by default): nothing is left to wake. */
11
+ parentGone?: () => boolean;
8
12
  }
9
13
  /**
10
14
  * The question as the user should read it later: each question (with its short header) and its options' labels.
@@ -10,12 +10,16 @@
10
10
  // Claude Code's permission requests with a denial (JSON on stdout: Claude Code does not honor exit 2 for that event),
11
11
  // keeping the request as a Pending Decision too; it keeps a turn going once when the model ended it on a question
12
12
  // written as plain text (`{"decision":"block","reason":…}` on stdout), keeping the question; and it declines an MCP
13
- // server's form, keeping what the server asked. A failure before the decision is made does nothing: that is
13
+ // server's form, keeping what the server asked. In Claude it also runs in the background after a turn that failed for
14
+ // a passing reason (`StopFailure`, `asyncRewake`): it waits, then wakes the session with exit 2 so the turn goes on, at
15
+ // most three times in a row, and keeps a Pending Decision when that did not help (Turn Retry, ADR-0067). A failure
16
+ // before the decision is made does nothing: that is
14
17
  // how a session behaves without the feature (unlike `network-hook`, which blocks when it cannot tell). Once the
15
18
  // decision is to refuse, it refuses: keeping the Pending Decision and writing the reason are best effort, and their
16
19
  // failure neither allows the call nor adds any output of its own.
17
20
  import { resolvePaths } from '../core/paths.js';
18
21
  import { addPendingDecision } from '../core/unattended-pending.js';
22
+ import { clearRetryStreak, countFailure, passingFailure, RETRY_LIMIT, readRetryStreak, retryDelay, retryGaveUpText, retryMessage, } from '../core/unattended-retry.js';
19
23
  import { clockText, readUnattendedConfig, readUnattendedOverride, UNATTENDED_ENV, unattendedState, } from '../core/unattended-state.js';
20
24
  export const UNATTENDED_HOOK_COMMAND = 'sideby unattended-hook';
21
25
  /** The tool each Host's model asks the user with. */
@@ -332,12 +336,21 @@ async function decide(argv, env, input, now) {
332
336
  if (!permission && !elicitation && !stop && (event !== 'PreToolUse' || !askTool))
333
337
  return undefined;
334
338
  const paths = resolvePaths(env);
339
+ // A turn that finished ends the session's run of retried failures (Turn Retry), whether Unattended Mode is on or
340
+ // not: a wait left from earlier must never wake a session whose turn is already done.
341
+ let early;
342
+ if (stop && family === 'claude') {
343
+ early = await readInput(input);
344
+ const sessionId = text(parseObject(early)?.session_id, 256);
345
+ if (sessionId)
346
+ await clearRetryStreak(paths.stateDir, sessionId).catch(() => { });
347
+ }
335
348
  const { schedule } = await readUnattendedConfig(paths.configFile);
336
349
  const override = await readUnattendedOverride(paths.stateDir);
337
350
  const state = unattendedState({ schedule, override, now, session: env[UNATTENDED_ENV] === '1' });
338
351
  if (!state.on)
339
352
  return undefined;
340
- const raw = await readInput(input);
353
+ const raw = early ?? (await readInput(input));
341
354
  const zh = prefersChinese(env);
342
355
  const account = text(env.SIDEBY_ACCOUNT, 256);
343
356
  if (stop || elicitation) {
@@ -418,6 +431,18 @@ async function decide(argv, env, input, now) {
418
431
  * record.
419
432
  */
420
433
  export async function runUnattendedHook(argv, env, input, io, deps = {}) {
434
+ if (argv[0] === 'claude' && argv[1] === 'StopFailure') {
435
+ try {
436
+ const wake = await retryAfterFailure(env, input, deps);
437
+ if (!wake)
438
+ return 0;
439
+ io.err.write(`${wake}\n`);
440
+ return 2;
441
+ }
442
+ catch {
443
+ return 0;
444
+ }
445
+ }
421
446
  let refusal;
422
447
  const now = deps.now ? deps.now() : new Date();
423
448
  try {
@@ -454,3 +479,62 @@ export async function runUnattendedHook(argv, env, input, io, deps = {}) {
454
479
  }
455
480
  return 2;
456
481
  }
482
+ /** Whether Unattended Mode is on right now, read fresh from the Schedule and the manual state. */
483
+ async function isOn(env, now) {
484
+ const paths = resolvePaths(env);
485
+ const { schedule } = await readUnattendedConfig(paths.configFile);
486
+ const override = await readUnattendedOverride(paths.stateDir);
487
+ return unattendedState({ schedule, override, now, session: env[UNATTENDED_ENV] === '1' }).on;
488
+ }
489
+ /**
490
+ * Turn Retry (spec §3.37 item 6, ADR-0067), Claude's background `StopFailure` hook (`asyncRewake`): Claude Code runs it
491
+ * when a turn ends on an API error and ignores its output, but wakes the idle session when it exits 2, with its stderr
492
+ * as the model's next note (checked with Claude Code 2.1.316). While Unattended Mode is on and the failure is a
493
+ * passing one, it counts the failure for the session; up to `RETRY_LIMIT` in a row it waits 1, 2, then 4 minutes and
494
+ * returns the note that wakes the session. Past the limit it keeps a Pending Decision and wakes nothing. It returns
495
+ * nothing (exit 0) when the mode is off, the failure is not passing, there is no session id, or by the end of the wait
496
+ * the mode went off, the Host is gone, or another failure or a finished turn has taken over the session's streak.
497
+ */
498
+ async function retryAfterFailure(env, input, deps) {
499
+ const clock = deps.now ?? (() => new Date());
500
+ const now = clock();
501
+ const v = parseObject(await readInput(input));
502
+ if (!v)
503
+ return undefined;
504
+ const sessionId = text(v.session_id, 256);
505
+ if (!sessionId)
506
+ return undefined;
507
+ const paths = resolvePaths(env);
508
+ const error = typeof v.error === 'string' ? v.error : undefined;
509
+ const said = [text(v.last_assistant_message, 1000), text(v.error_details, 1000)].filter(Boolean).join(' ');
510
+ // A later failure that is not retried (a used-up Quota, a lasting error) or comes while the mode is off still
511
+ // takes over the session: the wait an earlier failure left must not wake it.
512
+ if (!error || !passingFailure(error, said) || !(await isOn(env, now))) {
513
+ await clearRetryStreak(paths.stateDir, sessionId).catch(() => { });
514
+ return undefined;
515
+ }
516
+ const streak = await countFailure(paths.stateDir, sessionId, now);
517
+ if (streak.count > RETRY_LIMIT) {
518
+ const account = text(env.SIDEBY_ACCOUNT, 256);
519
+ const cwd = text(v.cwd);
520
+ await clearRetryStreak(paths.stateDir, sessionId).catch(() => { });
521
+ await addPendingDecision(paths.stateDir, {
522
+ kind: 'deferred',
523
+ family: 'claude',
524
+ ...(account ? { account } : {}),
525
+ sessionId,
526
+ ...(cwd ? { cwd } : {}),
527
+ text: retryGaveUpText(error, text(v.last_assistant_message, 1000) ?? ''),
528
+ }, now, { dedupe: true }).catch(() => { });
529
+ return undefined;
530
+ }
531
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
532
+ await sleep(retryDelay(streak.count));
533
+ if ((deps.parentGone ?? (() => process.ppid === 1))())
534
+ return undefined;
535
+ if ((await readRetryStreak(paths.stateDir, sessionId))?.token !== streak.token)
536
+ return undefined;
537
+ if (!(await isOn(env, clock())))
538
+ return undefined;
539
+ return retryMessage(error, text(v.last_assistant_message, 1000) ?? '', streak.count, prefersChinese(env));
540
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "Run work, personal and API-key accounts at the same time, without their configs drifting apart.",
5
5
  "license": "MIT",
6
6
  "author": "Adonis0123 (https://github.com/Adonis0123)",
@@ -78,7 +78,28 @@
78
78
  "const": "unknown"
79
79
  }
80
80
  ],
81
- "description": "`needs-you`: it waits for the user (a permission or a question); `unknown` where the host does not say."
81
+ "description": "`needs-you`: the user has to act on it (`reason` says why); `busy` and `idle` as the host says; `unknown` where the host does not say. The first matching row of spec §3.32 step 1's status table."
82
+ },
83
+ "reason": {
84
+ "anyOf": [
85
+ {
86
+ "type": "string",
87
+ "const": "host-waits"
88
+ },
89
+ {
90
+ "type": "string",
91
+ "const": "pending-decision"
92
+ },
93
+ {
94
+ "type": "string",
95
+ "const": "message-to-approve"
96
+ },
97
+ {
98
+ "type": "string",
99
+ "const": "message-to-paste"
100
+ }
101
+ ],
102
+ "description": "Only with `needs-you`: the host waits for a permission or an answer; an open Pending Decision names the session (`sideby unattended pending`); a Message to it waits for the user to approve it in its terminal; or a Message to it waits to be pasted (`sideby messages`). New values may be added."
82
103
  },
83
104
  "cwd": {
84
105
  "type": "string"
@@ -2,7 +2,7 @@
2
2
  name: sideby
3
3
  description: Use when the user runs, or wants to run, several AI coding accounts (Claude Code, Codex, Grok Build, pi) side by side. Covers installing sideby and setting up a new account ("install sideby", "set up another Claude account", "add cc008", "配置一个 cc00x", "再加一个 Codex 账号"), explaining what accounts share and what stays separate ("what do my accounts share?", "这些账号共享了什么"), showing which account a session is ("show [cc001] in the status line", "加上账号标识"), finding a past session of any account ("找一下我上周改登录页的那个会话"), telling another running session something, in any account ("告诉 cc002 ……", "给跑构建的那个会话发消息"; Claude Code's own SendMessage reaches only sessions of the same account), seeing accounts, quota and usage, moving on when one hits its 5-hour or weekly limit, moving the current task to another account ("用 cc008 继续", "交回 cc008"), adding a short command (alias) or a pick command that starts whichever account has the most quota ("加个 cc"), adding an API account from a vendor's docs ("加一个 DeepSeek API 账号"), supporting a new tool, and repairing drifted account directories (skills, hooks, rules or settings not shared, wrong symlinks, credential file permissions). Drives the `sideby` CLI with `--json`; the agent does every step except browser sign-in, filling in secrets and starting interactive sessions, which it hands to the user as one command (inside an Auto Handoff session, `sideby handoff ready --to` moves the task itself).
4
4
  metadata:
5
- version: "0.33.0"
5
+ version: "0.34.0"
6
6
  requires:
7
7
  bins: [sideby, node]
8
8
  cliHelp: sideby --help
@@ -7,7 +7,7 @@ For "which session is cc002 running", "cc002 现在在干嘛", "cc002 在哪个
7
7
  Run `sideby sessions --json` (or `sideby sessions <account|family> --json` for one account or host). Each entry of `sessions` is one running session:
8
8
 
9
9
  - `label` is the Session Label, `<account> · <the host's own title> · <first 8 of the id>`, as in `cc002 · knip cleanup · 61230c3d`. Use it when you name a session to the user; sideby never invents the title.
10
- - `status`: `needs-you` (it waits for a permission or an answer: tell the user first), `busy`, `idle`, or `unknown` where the host does not say. Sessions that need the user come first.
10
+ - `status`: `needs-you` (the user has to act on it: tell the user first), `busy`, `idle`, or `unknown` where the host does not say. Sessions that need the user come first. With `needs-you`, `reason` says why, so tell the user what to do: `host-waits` (it waits in its terminal for a permission or an answer), `pending-decision` (it asked something while Unattended Mode was on: show it with `sideby unattended pending --json`, see `unattended.md`), `message-to-approve` (a Message to it waits for the user to approve it in its terminal) or `message-to-paste` (a Message to it waits to be pasted: `sideby messages --to <session-id> --json` gives the line, see "Tell a session something" below).
11
11
  - `cwd`, `startedAt`, `updatedAt`, `transcript` (the path of its record), `resumeCommand`.
12
12
  - `guessed: true` means sideby could not tie a running Codex or pi program to a session and shows that account's newest session instead. Say "probably" when you report it.
13
13
 
@@ -1,6 +1,6 @@
1
1
  # Unattended Mode: sessions that do not stop to wait for a person
2
2
 
3
- Unattended Mode (spec §3.37, ADR-0058) is one state for the whole computer: nobody is there to answer, so the Claude and Codex sessions sideby starts never stop to wait. While it is on, sideby's hook refuses the Host's question tool (Claude `AskUserQuestion`, Codex `request_user_input`) and tells the model to take the recommended option where the choice can be undone and to skip anything hard to undo; each refused question is kept as a **Pending Decision**. When the model ends its turn on a question written as text instead, the hook sends the session on once with the same instructions and keeps that question too. In Claude sessions it also answers "no" to every permission prompt Claude Code is about to show (even in bypass mode, and in subagents), with how to do the step without one; each refused request is kept as a Pending Decision too; and it declines MCP server forms, keeping what the server asked. Codex's own approval prompts still wait.
3
+ Unattended Mode (spec §3.37, ADR-0058) is one state for the whole computer: nobody is there to answer, so the Claude and Codex sessions sideby starts never stop to wait. While it is on, sideby's hook refuses the Host's question tool (Claude `AskUserQuestion`, Codex `request_user_input`) and tells the model to take the recommended option where the choice can be undone and to skip anything hard to undo; each refused question is kept as a **Pending Decision**. When the model ends its turn on a question written as text instead, the hook sends the session on once with the same instructions and keeps that question too. In Claude sessions it also answers "no" to every permission prompt Claude Code is about to show (even in bypass mode, and in subagents), with how to do the step without one; each refused request is kept as a Pending Decision too; and it declines MCP server forms, keeping what the server asked; and a Claude turn that failed for a passing reason (an overloaded or failing server, a dropped connection, a rate limit that is not a used-up quota) is started again after 1, 2, then 4 minutes, and after a fourth failure in a row the session is left with a Pending Decision saying why (Turn Retry, ADR-0067). Codex's own approval prompts still wait.
4
4
 
5
5
  ## Turn it on when the user is leaving
6
6
 
@@ -47,6 +47,8 @@ sideby unattended defer "deleting the old release branch is left for the user" -
47
47
 
48
48
  Then go on with the rest. Do not retry the question, and do not work around the refusal.
49
49
 
50
+ When a note from sideby says your last turn failed for a passing reason, the session was woken to go on: check what is already done (files, commits, background work), do not redo it, and continue where the turn stopped.
51
+
50
52
  ## When the user is back
51
53
 
52
54
  ```sh
@@ -55,6 +57,6 @@ sideby unattended pending --json # each question, refused permission or skipp
55
57
  sideby unattended pending done <id> --json # or --all, once the user has dealt with them
56
58
  ```
57
59
 
58
- Go through the open ones with the user (a `permission` one names the tool, for Bash only the program and the model's description of the step, and `agentType` when a subagent asked; the whole command is in the session itself). A decision with a `sessionId` can be continued in its session: `sideby sessions copy <sessionId> --as resume` copies the command. Done ones are deleted 30 days later. A plugin can be told when a stretch ends through the `unattended.ended` event (`docs/guide/plugins.md`); sideby itself sends no notification.
60
+ Go through the open ones with the user (a `deferred` one that starts "The session stopped" is a session whose turn kept failing after three retries; a `permission` one names the tool, for Bash only the program and the model's description of the step, and `agentType` when a subagent asked; the whole command is in the session itself). A decision with a `sessionId` can be continued in its session: `sideby sessions copy <sessionId> --as resume` copies the command. Done ones are deleted 30 days later. A plugin can be told when a stretch ends through the `unattended.ended` event (`docs/guide/plugins.md`); sideby itself sends no notification.
59
61
 
60
62
  The same is on the Panel's **Unattended** tab (`sideby ui`): the status with **Turn on now**, the Schedule, and the Pending Decisions with **Done**. Point the user there when they prefer clicking.