sideby 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) 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 +32 -1
  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/network.d.ts +11 -1
  12. package/dist/src/core/network.js +21 -1
  13. package/dist/src/core/progress-state.d.ts +80 -0
  14. package/dist/src/core/progress-state.js +216 -0
  15. package/dist/src/core/progress.d.ts +36 -0
  16. package/dist/src/core/progress.js +77 -0
  17. package/dist/src/core/prompt-origin.d.ts +40 -0
  18. package/dist/src/core/prompt-origin.js +98 -0
  19. package/dist/src/core/search-catalog.js +25 -0
  20. package/dist/src/core/unattended-attended.d.ts +109 -0
  21. package/dist/src/core/unattended-attended.js +337 -0
  22. package/dist/src/core/unattended.d.ts +10 -2
  23. package/dist/src/core/unattended.js +11 -2
  24. package/dist/src/handoff/hook.js +19 -4
  25. package/dist/src/menubar/script.js +9 -3
  26. package/dist/src/network/hook.d.ts +9 -0
  27. package/dist/src/network/hook.js +186 -4
  28. package/dist/src/panel/handler.d.ts +3 -0
  29. package/dist/src/panel/handler.js +15 -0
  30. package/dist/src/panel/i18n.d.ts +18 -0
  31. package/dist/src/panel/i18n.js +36 -0
  32. package/dist/src/panel/page-script.js +67 -2
  33. package/dist/src/panel/page-styles.js +14 -0
  34. package/dist/src/progress/hook.d.ts +50 -0
  35. package/dist/src/progress/hook.js +251 -0
  36. package/dist/src/runtime.d.ts +9 -0
  37. package/dist/src/runtime.js +45 -2
  38. package/dist/src/unattended/hook.d.ts +5 -0
  39. package/dist/src/unattended/hook.js +103 -9
  40. package/package.json +1 -1
  41. package/schemas/config.json +13 -0
  42. package/schemas/progress.json +137 -0
  43. package/schemas/unattended.json +38 -0
  44. package/skills/sideby/SKILL.md +3 -1
  45. package/skills/sideby/references/network.md +1 -1
  46. package/skills/sideby/references/progress.md +25 -0
  47. package/skills/sideby/references/unattended.md +9 -1
