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
@@ -44,7 +44,7 @@ Usage:
44
44
  sideby login <account> sign in to an account
45
45
  sideby resume <family> [-- args] run the host; a session resumed by id (claude --resume <id>,
46
46
  codex resume <id>) starts in the account that holds it
47
- sideby next <family> [--dry-run] [--include-api] [--ignore-network] [-- args]
47
+ sideby next <family> [--dry-run] [--include-api] [--ignore-network] [--unattended] [-- args]
48
48
  recommend the account with the most quota left (claude, codex, grok)
49
49
  and start it; --dry-run only recommends
50
50
  sideby doctor [target] [--fix] [--force]
@@ -100,6 +100,9 @@ Usage:
100
100
  config.toml) in your editor
101
101
  sideby network [check] stop Claude and Codex when requests would leave from a country
102
102
  you did not allow (network on|off|allow <CC>... [--yes])
103
+ sideby unattended [on|off] nobody is here: sessions sideby starts do not stop to ask; on takes
104
+ --for 4h, --until 07:30 or --slot-end (schedule add|remove|preset weeknights,
105
+ pending [done <id>|--all], defer "<text>"); run --unattended for one session
103
106
  sideby browser [--enable [--yes]] which Chrome browser user signed in to each account's website
104
107
  (read on this computer only; off until you enable it)
105
108
  sideby browser open <account> [--profile <name>]
@@ -135,9 +138,9 @@ Usage:
135
138
  Options:
136
139
  --json machine-readable output (list, new, next, alias, doctor, quota, tune, model, remote-control, handoff,
137
140
  families, commands, plugins, app, desktop, sessions, history, send, messages, edit, browser, update, local, ask,
138
- terminal, key, try, autostart, menubar, config)
141
+ terminal, key, try, autostart, menubar, config, network, unattended)
139
142
  -h, --help show this help; \`sideby <command> --help\` for new, alias, login, doctor, families, commands, desktop, edit, browser,
140
- autostart, menubar, config, sessions, history, send, messages
143
+ autostart, menubar, config, sessions, history, send, messages, network, unattended
141
144
  -v, --version show the version
142
145
 
143
146
  An <account> is <family>:<name> (claude:work) or just <name> when it is unique.
@@ -465,6 +468,43 @@ Examples:
465
468
  sideby network check
466
469
  Exit: 0 shown or changed; 10 a change was shown and waits for --yes; 1 a country code that is not one, or on with
467
470
  no country allowed; 2 malformed command line.`,
