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
@@ -1,11 +1,11 @@
1
1
  // Network Guard (spec §3.35, ADR-0053): which address each Account's Egress is checked at, the check before a
2
2
  // Launch, and the hooks that keep checking inside a session sideby starts. The check itself is core/egress.ts.
3
3
  import { mkdir, readFile } from 'node:fs/promises';
4
- import { extname, join } from 'node:path';
5
- import { fileURLToPath } from 'node:url';
4
+ import { join } from 'node:path';
6
5
  import { blockMessage, cacheKey, judge, NETWORK_ENV, prefersChinese, readEntry, refresh, verdict, } from './egress.js';
7
6
  import { UserError } from './errors.js';
8
7
  import { writeFileAtomic } from './fs-safe.js';
8
+ import { sessionHookArgs, sidebyHookCommand, withClaudeHooks } from './session-hooks.js';
9
9
  import { inCi } from './update.js';
10
10
  /** Families Network Guard covers in v1. */
11
11
  export const GUARDED_FAMILIES = ['claude', 'codex'];
@@ -90,17 +90,7 @@ export function ipChangedLine(v, env) {
90
90
  ? 'sideby:网络出口 IP 和上次不同(国家没变,没有拦截)。'
91
91
  : 'sideby: the network exit address changed since the last check (same country, nothing blocked).';
92
92
  }
