sideby 0.30.2 → 0.31.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.
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261029T113804-48bf3a"}
1
+ {"id":"20261029T160058-18f53c"}
@@ -598,7 +598,7 @@ export async function cmdResume(a, io, runtime) {
598
598
  const rt = runtime ?? (await createRuntime());
599
599
  const { args, flags } = takeLaunchFlags([...extra, ...a.rest]);
600
600
  const route = await rt.resumeLaunch(family, args, flags);
601
- // The Main Account under `handoff.auto` starts exactly as `sideby run` would (ADR-0058).
601
+ // The Main Account under `handoff.auto` starts exactly as `sideby run` would (ADR-0059).
602
602
  if (route.run && route.account) {
603
603
  io.err(c.dim(route.newSession
604
604
  ? `sideby: session ${route.sessionId} was never saved; starting a new session in ${route.account.ref} with Auto Handoff`
@@ -4021,7 +4021,7 @@ function printUnattended(io, s, now, opts = {}) {
4021
4021
  if (!s.configured)
4022
4022
  io.out(c.cyan('Not set up yet: `sideby unattended on` or `sideby unattended schedule preset weeknights` sets it up, and Claude and Codex sessions sideby starts after that are covered.'));
4023
4023
  else
4024
- io.out(c.dim('Covers Claude sessions sideby starts (questions and permission prompts), and questions in Codex sessions once you trust `unattended-hook` in /hooks; Codex approval prompts still wait. Not Grok, pi, desktop apps or sessions started without sideby.'));
4024
+ io.out(c.dim('Covers Claude sessions sideby starts (questions, permission prompts and MCP forms), and questions in Codex sessions once you trust both `unattended-hook` entries in /hooks; Codex approval prompts still wait. Not Grok, pi, desktop apps or sessions started without sideby.'));
4025
4025
  }
4026
4026
  /** `sideby unattended …` (spec §3.37, ADR-0058): status, on and off, the Schedule, Pending Decisions and `defer`. */
4027
4027
  export async function cmdUnattended(a, io) {
@@ -490,10 +490,10 @@ When it is on: during a Slot of the Schedule (local days and times; an end befor
490
490
  hours), or for one session started with \`--unattended\` (\`sideby run <account> --unattended\`, also next, resume,
491
491
  short commands and pick commands). \`off\` outside a Slot turns it off; during a Slot it pauses until that Slot ends.
492
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").
493
+ It covers Claude and Codex sessions sideby starts after the first use (sideby adds its hooks to them; nothing is
494
+ written into the account folders). Codex runs the hooks once you trust both \`unattended-hook\` entries in /hooks.
495
+ Grok, pi, desktop apps and sessions started without sideby are not covered. Pending Decisions stay on this computer;
496
+ \`pending done\` marks them done, and they are deleted 30 days later. \`defer\` keeps a line from inside a session ("deploy left for the user").
497
497
 
498
498
  --days takes mon…sun, ranges and lists: mon-fri, sat,sun, fri-mon, weekdays, daily. Each change prints its undo.
499
499
 
@@ -741,7 +741,7 @@ export async function main(argv) {
741
741
  const { runNetworkHook } = await import('../network/hook.js');
742
742
  return runNetworkHook(rest, process.env, process.stderr);
743
743
  }
744
- // Unattended Mode's hook runs before every tool call it matches (spec §3.37); same fast path.
744
+ // Unattended Mode's hook runs before every tool call it matches and at every turn end (spec §3.37); same fast path.
745
745
  if (first === 'unattended-hook') {
746
746
  const { runUnattendedHook } = await import('../unattended/hook.js');
747
747
  return runUnattendedHook(rest, process.env, process.stdin, { out: process.stdout, err: process.stderr });
@@ -8,6 +8,17 @@ export declare const NETWORK_ENV: {
8
8
  readonly dir: 'SIDEBY_NETWORK_DIR';
9
9
  };
10
10
  export declare const TIMEOUT_MS = 3000;
11
+ /**
12
+ * Inside a session a check that cannot tell is asked again after these waits, before it blocks: a prompt the Host made
13
+ * itself (a background task's notification) is not sent again once blocked, and a short outage would drop it.
14
+ */
15
+ export declare const RETRY_DELAYS_MS: readonly [1000, 2000, 4000, 8000];
16
+ /**
17
+ * All tries of one in-session check end within this time: five requests of at most 3 seconds and the waits between
18
+ * them. It stays under the 60-second timeout sideby gives its Claude hooks (core/network.ts) and Codex's 600-second
19
+ * default.
20
+ */
21
+ export declare const RETRY_BUDGET_MS = 30000;
11
22
  /** A result this young is used as it is. */
12
23
  export declare const FRESH_MS = 60000;
13
24
  /** Up to this age a tool call goes on while a detached process refreshes the result. */
@@ -37,9 +48,14 @@ export interface Verdict {
37
48
  fresh: boolean;
38
49
  /** True when this call saw the address change. */
39
50
  ipChanged: boolean;
51
+ /** Requests this call made (more than one when it asked again after a check that could not tell). */
52
+ attempts?: number;
53
+ /** Time from the first request to the answer, in milliseconds. */
54
+ triedMs?: number;
40
55
  }
41
56
  type Env = Record<string, string | undefined>;
42
57
  export type TraceFetcher = (url: string, env: Env, timeoutMs: number) => Promise<string>;
58
+ export type Sleep = (ms: number) => Promise<unknown>;
43
59
  /** The proxy a request to `url` goes through under `env`, or null for a direct connection. */
44
60
  export declare function proxyFor(url: string, env: Env): string | null;
45
61
  /** The key a cached result is kept under: the URL and the proxy settings, never their values in clear. */
@@ -76,8 +92,10 @@ export declare function refresh(opts: {
76
92
  ipChanged: boolean;
77
93
  }>;
78
94
  /**
79
- * The verdict at `moment`: from the cache when it is young enough, else from one request. `background` starts a
80
- * detached refresh for the tool-call middle tier; without it that tier checks now.
95
+ * The verdict at `moment`: from the cache when it is young enough, else from a request. `background` starts a
96
+ * detached refresh for the tool-call middle tier; without it that tier checks now. Inside a session (`prompt`, `tool`)
97
+ * a request that cannot tell is made again after each of `RETRY_DELAYS_MS` while the tries fit in `RETRY_BUDGET_MS`;
98
+ * a country outside the list blocks at once. Before a Launch one request decides: the user is there to start again.
81
99
  */
82
100
  export declare function verdict(opts: {
83
101
  url: string;
@@ -89,6 +107,8 @@ export declare function verdict(opts: {
89
107
  fetcher?: TraceFetcher;
90
108
  print?: string;
91
109
  background?: () => void;
110
+ /** Waits between tries; tests replace it so they do not really wait. */
111
+ sleep?: Sleep;
92
112
  }): Promise<Verdict>;
93
113
  /** "香港(HK)" or "HK": a country for a sentence. */
94
114
  export declare function countryLabel(code: string, zh: boolean): string;
@@ -98,7 +118,7 @@ export declare function prefersChinese(env: Env): boolean;
98
118
  * What the user reads when Network Guard stops something (spec §3.35): what happened, why, what to do.
99
119
  * `at`: `prompt`/`tool` inside a session, `launch` before one.
100
120
  */
101
- export declare function blockMessage(v: Pick<Verdict, 'status' | 'entry'>, allow: readonly string[], opts: {
121
+ export declare function blockMessage(v: Pick<Verdict, 'status' | 'entry' | 'attempts' | 'triedMs'>, allow: readonly string[], opts: {
102
122
  ref?: string;
103
123
  at: CheckMoment;
104
124
  zh: boolean;
@@ -7,6 +7,7 @@ import { request as httpRequest } from 'node:http';
7
7
  import { request as httpsRequest } from 'node:https';
8
8
  import { networkInterfaces } from 'node:os';
9
9
  import { join } from 'node:path';
10
+ import { setTimeout as delay } from 'node:timers/promises';
10
11
  import { connect as tlsConnect } from 'node:tls';
11
12
  import { writeFileAtomic } from './fs-safe.js';
12
13
  /** Variables a launched Host reads for its proxy; the check uses the same ones, so it takes the same route. */
@@ -27,6 +28,17 @@ export const NETWORK_ENV = {
27
28
  dir: 'SIDEBY_NETWORK_DIR',
28
29
  };
29
30
  export const TIMEOUT_MS = 3000;
31
+ /**
32
+ * Inside a session a check that cannot tell is asked again after these waits, before it blocks: a prompt the Host made
33
+ * itself (a background task's notification) is not sent again once blocked, and a short outage would drop it.
34
+ */
35
+ export const RETRY_DELAYS_MS = [1000, 2000, 4000, 8000];
36
+ /**
37
+ * All tries of one in-session check end within this time: five requests of at most 3 seconds and the waits between
38
+ * them. It stays under the 60-second timeout sideby gives its Claude hooks (core/network.ts) and Codex's 600-second
39
+ * default.
40
+ */
41
+ export const RETRY_BUDGET_MS = 30_000;
30
42
  /** A result this young is used as it is. */
31
43
  export const FRESH_MS = 60_000;
32
44
  /** Up to this age a tool call goes on while a detached process refreshes the result. */
@@ -87,13 +99,19 @@ export const fetchTrace = (url, env, timeoutMs, userAgent = 'sideby-network-guar
87
99
  const target = new URL(url);
88
100
  const proxy = proxyFor(url, env);
89
101
  let done = false;
102
+ // Requests and sockets this call opened. A failure (a timeout included) destroys them, so no handle outlives the
103
+ // call: a proxy that accepts and never answers would otherwise keep `network-hook` alive past the Host's timeout.
104
+ const open = [];
90
105
  const finish = (err, body) => {
91
106
  if (done)
92
107
  return;
93
108
  done = true;
94
109
  clearTimeout(timer);
95
- if (err)
110
+ if (err) {
111
+ for (const h of open)
112
+ h.destroy();
96
113
  reject(err);
114
+ }
97
115
  else
98
116
  resolve(body ?? '');
99
117
  };
@@ -120,6 +138,7 @@ export const fetchTrace = (url, env, timeoutMs, userAgent = 'sideby-network-guar
120
138
  headers: { 'user-agent': userAgent, accept: 'application/json, text/plain' },
121
139
  ...(socket ? { createConnection: () => socket } : {}),
122
140
  }, read);
141
+ open.push(req);
123
142
  req.on('error', (e) => finish(e));
124
143
  req.end();
125
144
  };
@@ -145,12 +164,17 @@ export const fetchTrace = (url, env, timeoutMs, userAgent = 'sideby-network-guar
145
164
  path: `${target.hostname}:443`,
146
165
  headers,
147
166
  });
167
+ open.push(req);
148
168
  req.on('connect', (res, socket) => {
169
+ open.push(socket);
149
170
  if (res.statusCode !== 200) {
150
171
  socket.destroy();
151
172
  return finish(new Error(`the proxy answered ${res.statusCode}`));
152
173
  }
174
+ if (done)
175
+ return;
153
176
  const tls = tlsConnect({ socket, servername: target.hostname });
177
+ open.push(tls);
154
178
  tls.on('error', (e) => finish(e));
155
179
  get(tls);
156
180
  });
@@ -244,22 +268,46 @@ export async function refresh(opts) {
244
268
  return { entry, ipChanged };
245
269
  }
246
270
  /**
247
- * The verdict at `moment`: from the cache when it is young enough, else from one request. `background` starts a
248
- * detached refresh for the tool-call middle tier; without it that tier checks now.
271
+ * The verdict at `moment`: from the cache when it is young enough, else from a request. `background` starts a
272
+ * detached refresh for the tool-call middle tier; without it that tier checks now. Inside a session (`prompt`, `tool`)
273
+ * a request that cannot tell is made again after each of `RETRY_DELAYS_MS` while the tries fit in `RETRY_BUDGET_MS`;
274
+ * a country outside the list blocks at once. Before a Launch one request decides: the user is there to start again.
249
275
  */
250
276
  export async function verdict(opts) {
251
277
  const key = cacheKey(opts.url, opts.env);
252
278
  const cached = await readEntry(opts.dir, key);
253
279
  const print = opts.print ?? netPrint();
254
- const now = (opts.now?.() ?? new Date()).getTime();
280
+ const clock = () => (opts.now?.() ?? new Date()).getTime();
281
+ const now = clock();
255
282
  const what = plan(cached, opts.allow, opts.moment, now, print);
256
283
  if (cached && (what === 'use' || (what === 'refresh' && opts.background))) {
257
284
  if (what === 'refresh')
258
285
  opts.background?.();
259
286
  return { status: judge(cached, opts.allow), entry: cached, fresh: false, ipChanged: false };
260
287
  }
261
- const { entry, ipChanged } = await refresh({ ...opts, print });
262
- return { status: judge(entry, opts.allow), entry, fresh: true, ipChanged };
288
+ let { entry, ipChanged } = await refresh({ ...opts, print });
289
+ let attempts = 1;
290
+ if (opts.moment !== 'launch') {
291
+ for (const wait of RETRY_DELAYS_MS) {
292
+ if (judge(entry, opts.allow) !== 'unknown')
293
+ break;
294
+ if (clock() - now + wait + TIMEOUT_MS > RETRY_BUDGET_MS)
295
+ break;
296
+ await (opts.sleep ?? delay)(wait);
297
+ const again = await refresh({ ...opts, print });
298
+ entry = again.entry;
299
+ ipChanged ||= again.ipChanged;
300
+ attempts++;
301
+ }
302
+ }
303
+ return {
304
+ status: judge(entry, opts.allow),
305
+ entry,
306
+ fresh: true,
307
+ ipChanged,
308
+ attempts,
309
+ triedMs: Math.max(0, clock() - now),
310
+ };
263
311
  }
264
312
  const NAMES_ZH = {
265
313
  US: '美国',
@@ -313,9 +361,12 @@ export function blockMessage(v, allow, opts) {
313
361
  const allowed = allow.map((c) => countryLabel(c, opts.zh)).join(opts.zh ? '、' : ', ');
314
362
  const skip = `sideby run ${ref} --ignore-network`;
315
363
  const reason = v.entry.error ?? 'no answer within 3 seconds';
364
+ const tries = v.attempts ?? 1;
365
+ const secs = Math.max(1, Math.round((v.triedMs ?? 0) / 1000));
316
366
  if (opts.zh) {
367
+ const tried = tries > 1 ? `试了 ${tries} 次(约 ${secs} 秒)仍` : '';
317
368
  const what = v.status === 'unknown'
318
- ? `已拦截:没能确认网络出口(${reasonZh(reason)}),可能是代理没开或断网。`
369
+ ? `已拦截:${tried}没能确认网络出口(${reasonZh(reason)}),可能是代理没开或断网。`
319
370
  : `已拦截:现在的网络出口在${countryLabel(v.entry.loc ?? '?', true)},不在允许的地区(${allowed})里。`;
320
371
  const next = opts.at === 'launch'
321
372
  ? '检查代理是否开着、节点是否正确,然后再启动。'
@@ -324,8 +375,9 @@ export function blockMessage(v, allow, opts) {
324
375
  : '检查代理是否开着、节点是否正确,然后让它继续。';
325
376
  return `${what}${next}临时跳过:\`${skip}\`。`;
326
377
  }
378
+ const tried = tries > 1 ? ` after ${tries} tries in about ${secs} s` : '';
327
379
  const what = v.status === 'unknown'
328
- ? `Blocked: sideby could not tell this network's exit (${reason}); the proxy may be off or the network down.`
380
+ ? `Blocked: sideby could not tell this network's exit${tried} (${reason}); the proxy may be off or the network down.`
329
381
  : `Blocked: this network exits in ${v.entry.loc}, which is not an allowed country (${allowed}).`;
330
382
  const next = opts.at === 'launch'
331
383
  ? 'Check that the proxy is on and the node is right, then start again.'
@@ -45,6 +45,12 @@ export declare function guardLaunch(opts: {
45
45
  }): Promise<LaunchGuardResult | null>;
46
46
  /** The line a Launch prints when the check saw the address change (a notice, never a block). */
47
47
  export declare function ipChangedLine(v: Verdict, env: Env): string | undefined;
48
+ /**
49
+ * Seconds Claude Code waits for `network-hook`. Its own default for `UserPromptSubmit` is 30, and a hook that runs out
50
+ * of time lets the prompt through; the check may ask again for up to `RETRY_BUDGET_MS`, so it gets twice that.
51
+ * Codex's default (600 seconds) is already long enough.
52
+ */
53
+ export declare const CLAUDE_NETWORK_HOOK_TIMEOUT_S = 60;
48
54
  /** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
49
55
  export declare function claudeNetworkHooks(): Record<string, unknown[]>;
50
56
  /** The file holding Network Guard's Claude hooks alone. */
@@ -92,11 +92,23 @@ export function ipChangedLine(v, env) {
92
92
  }
93
93
  const hookCommand = (family, event) => sidebyHookCommand('network-hook', family, event);
94
94
  const HOOK_EVENTS = ['UserPromptSubmit', 'PreToolUse'];
95
+ /**
96
+ * Seconds Claude Code waits for `network-hook`. Its own default for `UserPromptSubmit` is 30, and a hook that runs out
97
+ * of time lets the prompt through; the check may ask again for up to `RETRY_BUDGET_MS`, so it gets twice that.
98
+ * Codex's default (600 seconds) is already long enough.
99
+ */
100
+ export const CLAUDE_NETWORK_HOOK_TIMEOUT_S = 60;
95
101
  /** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
96
102
  export function claudeNetworkHooks() {
97
103
  const out = {};
98
104
  for (const e of HOOK_EVENTS)
99
- out[e] = [{ hooks: [{ type: 'command', command: hookCommand('claude', e) }] }];
105
+ out[e] = [
106
+ {
107
+ hooks: [
108
+ { type: 'command', command: hookCommand('claude', e), timeout: CLAUDE_NETWORK_HOOK_TIMEOUT_S },
109
+ ],
110
+ },
111
+ ];
100
112
  return out;
101
113
  }
102
114
  /** The file holding Network Guard's Claude hooks alone. */
@@ -130,13 +130,15 @@ export declare function slotFromOptions(o: {
130
130
  /** How a time reads in the CLI (`08:00`, `tomorrow 08:00`, `Mon 08:00`). */
131
131
  export declare const unattendedClock: (iso: string, now: Date, zh?: boolean) => string;
132
132
  /**
133
- * Unattended Mode's session hooks: before the ask tool in Claude and Codex, and on every permission request Claude
134
- * Code is about to show (Codex has no such event for it; its own approval prompts are not covered).
133
+ * Unattended Mode's session hooks: before the ask tool and when the model ends its turn (`Stop`, which keeps a turn
134
+ * that ended on a question going once) in Claude and Codex; and in Claude on every permission request Claude Code is
135
+ * about to show and every MCP server form (`Elicitation`). Codex has no such events for them; its own approval
136
+ * prompts are not covered.
135
137
  */
136
138
  export declare function unattendedHookPart(): SessionHookPart;
137
139
  /** The line a Claude Launch prints when the user's own `--settings` leaves no room for the hook. */
138
140
  export declare function unattendedSettingsLine(env: Env): string;
139
141
  /** The line a Launch prints when `--unattended` asks for a Family Unattended Mode does not cover. */
140
142
  export declare function unattendedFamilyLine(family: string, env: Env): string;
141
- /** Once per Codex Account: Codex runs the hook only after the user trusts it in `/hooks`. */
143
+ /** Once per Codex Account: Codex runs the hooks only after the user trusts them in `/hooks`. */
142
144
  export declare function codexUnattendedTrustLine(stateDir: string, ref: string, env: Env): Promise<string | undefined>;
@@ -289,21 +289,26 @@ export function slotFromOptions(o) {
289
289
  /** How a time reads in the CLI (`08:00`, `tomorrow 08:00`, `Mon 08:00`). */
290
290
  export const unattendedClock = (iso, now, zh = false) => clockText(Date.parse(iso), now.getTime(), zh);
291
291
  /**
292
- * Unattended Mode's session hooks: before the ask tool in Claude and Codex, and on every permission request Claude
293
- * Code is about to show (Codex has no such event for it; its own approval prompts are not covered).
292
+ * Unattended Mode's session hooks: before the ask tool and when the model ends its turn (`Stop`, which keeps a turn
293
+ * that ended on a question going once) in Claude and Codex; and in Claude on every permission request Claude Code is
294
+ * about to show and every MCP server form (`Elicitation`). Codex has no such events for them; its own approval
295
+ * prompts are not covered.
294
296
  */
295
297
  export function unattendedHookPart() {
296
298
  const command = (family, event = 'PreToolUse') => sidebyHookCommand('unattended-hook', family, event);
299
+ const claude = (event) => [{ type: 'command', command: command('claude', event) }];
300
+ const codex = (event) => `hooks=[{type="command",command="${command('codex', event)}"}]`;
297
301
  return {
298
302
  id: 'unattended',
299
303
  claude: {
300
- PreToolUse: [{ matcher: 'AskUserQuestion', hooks: [{ type: 'command', command: command('claude') }] }],
301
- PermissionRequest: [
302
- { matcher: '*', hooks: [{ type: 'command', command: command('claude', 'PermissionRequest') }] },
303
- ],
304
+ PreToolUse: [{ matcher: 'AskUserQuestion', hooks: claude('PreToolUse') }],
305
+ PermissionRequest: [{ matcher: '*', hooks: claude('PermissionRequest') }],
306
+ Stop: [{ hooks: claude('Stop') }],
307
+ Elicitation: [{ matcher: '*', hooks: claude('Elicitation') }],
304
308
  },
305
309
  codex: {
306
- PreToolUse: [`{matcher="^request_user_input$",hooks=[{type="command",command="${command('codex')}"}]}`],
310
+ PreToolUse: [`{matcher="^request_user_input$",${codex('PreToolUse')}}`],
311
+ Stop: [`{${codex('Stop')}}`],
307
312
  },
308
313
  };
309
314
  }
@@ -322,7 +327,12 @@ export function unattendedFamilyLine(family, env) {
322
327
  ? `sideby:无人值守只管 Claude 和 Codex 会话,这个 ${family} 会话不受影响。`
323
328
  : `sideby: Unattended Mode covers Claude and Codex sessions only; this ${family} session is not covered.`;
324
329
  }
325
- /** Once per Codex Account: Codex runs the hook only after the user trusts it in `/hooks`. */
330
+ /**
331
+ * What a Codex Account has been told about, in `codex-trust-notices.json`: its ref once told to trust the hook before
332
+ * questions, `<ref>#stop` once also told about the `Stop` hook (added later, and trusted on its own in `/hooks`).
333
+ */
334
+ const trustNoticeKey = (ref) => `${ref}#stop`;
335
+ /** Once per Codex Account: Codex runs the hooks only after the user trusts them in `/hooks`. */
326
336
  export async function codexUnattendedTrustLine(stateDir, ref, env) {
327
337
  const file = join(stateDir, 'unattended', 'codex-trust-notices.json');
328
338
  let seen = [];
@@ -334,16 +344,17 @@ export async function codexUnattendedTrustLine(stateDir, ref, env) {
334
344
  catch {
335
345
  // first notice
336
346
  }
337
- if (seen.includes(ref))
347
+ const key = trustNoticeKey(ref);
348
+ if (seen.includes(key))
338
349
  return undefined;
339
350
  try {
340
351
  await ensureUnattendedDir(stateDir);
341
- await writeFileAtomic(file, `${JSON.stringify({ refs: [...seen, ref] })}\n`, 0o600);
352
+ await writeFileAtomic(file, `${JSON.stringify({ refs: [...seen, key] })}\n`, 0o600);
342
353
  }
343
354
  catch {
344
355
  // shown again next time
345
356
  }
346
357
  return prefersChinese(env)
347
- ? `sideby:Codex 要先信任 hook,无人值守才拦得住它的提问:在 ${ref} 里输入 /hooks,信任 \`unattended-hook\`。`
348
- : `sideby: Codex runs Unattended Mode's hook only after you trust it: in ${ref}, type /hooks and trust \`unattended-hook\`. Until then its questions are not stopped.`;
358
+ ? `sideby:Codex 要先信任 hook,无人值守才拦得住它的提问:在 ${ref} 里输入 /hooks,信任两个 \`unattended-hook\`(提问前和回合结束时各一个)。`
359
+ : `sideby: Codex runs Unattended Mode's hooks only after you trust them: in ${ref}, type /hooks and trust both \`unattended-hook\` entries (before a question and at the end of a turn). Until then its questions are not stopped.`;
349
360
  }
@@ -1,10 +1,12 @@
1
- import { type TraceFetcher } from '../core/egress.ts';
1
+ import { type Sleep, type TraceFetcher } from '../core/egress.ts';
2
2
  export declare const NETWORK_HOOK_COMMAND = "sideby network-hook";
3
3
  type Env = Record<string, string | undefined>;
4
4
  export interface NetworkHookDeps {
5
5
  fetcher?: TraceFetcher;
6
6
  now?: () => Date;
7
7
  print?: string;
8
+ /** Waits between tries of a check that could not tell; tests replace it. */
9
+ sleep?: Sleep;
8
10
  /** Starts the detached refresh; tests replace it. */
9
11
  background?: (family: string, env: Env) => void;
10
12
  }
@@ -1,7 +1,8 @@
1
1
  // Entry for `sideby network-hook <family> <event>` (spec §3.35, ADR-0053). A Host runs it before every prompt and tool
2
2
  // call in a session sideby started with Network Guard on, so it imports only Node built-ins and leaf modules: never
3
3
  // the Runtime, a Family index or core/accounts.ts. Unlike `handoff-hook` it exists to stop the Host: exit 2 with the
4
- // reason on stderr blocks the prompt or the tool call; anything it cannot tell blocks too.
4
+ // reason on stderr blocks the prompt or the tool call; anything it cannot tell blocks too, after asking again for up to
5
+ // about 30 seconds (a prompt the Host made itself is not sent again once blocked).
5
6
  import { spawn } from 'node:child_process';
6
7
  import { blockMessage, NETWORK_ENV, prefersChinese, refresh, verdict, } from '../core/egress.js';
7
8
  export const NETWORK_HOOK_COMMAND = 'sideby network-hook';
@@ -53,6 +54,7 @@ export async function runNetworkHook(argv, env, err, deps = {}) {
53
54
  ...common,
54
55
  allow,
55
56
  moment,
57
+ ...(deps.sleep ? { sleep: deps.sleep } : {}),
56
58
  background: () => (deps.background ?? startRefresh)(family, env),
57
59
  });
58
60
  if (v.status === 'ok')
@@ -1568,7 +1568,7 @@ const en = {
1568
1568
  'ua.less': 'Show less',
1569
1569
  'ua.cover': 'Where it works',
1570
1570
  'ua.coverLine': 'Only in Claude Code and Codex sessions that sideby starts. Running claude or codex yourself is not covered.',
1571
- 'ua.codexTrust': 'Codex: only its questions. Open {cmd} in Codex once and trust sideby’s hook; Codex’s own approval prompts still wait for you.',
1571
+ 'ua.codexTrust': 'Codex: only its questions. Open {cmd} in Codex once and trust both of sideby’s hooks; Codex’s own approval prompts still wait for you.',
1572
1572
  'ua.notSupported': '{hosts}: not supported yet.',
1573
1573
  'ua.listSep': ', ',
1574
1574
  'ua.readOnly': 'Read-only view. Use sideby unattended to change it.',
@@ -3143,7 +3143,7 @@ const zh = {
3143
3143
  'ua.less': '收起',
3144
3144
  'ua.cover': '受保护范围',
3145
3145
  'ua.coverLine': '只对 sideby 启动的 Claude、Codex 会话生效;直接运行 claude 或 codex 的会话不受影响。',
3146
- 'ua.codexTrust': 'Codex:只管提问。在 Codex 里打开一次 {cmd},信任 sideby 的 hook;Codex 自己的批准提示仍会等你。',
3146
+ 'ua.codexTrust': 'Codex:只管提问。在 Codex 里打开一次 {cmd},信任 sideby 的两个 hook;Codex 自己的批准提示仍会等你。',
3147
3147
  'ua.notSupported': '{hosts}:暂不支持。',
3148
3148
  'ua.listSep': '、',
3149
3149
  'ua.readOnly': '只读视图。修改请用 sideby unattended 命令。',
@@ -36,7 +36,7 @@ export interface ResumeLaunch {
36
36
  /** Set when the session was never saved: `launch` starts a new session in `account` without the resume (ADR-0009). */
37
37
  newSession?: true;
38
38
  /**
39
- * Set when `account` is the Main Account and config `handoff.auto` is on (ADR-0058): the caller starts it exactly as
39
+ * Set when `account` is the Main Account and config `handoff.auto` is on (ADR-0059): the caller starts it exactly as
40
40
  * `sideby run <account> -- <args>` would, so Auto Handoff applies, instead of `launch` (the Host unchanged).
41
41
  */
42
42
  run?: {
@@ -792,7 +792,7 @@ export async function createRuntime(opts = {}) {
792
792
  return { launch: await guarded(host) };
793
793
  const route = await findResumeRoute(family, await accounts(), userArgs);
794
794
  const id = route.sessionId ? { sessionId: route.sessionId } : {};
795
- // In the Main Account with Auto Handoff on, start it as `sideby run` would (ADR-0058).
795
+ // In the Main Account with Auto Handoff on, start it as `sideby run` would (ADR-0059).
796
796
  const asRun = route.account?.isMain && handoffSettings(config).auto;
797
797
  if (route.neverSaved && route.account && family.withoutResume) {
798
798
  const args = family.withoutResume(userArgs);
@@ -14,6 +14,26 @@ export interface UnattendedHookDeps {
14
14
  export declare function questionText(input: Record<string, unknown>): string;
15
15
  /** What the model reads instead of an answer. */
16
16
  export declare function questionReason(state: UnattendedState, now: Date, zh: boolean, kept: boolean): string;
17
+ /** How much of the end of the model's last message is read to tell whether it ends on a question. */
18
+ export declare const QUESTION_TAIL = 600;
19
+ /**
20
+ * Ways a model asks the user in plain text, in English and Chinese, checked against the end of its last message (the
21
+ * last paragraph, and the one before it when the last is a list of options). Kept to asks that wait for an answer:
22
+ * a closing such as "Let me know if you have any questions" or "如有问题随时告诉我" is not one.
23
+ */
24
+ export declare const QUESTION_PATTERNS: readonly RegExp[];
25
+ /**
26
+ * The part of the model's last message that asks the user something, or undefined when it does not end on a
27
+ * question. Code blocks (``` and ~~~), inline code and quoted lines (`> …`) are left out first, then the last
28
+ * {@link QUESTION_TAIL} characters are read: a line that starts with the `需要你拍板` marker (from it to the end); a last line that ends with `?`
29
+ * or `?`, or a list of options at the end right after such a line; or one of {@link QUESTION_PATTERNS} in the last
30
+ * paragraph (and the one before it when the last is a list), unless a negation comes just before it ("无需你来决定").
31
+ */
32
+ export declare function endingQuestion(message: string): string | undefined;
33
+ /** What the model reads when it ended its turn on a question and nobody is here to answer. */
34
+ export declare function stopReason(state: UnattendedState, now: Date, zh: boolean, kept: boolean): string;
35
+ /** What a declined MCP form is kept as: the server's name and what it asked, never a field's value. */
36
+ export declare function elicitationText(v: Record<string, unknown>): string;
17
37
  /**
18
38
  * The program a command runs, by its file name only: the first word after `NAME=value` settings and wrappers such as
19
39
  * `sudo` and `env`. Undefined when it cannot be told plainly (a quote, a variable, a subshell, anything but a name).
@@ -32,8 +52,9 @@ export declare function permissionText(tool: string, input: Record<string, unkno
32
52
  export declare function permissionReason(state: UnattendedState, now: Date, kept: boolean): string;
33
53
  /**
34
54
  * Returns the exit code: 0 lets the Host go on, 2 refuses the tool call (the reason is written to `err`). A permission
35
- * request is refused with exit 0 and the decision written to `out`. Errors before the decision write nothing and
36
- * exit 0; once it is a refusal, it is answered as one whatever happens to the record.
55
+ * request, a stop on a question and an MCP form are answered with exit 0 and the decision written to `out`. Errors
56
+ * before the decision write nothing and exit 0; once it is a refusal, it is answered as one whatever happens to the
57
+ * record.
37
58
  */
38
59
  export declare function runUnattendedHook(argv: readonly string[], env: Env, input: AsyncIterable<string | Uint8Array> | string, io: {
39
60
  out: {
@@ -1,13 +1,16 @@
1
1
  // Entry for `sideby unattended-hook <family> <event>` (spec §3.37, ADR-0058). Claude Code and Codex run it before the
2
- // ask tool, and Claude Code also when it is about to ask the user for a permission (`PermissionRequest`), in every
2
+ // ask tool and when the model ends its turn (`Stop`), and Claude Code also when it is about to ask the user for a
3
+ // permission (`PermissionRequest`) and when an MCP server asks the user to fill in a form (`Elicitation`), in every
3
4
  // session sideby starts once the config has an `unattended` section. It imports only Node built-ins and leaf modules:
4
5
  // never the Runtime, a Family index or core/accounts.ts. It reads the Schedule and the manual state on every call, so
5
6
  // a session started before a Slot stops asking once the Slot begins.
6
7
  //
7
8
  // While Unattended Mode is off it does nothing (no output, exit 0). While on, it refuses the Host's ask tool (exit 2,
8
- // the reason on stderr, which both Hosts hand to the model) and keeps the question as a Pending Decision; and it
9
- // answers Claude Code's permission requests with a denial (JSON on stdout: Claude Code does not honor exit 2 for that
10
- // event), keeping the request as a Pending Decision too. A failure before the decision is made does nothing: that is
9
+ // the reason on stderr, which both Hosts hand to the model) and keeps the question as a Pending Decision; it answers
10
+ // Claude Code's permission requests with a denial (JSON on stdout: Claude Code does not honor exit 2 for that event),
11
+ // keeping the request as a Pending Decision too; it keeps a turn going once when the model ended it on a question
12
+ // written as plain text (`{"decision":"block","reason":…}` on stdout), keeping the question; and it declines an MCP
13
+ // server's form, keeping what the server asked. A failure before the decision is made does nothing: that is
11
14
  // how a session behaves without the feature (unlike `network-hook`, which blocks when it cannot tell). Once the
12
15
  // decision is to refuse, it refuses: keeping the Pending Decision and writing the reason are best effort, and their
13
16
  // failure neither allows the call nor adds any output of its own.
@@ -39,10 +42,19 @@ async function readInput(input) {
39
42
  return Buffer.concat(chunks).toString('utf8');
40
43
  }
41
44
  const text = (v, max = 4096) => typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined;
42
- function parsePayload(raw) {
45
+ function parseObject(raw) {
43
46
  try {
44
47
  const v = JSON.parse(raw);
45
- if (!v || typeof v !== 'object' || typeof v.tool_name !== 'string')
48
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ }
54
+ function parsePayload(raw) {
55
+ try {
56
+ const v = parseObject(raw);
57
+ if (!v || typeof v.tool_name !== 'string')
46
58
  return undefined;
47
59
  const input = v.tool_input && typeof v.tool_input === 'object' ? v.tool_input : {};
48
60
  const sessionId = text(v.session_id, 256);
@@ -102,6 +114,122 @@ export function questionReason(state, now, zh, kept) {
102
114
  : 'sideby could not keep this question, so put it in your final report';
103
115
  return `Not shown: sideby's Unattended Mode is on ${when}, so nobody is here to answer, and ${keep}. Do not ask again. Where the choice can be undone, go on with the recommended option, and list the question and your choice in your final report. Do not do anything hard to undo (deleting, sending or posting anything outside, publishing, deploying, paying): skip it, record it with \`sideby unattended defer "<one sentence>"\`, and go on with the rest.`;
104
116
  }
117
+ /** How much of the end of the model's last message is read to tell whether it ends on a question. */
118
+ export const QUESTION_TAIL = 600;
119
+ /**
120
+ * Ways a model asks the user in plain text, in English and Chinese, checked against the end of its last message (the
121
+ * last paragraph, and the one before it when the last is a list of options). Kept to asks that wait for an answer:
122
+ * a closing such as "Let me know if you have any questions" or "如有问题随时告诉我" is not one.
123
+ */
124
+ export const QUESTION_PATTERNS = [
125
+ /\b(?:do you )?want me to\b/i,
126
+ /\b(?:should|shall) I\b/i,
127
+ /\bwould you (?:like|prefer)\b/i,
128
+ /\bdo you (?:want|prefer)\b/i,
129
+ /\blet me know (?:which|whether|what you|how you|if I should|if you(?:'d| would)? (?:like|want|prefer) me to)\b/i,
130
+ /\bwhich (?:one |option )?(?:do|would) you (?:prefer|like|choose|pick)\b/i,
131
+ /\b(?:your call|up to you)\b/i,
132
+ /\bplease confirm\b/i,
133
+ /\b(?:when|once) you(?:'re| are) back\b/i,
134
+ /\bwaiting (?:for|on) your\b/i,
135
+ /要不要|需不需要|是否要|是否需要/,
136
+ /你来决定|由你决定|需要你决定|你决定一下|你来定|你定一下|你拍板|你来选|你选一个|你选哪|选哪个/,
137
+ /等你回来|你回来后|你回来再/,
138
+ /请确认|请你确认|确认一下|帮我确认/,
139
+ /你看呢|你觉得呢|你看怎么样|可以吗|行吗|好吗/,
140
+ ];
141
+ /**
142
+ * The marker agent rules often prescribe for a question written as text: at the start of a line, with or without
143
+ * `#` and emphasis, and with or without text after a colon. Finished reports do not use it.
144
+ */
145
+ const DECIDE_HEADING = /^[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*|__)?(?:需要你拍板|Needs your decision)(?:\*\*|__)?[ \t]*(?:[::].*)?$/im;
146
+ const LIST_LINE = /^[ \t]*(?:[-*+•]|\d+[.)、]|[A-Za-z][.)]|[((]?[A-Za-z0-9一二三四五六七八九十][))])[ \t]+/;
147
+ /** A question mark at the end of a line, before only closing quotes, brackets, emphasis or spaces. */
148
+ const ENDS_ON_QUESTION = /[??][\s*_"'”’))\]】」』]*$/;
149
+ /** Words that, just before an ask, turn it into a statement ("无需你来决定", "no need to confirm"). */
150
+ const NEGATION = /(?:无需|无须|不用|不需要|不必|没必要|没有|\bno need\b|\bdon'?t need\b|\bnot\b|\bnever\b)[^.!?。!?\n]{0,6}$/i;
151
+ /** Whether `pattern` matches `text` somewhere that is not negated just before it. */
152
+ function asks(pattern, text) {
153
+ for (const m of text.matchAll(new RegExp(pattern.source, `${pattern.flags.replace('g', '')}g`)))
154
+ if (!NEGATION.test(text.slice(Math.max(0, m.index - 16), m.index)))
155
+ return true;
156
+ return false;
157
+ }
158
+ /**
159
+ * The part of the model's last message that asks the user something, or undefined when it does not end on a
160
+ * question. Code blocks (``` and ~~~), inline code and quoted lines (`> …`) are left out first, then the last
161
+ * {@link QUESTION_TAIL} characters are read: a line that starts with the `需要你拍板` marker (from it to the end); a last line that ends with `?`
162
+ * or `?`, or a list of options at the end right after such a line; or one of {@link QUESTION_PATTERNS} in the last
163
+ * paragraph (and the one before it when the last is a list), unless a negation comes just before it ("无需你来决定").
164
+ */
165
+ export function endingQuestion(message) {
166
+ // Judged on a copy where code and quotes are blanked out at the same length, so a span of it is the same span of
167
+ // the message as written: that span is what is kept for the user, inline code and all.
168
+ const written = message.replace(/\r\n?/g, '\n');
169
+ const blank = (m) => m.replace(/[^\n]/g, ' ');
170
+ const plain = written
171
+ .replace(/^[ \t]*(```|~~~)[\s\S]*?(?:^[ \t]*\1[^\n]*$|(?![\s\S]))/gm, blank)
172
+ .replace(/`[^`\n]*`/g, (m) => 'x'.repeat(m.length))
173
+ .replace(/^[ \t]*>.*$/gm, blank);
174
+ const stop = plain.trimEnd().length;
175
+ const from = Math.max(0, stop - QUESTION_TAIL);
176
+ const tail = plain.slice(from, stop);
177
+ if (!tail.trim())
178
+ return undefined;
179
+ const kept = (at) => written.slice(from + at, stop).trim();
180
+ const heading = DECIDE_HEADING.exec(tail);
181
+ if (heading)
182
+ return kept(heading.index);
183
+ // Each paragraph with where it starts in the tail.
184
+ const paragraphs = [];
185
+ let at = 0;
186
+ for (const sep of [...tail.matchAll(/\n[ \t]*\n/g), { index: tail.length, 0: '' }]) {
187
+ const text = tail.slice(at, sep.index);
188
+ if (text.trim())
189
+ paragraphs.push({ at: at + (text.length - text.trimStart().length), text: text.trim() });
190
+ at = sep.index + sep[0].length;
191
+ }
192
+ const last = paragraphs.at(-1);
193
+ if (!last)
194
+ return undefined;
195
+ const isList = last.text.split('\n').some((l) => LIST_LINE.test(l));
196
+ const first = isList && paragraphs.length > 1 ? paragraphs.at(-2) : last;
197
+ const zone = tail.slice(first.at);
198
+ const question = kept(first.at);
199
+ // The last line, or the line just before a list of options that ends the message.
200
+ const lines = tail.split('\n').filter((l) => l.trim());
201
+ let line = lines.length - 1;
202
+ if (ENDS_ON_QUESTION.test(lines[line] ?? ''))
203
+ return question;
204
+ while (line >= 0 && LIST_LINE.test(lines[line]))
205
+ line--;
206
+ if (line >= 0 && line < lines.length - 1 && ENDS_ON_QUESTION.test(lines[line]))
207
+ return question;
208
+ if (QUESTION_PATTERNS.some((p) => asks(p, zone)))
209
+ return question;
210
+ return undefined;
211
+ }
212
+ /** What the model reads when it ended its turn on a question and nobody is here to answer. */
213
+ export function stopReason(state, now, zh, kept) {
214
+ const until = state.until ? clockText(Date.parse(state.until), now.getTime(), zh) : undefined;
215
+ const session = state.reason === 'session';
216
+ if (zh) {
217
+ const when = session ? '(这个会话)' : until ? `(到 ${until})` : '(没有结束时间)';
218
+ const keep = kept ? 'sideby 已把你的问题记下,等用户回来看' : 'sideby 没能记下你的问题,请写进最终汇报';
219
+ return `没人能回答:sideby 无人值守已开启${when},${keep}。不要等回复,也不要再问。能撤回的选择按推荐的选项继续,一直做到完。删除、对外发送或发布、部署、付费等难撤回的操作不要做:跳过它,运行 \`sideby unattended defer "<一句话>"\` 记下,再做完其余的事。最后写一份最终汇报,列出你做的每个选择和记下的每件事,不提任何问题。`;
220
+ }
221
+ const when = session ? 'for this session' : until ? `until ${until}` : 'with no end set';
222
+ const keep = kept
223
+ ? 'sideby kept your question for the user to look at later'
224
+ : 'sideby could not keep your question, so put it in your final report';
225
+ return `Nobody is here to answer: sideby's Unattended Mode is on ${when}, and ${keep}. Do not wait for an answer and do not ask again. Where the choice can be undone, go on with the recommended option and carry on to the end. Do not do anything hard to undo (deleting, sending or posting anything outside, publishing, deploying, paying): skip it, record it with \`sideby unattended defer "<one sentence>"\`, and finish the rest. Then end with a final report that lists each choice you made and each item you recorded, without asking anything.`;
226
+ }
227
+ /** What a declined MCP form is kept as: the server's name and what it asked, never a field's value. */
228
+ export function elicitationText(v) {
229
+ const server = text(v.mcp_server_name, 200);
230
+ const message = text(v.message, 1000);
231
+ return [server ? `MCP ${server}` : 'MCP', message].filter(Boolean).join(': ');
232
+ }
105
233
  /** Tools whose kept summary is the file they work on, and the field it is in. */
106
234
  const FILE_TOOLS = {
107
235
  Read: 'file_path',
@@ -199,7 +327,9 @@ async function decide(argv, env, input, now) {
199
327
  const [family = '', event = ''] = argv;
200
328
  const askTool = ASK_TOOLS[family];
201
329
  const permission = family === 'claude' && event === 'PermissionRequest';
202
- if (!permission && (event !== 'PreToolUse' || !askTool))
330
+ const elicitation = family === 'claude' && event === 'Elicitation';
331
+ const stop = Boolean(askTool) && event === 'Stop';
332
+ if (!permission && !elicitation && !stop && (event !== 'PreToolUse' || !askTool))
203
333
  return undefined;
204
334
  const paths = resolvePaths(env);
205
335
  const { schedule } = await readUnattendedConfig(paths.configFile);
@@ -207,14 +337,52 @@ async function decide(argv, env, input, now) {
207
337
  const state = unattendedState({ schedule, override, now, session: env[UNATTENDED_ENV] === '1' });
208
338
  if (!state.on)
209
339
  return undefined;
210
- const payload = parsePayload(await readInput(input));
211
- if (!payload)
212
- return undefined;
340
+ const raw = await readInput(input);
213
341
  const zh = prefersChinese(env);
214
342
  const account = text(env.SIDEBY_ACCOUNT, 256);
343
+ if (stop || elicitation) {
344
+ const v = parseObject(raw);
345
+ if (!v)
346
+ return undefined;
347
+ const sessionId = text(v.session_id, 256);
348
+ const cwd = text(v.cwd);
349
+ const where = {
350
+ family,
351
+ ...(account ? { account } : {}),
352
+ ...(sessionId ? { sessionId } : {}),
353
+ ...(cwd ? { cwd } : {}),
354
+ };
355
+ if (elicitation)
356
+ return {
357
+ json: () => ({ hookSpecificOutput: { hookEventName: 'Elicitation', action: 'decline' } }),
358
+ reason: () => '',
359
+ keep: () => addPendingDecision(paths.stateDir, { kind: 'question', ...where, text: elicitationText(v) }, now, {
360
+ dedupe: true,
361
+ }),
362
+ };
363
+ // Once per stop: a turn the hook already kept going ends as the model leaves it.
364
+ if (v.stop_hook_active !== false)
365
+ return undefined;
366
+ const message = typeof v.last_assistant_message === 'string' ? v.last_assistant_message : '';
367
+ const question = endingQuestion(message);
368
+ if (!question)
369
+ return undefined;
370
+ return {
371
+ json: (reason) => ({ decision: 'block', reason }),
372
+ reason: (kept) => stopReason(state, now, zh, kept),
373
+ keep: () => addPendingDecision(paths.stateDir, { kind: 'question', ...where, text: question }, now, {
374
+ dedupe: true,
375
+ }),
376
+ };
377
+ }
378
+ const payload = parsePayload(raw);
379
+ if (!payload)
380
+ return undefined;
215
381
  if (permission)
216
382
  return {
217
- json: true,
383
+ json: (message) => ({
384
+ hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'deny', message } },
385
+ }),
218
386
  reason: (kept) => permissionReason(state, now, kept),
219
387
  keep: () => addPendingDecision(paths.stateDir, {
220
388
  kind: 'permission',
@@ -245,8 +413,9 @@ async function decide(argv, env, input, now) {
245
413
  }
246
414
  /**
247
415
  * Returns the exit code: 0 lets the Host go on, 2 refuses the tool call (the reason is written to `err`). A permission
248
- * request is refused with exit 0 and the decision written to `out`. Errors before the decision write nothing and
249
- * exit 0; once it is a refusal, it is answered as one whatever happens to the record.
416
+ * request, a stop on a question and an MCP form are answered with exit 0 and the decision written to `out`. Errors
417
+ * before the decision write nothing and exit 0; once it is a refusal, it is answered as one whatever happens to the
418
+ * record.
250
419
  */
251
420
  export async function runUnattendedHook(argv, env, input, io, deps = {}) {
252
421
  let refusal;
@@ -269,12 +438,11 @@ export async function runUnattendedHook(argv, env, input, io, deps = {}) {
269
438
  kept = false;
270
439
  }
271
440
  if (refusal.json) {
272
- const decision = { behavior: 'deny', message: refusal.reason(kept) };
273
441
  try {
274
- io.out.write(`${JSON.stringify({ hookSpecificOutput: { hookEventName: 'PermissionRequest', decision } })}\n`);
442
+ io.out.write(`${JSON.stringify(refusal.json(refusal.reason(kept)))}\n`);
275
443
  }
276
444
  catch {
277
- // Nothing reached Claude Code: it shows its prompt as it would without this hook.
445
+ // Nothing reached the Host: it goes on as it would without this hook (a prompt, a form, a stop).
278
446
  }
279
447
  return 0;
280
448
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.30.2",
3
+ "version": "0.31.0",
4
4
  "description": "Run work, personal and API-key accounts at the same time, without their configs drifting apart.",
5
5
  "license": "MIT",
6
6
  "author": "Adonis0123 (https://github.com/Adonis0123)",
@@ -2,7 +2,7 @@
2
2
  name: sideby
3
3
  description: Use when the user runs, or wants to run, several AI coding accounts (Claude Code, Codex, Grok Build, pi) side by side. Covers installing sideby and setting up a new account ("install sideby", "set up another Claude account", "add cc008", "配置一个 cc00x", "再加一个 Codex 账号"), explaining what accounts share and what stays separate ("what do my accounts share?", "这些账号共享了什么"), showing which account a session is ("show [cc001] in the status line", "加上账号标识"), finding a past session of any account ("找一下我上周改登录页的那个会话"), telling another running session something, in any account ("告诉 cc002 ……", "给跑构建的那个会话发消息"; Claude Code's own SendMessage reaches only sessions of the same account), seeing accounts, quota and usage, moving on when one hits its 5-hour or weekly limit, moving the current task to another account ("用 cc008 继续", "交回 cc008"), adding a short command (alias) or a pick command that starts whichever account has the most quota ("加个 cc"), adding an API account from a vendor's docs ("加一个 DeepSeek API 账号"), supporting a new tool, and repairing drifted account directories (skills, hooks, rules or settings not shared, wrong symlinks, credential file permissions). Drives the `sideby` CLI with `--json`; the agent does every step except browser sign-in, filling in secrets and starting interactive sessions, which it hands to the user as one command (inside an Auto Handoff session, `sideby handoff ready --to` moves the task itself).
4
4
  metadata:
5
- version: "0.30.2"
5
+ version: "0.31.0"
6
6
  requires:
7
7
  bins: [sideby, node]
8
8
  cliHelp: sideby --help
@@ -1,6 +1,6 @@
1
1
  # Network check: stop Claude and Codex on the wrong network
2
2
 
3
- Network Guard (spec §3.35, ADR-0053) checks the country a Host's requests leave from (its Egress): before sideby starts a Claude or Codex account, and before each prompt and tool call in a session sideby started. When the country is not one the user allows, or cannot be told within 3 seconds, it stops and says what to do. It guards against a proxy that stopped or a node in the wrong country. It does not make use from a region the vendor does not support allowed; say so if the user seems to expect that, and never help hide where they are (time zone, fingerprints).
3
+ Network Guard (spec §3.35, ADR-0053) checks the country a Host's requests leave from (its Egress): before sideby starts a Claude or Codex account, and before each prompt and tool call in a session sideby started. When the country is not one the user allows, or cannot be told, it stops and says what to do; inside a session it first asks again for up to about 30 seconds. It guards against a proxy that stopped or a node in the wrong country. It does not make use from a region the vendor does not support allowed; say so if the user seems to expect that, and never help hide where they are (time zone, fingerprints).
4
4
 
5
5
  ## See where requests leave from
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Unattended Mode: sessions that do not stop to wait for a person
2
2
 
3
- Unattended Mode (spec §3.37, ADR-0058) is one state for the whole computer: nobody is there to answer, so the Claude and Codex sessions sideby starts never stop to wait. While it is on, sideby's hook refuses the Host's question tool (Claude `AskUserQuestion`, Codex `request_user_input`) and tells the model to take the recommended option where the choice can be undone and to skip anything hard to undo; each refused question is kept as a **Pending Decision**. In Claude sessions it also answers "no" to every permission prompt Claude Code is about to show (even in bypass mode, and in subagents), with how to do the step without one; each refused request is kept as a Pending Decision too. Codex's own approval prompts still wait.
3
+ Unattended Mode (spec §3.37, ADR-0058) is one state for the whole computer: nobody is there to answer, so the Claude and Codex sessions sideby starts never stop to wait. While it is on, sideby's hook refuses the Host's question tool (Claude `AskUserQuestion`, Codex `request_user_input`) and tells the model to take the recommended option where the choice can be undone and to skip anything hard to undo; each refused question is kept as a **Pending Decision**. When the model ends its turn on a question written as text instead, the hook sends the session on once with the same instructions and keeps that question too. In Claude sessions it also answers "no" to every permission prompt Claude Code is about to show (even in bypass mode, and in subagents), with how to do the step without one; each refused request is kept as a Pending Decision too; and it declines MCP server forms, keeping what the server asked. Codex's own approval prompts still wait.
4
4
 
5
5
  ## Turn it on when the user is leaving
6
6
 
@@ -14,7 +14,7 @@ sideby unattended on --until 08:00 --json # or --for 4h; at most 72 hours
14
14
  Tell the user, in one line each:
15
15
  - It covers Claude and Codex sessions sideby starts (`sideby run`, short commands, pick commands, `sideby next`, Auto Handoff, AI Tasks). Running `claude` or `codex` directly, Grok, pi and desktop apps are not covered.
16
16
  - Sessions started before the feature was first used have no hook. If `configured` was `false` before this command, the sessions already running are not covered: suggest restarting long tasks with `sideby run <account> --unattended`.
17
- - A Codex account runs the hook only after the user trusts it once: in that account type `/hooks` and trust `unattended-hook` (`coverage.codex` is `needs-trust`).
17
+ - A Codex account runs the hooks only after the user trusts them once: in that account type `/hooks` and trust both `unattended-hook` entries, before a question and at the end of a turn (`coverage.codex` is `needs-trust`).
18
18
  - `sideby unattended off --json` turns it off; inside a Slot it pauses until that Slot ends.
19
19
 
20
20
  Every change prints `undo`, the command that puts back what was there.
@@ -37,6 +37,8 @@ sideby unattended schedule remove 2 --json # the number `sideby unatt
37
37
 
38
38
  ## When a session was refused a question or a permission
39
39
 
40
+ While Unattended Mode is on, do not end your turn on a question either: a turn that ends on one (a `需要你拍板` line, a last line ending in `?`, "Want me to …", "要不要 …") is sent back to you once with the same instructions. End with a final report instead.
41
+
40
42
  The refusal tells you what to do: go on with the recommended option where it can be undone, and list the question and your choice in your final report. A refused permission means Claude Code wanted a person to confirm that step: rewrite it so it needs none (literal paths, `"${VAR:?}"` for a variable in an `rm` target, plain bash syntax, `rm` as a command of its own), or skip it. For anything hard to undo (deleting, sending or posting outside, publishing, deploying, paying), skip it and record it:
41
43
 
42
44
  ```sh