sideby 0.30.2 → 0.30.3

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":"20261029T152132-77cb9c"}
@@ -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`
@@ -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. */
@@ -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')
@@ -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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.30.2",
3
+ "version": "0.30.3",
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.30.3"
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