sideby 0.28.3 → 0.30.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 (64) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +12 -0
  3. package/dist/src/cli/commands.js +337 -13
  4. package/dist/src/cli/json-schemas.js +87 -1
  5. package/dist/src/cli/main.js +65 -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/live-sessions.d.ts +2 -0
  14. package/dist/src/core/messages.d.ts +2 -0
  15. package/dist/src/core/messages.js +12 -34
  16. package/dist/src/core/network.d.ts +5 -2
  17. package/dist/src/core/network.js +15 -45
  18. package/dist/src/core/run-link.d.ts +6 -1
  19. package/dist/src/core/run-link.js +62 -22
  20. package/dist/src/core/search-catalog.d.ts +1 -1
  21. package/dist/src/core/search-catalog.js +37 -0
  22. package/dist/src/core/session-handoffs.d.ts +22 -0
  23. package/dist/src/core/session-handoffs.js +110 -0
  24. package/dist/src/core/session-hooks.d.ts +33 -0
  25. package/dist/src/core/session-hooks.js +92 -0
  26. package/dist/src/core/session-select.d.ts +18 -3
  27. package/dist/src/core/session-select.js +82 -8
  28. package/dist/src/core/unattended-ended.d.ts +62 -0
  29. package/dist/src/core/unattended-ended.js +275 -0
  30. package/dist/src/core/unattended-pending.d.ts +56 -0
  31. package/dist/src/core/unattended-pending.js +182 -0
  32. package/dist/src/core/unattended-state.d.ts +129 -0
  33. package/dist/src/core/unattended-state.js +373 -0
  34. package/dist/src/core/unattended.d.ts +142 -0
  35. package/dist/src/core/unattended.js +349 -0
  36. package/dist/src/panel/background.js +8 -0
  37. package/dist/src/panel/handler.d.ts +37 -0
  38. package/dist/src/panel/handler.js +156 -2
  39. package/dist/src/panel/i18n.d.ts +97 -0
  40. package/dist/src/panel/i18n.js +194 -0
  41. package/dist/src/panel/page-logic.d.ts +129 -0
  42. package/dist/src/panel/page-logic.js +166 -0
  43. package/dist/src/panel/page-script.js +638 -7
  44. package/dist/src/panel/page-styles.js +69 -0
  45. package/dist/src/panel/page.js +2 -0
  46. package/dist/src/plugins/bus.js +1 -0
  47. package/dist/src/runtime.d.ts +17 -1
  48. package/dist/src/runtime.js +78 -15
  49. package/dist/src/types.d.ts +48 -0
  50. package/dist/src/unattended/hook.d.ts +46 -0
  51. package/dist/src/unattended/hook.js +288 -0
  52. package/package.json +1 -1
  53. package/schemas/config.json +76 -0
  54. package/schemas/messages.json +4 -0
  55. package/schemas/send.json +4 -0
  56. package/schemas/sessions-copy.json +4 -0
  57. package/schemas/sessions-open-run.json +4 -0
  58. package/schemas/sessions.json +7 -0
  59. package/schemas/unattended-defer.json +143 -0
  60. package/schemas/unattended-pending.json +154 -0
  61. package/schemas/unattended.json +291 -0
  62. package/skills/sideby/SKILL.md +3 -2
  63. package/skills/sideby/references/sessions.md +1 -1
  64. package/skills/sideby/references/unattended.md +58 -0
