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,92 @@
1
+ // The hooks sideby adds to a session it starts (Network Guard §3.35, Unattended Mode §3.37) and how they go together
2
+ // with each other and with Auto Handoff's (§3.17). Claude Code takes one `--settings`, so every part goes into one file
3
+ // sideby writes in its state folder; Codex takes `-c hooks.<event>=[…]`, where a second value for the same event would
4
+ // replace the first, so the entries of one event go into one value. Nothing is written into a Host directory.
5
+ import { mkdir, readFile } from 'node:fs/promises';
6
+ import { basename, dirname, extname, join } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { ownedFolder, writeFileAtomic } from './fs-safe.js';
9
+ /**
10
+ * The command a Host runs for a hook entry: this Node and this sideby by absolute path, never `sideby` by name. A
11
+ * missing or older `sideby` on PATH would fail the hook, and a failing hook lets the Host go on.
12
+ */
13
+ export function sidebyHookCommand(entry, family, event) {
14
+ const main = fileURLToPath(new URL(`../cli/main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
15
+ const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
16
+ const safe = (s) => !/["\\\n]/.test(s);
17
+ const bin = safe(process.execPath) && safe(main) ? `${q(process.execPath)} ${q(main)}` : 'sideby';
18
+ return `${bin} ${entry} ${family} ${event}`;
19
+ }
20
+ /** Every part's Claude hooks in one object, each event's groups in part order. */
21
+ export function mergeClaudeHooks(...parts) {
22
+ const out = {};
23
+ for (const part of parts)
24
+ for (const [e, list] of Object.entries(part))
25
+ out[e] = [...(out[e] ?? []), ...list];
26
+ return out;
27
+ }
28
+ /**
29
+ * Host arguments that add every part's hooks to a session: one `--settings` file for Claude (in the first part's
30
+ * folder, named after the parts: `network/claude-settings.json`, `network/claude-settings-unattended.json`), one
31
+ * `-c hooks.<event>=[…]` per event for Codex. Empty for other Families or no parts.
32
+ */
33
+ export async function sessionHookArgs(family, stateDir, parts) {
34
+ if (!parts.length)
35
+ return [];
36
+ if (family === 'claude') {
37
+ // A real folder of the user that nobody else can write to, so the file is never written through a link.
38
+ const dir = (await ownedFolder(stateDir, [parts[0].id], { create: true, private: true }));
39
+ const name = `claude-settings${parts
40
+ .slice(1)
41
+ .map((p) => `-${p.id}`)
42
+ .join('')}.json`;
43
+ const hooks = mergeClaudeHooks(...parts.map((p) => p.claude));
44
+ await writeFileAtomic(join(dir, name), `${JSON.stringify({ hooks }, null, 2)}\n`, 0o600);
45
+ return ['--settings', join(dir, name)];
46
+ }
47
+ if (family === 'codex') {
48
+ const events = new Map();
49
+ for (const p of parts)
50
+ for (const [e, list] of Object.entries(p.codex))
51
+ events.set(e, [...(events.get(e) ?? []), ...list]);
52
+ return [...events].flatMap(([e, list]) => ['-c', `hooks.${e}=[${list.join(',')}]`]);
53
+ }
54
+ return [];
55
+ }
56
+ async function settingsOf(args) {
57
+ const at = args.indexOf('--settings');
58
+ const file = at === -1 ? undefined : args[at + 1];
59
+ if (!file)
60
+ return {};
61
+ try {
62
+ const v = JSON.parse(await readFile(file, 'utf8'));
63
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
64
+ }
65
+ catch {
66
+ return {};
67
+ }
68
+ }
69
+ /**
70
+ * Auto Handoff's Claude hook arguments with `extra` hooks added to its `--settings` file, written as `out` (Claude
71
+ * Code takes one `--settings`). Auto Handoff's own hooks and options come first and are kept as they are.
72
+ */
73
+ export async function withClaudeHooks(hookArgs, extra, out) {
74
+ const settings = await settingsOf(hookArgs);
75
+ const hooks = mergeClaudeHooks(settings.hooks ?? {}, extra);
76
+ await mkdir(dirname(out), { recursive: true, mode: 0o700 });
77
+ await writeFileAtomic(out, `${JSON.stringify({ ...settings, hooks }, null, 2)}\n`, 0o600);
78
+ const at = hookArgs.indexOf('--settings');
79
+ return at === -1 ? [...hookArgs, '--settings', out] : hookArgs.map((a, i) => (i === at + 1 ? out : a));
80
+ }
81
+ /**
82
+ * Auto Handoff's Claude hook arguments with the session's own sideby hooks (`sessionArgs`, from `sessionHookArgs`)
83
+ * merged into one `--settings` file, written next to the session's file with `-handoff` added to its name.
84
+ */
85
+ export async function withClaudeSessionHooks(hookArgs, sessionArgs) {
86
+ const at = sessionArgs.indexOf('--settings');
87
+ const file = at === -1 ? undefined : sessionArgs[at + 1];
88
+ if (!file)
89
+ return [...hookArgs];
90
+ const extra = (await settingsOf(sessionArgs)).hooks ?? {};
91
+ return withClaudeHooks(hookArgs, extra, join(dirname(file), `${basename(file, '.json')}-handoff.json`));
92
+ }
@@ -0,0 +1,62 @@
1
+ import type { Env, UnattendedEndedContext } from '../types.ts';
2
+ import { type Paths } from './paths.ts';
3
+ export type UnattendedEndedEmit = (ctx: UnattendedEndedContext) => Promise<void> | void;
4
+ interface Seen {
5
+ startedAt: string;
6
+ reason: 'slot' | 'manual';
7
+ }
8
+ /** An event found and not yet delivered. */
9
+ interface Notice {
10
+ id: string;
11
+ startedAt: string;
12
+ endedAt: string;
13
+ reason: 'slot' | 'manual';
14
+ late?: true;
15
+ /** When a process took it to deliver; another takes it again once this is older than the lease. */
16
+ claimedAt?: string;
17
+ }
18
+ interface Checkpoint {
19
+ /** When a process last looked: stretches that ended after this are still to be found. */
20
+ checkedAt: string;
21
+ /** The stretch running then, as that process saw it start. */
22
+ current?: Seen;
23
+ /** Ids of the events delivered, newest last. */
24
+ emitted: string[];
25
+ /** Events found and not yet delivered, oldest first. */
26
+ outbox: Notice[];
27
+ }
28
+ /** At most this many events wait in the outbox; a look that finds more takes the oldest and leaves the rest. */
29
+ export declare const MAX_OUTBOX = 50;
30
+ /**
31
+ * Under the lock: finds the stretches that ended since the last look (oldest first, up to the outbox's room), adds
32
+ * them to the outbox, and claims every event in it that no other process holds. Returns the claimed events, oldest
33
+ * first; never throws.
34
+ */
35
+ export declare function claimUnattendedEnded(paths: Paths, now?: Date): Promise<Notice[]>;
36
+ /**
37
+ * Runs `emit` for each claimed event, with the Pending Decisions kept during it that are still open, then marks the
38
+ * ones whose `emit` returned as delivered. One whose `emit` threw stays in the outbox and is tried again after the
39
+ * lease. Never throws.
40
+ */
41
+ export declare function deliverUnattendedEnded(paths: Paths, notices: readonly Notice[], emit: UnattendedEndedEmit, now?: Date): Promise<void>;
42
+ /**
43
+ * Looks once: claims what ended since the last look and what still waits to be delivered, then delivers it. Cheap
44
+ * when the feature was never used (one read of the config). Never throws.
45
+ */
46
+ export declare function checkUnattendedEnded(paths: Paths, emit: UnattendedEndedEmit, now?: Date): Promise<void>;
47
+ /**
48
+ * The background Panel's watch (spec §3.37): looks now and every 30 seconds until the returned function stops it.
49
+ * Only a standalone Panel server starts one; a Panel embedded in a Portal through `createPanelHandler` does not.
50
+ */
51
+ export declare function watchUnattendedEnded(paths: Paths, emit: UnattendedEndedEmit, everyMs?: number): () => void;
52
+ /**
53
+ * A command's look when it starts: waits only for the look itself (two small file reads when nothing ended), and
54
+ * returns the delivery of what it found as `emitted`, which runs alongside the command. Plugins are loaded only when
55
+ * there is something to deliver; an event whose delivery does not finish is delivered by a later look.
56
+ */
57
+ export declare function noticeUnattendedEnded(env: Env): Promise<{
58
+ emitted: Promise<void>;
59
+ }>;
60
+ /** Reads the checkpoint, for tests and diagnostics. */
61
+ export declare function readEndedCheckpoint(stateDir: string): Promise<Checkpoint | undefined>;
62
+ export {};
@@ -0,0 +1,275 @@
1
+ // The end of a stretch of Unattended Mode (spec §3.37, ADR-0058): the first sideby process that notices it emits the
2
+ // plugin event `unattended.ended`. The background Panel looks every 30 seconds and other commands look when they
3
+ // start; none of the session hooks does. `<state>/unattended/ended.json` keeps when it last looked, the stretch it saw
4
+ // running then, the events found but not yet delivered (the outbox) and the ids of those delivered.
5
+ //
6
+ // Delivery is at least once: an event stays in the outbox until the plugin hooks have run for it, and one a process
7
+ // claimed but did not finish (it crashed, or was ended) is tried again after a lease. Each event has a stable `id`, so
8
+ // a plugin can skip one it has seen. Stretches that ended while no sideby process ran are found from the last look
9
+ // onward, oldest first, at most 50 a look; the rest wait for the next look.
10
+ import { join } from 'node:path';
11
+ import { writeFileAtomic } from './fs-safe.js';
12
+ import { takeFileLock } from './lock.js';
13
+ import { resolvePaths } from './paths.js';
14
+ import { listPendingDecisions } from './unattended-pending.js';
15
+ import { ensureUnattendedDir, readSmallJson, readUnattendedConfig, readUnattendedOverride, unattendedDir, unattendedTimeline, } from './unattended-state.js';
16
+ const DAY_MS = 24 * 60 * 60 * 1000;
17
+ /** Noticed this long after its end, the event says `late`. */
18
+ const LATE_MS = 12 * 60 * 60 * 1000;
19
+ /** A look that changes nothing is written down at most this often. */
20
+ const REWRITE_MS = 60 * 1000;
21
+ const KEEP_EMITTED = 100;
22
+ /** At most this many events wait in the outbox; a look that finds more takes the oldest and leaves the rest. */
23
+ export const MAX_OUTBOX = 50;
24
+ /** A claimed event not delivered after this long is taken again (its process is gone or stuck). */
25
+ const LEASE_MS = 2 * 60 * 1000;
26
+ const file = (stateDir) => join(unattendedDir(stateDir), 'ended.json');
27
+ const lockFile = (dir) => join(dir, 'ended.lock');
28
+ const LOCK = { staleMs: 30_000, beatMs: 10_000 };
29
+ const isTime = (v) => typeof v === 'string' && Number.isFinite(Date.parse(v));
30
+ const isReason = (v) => v === 'slot' || v === 'manual';
31
+ function parseNotice(value) {
32
+ if (!value || typeof value !== 'object')
33
+ return undefined;
34
+ const v = value;
35
+ if (typeof v.id !== 'string' || !isTime(v.startedAt) || !isTime(v.endedAt) || !isReason(v.reason))
36
+ return undefined;
37
+ return {
38
+ id: v.id,
39
+ startedAt: v.startedAt,
40
+ endedAt: v.endedAt,
41
+ reason: v.reason,
42
+ ...(v.late === true ? { late: true } : {}),
43
+ ...(isTime(v.claimedAt) ? { claimedAt: v.claimedAt } : {}),
44
+ };
45
+ }
46
+ function parseCheckpoint(value) {
47
+ if (!value || typeof value !== 'object')
48
+ return undefined;
49
+ const v = value;
50
+ if (!isTime(v.checkedAt))
51
+ return undefined;
52
+ const c = v.current;
53
+ const current = c && isTime(c.startedAt) && isReason(c.reason) ? { startedAt: c.startedAt, reason: c.reason } : undefined;
54
+ const emitted = Array.isArray(v.emitted) ? v.emitted.filter((e) => typeof e === 'string') : [];
55
+ const outbox = (Array.isArray(v.outbox) ? v.outbox : [])
56
+ .map(parseNotice)
57
+ .filter((n) => n !== undefined);
58
+ return {
59
+ checkedAt: v.checkedAt,
60
+ ...(current ? { current } : {}),
61
+ emitted: emitted.slice(-KEEP_EMITTED),
62
+ outbox: outbox.slice(0, MAX_OUTBOX),
63
+ };
64
+ }
65
+ const iso = (ms) => new Date(ms).toISOString();
66
+ /** The event's id: its start and end, which do not change once it is found. */
67
+ const eventId = (startedAt, endedAt) => `${iso(startedAt)}/${iso(endedAt)}`;
68
+ async function writeCheckpoint(stateDir, c) {
69
+ await writeFileAtomic(file(stateDir), `${JSON.stringify(c)}\n`, 0o600);
70
+ }
71
+ /**
72
+ * Under the lock: finds the stretches that ended since the last look (oldest first, up to the outbox's room), adds
73
+ * them to the outbox, and claims every event in it that no other process holds. Returns the claimed events, oldest
74
+ * first; never throws.
75
+ */
76
+ export async function claimUnattendedEnded(paths, now = new Date()) {
77
+ try {
78
+ const { configured, schedule } = await readUnattendedConfig(paths.configFile);
79
+ if (!configured && (await readSmallJson(file(paths.stateDir), 256 * 1024)) === undefined)
80
+ return [];
81
+ const dir = await ensureUnattendedDir(paths.stateDir);
82
+ const release = await takeFileLock(lockFile(dir), LOCK);
83
+ // Another process is looking right now and will report what there is.
84
+ if (!release)
85
+ return [];
86
+ try {
87
+ const before = parseCheckpoint(await readSmallJson(file(paths.stateDir), 256 * 1024));
88
+ const t = now.getTime();
89
+ // A clock that went back: look again once it has caught up.
90
+ if (before && Date.parse(before.checkedAt) > t)
91
+ return [];
92
+ const override = await readUnattendedOverride(paths.stateDir);
93
+ const last = before ? Date.parse(before.checkedAt) : t;
94
+ const from = Math.min(last, before?.current ? Date.parse(before.current.startedAt) : last) - 9 * DAY_MS;
95
+ const timeline = unattendedTimeline(schedule, override, from, t + DAY_MS);
96
+ const ended = [];
97
+ let current;
98
+ if (before) {
99
+ // The stretch seen running at the last look: it went on as long as the Schedule and the manual state now say;
100
+ // when they no longer cover that moment (the user turned it off), it ended now.
101
+ const seen = before.current;
102
+ const cont = seen ? timeline.find((s) => s.start <= last && last < s.end) : undefined;
103
+ if (seen) {
104
+ const end = cont ? cont.end : t;
105
+ if (end <= t)
106
+ ended.push({ startedAt: Date.parse(seen.startedAt), endedAt: end, reason: seen.reason });
107
+ else
108
+ current = seen;
109
+ }
110
+ for (const s of timeline) {
111
+ if (s === cont || s.end <= last || s.start > t)
112
+ continue;
113
+ // A stretch the last look did not see running counts from that look, at the earliest.
114
+ const start = Math.max(s.start, last);
115
+ if (s.end <= t) {
116
+ if (start < s.end)
117
+ ended.push({ startedAt: start, endedAt: s.end, reason: s.reason });
118
+ }
119
+ else if (!current)
120
+ current = { startedAt: iso(start), reason: s.reason };
121
+ }
122
+ }
123
+ else {
124
+ const running = timeline.find((s) => s.start <= t && t < s.end);
125
+ if (running)
126
+ current = { startedAt: iso(running.start), reason: running.reason };
127
+ }
128
+ ended.sort((a, b) => a.endedAt - b.endedAt);
129
+ const outbox = [...(before?.outbox ?? [])];
130
+ const emitted = [...(before?.emitted ?? [])];
131
+ const known = new Set([...emitted, ...outbox.map((n) => n.id)]);
132
+ const fresh = ended.filter((e) => !known.has(eventId(e.startedAt, e.endedAt)));
133
+ const room = MAX_OUTBOX - outbox.length;
134
+ let checkedAt = t;
135
+ if (fresh.length > room) {
136
+ // More than fit: take the oldest and look again from the end of the last one taken, so none is lost.
137
+ fresh.length = Math.max(0, room);
138
+ const lastTaken = fresh.at(-1);
139
+ checkedAt = lastTaken ? lastTaken.endedAt : last;
140
+ current = lastTaken ? undefined : before?.current;
141
+ }
142
+ for (const e of fresh)
143
+ outbox.push({
144
+ id: eventId(e.startedAt, e.endedAt),
145
+ startedAt: iso(e.startedAt),
146
+ endedAt: iso(e.endedAt),
147
+ reason: e.reason,
148
+ ...(t - e.endedAt > LATE_MS ? { late: true } : {}),
149
+ });
150
+ const claimed = [];
151
+ for (const n of outbox)
152
+ if (!n.claimedAt || t - Date.parse(n.claimedAt) > LEASE_MS || Date.parse(n.claimedAt) > t) {
153
+ n.claimedAt = iso(t);
154
+ claimed.push(n);
155
+ }
156
+ const next = { checkedAt: iso(checkedAt), ...(current ? { current } : {}), emitted, outbox };
157
+ const same = before &&
158
+ !fresh.length &&
159
+ !claimed.length &&
160
+ JSON.stringify(before.current ?? null) === JSON.stringify(current ?? null) &&
161
+ t - last < REWRITE_MS;
162
+ // Claimed before any plugin runs: another process does not take the same events while the lease holds.
163
+ if (!same)
164
+ await writeCheckpoint(paths.stateDir, next);
165
+ return claimed.map(({ claimedAt: _, ...n }) => n);
166
+ }
167
+ finally {
168
+ await release();
169
+ }
170
+ }
171
+ catch {
172
+ return [];
173
+ }
174
+ }
175
+ /**
176
+ * Runs `emit` for each claimed event, with the Pending Decisions kept during it that are still open, then marks the
177
+ * ones whose `emit` returned as delivered. One whose `emit` threw stays in the outbox and is tried again after the
178
+ * lease. Never throws.
179
+ */
180
+ export async function deliverUnattendedEnded(paths, notices, emit, now = new Date()) {
181
+ if (!notices.length)
182
+ return;
183
+ const pending = await listPendingDecisions(paths.stateDir, { now }).catch(() => []);
184
+ const done = [];
185
+ for (const n of notices) {
186
+ const [start, end] = [Date.parse(n.startedAt), Date.parse(n.endedAt)];
187
+ try {
188
+ await emit({
189
+ id: n.id,
190
+ startedAt: n.startedAt,
191
+ endedAt: n.endedAt,
192
+ reason: n.reason,
193
+ ...(n.late ? { late: true } : {}),
194
+ pending: pending.filter((p) => {
195
+ const at = Date.parse(p.at);
196
+ return at >= start && at <= end;
197
+ }),
198
+ });
199
+ done.push(n.id);
200
+ }
201
+ catch {
202
+ // Not delivered: it stays in the outbox and is tried again.
203
+ }
204
+ }
205
+ if (!done.length)
206
+ return;
207
+ try {
208
+ const dir = await ensureUnattendedDir(paths.stateDir);
209
+ const release = await takeFileLock(lockFile(dir), { ...LOCK, wait: { timeoutMs: 5_000, pollMs: 50 } });
210
+ // Not marked: the lease runs out and they are delivered again, which `id` lets a plugin notice.
211
+ if (!release)
212
+ return;
213
+ try {
214
+ const c = parseCheckpoint(await readSmallJson(file(paths.stateDir), 256 * 1024));
215
+ if (!c)
216
+ return;
217
+ const ids = new Set(done);
218
+ c.outbox = c.outbox.filter((n) => !ids.has(n.id));
219
+ c.emitted = [...c.emitted.filter((id) => !ids.has(id)), ...done].slice(-KEEP_EMITTED);
220
+ await writeCheckpoint(paths.stateDir, c);
221
+ }
222
+ finally {
223
+ await release();
224
+ }
225
+ }
226
+ catch {
227
+ // as above
228
+ }
229
+ }
230
+ /**
231
+ * Looks once: claims what ended since the last look and what still waits to be delivered, then delivers it. Cheap
232
+ * when the feature was never used (one read of the config). Never throws.
233
+ */
234
+ export async function checkUnattendedEnded(paths, emit, now = new Date()) {
235
+ await deliverUnattendedEnded(paths, await claimUnattendedEnded(paths, now), emit, now);
236
+ }
237
+ /**
238
+ * The background Panel's watch (spec §3.37): looks now and every 30 seconds until the returned function stops it.
239
+ * Only a standalone Panel server starts one; a Panel embedded in a Portal through `createPanelHandler` does not.
240
+ */
241
+ export function watchUnattendedEnded(paths, emit, everyMs = 30_000) {
242
+ let running = false;
243
+ const look = () => {
244
+ if (running)
245
+ return;
246
+ running = true;
247
+ void checkUnattendedEnded(paths, emit).finally(() => {
248
+ running = false;
249
+ });
250
+ };
251
+ const timer = setInterval(look, everyMs);
252
+ timer.unref();
253
+ look();
254
+ return () => clearInterval(timer);
255
+ }
256
+ /**
257
+ * A command's look when it starts: waits only for the look itself (two small file reads when nothing ended), and
258
+ * returns the delivery of what it found as `emitted`, which runs alongside the command. Plugins are loaded only when
259
+ * there is something to deliver; an event whose delivery does not finish is delivered by a later look.
260
+ */
261
+ export async function noticeUnattendedEnded(env) {
262
+ const paths = resolvePaths(env);
263
+ const notices = await claimUnattendedEnded(paths);
264
+ let rt;
265
+ const emitted = deliverUnattendedEnded(paths, notices, async (ctx) => {
266
+ rt ??= import('../runtime.js').then((m) => m.createRuntime({ env }));
267
+ for (const f of await (await rt).unattendedEnded(ctx))
268
+ console.error(`sideby: [${f.plugin}] unattended.ended failed: ${f.error}`);
269
+ });
270
+ return { emitted };
271
+ }
272
+ /** Reads the checkpoint, for tests and diagnostics. */
273
+ export async function readEndedCheckpoint(stateDir) {
274
+ return parseCheckpoint(await readSmallJson(file(stateDir), 256 * 1024));
275
+ }
@@ -0,0 +1,56 @@
1
+ export interface PendingDecision {
2
+ id: string;
3
+ /** When it was kept (ISO). */
4
+ at: string;
5
+ /**
6
+ * question: a question the Host's ask tool was not allowed to show; permission: a permission request Claude Code
7
+ * would have shown, refused; deferred: `sideby unattended defer`.
8
+ */
9
+ kind: PendingKind;
10
+ family: string;
11
+ /** The Account the session ran as (`SIDEBY_ACCOUNT`). */
12
+ account?: string;
13
+ sessionId?: string;
14
+ cwd?: string;
15
+ /** The subagent that made the request, when a subagent did (Claude's `agent_id` and `agent_type`). */
16
+ agentId?: string;
17
+ agentType?: string;
18
+ /** The question and its options, the tool and what it was to do, or the deferred text; at most 4000 characters. */
19
+ text: string;
20
+ /** When the user marked it done (ISO). */
21
+ doneAt?: string;
22
+ }
23
+ export type PendingKind = 'question' | 'permission' | 'deferred';
24
+ export declare const PENDING_KINDS: readonly PendingKind[];
25
+ export type PendingInput = Omit<PendingDecision, 'id' | 'at' | 'doneAt'>;
26
+ export declare const PENDING_TEXT_MAX = 4000;
27
+ export declare const pendingDir: (stateDir: string) => string;
28
+ /** At most `PENDING_TEXT_MAX` characters (whole characters, never half of one), ending in `…` when cut. */
29
+ export declare function clipPendingText(text: string): string;
30
+ /**
31
+ * Keeps one Pending Decision and returns it. With `dedupe`, an open one of the same kind, session and text is
32
+ * returned instead of a second copy (a model that asks the same question twice leaves one).
33
+ */
34
+ export declare function addPendingDecision(stateDir: string, input: PendingInput, at?: Date, opts?: {
35
+ dedupe?: boolean;
36
+ }): Promise<PendingDecision>;
37
+ /**
38
+ * The Pending Decisions, oldest first: open ones, or with `all` the done ones too. Deletes the files of those done
39
+ * more than 30 days ago.
40
+ */
41
+ export declare function listPendingDecisions(stateDir: string,
42
+ /** `prune: false` only reads (a read-only Panel): old done ones are left out but not deleted. */
43
+ opts?: {
44
+ all?: boolean;
45
+ now?: Date;
46
+ prune?: boolean;
47
+ }): Promise<PendingDecision[]>;
48
+ /** Opens a Pending Decision marked done again (the Panel's Undo after "Done"); throws when there is no such id. */
49
+ export declare function reopenPendingDecision(stateDir: string, id: string): Promise<PendingDecision>;
50
+ /** The open Pending Decision an id names: the whole id, or a start of it that only one has. */
51
+ export declare function findPendingDecision(stateDir: string, id: string): Promise<PendingDecision | undefined>;
52
+ /**
53
+ * Marks Pending Decisions done: one by id (or a unique start of it), or every open one with `'all'`. Returns the ones
54
+ * it marked; an id no Pending Decision has throws an Error whose message says how to list them.
55
+ */
56
+ export declare function markPendingDone(stateDir: string, id: string | 'all', at?: Date): Promise<PendingDecision[]>;
@@ -0,0 +1,182 @@
1
+ // Pending Decisions (spec §3.37, ADR-0058): questions the model was not allowed to ask, permission requests nobody was
2
+ // there to answer, and actions it left undone, while Unattended Mode was on. One file each under `<state>/unattended/pending/` (folder 700, files 600), so writes
3
+ // from several sessions never meet. Kept until the user marks one done, deleted 30 days after that. A leaf module
4
+ // (Node built-ins and core/fs-safe.ts only): `unattended-hook` writes here.
5
+ //
6
+ // Both folders must be real folders of the user that nobody else can write to (`ownedFolder`); when one is not, nothing
7
+ // is read from or written there. Files are read without following a link.
8
+ import { randomBytes } from 'node:crypto';
9
+ import { readdir, rm } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { ownedFolder, readSmallFile, writeFileAtomic } from './fs-safe.js';
12
+ export const PENDING_KINDS = ['question', 'permission', 'deferred'];
13
+ export const PENDING_TEXT_MAX = 4000;
14
+ const KEEP_DONE_MS = 30 * 24 * 60 * 60 * 1000;
15
+ const ID = /^[a-z0-9]{6,16}-[0-9a-f]{6}$/;
16
+ const FIELD = /^[\x20-\x7e]{1,256}$/;
17
+ export const pendingDir = (stateDir) => join(stateDir, 'unattended', 'pending');
18
+ const PARTS = ['unattended', 'pending'];
19
+ /** The pending folder, made (mode 700) when missing; throws `UnsafeFolderError` when a level is not safe to use. */
20
+ async function ensureDir(stateDir) {
21
+ return (await ownedFolder(stateDir, PARTS, { create: true, private: true }));
22
+ }
23
+ /** The pending folder when it exists and is safe to read; null otherwise. */
24
+ async function existingDir(stateDir) {
25
+ return ownedFolder(stateDir, PARTS, { create: false }).catch(() => null);
26
+ }
27
+ /** At most `PENDING_TEXT_MAX` characters (whole characters, never half of one), ending in `…` when cut. */
28
+ export function clipPendingText(text) {
29
+ const chars = [...text.trim()];
30
+ return chars.length <= PENDING_TEXT_MAX
31
+ ? chars.join('')
32
+ : `${chars.slice(0, PENDING_TEXT_MAX - 1).join('')}…`;
33
+ }
34
+ function parse(value) {
35
+ if (!value || typeof value !== 'object')
36
+ return undefined;
37
+ const v = value;
38
+ if (typeof v.id !== 'string' || !ID.test(v.id))
39
+ return undefined;
40
+ if (typeof v.at !== 'string' || !Number.isFinite(Date.parse(v.at)))
41
+ return undefined;
42
+ if (!PENDING_KINDS.includes(v.kind))
43
+ return undefined;
44
+ if (typeof v.family !== 'string' || !FIELD.test(v.family) || typeof v.text !== 'string')
45
+ return undefined;
46
+ const opt = (k) => typeof v[k] === 'string' && v[k] ? { [k]: v[k].slice(0, 4096) } : {};
47
+ const done = typeof v.doneAt === 'string' && Number.isFinite(Date.parse(v.doneAt)) ? { doneAt: v.doneAt } : {};
48
+ return {
49
+ id: v.id,
50
+ at: v.at,
51
+ kind: v.kind,
52
+ family: v.family,
53
+ ...opt('account'),
54
+ ...opt('sessionId'),
55
+ ...opt('cwd'),
56
+ ...opt('agentId'),
57
+ ...opt('agentType'),
58
+ text: clipPendingText(v.text),
59
+ ...done,
60
+ };
61
+ }
62
+ async function readOne(file) {
63
+ const text = await readSmallFile(file, 64 * 1024);
64
+ if (text === undefined)
65
+ return undefined;
66
+ try {
67
+ return parse(JSON.parse(text));
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ }
73
+ async function readAll(stateDir) {
74
+ const dir = await existingDir(stateDir);
75
+ if (!dir)
76
+ return [];
77
+ let names;
78
+ try {
79
+ names = await readdir(dir);
80
+ }
81
+ catch {
82
+ return [];
83
+ }
84
+ const ids = names.filter((n) => n.endsWith('.json')).map((n) => n.slice(0, -5));
85
+ const read = await Promise.all(ids.filter((id) => ID.test(id)).map((id) => readOne(join(dir, `${id}.json`))));
86
+ return read
87
+ .filter((d) => d !== undefined)
88
+ .sort((a, b) => Date.parse(a.at) - Date.parse(b.at) || a.id.localeCompare(b.id));
89
+ }
90
+ const fileOf = (stateDir, id) => join(pendingDir(stateDir), `${id}.json`);
91
+ /**
92
+ * Keeps one Pending Decision and returns it. With `dedupe`, an open one of the same kind, session and text is
93
+ * returned instead of a second copy (a model that asks the same question twice leaves one).
94
+ */
95
+ export async function addPendingDecision(stateDir, input, at = new Date(), opts = {}) {
96
+ const text = clipPendingText(input.text);
97
+ if (opts.dedupe) {
98
+ const same = (await readAll(stateDir)).find((d) => !d.doneAt && d.kind === input.kind && d.sessionId === input.sessionId && d.text === text);
99
+ if (same)
100
+ return same;
101
+ }
102
+ const dir = await ensureDir(stateDir);
103
+ const decision = {
104
+ id: `${at.getTime().toString(36)}-${randomBytes(3).toString('hex')}`,
105
+ at: at.toISOString(),
106
+ kind: input.kind,
107
+ family: input.family,
108
+ ...(input.account ? { account: input.account } : {}),
109
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
110
+ ...(input.cwd ? { cwd: input.cwd } : {}),
111
+ ...(input.agentId ? { agentId: input.agentId } : {}),
112
+ ...(input.agentType ? { agentType: input.agentType } : {}),
113
+ text,
114
+ };
115
+ await writeFileAtomic(join(dir, `${decision.id}.json`), `${JSON.stringify(decision)}\n`, 0o600);
116
+ return decision;
117
+ }
118
+ /**
119
+ * The Pending Decisions, oldest first: open ones, or with `all` the done ones too. Deletes the files of those done
120
+ * more than 30 days ago.
121
+ */
122
+ export async function listPendingDecisions(stateDir,
123
+ /** `prune: false` only reads (a read-only Panel): old done ones are left out but not deleted. */
124
+ opts = {}) {
125
+ const now = (opts.now ?? new Date()).getTime();
126
+ const out = [];
127
+ for (const d of await readAll(stateDir)) {
128
+ if (d.doneAt && now - Date.parse(d.doneAt) > KEEP_DONE_MS) {
129
+ if (opts.prune !== false)
130
+ await rm(fileOf(stateDir, d.id), { force: true }).catch(() => { });
131
+ continue;
132
+ }
133
+ if (opts.all || !d.doneAt)
134
+ out.push(d);
135
+ }
136
+ return out;
137
+ }
138
+ /** Opens a Pending Decision marked done again (the Panel's Undo after "Done"); throws when there is no such id. */
139
+ export async function reopenPendingDecision(stateDir, id) {
140
+ const d = (await readAll(stateDir)).find((x) => x.id === id);
141
+ if (!d)
142
+ throw new Error(`no Pending Decision has the id "${id}"; \`sideby unattended pending --all\` lists them`);
143
+ if (!d.doneAt)
144
+ return d;
145
+ const { doneAt: _, ...open } = d;
146
+ await ensureDir(stateDir);
147
+ await writeFileAtomic(fileOf(stateDir, d.id), `${JSON.stringify(open)}\n`, 0o600);
148
+ return open;
149
+ }
150
+ /** The open Pending Decision an id names: the whole id, or a start of it that only one has. */
151
+ export async function findPendingDecision(stateDir, id) {
152
+ const all = await readAll(stateDir);
153
+ const exact = all.find((d) => d.id === id);
154
+ if (exact)
155
+ return exact;
156
+ const starts = all.filter((d) => id.length >= 4 && d.id.startsWith(id));
157
+ return starts.length === 1 ? starts[0] : undefined;
158
+ }
159
+ /**
160
+ * Marks Pending Decisions done: one by id (or a unique start of it), or every open one with `'all'`. Returns the ones
161
+ * it marked; an id no Pending Decision has throws an Error whose message says how to list them.
162
+ */
163
+ export async function markPendingDone(stateDir, id, at = new Date()) {
164
+ const targets = id === 'all'
165
+ ? (await readAll(stateDir)).filter((d) => !d.doneAt)
166
+ : [await findPendingDecision(stateDir, id)].filter((d) => d !== undefined);
167
+ if (id !== 'all' && !targets.length)
168
+ throw new Error(`no Pending Decision has the id "${id}"; \`sideby unattended pending --all\` lists them`);
169
+ if (targets.length)
170
+ await ensureDir(stateDir);
171
+ const out = [];
172
+ for (const d of targets) {
173
+ if (d.doneAt) {
174
+ out.push(d);
175
+ continue;
176
+ }
177
+ const done = { ...d, doneAt: at.toISOString() };
178
+ await writeFileAtomic(fileOf(stateDir, d.id), `${JSON.stringify(done)}\n`, 0o600);
179
+ out.push(done);
180
+ }
181
+ return out;
182
+ }