471
+ unattended: `sideby unattended [status] [--json]
472
+ sideby unattended on [--for <n>h|<n>m | --until <HH:MM|date and time> | --slot-end] [--json]
473
+ sideby unattended off [--json]
474
+ sideby unattended schedule [add --days <days> --from HH:MM --to HH:MM [--name <name>] [--at <n>]] [--json]
475
+ sideby unattended schedule remove <n> | preset weeknights [--json]
476
+ sideby unattended pending [--all] [--json]
477
+ sideby unattended pending done <id> | --all [--json]
478
+ sideby unattended defer "<text>" [--json]
479
+
480
+ Unattended Mode: nobody is at the computer, so sessions sideby starts never stop to wait for a person. While it is on,
481
+ a Claude or Codex session sideby started is not allowed to ask a question: the model takes the recommended option
482
+ where it can be undone, and skips anything hard to undo (deleting, sending, publishing, deploying, paying). Each
483
+ question it could not ask, and each thing it skipped (\`defer\`), is kept as a Pending Decision for when you are back.
484
+ In Claude sessions, a permission prompt Claude Code is about to show (a command it wants a person to confirm, also in
485
+ a subagent) is answered with "no" and how to do it without one, and kept as a Pending Decision too. Codex's own
486
+ approval prompts are not covered.
487
+
488
+ When it is on: during a Slot of the Schedule (local days and times; an end before the start is the next day), from
489
+ \`on\` until the time you choose (at most 72 hours; without an option, until the current or next Slot ends, else 12
490
+ hours), or for one session started with \`--unattended\` (\`sideby run <account> --unattended\`, also next, resume,
491
+ short commands and pick commands). \`off\` outside a Slot turns it off; during a Slot it pauses until that Slot ends.
492
+
493
+ It covers Claude and Codex sessions sideby starts after the first use (sideby adds its hook to them; nothing is written
494
+ into the account folders). Codex runs the hook once you trust \`unattended-hook\` in /hooks. Grok, pi, desktop apps and
495
+ sessions started without sideby are not covered. Pending Decisions stay on this computer; \`pending done\` marks them
496
+ done, and they are deleted 30 days later. \`defer\` keeps a line from inside a session ("deploy left for the user").
497
+
498
+ --days takes mon…sun, ranges and lists: mon-fri, sat,sun, fri-mon, weekdays, daily. Each change prints its undo.
499
+
500
+ Examples:
501
+ sideby unattended on --until 07:30
502
+ sideby unattended schedule preset weeknights
503
+ sideby unattended schedule add --days sat,sun --from 01:00 --to 09:00 --name "Weekend nights"
504
+ sideby unattended pending
505
+ sideby unattended defer "deleting the old branch is left for the user"
506
+ Exit: 0 shown or done; 1 no such Slot or Pending Decision; 2 a time or option it does not take (the message says
507
+ which to use).`,
468
508
  browser: `sideby browser [--enable|--disable] [--yes] [--json]
469
509
  sideby browser open <account> [--profile <folder|name>] [--json]
470
510
  sideby browser set <account> <folder|name> [--json]
@@ -549,8 +589,12 @@ const COMMANDS = {
549
589
  run: { flags: [] },
550
590
  resume: { flags: [] },
551
591
  login: { flags: [] },
552
- next: { flags: ['dry-run', 'include-api', 'json', 'ignore-network'] },
592
+ next: { flags: ['dry-run', 'include-api', 'json', 'ignore-network', 'unattended'] },
553
593
  network: { flags: ['json', 'yes'] },
594
+ unattended: {
595
+ flags: ['json', 'all', 'slot-end'],
596
+ valued: ['for', 'until', 'days', 'from', 'to', 'name', 'at'],
597
+ },
554
598
  new: { flags: ['api', 'json', 'next'], valued: ['alias'] },
555
599
  alias: { flags: ['json', 'yes'], valued: ['pick'] },
556
600
  doctor: { flags: ['fix', 'force', 'json'] },
@@ -697,6 +741,11 @@ export async function main(argv) {
697
741
  const { runNetworkHook } = await import('../network/hook.js');
698
742
  return runNetworkHook(rest, process.env, process.stderr);
699
743
  }
744
+ // Unattended Mode's hook runs before every tool call it matches (spec §3.37); same fast path.
745
+ if (first === 'unattended-hook') {
746
+ const { runUnattendedHook } = await import('../unattended/hook.js');
747
+ return runUnattendedHook(rest, process.env, process.stdin, { out: process.stdout, err: process.stderr });
748
+ }
700
749
  if (nodeTooOld()) {
701
750
  console.error(`sideby needs Node ${MIN_NODE.join('.')} or newer (you have ${process.versions.node}). Upgrade: https://nodejs.org, or with nvm: \`nvm install 22 && nvm alias default 22\`, then \`npm i -g sideby\` again (each Node version has its own global packages).`);
702
751
  return 1;
