sideby 0.29.0 → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +10 -0
  3. package/dist/src/cli/commands.js +306 -8
  4. package/dist/src/cli/json-schemas.js +75 -1
  5. package/dist/src/cli/main.js +83 -4
  6. package/dist/src/core/config.d.ts +25 -0
  7. package/dist/src/core/config.js +34 -0
  8. package/dist/src/core/fs-safe.d.ts +22 -1
  9. package/dist/src/core/fs-safe.js +68 -1
  10. package/dist/src/core/handoff-run.d.ts +2 -0
  11. package/dist/src/core/handoff-run.js +12 -6
  12. package/dist/src/core/launch.d.ts +6 -1
  13. package/dist/src/core/messages.js +9 -31
  14. package/dist/src/core/network.d.ts +5 -2
  15. package/dist/src/core/network.js +15 -45
  16. package/dist/src/core/search-catalog.d.ts +1 -1
  17. package/dist/src/core/search-catalog.js +37 -0
  18. package/dist/src/core/session-hooks.d.ts +33 -0
  19. package/dist/src/core/session-hooks.js +92 -0
  20. package/dist/src/core/unattended-ended.d.ts +62 -0
  21. package/dist/src/core/unattended-ended.js +275 -0
  22. package/dist/src/core/unattended-pending.d.ts +56 -0
  23. package/dist/src/core/unattended-pending.js +182 -0
  24. package/dist/src/core/unattended-state.d.ts +129 -0
  25. package/dist/src/core/unattended-state.js +373 -0
  26. package/dist/src/core/unattended.d.ts +142 -0
  27. package/dist/src/core/unattended.js +349 -0
  28. package/dist/src/panel/background.js +8 -0
  29. package/dist/src/panel/handler.d.ts +37 -0
  30. package/dist/src/panel/handler.js +153 -1
  31. package/dist/src/panel/i18n.d.ts +97 -0
  32. package/dist/src/panel/i18n.js +194 -0
  33. package/dist/src/panel/page-logic.d.ts +129 -0
  34. package/dist/src/panel/page-logic.js +166 -0
  35. package/dist/src/panel/page-script.js +638 -7
  36. package/dist/src/panel/page-styles.js +69 -0
  37. package/dist/src/panel/page.js +2 -0
  38. package/dist/src/plugins/bus.js +1 -0
  39. package/dist/src/runtime.d.ts +17 -1
  40. package/dist/src/runtime.js +78 -15
  41. package/dist/src/types.d.ts +48 -0
  42. package/dist/src/unattended/hook.d.ts +46 -0
  43. package/dist/src/unattended/hook.js +288 -0
  44. package/package.json +1 -1
  45. package/schemas/config.json +76 -0
  46. package/schemas/unattended-defer.json +143 -0
  47. package/schemas/unattended-pending.json +154 -0
  48. package/schemas/unattended.json +291 -0
  49. package/skills/sideby/SKILL.md +2 -1
  50. package/skills/sideby/references/unattended.md +58 -0