93
- /**
94
- * The command a Host runs for the hook: this Node and this sideby by absolute path, never `sideby` by name. A
95
- * missing or older `sideby` on PATH would fail the hook, and a failing hook lets the Host go on.
96
- */
97
- function hookCommand(family, event) {
98
- const main = fileURLToPath(new URL(`../cli/main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
99
- const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
100
- const safe = (s) => !/["\\\n]/.test(s);
101
- const bin = safe(process.execPath) && safe(main) ? `${q(process.execPath)} ${q(main)}` : 'sideby';
102
- return `${bin} network-hook ${family} ${event}`;
103
- }
93
+ const hookCommand = (family, event) => sidebyHookCommand('network-hook', family, event);
104
94
  const HOOK_EVENTS = ['UserPromptSubmit', 'PreToolUse'];
105
95
  /** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
106
96
  export function claudeNetworkHooks() {
@@ -111,23 +101,20 @@ export function claudeNetworkHooks() {
111
101
  }
112
102
  /** The file holding Network Guard's Claude hooks alone. */
113
103
  export const claudeNetworkSettings = (stateDir) => join(networkDir(stateDir), 'claude-settings.json');
104
+ /** Network Guard's session hooks (spec §3.35), to combine with others through `sessionHookArgs`. */
105
+ export function networkHookPart() {
106
+ return {
107
+ id: 'network',
108
+ claude: claudeNetworkHooks(),
109
+ codex: Object.fromEntries(HOOK_EVENTS.map((e) => [e, [`{hooks=[{type="command",command="${hookCommand('codex', e)}"}]}`]])),
110
+ };
111
+ }
114
112
  /**
115
- * Host arguments that add Network Guard's hooks to a session: Claude through a `--settings` file sideby writes,
113
+ * Host arguments that add Network Guard's hooks alone to a session: Claude through a `--settings` file sideby writes,
116
114
  * Codex through `-c hooks.*`. Nothing is written into a Host directory.
117
115
  */
118
116
  export async function networkHookArgs(family, stateDir) {
119
- if (family === 'claude') {
120
- const file = claudeNetworkSettings(stateDir);
121
- await mkdir(networkDir(stateDir), { recursive: true, mode: 0o700 });
122
- await writeFileAtomic(file, `${JSON.stringify({ hooks: claudeNetworkHooks() }, null, 2)}\n`, 0o600);
123
- return ['--settings', file];
124
- }
125
- if (family === 'codex')
126
- return HOOK_EVENTS.flatMap((e) => [
127
- '-c',
128
- `hooks.${e}=[{hooks=[{type="command",command="${hookCommand('codex', e)}"}]}]`,
129
- ]);
130
- return [];
117
+ return sessionHookArgs(family, stateDir, [networkHookPart()]);
131
118
  }
132
119
  /** The line a Claude Launch prints when the user's own `--settings` leaves no room for the session hooks. */
133
120
  export function networkSettingsLine(env) {
@@ -164,26 +151,9 @@ export async function codexNetworkTrustLine(stateDir, ref, env) {
164
151
  * file next to Network Guard's own (Claude Code takes one `--settings`).
165
152
  */
166
153
  export async function withClaudeNetworkHooks(hookArgs, stateDir) {
167
- const at = hookArgs.indexOf('--settings');
168
- const file = at === -1 ? undefined : hookArgs[at + 1];
169
- let settings = {};
170
- if (file) {
171
- try {
172
- settings = JSON.parse(await readFile(file, 'utf8'));
173
- }
174
- catch {
175
- settings = {};
176
- }
177
- }
178
- const hooks = { ...(settings.hooks ?? {}) };
179
- for (const [e, list] of Object.entries(claudeNetworkHooks()))
180
- hooks[e] = [...(hooks[e] ?? []), ...list];
181
- const out = join(networkDir(stateDir), 'claude-settings-handoff.json');
182
- await mkdir(networkDir(stateDir), { recursive: true, mode: 0o700 });
183
- await writeFileAtomic(out, `${JSON.stringify({ ...settings, hooks }, null, 2)}\n`, 0o600);
184
- return at === -1 ? [...hookArgs, '--settings', out] : hookArgs.map((a, i) => (i === at + 1 ? out : a));
154
+ return withClaudeHooks(hookArgs, claudeNetworkHooks(), join(networkDir(stateDir), 'claude-settings-handoff.json'));
185
155
  }
186
- /** `args` without the Network Guard arguments `networkHookArgs` added (Auto Handoff merges them into its own). */
156
+ /** `args` without one run of arguments sideby added (Auto Handoff merges its session hooks into its own file). */
187
157
  export function withoutArgs(args, drop) {
188
158
  if (!drop.length)
189
159
  return [...args];
@@ -59,9 +59,14 @@ export declare function stillTheBoard(board: string, check: BoardCheck, id: Boar
59
59
  export declare function byRole(list: readonly RunEntry[]): RunEntry[];
60
60
  /** The Run each of `sessionIds` works for; an empty map when there is no index, no boards folder or no match. */
61
61
  export declare function runsForSessions(env: Env, home: string, sessionIds: readonly string[], uid?: number): Promise<Map<string, SessionRun>>;
62
- /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
62
+ /**
63
+ * The same Sessions, each with `run` where the Session Index ties it to a Run: by its own id, else by the ids it was
64
+ * handed over from, newest first, so a Run Board stays linked after its coordinator moves to another Account. An id
65
+ * whose boards all fail the checks is passed over, as `openRunBoard` passes it over.
66
+ */
63
67
  export declare function withRuns<T extends {
64
68
  sessionId: string;
69
+ handedOverFrom?: readonly string[];
65
70
  }>(env: Env, home: string, sessions: T[], uid?: number): Promise<(T & {
66
71
  run?: SessionRun;
67
72
  })[]>;
@@ -8,6 +8,7 @@ import { basename, dirname, isAbsolute, join } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { openWithDefault } from './edit-settings.js';
10
10
  import { UserError } from './errors.js';
11
+ import { earlierHops, readHandoffChains } from './session-handoffs.js';
11
12
  /** The largest Session Index sideby reads; a bigger one is ignored. */
12
13
  export const INDEX_MAX_BYTES = 256 * 1024;
13
14
  const MAX_TEXT = 120;
@@ -202,26 +203,64 @@ export async function runsForSessions(env, home, sessionIds, uid) {
202
203
  if (!check)
203
204
  return out;
204
205
  for (const id of wanted) {
205
- const [first, ...rest] = await checkedRuns(index.get(id), check);
206
- if (!first)
207
- continue;
208
- const others = rest.map((e) => ({
209
- title: e.title,
210
- ...(e.laneTitle ? { laneTitle: e.laneTitle } : {}),
211
- ...(e.role ? { role: e.role } : {}),
212
- board: e.board,
213
- }));
214
- out.set(id, { ...first, ...(others.length ? { others } : {}) });
206
+ const run = sessionRun(await checkedRuns(index.get(id), check));
207
+ if (run)
208
+ out.set(id, run);
215
209
  }
216
210
  return out;
217
211
  }
218
- /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
212
+ /** The first checked entry as the Session's Run, the rest as its `others`; undefined when none checked out. */
213
+ function sessionRun([first, ...rest]) {
214
+ if (!first)
215
+ return undefined;
216
+ const others = rest.map((e) => ({
217
+ title: e.title,
218
+ ...(e.laneTitle ? { laneTitle: e.laneTitle } : {}),
219
+ ...(e.role ? { role: e.role } : {}),
220
+ board: e.board,
221
+ }));
222
+ return { ...first, ...(others.length ? { others } : {}) };
223
+ }
224
+ /** A Session's own id, then the ids an Auto Handoff chain passed it from, newest first (ADR-0057). */
225
+ const linkIds = (s) => [
226
+ s.sessionId,
227
+ ...[...(s.handedOverFrom ?? [])].reverse(),
228
+ ];
229
+ /**
230
+ * The one rule a Run Link follows, for listing and opening alike: the entries of the first id in `ids` that has an
231
+ * entry whose board checks out, those that check out ordered by role, each with its board's identity at the check.
232
+ */
233
+ async function linkedEntries(index, check, ids) {
234
+ for (const sessionId of ids) {
235
+ const entries = index.get(sessionId);
236
+ if (!entries)
237
+ continue;
238
+ const ok = (await Promise.all(entries.map((e) => inspectEntry(e, check)))).filter((x) => x !== undefined);
239
+ if (!ok.length)
240
+ continue;
241
+ const order = byRole(ok.map((x) => x.entry));
242
+ return order.map((entry) => ok.find((x) => x.entry === entry));
243
+ }
244
+ return [];
245
+ }
246
+ /**
247
+ * The same Sessions, each with `run` where the Session Index ties it to a Run: by its own id, else by the ids it was
248
+ * handed over from, newest first, so a Run Board stays linked after its coordinator moves to another Account. An id
249
+ * whose boards all fail the checks is passed over, as `openRunBoard` passes it over.
250
+ */
219
251
  export async function withRuns(env, home, sessions, uid) {
220
- const runs = await runsForSessions(env, home, sessions.map((s) => s.sessionId), uid);
221
- return sessions.map((s) => {
222
- const run = runs.get(s.sessionId);
252
+ if (!sessions.length)
253
+ return sessions;
254
+ const index = await readSessionIndex(sessionIndexPath(env, home));
255
+ const check = index && sessions.some((s) => linkIds(s).some((id) => index.has(id)))
256
+ ? await boardsCheck(env, home, uid)
257
+ : undefined;
258
+ if (!index || !check)
259
+ return sessions;
260
+ return Promise.all(sessions.map(async (s) => {
261
+ const run = sessionRun((await linkedEntries(index, check, linkIds(s))).map((x) => x.entry));
223
262
  return run ? { ...s, run } : s;
224
- });
263
+ }));
225
264
  }
226
265
  /**
227
266
  * Opens the Run Board of `sessionId` with the system's default program. The path comes only from the Session Index,
@@ -230,15 +269,16 @@ export async function withRuns(env, home, sessions, uid) {
230
269
  */
231
270
  export async function openRunBoard(rt, sessionId) {
232
271
  const gone = () => new UserError('This session is not part of a run any more, or its board file is gone; ask the coordinating AI to show the board again', { code: 'no-run' });
233
- const entries = (await readSessionIndex(sessionIndexPath(rt.env, rt.paths.home)))?.get(sessionId);
234
- const check = entries && (await boardsCheck(rt.env, rt.paths.home));
235
- if (!entries || !check)
272
+ const index = await readSessionIndex(sessionIndexPath(rt.env, rt.paths.home));
273
+ const check = index && (await boardsCheck(rt.env, rt.paths.home));
274
+ if (!index || !check)
236
275
  throw gone();
237
- const ok = (await Promise.all(entries.map((e) => inspectEntry(e, check)))).filter((x) => x !== undefined);
238
- const first = byRole(ok.map((x) => x.entry))[0];
239
- const id = ok.find((x) => x.entry === first)?.id;
240
- if (!first || !id)
276
+ // The same rule as the listing: its own id, then the ids it was handed over from, newest first (ADR-0057).
277
+ const earlier = earlierHops(await readHandoffChains(rt.paths.stateDir), sessionId) ?? [];
278
+ const [picked] = await linkedEntries(index, check, linkIds({ sessionId, handedOverFrom: earlier }));
279
+ if (!picked)
241
280
  throw gone();
281
+ const { entry: first, id } = picked;
242
282
  if (!(await stillTheBoard(first.board, check, id)))
243
283
  throw new UserError('The board file changed while sideby checked it; ask the coordinating AI to show the board again', { code: 'board-changed' });
244
284
  return { board: first.board, command: await openWithDefault(rt, first.board, { text: false }) };
@@ -1,5 +1,5 @@
1
1
  export type SearchKind = 'page' | 'setting' | 'action';
2
- export type PanelPage = 'accounts' | 'sessions' | 'tuning' | 'handoff';
2
+ export type PanelPage = 'accounts' | 'sessions' | 'tuning' | 'handoff' | 'unattended';
3
3
  /** Where the Panel takes the user. Internal: the CLI shows `panel`, never this. */
4
4
  export type SearchTarget =
5
5
  /** A page of its own (the tabs under the header). */
@@ -68,6 +68,25 @@ const ENTRIES = [
68
68
  target: { page: 'handoff' },
69
69
  cliCommand: 'sideby handoff',
70
70
  },
71
+ {
72
+ id: 'page.unattended',
73
+ kind: 'page',
74
+ title: { en: 'Unattended Mode', zh: '无人值守' },
75
+ synonyms: [
76
+ 'unattended',
77
+ 'away',
78
+ 'overnight',
79
+ 'do not disturb',
80
+ 'pending decisions',
81
+ '挂机',
82
+ '今晚自己跑完',
83
+ '别问我',
84
+ '待你决定',
85
+ ],
86
+ panel: { en: 'Unattended page', zh: '无人值守页' },
87
+ target: { page: 'unattended' },
88
+ cliCommand: 'sideby unattended',
89
+ },
71
90
  {
72
91
  id: 'setting.language',
73
92
  kind: 'setting',
@@ -239,6 +258,24 @@ const ENTRIES = [
239
258
  target: { action: 'handoff-on', write: true },
240
259
  cliCommand: 'sideby handoff enable',
241
260
  },
261
+ {
262
+ id: 'action.unattended-on',
263
+ kind: 'action',
264
+ title: { en: 'Turn on Unattended Mode now', zh: '现在开无人值守' },
265
+ synonyms: ['unattended on', 'go unattended', 'until morning', '现在开', '开启无人值守', '挂机到明早'],
266
+ panel: { en: 'Unattended page', zh: '无人值守页' },
267
+ target: { action: 'unattended-on', write: true },
268
+ cliCommand: 'sideby unattended on',
269
+ },
270
+ {
271
+ id: 'action.unattended-add-slot',
272
+ kind: 'action',
273
+ title: { en: 'Add an Unattended Slot', zh: '添加无人值守时段' },
274
+ synonyms: ['add a slot', 'unattended schedule', 'weeknights', '添加时段', '时间表', '工作日夜间'],
275
+ panel: at({ en: 'Unattended page', zh: '无人值守页' }, { en: 'Schedule', zh: '时间表' }),
276
+ target: { action: 'unattended-add-slot', write: true },
277
+ cliCommand: 'sideby unattended schedule add',
278
+ },
242
279
  {
243
280
  id: 'action.network-guard',
244
281
  kind: 'action',
@@ -0,0 +1,22 @@
1
+ /** One hop of a chain: its session, and when the hop started (the time its run id starts with). */
2
+ export interface HandoffHop {
3
+ sessionId: string;
4
+ /** Milliseconds since the epoch, from the run id's base36 time; 0 when it has none. */
5
+ at: number;
6
+ }
7
+ /** The hops of one chain, oldest first. A resumed session handed over again starts a new chain. */
8
+ export type HandoffChain = readonly HandoffHop[];
9
+ /** Every Handoff chain under `<stateDir>/handoffs`, each its hops in run-id order; links are not followed. */
10
+ export declare function readHandoffChains(stateDir: string): Promise<HandoffHop[][]>;
11
+ /** The session ids the task passed through before `sessionId`, oldest first; undefined when no chain led to it. */
12
+ export declare function earlierHops(chains: readonly HandoffChain[], sessionId: string): string[] | undefined;
13
+ /** The same Sessions, each with `handedOverFrom` where a Handoff chain led to it. */
14
+ export declare function withHandoffs<T extends {
15
+ sessionId: string;
16
+ }>(chains: readonly HandoffChain[], sessions: readonly T[]): (T & {
17
+ handedOverFrom?: string[];
18
+ })[];
19
+ /** The full session ids in any chain that `target` names: the id itself, or its first 8 or more characters. */
20
+ export declare function chainIdsMatching(chains: readonly HandoffChain[], target: string): string[];
21
+ /** The sessions the task passed to after `sessionId`, across every chain, the newest hop first. */
22
+ export declare function laterHops(chains: readonly HandoffChain[], sessionId: string): string[];
@@ -0,0 +1,110 @@
1
+ // Which Sessions an Auto Handoff chain passed a task through (spec §3.32 step 2, ADR-0057): each hop of a chain
2
+ // writes `run-<runId>.json` under `<state>/handoffs/<chain>/`, and run ids start with the time, so sorting them sorts
3
+ // the hops. Read-only and best effort: only the `sessionId` of run files is read (never a Brief or another chain
4
+ // file), a file that cannot be read or parsed is skipped, and nothing is written. Imports Node built-ins only.
5
+ import { lstat, readdir, readFile } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ /** A run file bigger than this is not a hop sideby wrote; it is skipped. */
8
+ const RUN_MAX_BYTES = 256 * 1024;
9
+ const RUN_FILE = /^run-.+\.json$/;
10
+ async function names(dir) {
11
+ try {
12
+ return await readdir(dir);
13
+ }
14
+ catch {
15
+ return [];
16
+ }
17
+ }
18
+ async function hopSession(file) {
19
+ try {
20
+ const st = await lstat(file);
21
+ if (!st.isFile() || st.size > RUN_MAX_BYTES)
22
+ return undefined;
23
+ const raw = JSON.parse(await readFile(file, 'utf8'));
24
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
25
+ return undefined;
26
+ const id = raw.sessionId;
27
+ return typeof id === 'string' && id ? id : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ /** The time a run id starts with (`<base36 ms>-<hex>`, `newId` in handoff-chain.ts); 0 when it has none. */
34
+ function runTime(name) {
35
+ const t = Number.parseInt(name.slice('run-'.length).split('-')[0] ?? '', 36);
36
+ return Number.isFinite(t) ? t : 0;
37
+ }
38
+ /** Every Handoff chain under `<stateDir>/handoffs`, each its hops in run-id order; links are not followed. */
39
+ export async function readHandoffChains(stateDir) {
40
+ const root = join(stateDir, 'handoffs');
41
+ const chains = [];
42
+ for (const name of (await names(root)).sort()) {
43
+ const dir = join(root, name);
44
+ const st = await lstat(dir).catch(() => undefined);
45
+ if (!st?.isDirectory())
46
+ continue;
47
+ const runs = (await names(dir)).filter((n) => RUN_FILE.test(n)).sort();
48
+ const hops = [];
49
+ for (const run of runs) {
50
+ const sessionId = await hopSession(join(dir, run));
51
+ // A session that keeps its hop over two run files (a resumed wait) is one hop.
52
+ if (sessionId && sessionId !== hops[hops.length - 1]?.sessionId)
53
+ hops.push({ sessionId, at: runTime(run) });
54
+ }
55
+ if (hops.length)
56
+ chains.push(hops);
57
+ }
58
+ return chains;
59
+ }
60
+ /**
61
+ * The hops on one side of `sessionId`, following every chain that holds it and, through them, the chains of those
62
+ * hops (a session resumed and handed over again starts a new chain). Each session once, at its latest hop time.
63
+ */
64
+ function reach(chains, sessionId, side) {
65
+ const found = new Map();
66
+ const todo = [sessionId];
67
+ for (let id = todo.pop(); id !== undefined; id = todo.pop())
68
+ for (const chain of chains) {
69
+ const i = chain.map((h) => h.sessionId).lastIndexOf(id);
70
+ if (i === -1)
71
+ continue;
72
+ for (const hop of side === 'before' ? chain.slice(0, i) : chain.slice(i + 1)) {
73
+ if (hop.sessionId === sessionId)
74
+ continue;
75
+ const seen = found.get(hop.sessionId);
76
+ if (seen === undefined)
77
+ todo.push(hop.sessionId);
78
+ if (seen === undefined || hop.at > seen)
79
+ found.set(hop.sessionId, hop.at);
80
+ }
81
+ }
82
+ return [...found].map(([id, at]) => ({ sessionId: id, at }));
83
+ }
84
+ /** The session ids the task passed through before `sessionId`, oldest first; undefined when no chain led to it. */
85
+ export function earlierHops(chains, sessionId) {
86
+ const hops = reach(chains, sessionId, 'before').sort((a, b) => a.at - b.at);
87
+ return hops.length ? hops.map((h) => h.sessionId) : undefined;
88
+ }
89
+ /** The same Sessions, each with `handedOverFrom` where a Handoff chain led to it. */
90
+ export function withHandoffs(chains, sessions) {
91
+ return sessions.map((s) => {
92
+ const from = earlierHops(chains, s.sessionId);
93
+ return from ? { ...s, handedOverFrom: from } : s;
94
+ });
95
+ }
96
+ /** The full session ids in any chain that `target` names: the id itself, or its first 8 or more characters. */
97
+ export function chainIdsMatching(chains, target) {
98
+ const out = new Set();
99
+ for (const chain of chains)
100
+ for (const { sessionId: id } of chain)
101
+ if (id === target || (target.length >= 8 && id.startsWith(target)))
102
+ out.add(id);
103
+ return [...out];
104
+ }
105
+ /** The sessions the task passed to after `sessionId`, across every chain, the newest hop first. */
106
+ export function laterHops(chains, sessionId) {
107
+ return reach(chains, sessionId, 'after')
108
+ .sort((a, b) => b.at - a.at)
109
+ .map((h) => h.sessionId);
110
+ }
@@ -0,0 +1,33 @@
1
+ /** Claude Code `hooks` entries: per event, its matcher groups. */
2
+ export type ClaudeHooks = Record<string, unknown[]>;
3
+ /** One feature's session hooks. */
4
+ export interface SessionHookPart {
5
+ /** Its folder in the state directory, and its part of the settings file's name: `network`, `unattended`. */
6
+ id: string;
7
+ claude: ClaudeHooks;
8
+ /** Per Codex event, the inline TOML tables of its list, such as `{matcher="…",hooks=[{type="command",command="…"}]}`. */
9
+ codex: Record<string, string[]>;
10
+ }
11
+ /**
12
+ * The command a Host runs for a hook entry: this Node and this sideby by absolute path, never `sideby` by name. A
13
+ * missing or older `sideby` on PATH would fail the hook, and a failing hook lets the Host go on.
14
+ */
15
+ export declare function sidebyHookCommand(entry: string, family: string, event: string): string;
16
+ /** Every part's Claude hooks in one object, each event's groups in part order. */
17
+ export declare function mergeClaudeHooks(...parts: readonly ClaudeHooks[]): ClaudeHooks;
18
+ /**
19
+ * Host arguments that add every part's hooks to a session: one `--settings` file for Claude (in the first part's
20
+ * folder, named after the parts: `network/claude-settings.json`, `network/claude-settings-unattended.json`), one
21
+ * `-c hooks.<event>=[…]` per event for Codex. Empty for other Families or no parts.
22
+ */
23
+ export declare function sessionHookArgs(family: string, stateDir: string, parts: readonly SessionHookPart[]): Promise<string[]>;
24
+ /**
25
+ * Auto Handoff's Claude hook arguments with `extra` hooks added to its `--settings` file, written as `out` (Claude
26
+ * Code takes one `--settings`). Auto Handoff's own hooks and options come first and are kept as they are.
27
+ */
28
+ export declare function withClaudeHooks(hookArgs: readonly string[], extra: ClaudeHooks, out: string): Promise<string[]>;
29
+ /**
30
+ * Auto Handoff's Claude hook arguments with the session's own sideby hooks (`sessionArgs`, from `sessionHookArgs`)
31
+ * merged into one `--settings` file, written next to the session's file with `-handoff` added to its name.
32
+ */
33
+ export declare function withClaudeSessionHooks(hookArgs: readonly string[], sessionArgs: readonly string[]): Promise<string[]>;
@@ -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
+ }
@@ -1,11 +1,22 @@
1
1
  import type { Runtime } from '../runtime.ts';
2
2
  import { type LiveSession, type LiveSessionsResult } from './live-sessions.ts';
3
3
  import type { LiveSessionDeps } from './live-sessions-procs.ts';
4
+ import { type HandoffChain } from './session-handoffs.ts';
4
5
  /** How the candidates are offered when a target names several Sessions. */
5
6
  export interface SessionNext {
6
7
  verb: string;
7
8
  command: (id: string) => string;
8
9
  }
10
+ /** The Session picked, and the original id when an Auto Handoff chain led from it to this Session (ADR-0057). */
11
+ export interface PickedSession {
12
+ session: LiveSession;
13
+ handedOverFrom?: string;
14
+ }
15
+ export interface Handoffs {
16
+ chains: readonly HandoffChain[];
17
+ /** The Account label of a session id that no longer runs, when the Host still has its record. */
18
+ accountOf?: (sessionId: string) => string | undefined;
19
+ }
9
20
  /**
10
21
  * The one Session `target` names: a session id (or its first 8 or more characters), else an Account whose single
11
22
  * Live Session it is. Several Sessions, or none, are a UserError that says what to run next.
@@ -15,11 +26,14 @@ export declare function pickSession(target: string, sessions: readonly LiveSessi
15
26
  label: string;
16
27
  } | undefined,
17
28
  /** How the candidates are offered; `sessions copy` when left out. */
18
- next?: SessionNext): LiveSession;
29
+ next?: SessionNext,
30
+ /** The Handoff chains, and the Account label of a session id whose record the Host still has. */
31
+ handoffs?: Handoffs): PickedSession;
19
32
  /**
20
33
  * Lists the Live Sessions and picks the one `target` names, reading `target` as an Account (ref or alias) when it is
21
- * one. `onListed` sees the listing before the pick, so its problems can be shown also when the pick fails; the
22
- * listing is returned too, for callers that look for the sending Session in it.
34
+ * one, and following a Handoff chain when it is a session id that no longer runs (ADR-0057). `onListed` sees the
35
+ * listing before the pick, so its problems can be shown also when the pick fails; the listing is returned too, for
36
+ * callers that look for the sending Session in it. Its Sessions carry `handedOverFrom` where a chain led to them.
23
37
  */
24
38
  export declare function selectSession(rt: Runtime, target: string, opts?: {
25
39
  next?: SessionNext;
@@ -28,4 +42,5 @@ export declare function selectSession(rt: Runtime, target: string, opts?: {
28
42
  }): Promise<{
29
43
  session: LiveSession;
30
44
  listed: LiveSessionsResult;
45
+ handedOverFrom?: string;
31
46
  }>;