@@ -0,0 +1,142 @@
1
+ import type { Env } from '../types.ts';
2
+ import type { Paths } from './paths.ts';
3
+ import { type SessionHookPart } from './session-hooks.ts';
4
+ import { type UnattendedOverride, type UnattendedSlot, type UnattendedState } from './unattended-state.ts';
5
+ /** Families whose sessions Unattended Mode covers in v1. */
6
+ export declare const UNATTENDED_FAMILIES: readonly string[];
7
+ /**
8
+ * covered: sessions sideby starts get the hook; needs-trust: they get it, and Codex runs it once the user trusts it in
9
+ * `/hooks`; not-covered: the Family has no hook sideby can add (Grok, pi), or the feature was never used.
10
+ */
11
+ export type UnattendedCoverage = 'covered' | 'needs-trust' | 'not-covered';
12
+ /** Everything `sideby unattended --json` prints and the Panel shows. */
13
+ export interface UnattendedStatus extends UnattendedState {
14
+ /** The config has an `unattended` section, so sessions sideby starts get the hook. */
15
+ configured: boolean;
16
+ schedule: UnattendedSlot[];
17
+ /** Open Pending Decisions. */
18
+ pending: number;
19
+ coverage: Record<string, UnattendedCoverage>;
20
+ /** When `on --slot-end` would end: the end of the current or next Slot, when that is within 72 hours. */
21
+ slotEnd?: string;
22
+ /** The manual state in effect now: on until, or paused until. */
23
+ manual?: UnattendedOverride;
24
+ /**
25
+ * Why sideby cannot keep its state: `<state>/unattended` is a link, someone else's, or others can write to it. The
26
+ * message says what to do; until then the manual state and Pending Decisions are neither read nor written.
27
+ */
28
+ problem?: string;
29
+ }
30
+ /** What a change did, and the command that puts back what was there. */
31
+ export interface UnattendedChange {
32
+ changed: boolean;
33
+ status: UnattendedStatus;
34
+ undo?: string;
35
+ }
36
+ /** The Weeknights preset: Monday to Friday, 23:00 to 08:00. */
37
+ export declare const WEEKNIGHTS: UnattendedSlot;
38
+ /** The full status. `env` matters only for a session started with `--unattended`. */
39
+ export declare function unattendedStatus(opts: {
40
+ paths: Paths;
41
+ families: readonly string[];
42
+ env?: Env;
43
+ now?: Date;
44
+ /** Only read: old done Pending Decisions are not deleted (a read-only Panel). */
45
+ readOnly?: boolean;
46
+ }): Promise<UnattendedStatus>;
47
+ /** How long to turn it on for, as the CLI and the Panel take it. At most one of the three. */
48
+ export interface OnChoice {
49
+ /** `4h`, `90m` or `1h30m`. */
50
+ for?: string;
51
+ /** `07:30` (the next time it is 07:30) or an ISO date and time. */
52
+ until?: string;
53
+ /** Until the current or next Slot ends. */
54
+ slotEnd?: boolean;
55
+ }
56
+ /** `4h`, `90m`, `1h30m` in milliseconds; undefined for anything else. */
57
+ export declare function parseDuration(text: string): number | undefined;
58
+ /**
59
+ * When a manual "on" would end, or why it cannot (the message says what to do). Without a choice: until the current
60
+ * or next Slot ends when that is within 72 hours, else 12 hours.
61
+ */
62
+ export declare function onUntil(choice: OnChoice, schedule: readonly UnattendedSlot[], now: Date): {
63
+ until: number;
64
+ } | {
65
+ error: string;
66
+ };
67
+ /** Makes the config section, which starts adding the hook to sessions sideby starts. */
68
+ export declare function ensureUnattendedConfig(configFile: string): Promise<void>;
69
+ /**
70
+ * Turns it on until `until` (at most 72 hours), creating the config section the first time. A Slot that ends later
71
+ * keeps it on longer. Callers then run `checkUnattendedEnded`, so a stretch this ends is noticed at once.
72
+ */
73
+ export declare function turnUnattendedOn(opts: {
74
+ paths: Paths;
75
+ families: readonly string[];
76
+ until: number;
77
+ now?: Date;
78
+ }): Promise<UnattendedChange>;
79
+ /**
80
+ * 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
81
+ * on as usual. Callers then run `checkUnattendedEnded`.
82
+ */
83
+ export declare function turnUnattendedOff(opts: {
84
+ paths: Paths;
85
+ families: readonly string[];
86
+ now?: Date;
87
+ }): Promise<UnattendedChange>;
88
+ /**
89
+ * Adds a Slot (at position `at`, 1-based, else last), creating the config section. A Slot with the same days and
90
+ * times is not added twice.
91
+ */
92
+ export declare function addUnattendedSlot(opts: {
93
+ paths: Paths;
94
+ families: readonly string[];
95
+ slot: UnattendedSlot;
96
+ at?: number;
97
+ now?: Date;
98
+ }): Promise<UnattendedChange>;
99
+ /** Removes Slot `n` (1-based, as `sideby unattended` numbers them). Throws when there is none. */
100
+ export declare function removeUnattendedSlot(opts: {
101
+ paths: Paths;
102
+ families: readonly string[];
103
+ n: number;
104
+ now?: Date;
105
+ }): Promise<UnattendedChange>;
106
+ /**
107
+ * Replaces the whole Schedule (the Panel's editor writes each change this way), creating the config section. Every
108
+ * Slot is checked as the config schema does; a bad one is refused with what to fix. `previous` is the Schedule it
109
+ * replaced, which the Panel's Undo writes back.
110
+ */
111
+ export declare function setUnattendedSchedule(opts: {
112
+ paths: Paths;
113
+ families: readonly string[];
114
+ schedule: readonly unknown[];
115
+ now?: Date;
116
+ }): Promise<UnattendedChange & {
117
+ previous: UnattendedSlot[];
118
+ }>;
119
+ /** The preset names `schedule preset` takes, with what each adds. */
120
+ export declare const UNATTENDED_PRESETS: Readonly<Record<string, UnattendedSlot>>;
121
+ /** The Slot `schedule add` was given, or why it cannot be one (the message says what to do). */
122
+ export declare function slotFromOptions(o: {
123
+ days?: string;
124
+ from?: string;
125
+ to?: string;
126
+ name?: string;
127
+ }): UnattendedSlot | {
128
+ error: string;
129
+ };
130
+ /** How a time reads in the CLI (`08:00`, `tomorrow 08:00`, `Mon 08:00`). */
131
+ export declare const unattendedClock: (iso: string, now: Date, zh?: boolean) => string;
132
+ /**
133
+ * Unattended Mode's session hooks: before the ask tool in Claude and Codex, and on every permission request Claude
134
+ * Code is about to show (Codex has no such event for it; its own approval prompts are not covered).
135
+ */
136
+ export declare function unattendedHookPart(): SessionHookPart;
137
+ /** The line a Claude Launch prints when the user's own `--settings` leaves no room for the hook. */
138
+ export declare function unattendedSettingsLine(env: Env): string;
139
+ /** The line a Launch prints when `--unattended` asks for a Family Unattended Mode does not cover. */
140
+ export declare function unattendedFamilyLine(family: string, env: Env): string;
141
+ /** Once per Codex Account: Codex runs the hook only after the user trusts it in `/hooks`. */
142
+ export declare function codexUnattendedTrustLine(stateDir: string, ref: string, env: Env): Promise<string | undefined>;
@@ -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,