@@ -0,0 +1,349 @@
1
+ // Unattended Mode (spec §3.37, ADR-0058) for the CLI, the Runtime and the Panel: the full status, turning it on and
2
+ // off, editing the Schedule, and the hooks sideby adds to the sessions it starts. Whether it is on is decided in
3
+ // core/unattended-state.ts; Pending Decisions are kept by core/unattended-pending.ts; the end of a stretch is noticed by
4
+ // core/unattended-ended.ts.
5
+ import { readFile } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ import { editConfigUnattended } from './config.js';
8
+ import { UserError } from './errors.js';
9
+ import { ownedFolder, writeFileAtomic } from './fs-safe.js';
10
+ import { sidebyHookCommand } from './session-hooks.js';
11
+ import { listPendingDecisions } from './unattended-pending.js';
12
+ import { clearUnattendedOverride, clockText, ensureUnattendedDir, MAX_MANUAL_MS, parseClock, parseDays, parseSlot, readUnattendedConfig, readUnattendedOverride, scheduleStretchAt, slotEnd, UNATTENDED_ENV, unattendedState, writeUnattendedOverride, } from './unattended-state.js';
13
+ /** Families whose sessions Unattended Mode covers in v1. */
14
+ export const UNATTENDED_FAMILIES = ['claude', 'codex'];
15
+ const DEFAULT_HOURS = 12;
16
+ /** The Weeknights preset: Monday to Friday, 23:00 to 08:00. */
17
+ export const WEEKNIGHTS = {
18
+ name: 'Weeknights',
19
+ days: ['mon', 'tue', 'wed', 'thu', 'fri'],
20
+ start: '23:00',
21
+ end: '08:00',
22
+ };
23
+ function quote(arg) {
24
+ return /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
25
+ }
26
+ /** Whether the manual state is in effect at `now`: started, not yet over. */
27
+ function activeManual(o, now) {
28
+ if (!o)
29
+ return undefined;
30
+ // An open pause (no `until`) lasts until the user turns it on; the status shows it while the state says paused.
31
+ if (!o.until)
32
+ return o.mode === 'pause' && Date.parse(o.at) <= now ? o : undefined;
33
+ const end = o.mode === 'on' ? Math.min(Date.parse(o.until), Date.parse(o.at) + MAX_MANUAL_MS) : Date.parse(o.until);
34
+ return Date.parse(o.at) <= now && now < end ? o : undefined;
35
+ }
36
+ function coverageOf(families, configured) {
37
+ const out = {};
38
+ for (const f of families)
39
+ out[f] = !configured
40
+ ? 'not-covered'
41
+ : f === 'claude'
42
+ ? 'covered'
43
+ : f === 'codex'
44
+ ? 'needs-trust'
45
+ : 'not-covered';
46
+ return out;
47
+ }
48
+ /** The full status. `env` matters only for a session started with `--unattended`. */
49
+ export async function unattendedStatus(opts) {
50
+ const now = opts.now ?? new Date();
51
+ const { configured, schedule } = await readUnattendedConfig(opts.paths.configFile);
52
+ const override = await readUnattendedOverride(opts.paths.stateDir);
53
+ const state = unattendedState({ schedule, override, now, session: opts.env?.[UNATTENDED_ENV] === '1' });
54
+ const end = slotEnd(schedule, now);
55
+ const manual = activeManual(override, now.getTime());
56
+ const problem = await ownedFolder(opts.paths.stateDir, ['unattended'], { create: false }).then(() => undefined, (err) => err.message);
57
+ return {
58
+ ...state,
59
+ configured,
60
+ schedule,
61
+ pending: (await listPendingDecisions(opts.paths.stateDir, { now, prune: !opts.readOnly })).length,
62
+ coverage: coverageOf(opts.families, configured),
63
+ ...(end !== undefined && end - now.getTime() <= MAX_MANUAL_MS
64
+ ? { slotEnd: new Date(end).toISOString() }
65
+ : {}),
66
+ ...(manual ? { manual } : {}),
67
+ ...(problem ? { problem } : {}),
68
+ };
69
+ }
70
+ /** `4h`, `90m`, `1h30m` in milliseconds; undefined for anything else. */
71
+ export function parseDuration(text) {
72
+ const m = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(text.trim().toLowerCase());
73
+ if (!m || (m[1] === undefined && m[2] === undefined))
74
+ return undefined;
75
+ return (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60 * 1000;
76
+ }
77
+ /**
78
+ * When a manual "on" would end, or why it cannot (the message says what to do). Without a choice: until the current
79
+ * or next Slot ends when that is within 72 hours, else 12 hours.
80
+ */
81
+ export function onUntil(choice, schedule, now) {
82
+ const t = now.getTime();
83
+ const given = [choice.for !== undefined, choice.until !== undefined, Boolean(choice.slotEnd)].filter(Boolean);
84
+ if (given.length > 1)
85
+ return { error: 'choose one of --for, --until and --slot-end' };
86
+ const end = slotEnd(schedule, now);
87
+ if (choice.for !== undefined) {
88
+ const ms = parseDuration(choice.for);
89
+ if (!ms)
90
+ return { error: `--for takes hours or minutes, such as 4h, 90m or 1h30m; use one of those` };
91
+ if (ms > MAX_MANUAL_MS)
92
+ return { error: 'use --for 72h or less: Unattended Mode stays on at most 72 hours' };
93
+ return { until: t + ms };
94
+ }
95
+ if (choice.until !== undefined) {
96
+ const clock = parseClock(choice.until);
97
+ if (clock) {
98
+ // The day first, then the time on it, so a clock change between now and then cannot move the hour: 02:30
99
+ // asked at 03:45 on the day clocks go forward is 02:30 tomorrow, not 24 hours after a 02:30 that never was.
100
+ const [h, m] = [Number(clock.slice(0, 2)), Number(clock.slice(3))];
101
+ const [y, mo, d] = [now.getFullYear(), now.getMonth(), now.getDate()];
102
+ const today = new Date(y, mo, d, h, m).getTime();
103
+ return { until: today > t ? today : new Date(y, mo, d + 1, h, m).getTime() };
104
+ }
105
+ const at = /\d{4}-\d{2}-\d{2}/.test(choice.until) ? Date.parse(choice.until) : Number.NaN;
106
+ if (!Number.isFinite(at))
107
+ return {
108
+ error: '--until takes a time such as 07:30, or a date and time such as 2026-11-02T07:30; use one of those',
109
+ };
110
+ if (at <= t)
111
+ return { error: `--until ${choice.until} is not in the future; use a later time` };
112
+ if (at - t > MAX_MANUAL_MS)
113
+ return { error: 'use an --until within 72 hours: Unattended Mode stays on at most 72 hours' };
114
+ return { until: at };
115
+ }
116
+ if (choice.slotEnd) {
117
+ if (end === undefined && scheduleStretchAt(schedule, t)?.endless)
118
+ return {
119
+ error: 'your Schedule covers every hour, so its Slot never ends; use --for or --until, such as --for 12h',
120
+ };
121
+ if (end === undefined)
122
+ return {
123
+ error: '--slot-end needs a Slot; add one with `sideby unattended schedule add --days mon-fri --from 23:00 --to 08:00`, or use --for 12h',
124
+ };
125
+ if (end - t > MAX_MANUAL_MS)
126
+ return { error: 'the next Slot ends more than 72 hours from now; use --for or --until instead' };
127
+ return { until: end };
128
+ }
129
+ if (end !== undefined && end - t <= MAX_MANUAL_MS)
130
+ return { until: end };
131
+ return { until: t + DEFAULT_HOURS * 60 * 60 * 1000 };
132
+ }
133
+ /** The command that turns it back the way `before` had it, or undefined when there is none. */
134
+ function undoFor(before, now) {
135
+ if (before.on && before.reason !== 'session') {
136
+ // On with no end (the Schedule covers every hour): any `on` replaces the pause, and the Schedule goes on after it.
137
+ if (!before.until)
138
+ return 'sideby unattended on';
139
+ const until = Date.parse(before.until);
140
+ if (!Number.isFinite(until) || until - now.getTime() > MAX_MANUAL_MS)
141
+ return undefined;
142
+ return `sideby unattended on --until ${new Date(until).toISOString()}`;
143
+ }
144
+ return 'sideby unattended off';
145
+ }
146
+ /** Makes the config section, which starts adding the hook to sessions sideby starts. */
147
+ export async function ensureUnattendedConfig(configFile) {
148
+ await editConfigUnattended(configFile, (current) => (current === undefined ? {} : null));
149
+ }
150
+ /**
151
+ * Turns it on until `until` (at most 72 hours), creating the config section the first time. A Slot that ends later
152
+ * keeps it on longer. Callers then run `checkUnattendedEnded`, so a stretch this ends is noticed at once.
153
+ */
154
+ export async function turnUnattendedOn(opts) {
155
+ const now = opts.now ?? new Date();
156
+ const t = now.getTime();
157
+ if (!(opts.until > t) || opts.until - t > MAX_MANUAL_MS)
158
+ throw new UserError('Unattended Mode can be turned on for at most 72 hours; choose an end within that', {
159
+ code: 'bad-time',
160
+ });
161
+ await ensureUnattendedConfig(opts.paths.configFile);
162
+ const before = await unattendedStatus({ ...opts, now });
163
+ await writeUnattendedOverride(opts.paths.stateDir, {
164
+ mode: 'on',
165
+ at: now.toISOString(),
166
+ until: new Date(opts.until).toISOString(),
167
+ });
168
+ const status = await unattendedStatus({ ...opts, now });
169
+ const undo = undoFor(before, now);
170
+ return { changed: true, status, ...(undo ? { undo } : {}) };
171
+ }
172
+ /**
173
+ * Turns it off: outside a Slot it is off at once; in a Slot it pauses until that Slot ends, and the next Slot turns it
174
+ * on as usual. Callers then run `checkUnattendedEnded`.
175
+ */
176
+ export async function turnUnattendedOff(opts) {
177
+ const now = opts.now ?? new Date();
178
+ const t = now.getTime();
179
+ const before = await unattendedStatus({ ...opts, now });
180
+ if (!before.on || before.reason === 'session')
181
+ return { changed: false, status: before };
182
+ const { schedule } = await readUnattendedConfig(opts.paths.configFile);
183
+ const inSlot = scheduleStretchAt(schedule, t);
184
+ // In a Schedule that covers every hour, the pause has no end: it lasts until the user turns it on again.
185
+ if (inSlot)
186
+ await writeUnattendedOverride(opts.paths.stateDir, {
187
+ mode: 'pause',
188
+ at: now.toISOString(),
189
+ ...(inSlot.endless ? {} : { until: new Date(inSlot.stretch.end).toISOString() }),
190
+ });
191
+ else
192
+ await clearUnattendedOverride(opts.paths.stateDir);
193
+ const status = await unattendedStatus({ ...opts, now });
194
+ const undo = undoFor(before, now);
195
+ return { changed: true, status, ...(undo ? { undo } : {}) };
196
+ }
197
+ const sameSlot = (a, b) => a.start === b.start && a.end === b.end && a.days.join() === b.days.join();
198
+ function addCommand(slot, at) {
199
+ return [
200
+ 'sideby unattended schedule add',
201
+ `--days ${slot.days.join(',')}`,
202
+ `--from ${slot.start}`,
203
+ `--to ${slot.end}`,
204
+ ...(slot.name ? [`--name ${quote(slot.name)}`] : []),
205
+ ...(at !== undefined ? [`--at ${at}`] : []),
206
+ ].join(' ');
207
+ }
208
+ /**
209
+ * Adds a Slot (at position `at`, 1-based, else last), creating the config section. A Slot with the same days and
210
+ * times is not added twice.
211
+ */
212
+ export async function addUnattendedSlot(opts) {
213
+ let index = -1;
214
+ const r = await editConfigUnattended(opts.paths.configFile, (current) => {
215
+ const schedule = [...(current?.schedule ?? [])];
216
+ if (schedule.some((s) => sameSlot(s, opts.slot)))
217
+ return null;
218
+ index = opts.at === undefined ? schedule.length : Math.max(0, Math.min(schedule.length, opts.at - 1));
219
+ schedule.splice(index, 0, opts.slot);
220
+ return { ...current, schedule };
221
+ });
222
+ const status = await unattendedStatus(opts);
223
+ const added = r.changed && index >= 0;
224
+ return {
225
+ changed: added,
226
+ status,
227
+ ...(added ? { undo: `sideby unattended schedule remove ${index + 1}` } : {}),
228
+ };
229
+ }
230
+ /** Removes Slot `n` (1-based, as `sideby unattended` numbers them). Throws when there is none. */
231
+ export async function removeUnattendedSlot(opts) {
232
+ let removed;
233
+ await editConfigUnattended(opts.paths.configFile, (current) => {
234
+ const schedule = [...(current?.schedule ?? [])];
235
+ if (opts.n < 1 || opts.n > schedule.length)
236
+ return null;
237
+ removed = schedule.splice(opts.n - 1, 1)[0];
238
+ return { ...current, schedule };
239
+ });
240
+ if (!removed) {
241
+ const count = (await readUnattendedConfig(opts.paths.configFile)).schedule.length;
242
+ throw new UserError(count
243
+ ? `there is no Slot ${opts.n}; choose 1 to ${count} (\`sideby unattended\` lists them)`
244
+ : 'the Schedule has no Slot to remove; add one with `sideby unattended schedule add`', { code: 'no-slot' });
245
+ }
246
+ return { changed: true, status: await unattendedStatus(opts), undo: addCommand(removed, opts.n) };
247
+ }
248
+ /**
249
+ * Replaces the whole Schedule (the Panel's editor writes each change this way), creating the config section. Every
250
+ * Slot is checked as the config schema does; a bad one is refused with what to fix. `previous` is the Schedule it
251
+ * replaced, which the Panel's Undo writes back.
252
+ */
253
+ export async function setUnattendedSchedule(opts) {
254
+ const schedule = opts.schedule.map((value, i) => {
255
+ const slot = parseSlot(value);
256
+ const name = value?.name;
257
+ if (!slot || (name !== undefined && (typeof name !== 'string' || name.length > 60)))
258
+ throw new UserError(`Slot ${i + 1} is not one: give days (mon…sun, each once), a start and an end such as 23:00 and 08:00, and a name of at most 60 characters`, { code: 'bad-slot' });
259
+ return slot;
260
+ });
261
+ let previous = [];
262
+ const r = await editConfigUnattended(opts.paths.configFile, (current) => {
263
+ previous = (current?.schedule ?? []);
264
+ if (current && JSON.stringify(previous) === JSON.stringify(schedule))
265
+ return null;
266
+ return { ...current, schedule };
267
+ });
268
+ return { changed: r.changed, status: await unattendedStatus(opts), previous };
269
+ }
270
+ /** The preset names `schedule preset` takes, with what each adds. */
271
+ export const UNATTENDED_PRESETS = { weeknights: WEEKNIGHTS };
272
+ /** The Slot `schedule add` was given, or why it cannot be one (the message says what to do). */
273
+ export function slotFromOptions(o) {
274
+ const example = 'for example: sideby unattended schedule add --days mon-fri --from 23:00 --to 08:00';
275
+ if (!o.days || !o.from || !o.to)
276
+ return { error: `give --days, --from and --to, ${example}` };
277
+ const days = parseDays(o.days);
278
+ if (!days?.length)
279
+ return { error: `--days takes mon…sun, ranges and lists such as mon-fri or sat,sun; ${example}` };
280
+ const start = parseClock(o.from);
281
+ const end = parseClock(o.to);
282
+ if (!start || !end)
283
+ return { error: `--from and --to take a 24-hour time such as 23:00 or 08:00; ${example}` };
284
+ const name = o.name?.trim();
285
+ if (name !== undefined && (!name || [...name].length > 60))
286
+ return { error: 'use a --name of 1 to 60 characters, or leave it out' };
287
+ return { ...(name ? { name } : {}), days, start, end };
288
+ }
289
+ /** How a time reads in the CLI (`08:00`, `tomorrow 08:00`, `Mon 08:00`). */
290
+ export const unattendedClock = (iso, now, zh = false) => clockText(Date.parse(iso), now.getTime(), zh);
291
+ /**
292
+ * Unattended Mode's session hooks: before the ask tool in Claude and Codex, and on every permission request Claude
293
+ * Code is about to show (Codex has no such event for it; its own approval prompts are not covered).
294
+ */
295
+ export function unattendedHookPart() {
296
+ const command = (family, event = 'PreToolUse') => sidebyHookCommand('unattended-hook', family, event);
297
+ return {
298
+ id: 'unattended',
299
+ claude: {
300
+ PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: command('claude') }] }],
301
+ PermissionRequest: [
302
+ { matcher: '*', hooks: [{ type: 'command', command: command('claude', 'PermissionRequest') }] },
303
+ ],
304
+ },
305
+ codex: {
306
+ PreToolUse: [`{matcher="^request_user_input$",hooks=[{type="command",command="${command('codex')}"}]}`],
307
+ },
308
+ };
309
+ }
310
+ function prefersChinese(env) {
311
+ return /^zh/i.test(env.LC_ALL || env.LC_MESSAGES || env.LANG || '');
312
+ }
313
+ /** The line a Claude Launch prints when the user's own `--settings` leaves no room for the hook. */
314
+ export function unattendedSettingsLine(env) {
315
+ return prefersChinese(env)
316
+ ? 'sideby:已经给了 `--settings`,无人值守管不到这个会话(它的 hook 要通过 `--settings` 加入)。'
317
+ : 'sideby: `--settings` is already given, so Unattended Mode does not cover this session (its hook goes in through `--settings`).';
318
+ }
319
+ /** The line a Launch prints when `--unattended` asks for a Family Unattended Mode does not cover. */
320
+ export function unattendedFamilyLine(family, env) {
321
+ return prefersChinese(env)
322
+ ? `sideby:无人值守只管 Claude 和 Codex 会话,这个 ${family} 会话不受影响。`
323
+ : `sideby: Unattended Mode covers Claude and Codex sessions only; this ${family} session is not covered.`;
324
+ }
325
+ /** Once per Codex Account: Codex runs the hook only after the user trusts it in `/hooks`. */
326
+ export async function codexUnattendedTrustLine(stateDir, ref, env) {
327
+ const file = join(stateDir, 'unattended', 'codex-trust-notices.json');
328
+ let seen = [];
329
+ try {
330
+ const v = JSON.parse(await readFile(file, 'utf8'));
331
+ if (Array.isArray(v.refs))
332
+ seen = v.refs.filter((r) => typeof r === 'string');
333
+ }
334
+ catch {
335
+ // first notice
336
+ }
337
+ if (seen.includes(ref))
338
+ return undefined;
339
+ try {
340
+ await ensureUnattendedDir(stateDir);
341
+ await writeFileAtomic(file, `${JSON.stringify({ refs: [...seen, ref] })}\n`, 0o600);
342
+ }
343
+ catch {
344
+ // shown again next time
345
+ }
346
+ return prefersChinese(env)
347
+ ? `sideby:Codex 要先信任 hook,无人值守才拦得住它的提问:在 ${ref} 里输入 /hooks,信任 \`unattended-hook\`。`
348
+ : `sideby: Codex runs Unattended Mode's hook only after you trust it: in ${ref}, type /hooks and trust \`unattended-hook\`. Until then its questions are not stopped.`;
349
+ }
@@ -229,9 +229,17 @@ export async function serveDetached(opts) {
229
229
  rec.processStart = processStart;
230
230
  await writeFile(pidFilePath(paths), `${JSON.stringify(rec, null, 2)}\n`, { mode: 0o600 });
231
231
  send({ url: srv.url, reused: false });
232
+ // Unattended Mode (spec §3.37): the background Panel notices a stretch that ended within 30 seconds.
233
+ const { watchUnattendedEnded } = await import('../core/unattended-ended.js');
234
+ const stopWatch = watchUnattendedEnded(paths, async (ctx) => {
235
+ const rt = await opts.runtimeFactory(await envReady);
236
+ for (const f of await rt.unattendedEnded(ctx))
237
+ log(`[${new Date().toISOString()}] unattended.ended: [${f.plugin}] ${f.error}`);
238
+ });
232
239
  await new Promise((resolve) => {
233
240
  const stop = (sig) => {
234
241
  log(`[${new Date().toISOString()}] ${sig}: stopping`);
242
+ stopWatch();
235
243
  void srv.close().finally(resolve);
236
244
  };
237
245
  process.once('SIGTERM', () => stop('SIGTERM'));
@@ -9,6 +9,8 @@ import { listMessages, type MessageReceipt, sendMessage } from '../core/messages
9
9
  import { type AccountModel } from '../core/model-choice.ts';
10
10
  import { type NetworkOverview } from '../core/network.ts';
11
11
  import { type RemoteControlGroup } from '../core/remote-control.ts';
12
+ import { type UnattendedStatus } from '../core/unattended.ts';
13
+ import { type PendingDecision } from '../core/unattended-pending.ts';
12
14
  import * as update from '../core/update.ts';
13
15
  import type { AccountStatus, DoctorHistory, FamilyInfo, QuotaCheckInfo, Runtime } from '../runtime.ts';
14
16
  import type { Account, FamilyLogo, QuotaResult, QuotaSetupPlan, UsageResult } from '../types.ts';
@@ -259,6 +261,41 @@ export interface PanelState {
259
261
  panel?: PanelConfig;
260
262
  /** Network Guard (spec §3.35): the setting and the cached result per address; absent without Claude or Codex Accounts. */
261
263
  network?: NetworkOverview;
264
+ /** Unattended Mode (spec §3.37): whether it is on for the computer, why, until when, the Schedule; absent when unreadable. */
265
+ unattended?: PanelUnattendedStatus;
266
+ }
267
+ /** One Pending Decision as the Panel's Unattended page lists it, with the way back to its Session. */
268
+ export interface PanelPendingDecision extends PendingDecision {
269
+ /** The Account's short name (its Alias when it has one). */
270
+ accountLabel?: string;
271
+ /** The Session still runs: its label, so the Sessions page finds it. */
272
+ live?: {
273
+ label: string;
274
+ accountLabel: string;
275
+ };
276
+ /** The command that resumes the Session, from its folder when that is known; only for an id safe in a shell. */
277
+ resume?: string;
278
+ }
279
+ /**
280
+ * The status as the Panel gets it: with the ids of the open Pending Decisions, so a page that marked some done and
281
+ * waits for the answer subtracts only those a newer status still lists. `pending` is their number.
282
+ */
283
+ export type PanelUnattendedStatus = UnattendedStatus & {
284
+ pendingIds: string[];
285
+ };
286
+ /** The Unattended page: the status and every open Pending Decision. */
287
+ export interface PanelUnattended {
288
+ status: PanelUnattendedStatus;
289
+ pending: PanelPendingDecision[];
290
+ }
291
+ /** What a change on the Unattended page did, and the request that puts back what was there. */
292
+ export interface PanelUnattendedChange {
293
+ changed: boolean;
294
+ status: PanelUnattendedStatus;
295
+ undo?: {
296
+ route: '/api/unattended/on' | '/api/unattended/off';
297
+ body: Record<string, unknown>;
298
+ };
262
299
  }
263
300
  /**
264
301
  * Internal, for tests: replaces parts of the machine the Panel's start-at-login switch uses (platform, launcher,
@@ -17,7 +17,7 @@ import { handoffOverview } from '../core/handoff-overview.js';
17
17
  import { apiUndecided, handoffRulesView } from '../core/handoff-rules.js';
18
18
  import { configureHandoff, handoffStatus } from '../core/handoff-status.js';
19
19
  import { acceptInbound, groupsToAccept, inboundGroups, undoInbound, waitingFiles, } from '../core/inbound.js';
20
- import { listLiveSessions, liveKey, referenceText, sessionCopyText, } from '../core/live-sessions.js';
20
+ import { accountLabels, listLiveSessions, liveKey, referenceText, resumeCommandFor, sessionCopyText, } from '../core/live-sessions.js';
21
21
  import { listMessages, sendMessage } from '../core/messages.js';
22
22
  import { accountModel, setAccountModel } from '../core/model-choice.js';
23
23
  import { GUARDED_FAMILIES, setNetwork } from '../core/network.js';
@@ -30,6 +30,10 @@ import { SKILL_INSTALL } from '../core/skill-check.js';
30
30
  import { launchArgs, TERMINALS } from '../core/terminal.js';
31
31
  import { checkThemeData, listThemes, NO_THEME, previewColors, removeThemeFile, resolveColors, saveThemeFile, undoTheme, useTheme, } from '../core/themes.js';
32
32
  import { MIN_CALLS } from '../core/tuning.js';
33
+ import { onUntil, setUnattendedSchedule, turnUnattendedOff, turnUnattendedOn, unattendedStatus, } from '../core/unattended.js';
34
+ import { checkUnattendedEnded } from '../core/unattended-ended.js';
35
+ import { listPendingDecisions, markPendingDone, reopenPendingDecision, } from '../core/unattended-pending.js';
36
+ import { readUnattendedConfig } from '../core/unattended-state.js';
33
37
  import * as update from '../core/update.js';
34
38
  import { buildId, localBuild, packageVersion } from '../core/version.js';
35
39
  import { HOOK_FAMILIES } from '../handoff/hook.js';
@@ -592,6 +596,15 @@ async function buildState(rt, opts) {
592
596
  const { setupBlock, shellSetupStatus, userShell } = await import('../core/shell-setup.js');
593
597
  const shellSt = await shellSetupStatus(userShell(rt.env), ctx.home, rt.env, rt.config.shellInitFile);
594
598
  const browser = await browserReport(rt, accounts).catch(() => undefined);
599
+ // The Panel's own status leaves out a `--unattended` session the server itself may run in: it shows the computer.
600
+ const unattended = await unattendedStatus({
601
+ paths: rt.paths,
602
+ families: [...rt.families.keys()],
603
+ now: ctx.now,
604
+ readOnly: opts.readOnly,
605
+ })
606
+ .then((st) => withPendingIds(st, rt.paths.stateDir))
607
+ .catch(() => undefined);
595
608
  const showBrowser = browser && (browser.families.matched.length || browser.families.openOnly.length);
596
609
  return {
597
610
  schemaVersion: 1,
@@ -633,6 +646,60 @@ async function buildState(rt, opts) {
633
646
  ...(rt.quotaChecks().length ? { quotaChecks: rt.quotaChecks() } : {}),
634
647
  ...(rt.config.panel && Object.keys(rt.config.panel).length ? { panel: rt.config.panel } : {}),
635
648
  ...(network ? { network } : {}),
649
+ ...(unattended ? { unattended } : {}),
650
+ };
651
+ }
652
+ const SHELL_SAFE = /^[A-Za-z0-9_@%+=:,./-]+$/;
653
+ const shellArg = (v) => (SHELL_SAFE.test(v) ? v : `'${v.replaceAll("'", "'\\''")}'`);
654
+ /** A Session id a hook reported is text from the Host: only a plain one goes into a command. */
655
+ const SAFE_SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
656
+ /** The `undo` command a change printed, as the request the page sends for it. */
657
+ function undoRequest(undo) {
658
+ if (undo === 'sideby unattended off')
659
+ return { route: '/api/unattended/off', body: {} };
660
+ if (undo === 'sideby unattended on')
661
+ return { route: '/api/unattended/on', body: {} };
662
+ const until = undo?.startsWith('sideby unattended on --until ') ? undo.slice(29) : undefined;
663
+ return until ? { route: '/api/unattended/on', body: { until } } : undefined;
664
+ }
665
+ /** A status with the ids of the open Pending Decisions, read once more (read only: nothing is deleted here). */
666
+ async function withPendingIds(status, stateDir) {
667
+ const ids = (await listPendingDecisions(stateDir, { prune: false })).map((d) => d.id);
668
+ return { ...status, pending: ids.length, pendingIds: ids };
669
+ }
670
+ async function panelChange(c, stateDir) {
671
+ const undo = undoRequest(c.undo);
672
+ return { changed: c.changed, status: await withPendingIds(c.status, stateDir), ...(undo ? { undo } : {}) };
673
+ }
674
+ async function unattendedView(rt, readOnly, live) {
675
+ const families = [...rt.families.keys()];
676
+ const [status, decisions, accounts] = await Promise.all([
677
+ unattendedStatus({ paths: rt.paths, families, readOnly }),
678
+ listPendingDecisions(rt.paths.stateDir, { prune: !readOnly }),
679
+ rt.accounts(),
680
+ ]);
681
+ const labels = accountLabels(rt, accounts);
682
+ const running = decisions.some((d) => d.sessionId)
683
+ ? (await live(rt).catch(() => ({ sessions: [], problems: [] }))).sessions
684
+ : [];
685
+ const home = rt.paths.home;
686
+ return {
687
+ status: { ...status, pending: decisions.length, pendingIds: decisions.map((d) => d.id) },
688
+ pending: decisions.map((d) => {
689
+ const label = d.account ? labels.get(d.account) : undefined;
690
+ const session = d.sessionId ? running.find((s) => s.sessionId === d.sessionId) : undefined;
691
+ const known = d.account && accounts.some((a) => a.ref === d.account);
692
+ const resume = d.sessionId && SAFE_SESSION_ID.test(d.sessionId) && known
693
+ ? resumeCommandFor(d.family, d.account, d.sessionId)
694
+ : undefined;
695
+ return {
696
+ ...d,
697
+ ...(d.cwd ? { cwd: tildify(d.cwd, home) } : {}),
698
+ ...(label ? { accountLabel: label } : {}),
699
+ ...(session ? { live: { label: session.label, accountLabel: session.accountLabel } } : {}),
700
+ ...(resume ? { resume: d.cwd ? `cd ${shellArg(d.cwd)} && ${resume}` : resume } : {}),
701
+ };
702
+ }),
636
703
  };
637
704
  }
638
705
  /** The `display` of a /api/display-order body: null, or string lists only; anything else is refused. */
@@ -911,6 +978,12 @@ export function createPanelHandler(opts) {
911
978
  const getRuntime = typeof opts.runtime === 'function' ? opts.runtime : async () => opts.runtime;
912
979
  const sessionsSource = opts[LIVE_SESSIONS_SOURCE];
913
980
  const liveSessions = sessionsSource?.list ?? listLiveSessions;
981
+ // A change from this page can end a stretch of Unattended Mode: the plugins hear of it now, as after the CLI. The
982
+ // answer waits for that (two small reads when nothing ended), but at most 1 s; a slower plugin finishes on its own.
983
+ const noticeUnattendedEnd = (rt) => Promise.race([
984
+ checkUnattendedEnded(rt.paths, async (ctx) => void (await rt.unattendedEnded(ctx))),
985
+ new Promise((resolve) => setTimeout(resolve, 1000).unref()),
986
+ ]);
914
987
  const copyText = sessionsSource?.copyText ?? sessionCopyText;
915
988
  const orcaOf = (rt) => sessionsSource?.orca ?? systemOrca(rt.env);
916
989
  const sendTo = sessionsSource?.send ?? sendMessage;
@@ -1710,6 +1783,85 @@ export function createPanelHandler(opts) {
1710
1783
  return { ...r, path: tildify(r.path, home), ...(r.target ? { target: tildify(r.target, home) } : {}) };
1711
1784
  },
1712
1785
  },
1786
+ // Unattended Mode (spec §3.37): the page's status and Pending Decisions. A read-only Panel reads them too.
1787
+ '/api/unattended': {
1788
+ writes: () => false,
1789
+ queued: false,
1790
+ async run() {
1791
+ return unattendedView(await getRuntime(), readOnly, liveSessions);
1792
+ },
1793
+ },
1794
+ // Turns it on now: `slotEnd`, `for` (4h, 12h) or `until` (07:30, the next time it is 07:30; or a date and time).
1795
+ '/api/unattended/on': {
1796
+ async run(body) {
1797
+ const choice = {
1798
+ ...(body.slotEnd === true ? { slotEnd: true } : {}),
1799
+ ...(optString(body, 'for') ? { for: optString(body, 'for') } : {}),
1800
+ ...(optString(body, 'until') ? { until: optString(body, 'until') } : {}),
1801
+ };
1802
+ const rt = await getRuntime();
1803
+ const now = new Date();
1804
+ const { schedule } = await readUnattendedConfig(rt.paths.configFile);
1805
+ const r = onUntil(choice, schedule, now);
1806
+ if ('error' in r)
1807
+ throw new HttpError(400, r.error, 'bad-time');
1808
+ const change = await turnUnattendedOn({
1809
+ paths: rt.paths,
1810
+ families: [...rt.families.keys()],
1811
+ until: r.until,
1812
+ now,
1813
+ });
1814
+ await noticeUnattendedEnd(rt);
1815
+ return panelChange(change, rt.paths.stateDir);
1816
+ },
1817
+ },
1818
+ // Off now; inside a Slot, a pause until that Slot ends.
1819
+ '/api/unattended/off': {
1820
+ async run() {
1821
+ const rt = await getRuntime();
1822
+ const change = await turnUnattendedOff({ paths: rt.paths, families: [...rt.families.keys()] });
1823
+ await noticeUnattendedEnd(rt);
1824
+ return panelChange(change, rt.paths.stateDir);
1825
+ },
1826
+ },
1827
+ // The whole Schedule at once: every edit on the page writes it, and its Undo writes `previous` back.
1828
+ '/api/unattended/schedule': {
1829
+ async run(body) {
1830
+ if (!Array.isArray(body.schedule))
1831
+ throw new HttpError(400, '"schedule" must be a list of Slots');
1832
+ const rt = await getRuntime();
1833
+ const r = await setUnattendedSchedule({
1834
+ paths: rt.paths,
1835
+ families: [...rt.families.keys()],
1836
+ schedule: body.schedule,
1837
+ });
1838
+ await noticeUnattendedEnd(rt);
1839
+ return {
1840
+ changed: r.changed,
1841
+ status: await withPendingIds(r.status, rt.paths.stateDir),
1842
+ previous: r.previous,
1843
+ };
1844
+ },
1845
+ },
1846
+ // Marks one Pending Decision done (or every open one with `all`), or with `done: false` opens one again.
1847
+ '/api/unattended/pending': {
1848
+ async run(body) {
1849
+ const id = optString(body, 'id');
1850
+ const all = body.all === true;
1851
+ if (!id && !all)
1852
+ throw new HttpError(400, '"id" or "all" is required');
1853
+ const rt = await getRuntime();
1854
+ try {
1855
+ const changed = body.done === false && id
1856
+ ? [await reopenPendingDecision(rt.paths.stateDir, id)]
1857
+ : await markPendingDone(rt.paths.stateDir, all ? 'all' : id);
1858
+ return { ids: changed.map((d) => d.id) };
1859
+ }
1860
+ catch (err) {
1861
+ throw new HttpError(400, err.message, 'no-pending');
1862
+ }
1863
+ },
1864
+ },
1713
1865
  // Network Guard (spec §3.35): asks every address now. Only sideby's own cache changes, so a read-only Panel may.
1714
1866
  '/api/network/check': {
1715
1867
  writes: () => false,