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
@@ -38,6 +38,13 @@ export declare const HandoffSettingsSchema: Type.TObject<{
38
38
  }>>;
39
39
  }>;
40
40
  export type HandoffSettings = Static<typeof HandoffSettingsSchema>;
41
+ /** One Slot of Unattended Mode's Schedule (spec §3.37). Checked by hand where `unattended-hook` reads it. */
42
+ export declare const UnattendedSlotSchema: Type.TObject<{
43
+ name: Type.TOptional<Type.TString>;
44
+ days: Type.TArray<Type.TUnion<[Type.TLiteral<"mon">, Type.TLiteral<"tue">, Type.TLiteral<"wed">, Type.TLiteral<"thu">, Type.TLiteral<"fri">, Type.TLiteral<"sat">, Type.TLiteral<"sun">]>>;
45
+ start: Type.TString;
46
+ end: Type.TString;
47
+ }>;
41
48
  export declare const ConfigSchema: Type.TObject<{
42
49
  $schema: Type.TOptional<Type.TString>;
43
50
  panel: Type.TOptional<Type.TObject<{
@@ -103,6 +110,14 @@ export declare const ConfigSchema: Type.TObject<{
103
110
  guard: Type.TOptional<Type.TBoolean>;
104
111
  allow: Type.TOptional<Type.TArray<Type.TString>>;
105
112
  }>>;
113
+ unattended: Type.TOptional<Type.TObject<{
114
+ schedule: Type.TOptional<Type.TArray<Type.TObject<{
115
+ name: Type.TOptional<Type.TString>;
116
+ days: Type.TArray<Type.TUnion<[Type.TLiteral<"mon">, Type.TLiteral<"tue">, Type.TLiteral<"wed">, Type.TLiteral<"thu">, Type.TLiteral<"fri">, Type.TLiteral<"sat">, Type.TLiteral<"sun">]>>;
117
+ start: Type.TString;
118
+ end: Type.TString;
119
+ }>>>;
120
+ }>>;
106
121
  browser: Type.TOptional<Type.TObject<{
107
122
  signIns: Type.TOptional<Type.TBoolean>;
108
123
  choices: Type.TOptional<Type.TRecord<"^.*$", Type.TString>>;
@@ -164,6 +179,16 @@ export declare function editConfigNetwork(file: string, edit: (current: NetworkC
164
179
  before: NetworkConfig | undefined;
165
180
  after: NetworkConfig | undefined;
166
181
  }>;
182
+ export type UnattendedConfig = NonNullable<Config['unattended']>;
183
+ /**
184
+ * `sideby unattended on|schedule …` (spec §3.37): changes the config `unattended` key with `edit` (see `editConfigKey`
185
+ * for how the file is written); `edit` gets `undefined` while the section is missing and returns null to leave it.
186
+ */
187
+ export declare function editConfigUnattended(file: string, edit: (current: UnattendedConfig | undefined) => UnattendedConfig | null): Promise<{
188
+ changed: boolean;
189
+ before: UnattendedConfig | undefined;
190
+ after: UnattendedConfig | undefined;
191
+ }>;
167
192
  export type BrowserConfig = NonNullable<Config['browser']>;
168
193
  /**
169
194
  * `sideby browser --enable|--disable` and the Panel's switch (spec §3.24): changes the config `browser` key with
@@ -112,6 +112,25 @@ export const HandoffSettingsSchema = Type.Object({
112
112
  order: Type.Array(Type.String()),
113
113
  })),
114
114
  });
115
+ const CLOCK = '^([01][0-9]|2[0-3]):[0-5][0-9]$';
116
+ /** One Slot of Unattended Mode's Schedule (spec §3.37). Checked by hand where `unattended-hook` reads it. */
117
+ export const UnattendedSlotSchema = Type.Object({
118
+ name: Type.Optional(Type.String({ minLength: 1, maxLength: 60, description: 'What the Slot is called.' })),
119
+ days: Type.Array(Type.Union([
120
+ Type.Literal('mon'),
121
+ Type.Literal('tue'),
122
+ Type.Literal('wed'),
123
+ Type.Literal('thu'),
124
+ Type.Literal('fri'),
125
+ Type.Literal('sat'),
126
+ Type.Literal('sun'),
127
+ ]), { minItems: 1, uniqueItems: true, description: 'The days it starts on.' }),
128
+ start: Type.String({ pattern: CLOCK, description: 'When it starts, `HH:MM` in 24-hour local time.' }),
129
+ end: Type.String({
130
+ pattern: CLOCK,
131
+ description: 'When it ends, `HH:MM`. An end before the start is the next day; an end equal to the start lasts the whole day.',
132
+ }),
133
+ }, { additionalProperties: false });
115
134
  export const ConfigSchema = Type.Object({
116
135
  $schema: Type.Optional(Type.String()),
117
136
  panel: Type.Optional(Type.Object({
@@ -209,6 +228,14 @@ export const ConfigSchema = Type.Object({
209
228
  description: 'Countries (ISO 3166-1 alpha-2, such as `US` or `JP`) a Host may send requests from. Network Guard cannot be turned on while it is empty.',
210
229
  })),
211
230
  }, { additionalProperties: false, description: 'Network Guard (spec §3.35, ADR-0053).' })),
231
+ unattended: Type.Optional(Type.Object({
232
+ schedule: Type.Optional(Type.Array(UnattendedSlotSchema, {
233
+ description: "Slots that turn Unattended Mode on and off by themselves, in this computer's time zone. Empty by default.",
234
+ })),
235
+ }, {
236
+ additionalProperties: false,
237
+ description: 'Unattended Mode (spec §3.37, ADR-0058): while it is on, sessions sideby starts never stop to wait for a person. Present once the feature is used; from then on sideby adds its hook to every Claude and Codex session it starts, so turning it on later covers sessions already running. `sideby config unset unattended` stops adding it.',
238
+ })),
212
239
  browser: Type.Optional(Type.Object({
213
240
  signIns: Type.Optional(Type.Boolean({
214
241
  description: "Look in Google Chrome's local data for which browser user signed in to each Account's website (key names only, never cookies or passwords; nothing leaves this computer). Off by default.",
@@ -427,6 +454,13 @@ export function editConfigUpdate(file, edit, opts = {}) {
427
454
  export function editConfigNetwork(file, edit, opts = {}) {
428
455
  return editConfigKey(file, 'network', 'change the setting', (current) => edit(current ?? {}), opts);
429
456
  }
457
+ /**
458
+ * `sideby unattended on|schedule …` (spec §3.37): changes the config `unattended` key with `edit` (see `editConfigKey`
459
+ * for how the file is written); `edit` gets `undefined` while the section is missing and returns null to leave it.
460
+ */
461
+ export function editConfigUnattended(file, edit) {
462
+ return editConfigKey(file, 'unattended', 'run the command', edit);
463
+ }
430
464
  /**
431
465
  * `sideby browser --enable|--disable` and the Panel's switch (spec §3.24): changes the config `browser` key with
432
466
  * `edit` (see `editConfigKey` for how the file is written). With `dryRun`, shows the change without writing.
@@ -1,4 +1,4 @@
1
- import type { Stats } from 'node:fs';
1
+ import { type Stats } from 'node:fs';
2
2
  export declare function lstatOrNull(p: string): Promise<Stats | null>;
3
3
  export declare function statOrNull(p: string): Promise<Stats | null>;
4
4
  export declare function realpathOrNull(p: string): Promise<string | null>;
@@ -24,6 +24,27 @@ export declare function writeIfUnchanged(path: string, expectedHash: string | nu
24
24
  * symlink leading elsewhere), so a repair can never write into another Account or the Main Account.
25
25
  */
26
26
  export declare function assertInside(root: string, target: string): Promise<void>;
27
+ /** A folder sideby would read or write through that is a link, belongs to someone else, or others can write to. */
28
+ export declare class UnsafeFolderError extends Error {
29
+ readonly path: string;
30
+ constructor(path: string);
31
+ }
32
+ /**
33
+ * `<root>/<parts…>`, checked one folder at a time: each must be a real folder (not a link) of the current user that
34
+ * group and others cannot write, else `UnsafeFolderError`. `root` itself is made when missing (with `create`) but not
35
+ * checked. A missing level is made (mode 700) with `create`, else the answer is null. With `private`, an existing
36
+ * level others can still read or enter is narrowed to 700; otherwise only a folder made here gets its mode set.
37
+ * `sideby send` (`<state>/messages`) and Unattended Mode (`<state>/unattended`) put every path through this first.
38
+ */
39
+ export declare function ownedFolder(root: string, parts: readonly string[], opts: {
40
+ create: boolean;
41
+ private?: boolean;
42
+ }): Promise<string | null>;
43
+ /**
44
+ * The text of a small regular file, opened without following a link (so a link put in its place is never read);
45
+ * undefined when it is missing, a link, not a regular file, or larger than `max` bytes.
46
+ */
47
+ export declare function readSmallFile(path: string, max: number): Promise<string | undefined>;
27
48
  /** JSON.parse whose error never quotes the input: parse errors from Node include a slice of the text. */
28
49
  export declare function parseJsonSafely(text: string, label: string): unknown;
29
50
  /** Recursive comparison of files, directories and symlink targets. Modes and times are ignored. */
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { cp, lstat, open, readdir, readFile, readlink, realpath, rename, rm, stat } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { chmod, cp, lstat, mkdir, open, readdir, readFile, readlink, realpath, rename, rm, stat, } from 'node:fs/promises';
3
4
  import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
4
5
  export async function lstatOrNull(p) {
5
6
  try {
@@ -112,6 +113,72 @@ export async function assertInside(root, target) {
112
113
  if (real !== rootReal && !real.startsWith(`${rootReal}${sep}`))
113
114
  throw new Error(`refusing to write outside the account directory: ${target} (a parent directory is a link)`);
114
115
  }
116
+ /** A folder sideby would read or write through that is a link, belongs to someone else, or others can write to. */
117
+ export class UnsafeFolderError extends Error {
118
+ path;
119
+ constructor(path) {
120
+ super(`sideby will not use ${path}: it must be a real folder you own that nobody else can write to. Move or delete ${path}, then try again`);
121
+ this.path = path;
122
+ }
123
+ }
124
+ /**
125
+ * `<root>/<parts…>`, checked one folder at a time: each must be a real folder (not a link) of the current user that
126
+ * group and others cannot write, else `UnsafeFolderError`. `root` itself is made when missing (with `create`) but not
127
+ * checked. A missing level is made (mode 700) with `create`, else the answer is null. With `private`, an existing
128
+ * level others can still read or enter is narrowed to 700; otherwise only a folder made here gets its mode set.
129
+ * `sideby send` (`<state>/messages`) and Unattended Mode (`<state>/unattended`) put every path through this first.
130
+ */
131
+ export async function ownedFolder(root, parts, opts) {
132
+ if (opts.create)
133
+ await mkdir(root, { recursive: true, mode: 0o700 });
134
+ const uid = process.getuid?.();
135
+ let dir = root;
136
+ for (const part of parts) {
137
+ dir = join(dir, part);
138
+ let st = await lstat(dir).catch((err) => {
139
+ if (err.code === 'ENOENT')
140
+ return null;
141
+ throw err;
142
+ });
143
+ let made = false;
144
+ if (!st) {
145
+ if (!opts.create)
146
+ return null;
147
+ made = true;
148
+ await mkdir(dir, { mode: 0o700 }).catch((err) => {
149
+ if (err.code !== 'EEXIST')
150
+ throw err;
151
+ made = false;
152
+ });
153
+ st = await lstat(dir);
154
+ }
155
+ if (!st.isDirectory() || (uid !== undefined && st.uid !== uid) || (st.mode & 0o022) !== 0)
156
+ throw new UnsafeFolderError(dir);
157
+ if ((made || opts.private) && (st.mode & 0o777) !== 0o700)
158
+ await chmod(dir, 0o700);
159
+ }
160
+ return dir;
161
+ }
162
+ /**
163
+ * The text of a small regular file, opened without following a link (so a link put in its place is never read);
164
+ * undefined when it is missing, a link, not a regular file, or larger than `max` bytes.
165
+ */
166
+ export async function readSmallFile(path, max) {
167
+ let fh;
168
+ try {
169
+ fh = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
170
+ const st = await fh.stat();
171
+ if (!st.isFile() || st.size > max)
172
+ return undefined;
173
+ return await fh.readFile('utf8');
174
+ }
175
+ catch {
176
+ return undefined;
177
+ }
178
+ finally {
179
+ await fh?.close().catch(() => { });
180
+ }
181
+ }
115
182
  /** JSON.parse whose error never quotes the input: parse errors from Node include a slice of the text. */
116
183
  export function parseJsonSafely(text, label) {
117
184
  try {
@@ -28,6 +28,8 @@ export declare function runWithHandoff(rt: Runtime, ref: string, userArgs: reado
28
28
  aiTask?: boolean;
29
29
  /** `--ignore-network` (spec §3.35): no Launch of this run is checked. */
30
30
  ignoreNetwork?: boolean;
31
+ /** `--unattended` (spec §3.37): every Launch of this run is unattended, whatever the Schedule says. */
32
+ unattended?: boolean;
31
33
  }): Promise<number | null>;
32
34
  /**
33
35
  * For `sideby handoff ready`: where a Handoff from the session running under `env` would go now, using the chain's
@@ -12,8 +12,9 @@ import { UserError } from './errors.js';
12
12
  import { finishBrief } from './handoff-brief.js';
13
13
  import { briefPath, chainDir, ensureChainDir, FILES, HANDOFF_ENV, newId, readJsonFile, writeJsonFile, } from './handoff-chain.js';
14
14
  import { beforeDashes, runHost, sidebyBinProblem, spawnHost } from './launch.js';
15
- import { withClaudeNetworkHooks, withoutArgs } from './network.js';
15
+ import { withoutArgs } from './network.js';
16
16
  import { quotaPressure } from './quota-levels.js';
17
+ import { withClaudeSessionHooks } from './session-hooks.js';
17
18
  /** How long the Host gets to exit after SIGTERM (time for its SessionEnd hooks) before sideby gives up. */
18
19
  export const EXIT_GRACE_MS = 10_000;
19
20
  const PLAN_REFRESH_MS = 60_000;
@@ -122,9 +123,11 @@ async function codexTrustNotice(rt, account, io) {
122
123
  await writeJsonFile(file, { refs: [...seen, account.ref] });
123
124
  }
124
125
  export { beforeDashes };
125
- /** A Launch's arguments without Network Guard's Claude `--settings`, which would read as the user's own. */
126
+ /** A Launch's arguments without sideby's own Claude `--settings` (its session hooks), which would read as the user's. */
126
127
  function withoutNetwork(l) {
127
- return l.family.id === 'claude' ? withoutArgs(l.args, l.networkArgs ?? []) : [...l.args];
128
+ return l.family.id === 'claude'
129
+ ? withoutArgs(l.args, l.sessionHookArgs ?? l.networkArgs ?? [])
130
+ : [...l.args];
128
131
  }
129
132
  /** Whether the `sideby` on PATH has the hook entry: an older install would fail every hook call. */
130
133
  export function hookEntryWorks(env) {
@@ -156,6 +159,7 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
156
159
  const launchOpts = {
157
160
  ...(opts.aiTask ? { aiTask: true } : {}),
158
161
  ...(opts.ignoreNetwork ? { ignoreNetwork: true } : {}),
162
+ ...(opts.unattended ? { unattended: true } : {}),
159
163
  };
160
164
  const firstLaunch = await rt.prepareLaunch(ref, userArgs, 'run', launchOpts);
161
165
  const firstHandoff = firstLaunch.family.handoff;
@@ -199,11 +203,13 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
199
203
  const brief = briefPath(dir, n, account.ref);
200
204
  const extra = [...(elig.args ?? [])];
201
205
  const env = { ...launch.env };
202
- // Claude takes one `--settings`: Network Guard's hooks (spec §3.35) go into Auto Handoff's file.
203
- const mergeNet = canStart && account.family === 'claude' && Boolean(launch.networkArgs?.length);
206
+ // Claude takes one `--settings`: sideby's session hooks (Network Guard §3.35, Unattended Mode §3.37) go into Auto
207
+ // Handoff's file.
208
+ const sessionArgs = launch.sessionHookArgs ?? launch.networkArgs ?? [];
209
+ const mergeNet = canStart && account.family === 'claude' && sessionArgs.length > 0;
204
210
  if (canStart) {
205
211
  const hookArgs = (await h.hookArgs?.(hookCommand(account.family), rt.paths.stateDir)) ?? [];
206
- extra.push(...(mergeNet ? await withClaudeNetworkHooks(hookArgs, rt.paths.stateDir) : hookArgs));
212
+ extra.push(...(mergeNet ? await withClaudeSessionHooks(hookArgs, sessionArgs) : hookArgs));
207
213
  env[HANDOFF_ENV.run] = runId;
208
214
  env[HANDOFF_ENV.family] = account.family;
209
215
  env[HANDOFF_ENV.dir] = dir;
@@ -11,7 +11,12 @@ export interface PreparedLaunch {
11
11
  notice?: string;
12
12
  /** Terminal title set before the Host starts (config `accountTitle`), for example `[codex002]`. */
13
13
  title?: string;
14
- /** The arguments Network Guard added to `args` for its session hooks (spec §3.35); Auto Handoff merges them. */
14
+ /**
15
+ * Every argument sideby added to `args` for its own session hooks (Network Guard §3.35, Unattended Mode §3.37): one
16
+ * `--settings` for Claude, `-c hooks.*` for Codex. Auto Handoff merges Claude's into its own settings file.
17
+ */
18
+ sessionHookArgs?: string[];
19
+ /** The same as `sessionHookArgs`, set when Network Guard's hooks are among them (kept for tools that read it). */
15
20
  networkArgs?: string[];
16
21
  }
17
22
  /** What `runHost` needs: a prepared Account launch, or the Host run unchanged (`sideby resume`). */
@@ -3,12 +3,12 @@
3
3
  // through the Host's own channel where it has one, or handed to the user to paste.
4
4
  import { randomBytes } from 'node:crypto';
5
5
  import { constants } from 'node:fs';
6
- import { chmod, lstat, mkdir, open, readdir, readFile } from 'node:fs/promises';
6
+ import { lstat, open, readdir, readFile } from 'node:fs/promises';
7
7
  import { basename, dirname, join, resolve } from 'node:path';
8
8
  import { tailLinesWith } from '../families/claude/session-files.js';
9
9
  import { DELIVERERS } from '../families/messaging.js';
10
10
  import { UserError } from './errors.js';
11
- import { writeFileAtomic } from './fs-safe.js';
11
+ import { ownedFolder, UnsafeFolderError, writeFileAtomic } from './fs-safe.js';
12
12
  import { processView, systemDeps } from './live-sessions-procs.js';
13
13
  import { selectSession } from './session-select.js';
14
14
  /** The largest screenshot sideby copies. */
@@ -105,36 +105,14 @@ export async function messageFolder(stateDir, sub, create) {
105
105
  for (const part of sub)
106
106
  if (!isSafeName(part))
107
107
  throw unsafeFolder(join(messagesDir(stateDir), part));
108
- if (create)
109
- await mkdir(stateDir, { recursive: true, mode: 0o700 });
110
- const uid = process.getuid?.();
111
- let dir = stateDir;
112
- for (const part of ['messages', ...sub]) {
113
- dir = join(dir, part);
114
- let st = await lstat(dir).catch((err) => {
115
- if (err.code === 'ENOENT')
116
- return null;
117
- throw err;
118
- });
119
- if (!st) {
120
- if (!create)
121
- return null;
122
- let made = true;
123
- await mkdir(dir, { mode: 0o700 }).catch((err) => {
124
- if (err.code !== 'EEXIST')
125
- throw err;
126
- made = false;
127
- });
128
- st = await lstat(dir);
129
- if (made && st.isDirectory() && !st.isSymbolicLink() && st.uid === uid) {
130
- await chmod(dir, 0o700);
131
- st = await lstat(dir);
132
- }
133
- }
134
- if (!st.isDirectory() || (uid !== undefined && st.uid !== uid) || (st.mode & 0o022) !== 0)
135
- throw unsafeFolder(dir);
108
+ try {
109
+ return await ownedFolder(stateDir, ['messages', ...sub], { create });
110
+ }
111
+ catch (err) {
112
+ if (err instanceof UnsafeFolderError)
113
+ throw unsafeFolder(err.path);
114
+ throw err;
136
115
  }
137
- return dir;
138
116
  }
139
117
  /** The Live Session whose Host process is a parent of `pid` (the Session `sideby send` runs inside), if any. */
140
118
  export function senderSession(pid, procs, sessions) {
@@ -1,6 +1,7 @@
1
1
  import type { Account, Env } from '../types.ts';
2
2
  import type { Config } from './config.ts';
3
3
  import { type EgressStatus, type TraceFetcher, type Verdict } from './egress.ts';
4
+ import { type SessionHookPart } from './session-hooks.ts';
4
5
  /** Families Network Guard covers in v1. */
5
6
  export declare const GUARDED_FAMILIES: readonly ['claude', 'codex'];
6
7
  export declare const TRACE: {
@@ -48,8 +49,10 @@ export declare function ipChangedLine(v: Verdict, env: Env): string | undefined;
48
49
  export declare function claudeNetworkHooks(): Record<string, unknown[]>;
49
50
  /** The file holding Network Guard's Claude hooks alone. */
50
51
  export declare const claudeNetworkSettings: (stateDir: string) => string;
52
+ /** Network Guard's session hooks (spec §3.35), to combine with others through `sessionHookArgs`. */
53
+ export declare function networkHookPart(): SessionHookPart;
51
54
  /**
52
- * Host arguments that add Network Guard's hooks to a session: Claude through a `--settings` file sideby writes,
55
+ * Host arguments that add Network Guard's hooks alone to a session: Claude through a `--settings` file sideby writes,
53
56
  * Codex through `-c hooks.*`. Nothing is written into a Host directory.
54
57
  */
55
58
  export declare function networkHookArgs(family: string, stateDir: string): Promise<string[]>;
@@ -62,7 +65,7 @@ export declare function codexNetworkTrustLine(stateDir: string, ref: string, env
62
65
  * file next to Network Guard's own (Claude Code takes one `--settings`).
63
66
  */
64
67
  export declare function withClaudeNetworkHooks(hookArgs: readonly string[], stateDir: string): Promise<string[]>;
65
- /** `args` without the Network Guard arguments `networkHookArgs` added (Auto Handoff merges them into its own). */
68
+ /** `args` without one run of arguments sideby added (Auto Handoff merges its session hooks into its own file). */
66
69
  export declare function withoutArgs(args: readonly string[], drop: readonly string[]): string[];
67
70
  /** Where one Account is checked, or why not: a third-party endpoint, or an API Account decided at Launch. */
68
71
  export interface NetworkAccountRow {
@@ -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];
@@ -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,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[]>;