@@ -719,6 +768,7 @@ export async function main(argv) {
719
768
  const own = args.includes('--') ? args.slice(0, args.indexOf('--')) : args;
720
769
  const wantsJson = Boolean(spec?.flags.includes('json')) && own.includes('--json');
721
770
  let notice = null;
771
+ let ended;
722
772
  try {
723
773
  if (!spec)
724
774
  throw new UsageError(`unknown command "${cmd}"; run \`sideby --help\``);
@@ -758,6 +808,12 @@ export async function main(argv) {
758
808
  parsed.attach = repeatedValues(own, 'attach');
759
809
  if (cmd === 'send')
760
810
  parsed.images = repeatedValues(own, 'image');
811
+ // A stretch of Unattended Mode that ended is noticed when a command starts (spec §3.37); its plugin event runs
812
+ // alongside the command and is waited for before exiting.
813
+ if (cmd !== 'update-check' && !(cmd === 'ui' && parsed.flags.has('serve-detached'))) {
814
+ const { noticeUnattendedEnded } = await import('../core/unattended-ended.js');
815
+ ended = await noticeUnattendedEnded(process.env);
816
+ }
761
817
  const cmds = await import('./commands.js');
762
818
  if (wantsJson && noticeAllowed(cmd, parsed)) {
763
819
  notice = await jsonNoticeFor();
@@ -782,6 +838,9 @@ export async function main(argv) {
782
838
  console.error(err.stack);
783
839
  return usage ? 2 : 1;
784
840
  }
841
+ finally {
842
+ await ended?.emitted;
843
+ }
785
844
  }
786
845
  async function dispatch(cmd, parsed, io, cmds) {
787
846
  switch (cmd) {
@@ -847,6 +906,8 @@ async function dispatch(cmd, parsed, io, cmds) {
847
906
  return await cmds.cmdBrowser(parsed, io);
848
907
  case 'network':
849
908
  return await cmds.cmdNetwork(parsed, io);
909
+ case 'unattended':
910
+ return await cmds.cmdUnattended(parsed, io);
850
911
  case 'shell-init':
851
912
  return await cmds.cmdShellInit(parsed, io);
852
913
  case 'plugins':
@@ -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`). */
@@ -30,6 +30,8 @@ export interface LiveSession {
30
30
  reference: string;
31
31
  /** The Run of a local orchestrator the Session works for (spec §3.32 step 2b); set by `withRuns`, not the readers. */
32
32
  run?: SessionRun;
33
+ /** Earlier hops' session ids, oldest first, when an Auto Handoff chain led to this Session (ADR-0057); set by `withHandoffs`. */
34
+ handedOverFrom?: string[];
33
35
  }
34
36
  export interface LiveSessionsResult {
35
37
  sessions: LiveSession[];
@@ -25,6 +25,8 @@ export interface MessageReceipt {
25
25
  /** Delivered, but the target shows it only once the user approves it in its terminal (ADR-0045). */
26
26
  needsApproval?: boolean;
27
27
  sentAt: string;
28
+ /** The session id the sender named, when an Auto Handoff chain led from it to this target (ADR-0057). */
29
+ handedOverFrom?: string;
28
30
  }
29
31
  export interface SendOptions {
30
32
  text: string;
@@ -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) {
@@ -199,7 +177,7 @@ export async function sendMessage(rt, target, opts, deps = {}) {
199
177
  async function sendOpened(rt, target, opts, deps) {
200
178
  const { text, lang } = opts;
201
179
  const procDeps = deps.procs ?? systemDeps(rt.env);
202
- const { session: to, listed } = await selectSession(rt, target, {
180
+ const { session: to, listed, handedOverFrom, } = await selectSession(rt, target, {
203
181
  next: { verb: 'send to', command: (id) => `sideby send ${id} "<text>"` },
204
182
  deps: procDeps,
205
183
  });
@@ -254,7 +232,7 @@ async function sendOpened(rt, target, opts, deps) {
254
232
  // Without a receipt sideby could not follow it later, so it does not deliver it; the Message file is kept.
255
233
  receipt.status = 'paste-needed';
256
234
  receipt.note = `sideby saved the message file, but could not save its status (${err.code ?? err.message}). Paste the line into the session's tab`;
257
- return publicReceipt(receipt);
235
+ return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
258
236
  }
259
237
  let result;
260
238
  try {
@@ -279,7 +257,7 @@ async function sendOpened(rt, target, opts, deps) {
279
257
  else
280
258
  receipt.note = `${receipt.note ?? 'paste the line into its tab'} (sideby also could not save the message status: ${why})`;
281
259
  }
282
- return publicReceipt(receipt);
260
+ return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
283
261
  }
284
262
  async function deliver(rt, to, acct, r, text, procDeps, deps) {
285
263
  if (to.guessed)
@@ -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 {