@@ -0,0 +1,251 @@
1
+ // Entry for `sideby progress-hook claude <event>` (spec §3.42, ADR-0076): Progress Reminders. Claude Code runs it in
2
+ // the background after every turn (`Stop`, `asyncRewake`) and on every prompt (`UserPromptSubmit`, `async`) in a
3
+ // session sideby started while config `progress.every` is set. It imports only Node built-ins and leaf modules: never
4
+ // the Runtime, a Family index or core/accounts.ts. It never fails the Host: any problem means no output and exit 0.
5
+ //
6
+ // `UserPromptSubmit` keeps when the session's latest prompt came, a hash of its id, and whether it was a reminder's
7
+ // wake-up. `Stop` watches while the session waits on background work: every `every` minutes it wakes the session with
8
+ // exit 2 and asks the model to tell the user what it waits for, then end its turn. It ends without a word when a later
9
+ // `Stop` took over, a new turn began (told by the prompt's id), the Host is gone, the setting was turned off or Auto
10
+ // Handoff is handing over, and it stays quiet while the session is unattended (ADR-0075). A reminder Network Guard
11
+ // held and delivered later still counts as a reminder.
12
+ import { randomBytes } from 'node:crypto';
13
+ import { join } from 'node:path';
14
+ import { FILES, HANDOFF_ENV, readJsonFile } from '../core/handoff-chain.js';
15
+ import { resolvePaths } from '../core/paths.js';
16
+ import { hashOf, markWatchWoken, progressReminderTurn, readProgressEvery, readPromptRecord, readWatch, writePromptRecord, writeWatch, } from '../core/progress-state.js';
17
+ import { PROGRESS_MARK, progressWakeUp } from '../core/prompt-origin.js';
18
+ import { sessionUnattended } from '../core/unattended-attended.js';
19
+ import { UNATTENDED_ENV } from '../core/unattended-state.js';
20
+ /** How often a watch looks whether it is still wanted. */
21
+ export const CHECK_EVERY_MS = 60_000;
22
+ /** A watch ends by itself after this long, under the five-hour `timeout` Claude Code gives the hook. */
23
+ export const WATCH_FOR_MS = (4 * 60 + 55) * 60_000;
24
+ const STDIN_MAX = 8 * 1024 * 1024;
25
+ /** Input that has not ended after this long is not waited for: the hook then does nothing. */
26
+ const STDIN_WAIT_MS = 5000;
27
+ /** Background tasks named in a reminder, and the most of each description. */
28
+ const TASKS_NAMED = 5;
29
+ const DESCRIPTION_MAX = 80;
30
+ async function readInput(input) {
31
+ if (typeof input === 'string')
32
+ return input;
33
+ const read = (async () => {
34
+ const chunks = [];
35
+ let size = 0;
36
+ for await (const chunk of input) {
37
+ const b = Buffer.from(chunk);
38
+ size += b.length;
39
+ if (size > STDIN_MAX)
40
+ return '';
41
+ chunks.push(b);
42
+ }
43
+ return Buffer.concat(chunks).toString('utf8');
44
+ })();
45
+ read.catch(() => { });
46
+ // A Host that never ends the input must not keep the hook waiting.
47
+ let timer;
48
+ const late = new Promise((resolve) => {
49
+ timer = setTimeout(() => {
50
+ ;
51
+ input.destroy?.();
52
+ resolve('');
53
+ }, STDIN_WAIT_MS);
54
+ });
55
+ try {
56
+ return await Promise.race([read, late]);
57
+ }
58
+ finally {
59
+ clearTimeout(timer);
60
+ }
61
+ }
62
+ async function parseInput(input) {
63
+ try {
64
+ const v = JSON.parse(await readInput(input));
65
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ const str = (v) => (typeof v === 'string' && v ? v : undefined);
72
+ const iso = (ms) => new Date(ms).toISOString();
73
+ /** Notes the session's latest prompt: when, a hash of its id, and whether it is a reminder's wake-up. */
74
+ async function notePrompt(env, input, now) {
75
+ const v = await parseInput(input);
76
+ if (!v || v.agent_id !== undefined)
77
+ return;
78
+ const sessionId = str(v.session_id);
79
+ const promptId = str(v.prompt_id);
80
+ if (!sessionId || !promptId)
81
+ return;
82
+ const paths = resolvePaths(env);
83
+ if ((await readProgressEvery(paths.configFile, env)) === undefined)
84
+ return;
85
+ const prompt = typeof v.prompt === 'string' ? v.prompt : '';
86
+ await writePromptRecord(paths.stateDir, sessionId, { at: now.toISOString(), prompt: hashOf(promptId), reminder: progressWakeUp(prompt) }, now);
87
+ }
88
+ /** One line of text from the Host: no control characters or quotes, runs of space as one, at most `max` characters. */
89
+ function clean(s, max) {
90
+ const one = [...s]
91
+ .map((ch) => (ch < ' ' || ch === '\u007f' || ch === '"' || ch === '`' ? ' ' : ch))
92
+ .join('')
93
+ .replace(/\s+/g, ' ')
94
+ .trim();
95
+ return one.length > max ? `${one.slice(0, max - 1)}…` : one;
96
+ }
97
+ /** The background tasks as the reminder names them: kind and description, never the command. */
98
+ export function taskList(tasks) {
99
+ const named = tasks.slice(0, TASKS_NAMED).map((t) => {
100
+ const r = (t && typeof t === 'object' ? t : {});
101
+ const kind = r.type === 'shell'
102
+ ? 'command'
103
+ : r.type === 'subagent'
104
+ ? 'subagent'
105
+ : typeof r.type === 'string' && r.type
106
+ ? clean(r.type, 20)
107
+ : 'task';
108
+ const what = typeof r.description === 'string' ? clean(r.description, DESCRIPTION_MAX) : '';
109
+ return what ? `${kind} "${what}"` : kind;
110
+ });
111
+ const more = tasks.length > TASKS_NAMED ? `; and ${tasks.length - TASKS_NAMED} more` : '';
112
+ return `${tasks.length} ${tasks.length === 1 ? 'task' : 'tasks'}: ${named.join('; ')}${more}`;
113
+ }
114
+ const hhmm = (ms) => {
115
+ const d = new Date(ms);
116
+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
117
+ };
118
+ /**
119
+ * What the model is woken with. It starts with `PROGRESS_MARK`, names the clock time the wait began (so a reminder
120
+ * Network Guard held and delivered late still makes sense), and asks for one or two sentences and the end of the turn.
121
+ */
122
+ export function reminderMessage(o) {
123
+ const since = Date.parse(o.since);
124
+ const minutes = Math.max(1, Math.round((o.now.getTime() - since) / 60_000));
125
+ return [
126
+ `${PROGRESS_MARK} you are waiting on background work (${taskList(o.tasks)}), since ${hhmm(since)}, ${minutes} ${minutes === 1 ? 'minute' : 'minutes'} as of this reminder.`,
127
+ 'Tell the user in one or two sentences what you are waiting for, how long it has been, and whether there is new output (look only if that is quick), then end your turn.',
128
+ 'Do not start new work or stop the tasks.',
129
+ `sideby sends this every ${o.every} ${o.every === 1 ? 'minute' : 'minutes'} while background work runs; if the user asks how to stop it, the command is \`sideby progress off\`.`,
130
+ ].join(' ');
131
+ }
132
+ /** Whether Auto Handoff of this session's run is handing over: the threshold was sent or the run is ready. */
133
+ async function handingOver(env) {
134
+ const runId = env[HANDOFF_ENV.run];
135
+ const dir = env[HANDOFF_ENV.dir];
136
+ if (!runId || !dir)
137
+ return false;
138
+ if (await readJsonFile(join(dir, FILES.ready)))
139
+ return true;
140
+ return Boolean((await readJsonFile(join(dir, FILES.run(runId))))?.thresholdSentAt);
141
+ }
142
+ /**
143
+ * The `Stop` watch (spec §3.42). Replaces the session's earlier watch first, then, while background work runs and the
144
+ * setting is on, wakes the session every `progress.every` minutes with a reminder (exit 2). Ends with exit 0 when a
145
+ * later `Stop` took over, the session's latest prompt is not the one this `Stop` ended, the parent is gone, the
146
+ * setting is off, Auto Handoff is handing over, or time runs out. While the session is unattended a reminder is skipped and the wait starts again.
147
+ */
148
+ export async function watchWhileWaiting(input, env, deps = {}) {
149
+ const clock = deps.now ?? (() => new Date());
150
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
151
+ const startPpid = process.ppid;
152
+ const parentGone = deps.parentGone ?? (() => process.ppid !== startPpid || process.ppid === 1);
153
+ const checkEvery = deps.checkEveryMs ?? CHECK_EVERY_MS;
154
+ const sessionId = str(input.session_id);
155
+ if (!sessionId)
156
+ return { exit: 0 };
157
+ const promptId = str(input.prompt_id);
158
+ const paths = resolvePaths(env);
159
+ const start = clock().getTime();
160
+ // The wait goes on across the turns reminders start; any other turn starts a new one.
161
+ const prev = await readWatch(paths.stateDir, sessionId);
162
+ const afterReminder = await progressReminderTurn(paths.stateDir, sessionId, promptId);
163
+ const since = afterReminder && prev ? prev.since : iso(start);
164
+ const id = deps.id ?? randomBytes(8).toString('hex');
165
+ // Written first, so a watch left by an earlier Stop ends even when this one has nothing to watch. When the session's
166
+ // lock stays held nothing is written, and this Stop does not watch: an earlier watch may still hold the record.
167
+ if (!(await writeWatch(paths.stateDir, sessionId, { id, since, at: iso(start) }, deps)))
168
+ return { exit: 0 };
169
+ const tasks = input.background_tasks;
170
+ if (!Array.isArray(tasks) || tasks.length === 0)
171
+ return { exit: 0 };
172
+ let every = await readProgressEvery(paths.configFile, env);
173
+ if (every === undefined)
174
+ return { exit: 0 };
175
+ const ownPrompt = promptId ? hashOf(promptId) : undefined;
176
+ let base = start;
177
+ for (;;) {
178
+ const wait = Math.min(checkEvery, Math.max(1000, base + every * 60_000 - clock().getTime()));
179
+ await sleep(wait);
180
+ const now = clock();
181
+ const t = now.getTime();
182
+ if (t - start >= WATCH_FOR_MS || parentGone())
183
+ return { exit: 0 };
184
+ if ((await readWatch(paths.stateDir, sessionId))?.id !== id)
185
+ return { exit: 0 };
186
+ // The latest prompt is another one: a turn began after this Stop's, and its own Stop decides again. Compared by
187
+ // the prompt's id, never by time: the next prompt's record can be written before this watch even starts. Only a
188
+ // Stop without an id falls back to whether the record came after it.
189
+ const p = await readPromptRecord(paths.stateDir, sessionId);
190
+ if (p && (ownPrompt ? p.prompt !== ownPrompt : Date.parse(p.at) > start))
191
+ return { exit: 0 };
192
+ // Read every time: turning it off, or another interval, reaches a running session.
193
+ every = await readProgressEvery(paths.configFile, env);
194
+ if (every === undefined)
195
+ return { exit: 0 };
196
+ if (await handingOver(env))
197
+ return { exit: 0 };
198
+ if (t - base < every * 60_000)
199
+ continue;
200
+ let quiet = true;
201
+ try {
202
+ quiet = (await sessionUnattended({
203
+ stateDir: paths.stateDir,
204
+ configFile: paths.configFile,
205
+ session: env[UNATTENDED_ENV] === '1',
206
+ sessionId,
207
+ now,
208
+ })).on;
209
+ }
210
+ catch {
211
+ // cannot tell: no reminder
212
+ }
213
+ if (quiet) {
214
+ base = t;
215
+ continue;
216
+ }
217
+ // Checked and marked under the session's lock just before waking, so a Stop that came meanwhile is never
218
+ // answered by this watch, and never has its record put back to this one.
219
+ const hook = deps.beforeWake ? { beforeWrite: deps.beforeWake } : {};
220
+ if (!(await markWatchWoken(paths.stateDir, sessionId, id, now, hook)))
221
+ return { exit: 0 };
222
+ return { exit: 2, message: reminderMessage({ tasks, since, now, every }) };
223
+ }
224
+ }
225
+ export async function runProgressHook(argv, env, input, io, deps = {}) {
226
+ const [family, event] = argv;
227
+ if (family !== 'claude')
228
+ return 0;
229
+ try {
230
+ if (event === 'UserPromptSubmit') {
231
+ // In the background: its output and exit code change nothing, and it never holds a prompt back.
232
+ await notePrompt(env, input, deps.now ? deps.now() : new Date());
233
+ return 0;
234
+ }
235
+ if (event !== 'Stop')
236
+ return 0;
237
+ const v = await parseInput(input);
238
+ if (!v)
239
+ return 0;
240
+ const w = await watchWhileWaiting(v, env, deps);
241
+ // Exit 2 wakes the session (asyncRewake), which hands stderr to the model.
242
+ if (w.exit === 2 && w.message) {
243
+ io.err.write(`${w.message}\n`);
244
+ return 2;
245
+ }
246
+ }
247
+ catch {
248
+ // never fail the Host
249
+ }
250
+ return 0;
251
+ }
@@ -14,6 +14,7 @@ import { type LimitResetPlan, type LimitResetResult } from './core/limit-reset.t
14
14
  import { type NetworkOverview } from './core/network.ts';
15
15
  import { type Paths } from './core/paths.ts';
16
16
  import { type PickChoice } from './core/pick-commands.ts';
17
+ import { type ProgressView } from './core/progress.ts';
17
18
  import { type ProjectCategories } from './core/project-categories.ts';
18
19
  import { type QuotaFetchMode } from './core/quota-fetch.ts';
19
20
  import { type RemoteControlChange, type RemoteControlGroup } from './core/remote-control.ts';
@@ -376,6 +377,14 @@ export interface Runtime {
376
377
  setQuotaCheck(family: string, on: boolean): Promise<{
377
378
  changed: boolean;
378
379
  }>;
380
+ /** Progress Reminders (spec §3.42): whether they are on, how often, and for which Families. */
381
+ progressView(): ProgressView;
382
+ /** Turns Progress Reminders on with `every` minutes, or off (undefined); writes only config `progress`. */
383
+ setProgress(every: number | undefined): Promise<{
384
+ changed: boolean;
385
+ before?: number;
386
+ after?: number;
387
+ }>;
379
388
  /** The config `display` (spec §3.25), or an empty object. */
380
389
  displayOrder(): DisplayConfig;
381
390
  /** Replaces the config `display`; undefined or empty removes it. Returns what the file now holds. */
@@ -20,7 +20,10 @@ import { memoStore } from './core/memo-store.js';
20
20
  import { codexNetworkTrustLine, guardLaunch, guardOn, ipChangedLine, networkHookPart, networkOverview, networkSettingsLine, } from './core/network.js';
21
21
  import { resolvePaths } from './core/paths.js';
22
22
  import { choosePick, suggestPickName } from './core/pick-commands.js';
23
+ import { PROGRESS_FAMILIES, progressHookPart, progressSettingsLine, progressView, setProgress, } from './core/progress.js';
24
+ import { PROGRESS_ENV, validEvery } from './core/progress-state.js';
23
25
  import { categoryReader } from './core/project-categories.js';
26
+ import { LAUNCH_PROMPTS_ENV, LAUNCH_PROMPTS_UNSET } from './core/prompt-origin.js';
24
27
  import { FETCH_TIMEOUT_MS, fetchedQuota, loginProblemOf, quotaCheckOff, shownQuota, } from './core/quota-fetch.js';
25
28
  import { takeoverLimits } from './core/quota-levels.js';
26
29
  import { quotaStoreFile, readQuotaStore } from './core/quota-store.js';
@@ -150,8 +153,27 @@ export async function createRuntime(opts = {}) {
150
153
  }
151
154
  if (p.family.id === 'codex')
152
155
  addNotice(p, [await codexUnattendedTrustLine(paths.stateDir, p.account.ref, p.env)]);
156
+ // Which prompts sideby put on the command line, so the hook never takes one for typed (ADR-0075): filled in from
157
+ // the final arguments where the Host starts (`spawnHost`); left as it is, the session counts no prompt as typed.
158
+ if (p.family.id === 'claude')
159
+ p.env[LAUNCH_PROMPTS_ENV] = LAUNCH_PROMPTS_UNSET;
153
160
  return unattendedHookPart();
154
161
  };
162
+ /**
163
+ * Progress Reminders on a Claude session sideby starts (spec §3.42): their hooks while config `progress.every` is
164
+ * set, and the interval at launch in the environment (used only when the config cannot be read).
165
+ */
166
+ const progressPrepared = (p) => {
167
+ const every = config.progress?.every;
168
+ if (!validEvery(every) || !PROGRESS_FAMILIES.includes(p.family.id))
169
+ return null;
170
+ if (hasOption(p.args, ['--settings'])) {
171
+ addNotice(p, [progressSettingsLine(p.env)]);
172
+ return null;
173
+ }
174
+ p.env[PROGRESS_ENV] = String(every);
175
+ return progressHookPart();
176
+ };
155
177
  /** Puts every session hook into the Launch's arguments: one `--settings` for Claude, `-c hooks.*` for Codex. */
156
178
  const addSessionHooks = async (p, list) => {
157
179
  const parts = list.filter((x) => x !== null);
@@ -163,13 +185,18 @@ export async function createRuntime(opts = {}) {
163
185
  p.networkArgs = args;
164
186
  p.args = beforeDashes(p.args, args);
165
187
  };
166
- /** Network Guard and Unattended Mode on a prepared Launch, in that order; hooks only for a session (`run`). */
188
+ /**
189
+ * Network Guard, Unattended Mode and Progress Reminders on a prepared Launch, in that order; hooks only for a session
190
+ * (`run`).
191
+ */
167
192
  const sessionReady = async (p, session, o) => {
168
193
  const parts = [];
169
194
  if (!o.ignoreNetwork)
170
195
  parts.push(await guardPrepared(p, session));
171
196
  if (session)
172
197
  parts.push(await unattendedPrepared(p, Boolean(o.unattended)));
198
+ if (session)
199
+ parts.push(progressPrepared(p));
173
200
  await addSessionHooks(p, parts);
174
201
  };
175
202
  const familyOf = (id) => {
@@ -1003,6 +1030,8 @@ export async function createRuntime(opts = {}) {
1003
1030
  config.ask = fresh.ask;
1004
1031
  config.advisor = fresh.advisor;
1005
1032
  config.claude = fresh.claude;
1033
+ // Progress Reminders turned on, off or to another interval reach the next session a chain starts too.
1034
+ config.progress = fresh.progress;
1006
1035
  }
1007
1036
  const all = await accounts();
1008
1037
  const inputs = launchInputs(ref, all, userArgs, command);
@@ -1065,7 +1094,8 @@ export async function createRuntime(opts = {}) {
1065
1094
  const guarded = async (h) => {
1066
1095
  const net = !ro.ignoreNetwork && guardOn(config, h.env);
1067
1096
  const unattended = Boolean(ro.unattended) || config.unattended !== undefined;
1068
- if (!net && !unattended)
1097
+ const progress = validEvery(config.progress?.every) && PROGRESS_FAMILIES.includes(family.id);
1098
+ if (!net && !unattended && !progress)
1069
1099
  return h;
1070
1100
  const main = (await accounts()).find((a) => a.family === family.id && a.isMain);
1071
1101
  if (!main)
@@ -1387,6 +1417,19 @@ export async function createRuntime(opts = {}) {
1387
1417
  config.quota = r.after;
1388
1418
  return { changed: r.changed };
1389
1419
  },
1420
+ progressView: () => progressView(config),
1421
+ async setProgress(every) {
1422
+ const r = await setProgress(paths.configFile, every);
1423
+ if (r.config === undefined)
1424
+ delete config.progress;
1425
+ else
1426
+ config.progress = r.config;
1427
+ return {
1428
+ changed: r.changed,
1429
+ ...(r.before === undefined ? {} : { before: r.before }),
1430
+ ...(r.after === undefined ? {} : { after: r.after }),
1431
+ };
1432
+ },
1390
1433
  displayOrder: () => config.display ?? {},
1391
1434
  async setDisplayOrder(display) {
1392
1435
  const r = await editConfigDisplay(paths.configFile, display);
@@ -54,6 +54,11 @@ export declare function commandProgram(command: string): string | undefined;
54
54
  export declare function permissionText(tool: string, input: Record<string, unknown>): string;
55
55
  /** What the model reads instead of the permission prompt Claude Code would have shown. */
56
56
  export declare function permissionReason(state: UnattendedState, now: Date, kept: boolean): string;
57
+ /**
58
+ * What the user reads once in an Attended Session while Unattended Mode is on (ADR-0075), as a `systemMessage`: shown
59
+ * in the session, never to the model.
60
+ */
61
+ export declare function attendedNotice(state: UnattendedState, zh: boolean): string;
57
62
  /**
58
63
  * Returns the exit code: 0 lets the Host go on, 2 refuses the tool call (the reason is written to `err`). A permission
59
64
  * request, a stop on a question and an MCP form are answered with exit 0 and the decision written to `out`. Errors
@@ -12,12 +12,16 @@
12
12
  // written as plain text (`{"decision":"block","reason":…}` on stdout), keeping the question; and it declines an MCP
13
13
  // server's form, keeping what the server asked. In Claude it also runs in the background after a turn that failed for
14
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
15
+ // most three times in a row, and keeps a Pending Decision when that did not help (Turn Retry, ADR-0067). And in Claude
16
+ // it runs in the background on every prompt (`UserPromptSubmit`, `async`): a prompt a person typed makes that session
17
+ // an Attended Session for 30 minutes, which it leaves alone as if the mode were off, telling the user once (ADR-0075).
18
+ // A failure before the decision is made does nothing: that is
17
19
  // how a session behaves without the feature (unlike `network-hook`, which blocks when it cannot tell). Once the
18
20
  // decision is to refuse, it refuses: keeping the Pending Decision and writing the reason are best effort, and their
19
21
  // failure neither allows the call nor adds any output of its own.
20
22
  import { resolvePaths } from '../core/paths.js';
23
+ import { hostMade, launchPrompt, sidebyMessage } from '../core/prompt-origin.js';
24
+ import { ATTENDED_MS, markAttended, markTold, ownTranscript, promptOrigin, readAttended, sessionUnattended, } from '../core/unattended-attended.js';
21
25
  import { addPendingDecision } from '../core/unattended-pending.js';
22
26
  import { clearRetryStreak, countFailure, passingFailure, RETRY_LIMIT, readRetryStreak, retryDelay, retryGaveUpText, retryMessage, } from '../core/unattended-retry.js';
23
27
  import { clockText, readUnattendedConfig, readUnattendedOverride, UNATTENDED_ENV, unattendedState, } from '../core/unattended-state.js';
@@ -326,6 +330,16 @@ export function permissionReason(state, now, kept) {
326
330
  const keep = kept ? ' sideby kept this request for the user to look at later.' : '';
327
331
  return `Not allowed: Claude Code wanted a person to confirm this action, and nobody is here (sideby's Unattended Mode is on ${when}).${keep} Rewrite it so it needs no confirmation: literal paths, "\${VAR:?}" for variables in rm targets, plain bash syntax, and rm as a command of its own. Or skip it, record it with \`sideby unattended defer "<what and why>"\`, and go on with the rest.`;
328
332
  }
333
+ /**
334
+ * What the user reads once in an Attended Session while Unattended Mode is on (ADR-0075), as a `systemMessage`: shown
335
+ * in the session, never to the model.
336
+ */
337
+ export function attendedNotice(state, zh) {
338
+ const session = state.reason === 'session';
339
+ if (zh)
340
+ return `sideby:你在,这个会话在你最后一条消息后 30 分钟内照常问你。${session ? '它是按无人值守启动的,30 分钟没人打字后恢复。' : '其他会话仍然无人值守。要全部关掉,运行 `sideby unattended off`。'}`;
341
+ return `sideby: you're here, so this session asks you as usual for 30 minutes after your last message. ${session ? 'It was started unattended, and goes back to that once nobody has typed for 30 minutes.' : 'Other sessions stay unattended. To turn Unattended Mode off everywhere, run `sideby unattended off`.'}`;
342
+ }
329
343
  /** What to do with this call: undefined allows it. Any error here allows it too (the caller catches it). */
330
344
  async function decide(argv, env, input, now) {
331
345
  const [family = '', event = ''] = argv;
@@ -353,11 +367,35 @@ async function decide(argv, env, input, now) {
353
367
  const raw = early ?? (await readInput(input));
354
368
  const zh = prefersChinese(env);
355
369
  const account = text(env.SIDEBY_ACCOUNT, 256);
370
+ /**
371
+ * An Attended Session (ADR-0075) is left alone, as when the mode is off: undefined while the session is not one.
372
+ * Where a `systemMessage` reaches the user (`Stop`, the ask tool's `PreToolUse`), the first such call of a stretch
373
+ * tells them once.
374
+ */
375
+ const attended = async (sessionId, tell) => {
376
+ if (family !== 'claude' || !sessionId)
377
+ return undefined;
378
+ const r = await readAttended(paths.stateDir, sessionId, now);
379
+ if (!r)
380
+ return undefined;
381
+ if (!tell || r.toldAt)
382
+ return {};
383
+ return {
384
+ answer: {
385
+ json: (systemMessage) => ({ systemMessage }),
386
+ reason: () => attendedNotice(state, zh),
387
+ keep: () => markTold(paths.stateDir, sessionId, r.since, now),
388
+ },
389
+ };
390
+ };
356
391
  if (stop || elicitation) {
357
392
  const v = parseObject(raw);
358
393
  if (!v)
359
394
  return undefined;
360
395
  const sessionId = text(v.session_id, 256);
396
+ const here = await attended(sessionId, stop);
397
+ if (here)
398
+ return here.answer;
361
399
  const cwd = text(v.cwd);
362
400
  const where = {
363
401
  family,
@@ -391,6 +429,11 @@ async function decide(argv, env, input, now) {
391
429
  const payload = parsePayload(raw);
392
430
  if (!payload)
393
431
  return undefined;
432
+ if (permission || payload.tool === askTool) {
433
+ const here = await attended(payload.sessionId, !permission);
434
+ if (here)
435
+ return here.answer;
436
+ }
394
437
  if (permission)
395
438
  return {
396
439
  json: (message) => ({
@@ -431,6 +474,11 @@ async function decide(argv, env, input, now) {
431
474
  * record.
432
475
  */
433
476
  export async function runUnattendedHook(argv, env, input, io, deps = {}) {
477
+ if (argv[0] === 'claude' && argv[1] === 'UserPromptSubmit') {
478
+ // In the background: its output and exit code change nothing, and it never holds a prompt back.
479
+ await notePrompt(env, input, deps).catch(() => { });
480
+ return 0;
481
+ }
434
482
  if (argv[0] === 'claude' && argv[1] === 'StopFailure') {
435
483
  try {
436
484
  const wake = await retryAfterFailure(env, input, deps);
@@ -479,12 +527,58 @@ export async function runUnattendedHook(argv, env, input, io, deps = {}) {
479
527
  }
480
528
  return 2;
481
529
  }
482
- /** Whether Unattended Mode is on right now, read fresh from the Schedule and the manual state. */
483
- async function isOn(env, now) {
530
+ /**
531
+ * Whether the session is unattended right now: Unattended Mode is on, read fresh from the Schedule and the manual
532
+ * state, and the session is not an Attended Session.
533
+ */
534
+ async function isOn(env, now, sessionId) {
484
535
  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;
536
+ return (await sessionUnattended({
537
+ stateDir: paths.stateDir,
538
+ configFile: paths.configFile,
539
+ session: env[UNATTENDED_ENV] === '1',
540
+ sessionId,
541
+ now,
542
+ })).on;
543
+ }
544
+ /** A prompt id as Claude Code writes it; anything else is not looked for. */
545
+ const PROMPT_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
546
+ /**
547
+ * Claude's background `UserPromptSubmit` entry (spec §3.37 "有人在的会话", ADR-0075): makes the session an Attended
548
+ * Session when a person typed the prompt. Not counted: a prompt Claude Code made itself, a Message `sideby send`
549
+ * delivered, a prompt sideby put on the command line (or a session whose launch did not say which those are), a
550
+ * subagent's, and any prompt whose line in the session's own transcript does not say `human` within the wait. The
551
+ * transcript line decides, not the input: its text is checked as the prompt is, and its time is when the stretch is
552
+ * counted from, so an input made by hand that names another file, the launch's prompt or an old prompt marks nothing
553
+ * new. Nothing of the prompt is kept.
554
+ */
555
+ async function notePrompt(env, input, deps) {
556
+ const v = parseObject(await readInput(input));
557
+ if (!v || v.agent_id !== undefined)
558
+ return;
559
+ const sessionId = text(v.session_id, 256);
560
+ const promptId = typeof v.prompt_id === 'string' && PROMPT_ID.test(v.prompt_id) ? v.prompt_id : undefined;
561
+ const prompt = typeof v.prompt === 'string' ? v.prompt : undefined;
562
+ const transcript = typeof v.transcript_path === 'string' ? v.transcript_path : undefined;
563
+ if (!sessionId || !promptId || prompt === undefined || !transcript)
564
+ return;
565
+ const notTyped = (s) => hostMade(s) || sidebyMessage(s) || launchPrompt(s, env);
566
+ if (notTyped(prompt) || !(await ownTranscript(transcript, sessionId, env)))
567
+ return;
568
+ const clock = deps.now ?? (() => new Date());
569
+ const line = await promptOrigin(transcript, promptId, {
570
+ ...(deps.sleep ? { sleep: deps.sleep } : {}),
571
+ clock: () => clock().getTime(),
572
+ });
573
+ if (line?.origin !== 'human' || line.text === undefined || line.at === undefined || notTyped(line.text))
574
+ return;
575
+ const now = clock().getTime();
576
+ const at = Math.min(line.at, now);
577
+ if (at + ATTENDED_MS <= now)
578
+ return;
579
+ const account = text(env.SIDEBY_ACCOUNT, 256);
580
+ const cwd = text(v.cwd);
581
+ await markAttended(resolvePaths(env).stateDir, { sessionId, family: 'claude', ...(account ? { account } : {}), ...(cwd ? { cwd } : {}) }, new Date(at));
488
582
  }
489
583
  /**
490
584
  * Turn Retry (spec §3.37 item 6, ADR-0067), Claude's background `StopFailure` hook (`asyncRewake`): Claude Code runs it
@@ -509,7 +603,7 @@ async function retryAfterFailure(env, input, deps) {
509
603
  const said = [text(v.last_assistant_message, 1000), text(v.error_details, 1000)].filter(Boolean).join(' ');
510
604
  // A later failure that is not retried (a used-up Quota, a lasting error) or comes while the mode is off still
511
605
  // takes over the session: the wait an earlier failure left must not wake it.
512
- if (!error || !passingFailure(error, said) || !(await isOn(env, now))) {
606
+ if (!error || !passingFailure(error, said) || !(await isOn(env, now, sessionId))) {
513
607
  await clearRetryStreak(paths.stateDir, sessionId).catch(() => { });
514
608
  return undefined;
515
609
  }
@@ -534,7 +628,7 @@ async function retryAfterFailure(env, input, deps) {
534
628
  return undefined;
535
629
  if ((await readRetryStreak(paths.stateDir, sessionId))?.token !== streak.token)
536
630
  return undefined;
537
- if (!(await isOn(env, clock())))
631
+ if (!(await isOn(env, clock(), sessionId)))
538
632
  return undefined;
539
633
  return retryMessage(error, text(v.last_assistant_message, 1000) ?? '', streak.count, prefersChinese(env));
540
634
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.38.0",
3
+ "version": "0.39.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)",
@@ -505,6 +505,19 @@
505
505
  "additionalProperties": false,
506
506
  "description": "Unattended Mode (spec §3.37, ADR-0058): while it is on, sessions sideby starts never stop to wait for a person. Present once the feature is used; from then on sideby adds its hook to every Claude and Codex session it starts, so turning it on later covers sessions already running. `sideby config unset unattended` stops adding it."
507
507
  },
508
+ "progress": {
509
+ "type": "object",
510
+ "properties": {
511
+ "every": {
512
+ "type": "integer",
513
+ "minimum": 1,
514
+ "maximum": 240,
515
+ "description": "Progress Reminders: while a Claude session sideby started waits on background work (subagents, background commands), wake it every this many minutes so the model tells you in one or two sentences what it waits for. Each reminder is one model turn over the whole conversation, so it uses quota. Not set: off (the default). Sessions started afterwards get it; turning it off or changing the interval also reaches running sessions. Not while the session is unattended; Codex is not covered."
516
+ }
517
+ },
518
+ "additionalProperties": false,
519
+ "description": "Progress Reminders (spec §3.42, ADR-0076)."
520
+ },
508
521
  "browser": {
509
522
  "type": "object",
510
523
  "properties": {