sideby 0.38.0 → 0.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261115T154125-919503"}
1
+ {"id":"20261116T040114-0f0555"}
@@ -623,7 +623,9 @@ export async function main(argv) {
623
623
  // Network Guard's hook runs before every prompt and tool call it guards (spec §3.35); same fast path.
624
624
  if (first === 'network-hook') {
625
625
  const { runNetworkHook } = await import('../network/hook.js');
626
- return runNetworkHook(rest, process.env, process.stderr);
626
+ return runNetworkHook(rest, process.env, process.stderr, {
627
+ input: process.stdin.isTTY ? '' : process.stdin,
628
+ });
627
629
  }
628
630
  // Unattended Mode's hook runs before every tool call it matches and at every turn end (spec §3.37); same fast path.
629
631
  if (first === 'unattended-hook') {
@@ -51,7 +51,17 @@ export declare function ipChangedLine(v: Verdict, env: Env): string | undefined;
51
51
  * Codex's default (600 seconds) is already long enough.
52
52
  */
53
53
  export declare const CLAUDE_NETWORK_HOOK_TIMEOUT_S = 60;
54
- /** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
54
+ /**
55
+ * Seconds the background `Held` entry may wait for the exit to be allowed again (5 hours, as Auto Handoff's
56
+ * `IdleWatch`, ADR-0056). `network-hook` ends by itself a little earlier (`HELD_BUDGET_MS`).
57
+ */
58
+ export declare const CLAUDE_NETWORK_HELD_TIMEOUT_S = 18000;
59
+ /**
60
+ * Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). Next
61
+ * to the check before a prompt runs `Held` in the background (`asyncRewake`): a prompt Claude Code made itself (a
62
+ * background task's notification) is not sent again once blocked, so `Held` keeps it and wakes the session with it
63
+ * when the exit is allowed again (spec §3.35). Codex has no such hook, and gets none.
64
+ */
55
65
  export declare function claudeNetworkHooks(): Record<string, unknown[]>;
56
66
  /** The file holding Network Guard's Claude hooks alone. */
57
67
  export declare const claudeNetworkSettings: (stateDir: string) => string;
@@ -98,7 +98,17 @@ const HOOK_EVENTS = ['UserPromptSubmit', 'PreToolUse'];
98
98
  * Codex's default (600 seconds) is already long enough.
99
99
  */
100
100
  export const CLAUDE_NETWORK_HOOK_TIMEOUT_S = 60;
101
- /** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
101
+ /**
102
+ * Seconds the background `Held` entry may wait for the exit to be allowed again (5 hours, as Auto Handoff's
103
+ * `IdleWatch`, ADR-0056). `network-hook` ends by itself a little earlier (`HELD_BUDGET_MS`).
104
+ */
105
+ export const CLAUDE_NETWORK_HELD_TIMEOUT_S = 18_000;
106
+ /**
107
+ * Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). Next
108
+ * to the check before a prompt runs `Held` in the background (`asyncRewake`): a prompt Claude Code made itself (a
109
+ * background task's notification) is not sent again once blocked, so `Held` keeps it and wakes the session with it
110
+ * when the exit is allowed again (spec §3.35). Codex has no such hook, and gets none.
111
+ */
102
112
  export function claudeNetworkHooks() {
103
113
  const out = {};
104
114
  for (const e of HOOK_EVENTS)
@@ -106,6 +116,16 @@ export function claudeNetworkHooks() {
106
116
  {
107
117
  hooks: [
108
118
  { type: 'command', command: hookCommand('claude', e), timeout: CLAUDE_NETWORK_HOOK_TIMEOUT_S },
119
+ ...(e === 'UserPromptSubmit'
120
+ ? [
121
+ {
122
+ type: 'command',
123
+ command: hookCommand('claude', 'Held'),
124
+ asyncRewake: true,
125
+ timeout: CLAUDE_NETWORK_HELD_TIMEOUT_S,
126
+ },
127
+ ]
128
+ : []),
109
129
  ],
110
130
  },
111
131
  ];
@@ -212,13 +212,19 @@ function run(argv) {
212
212
  if (seen && seen === iconSeen) iconStable = seen;
213
213
  iconSeen = seen;
214
214
  }
215
- // Drops the menu from the icon when it shows; at the pointer when the icon is hidden, such as by a full menu bar or
216
- // under the notch, where clicking it would do nothing.
215
+ // Drops the menu from the icon when it shows. When the icon is hidden, such as by a full menu bar or under the
216
+ // notch, clicking it would drop the menu in the screen's top left corner, so the menu drops below the right end of
217
+ // the menu bar instead, where the icon would be, on the screen the user is typing in.
217
218
  function openMenu() {
218
219
  var w = item.button.window;
219
220
  if (w && !w.isNil() && (w.occlusionState & $.NSWindowOcclusionStateVisible)) { item.button.performClick(null); return; }
221
+ var screen = $.NSScreen.mainScreen;
222
+ if (!screen || screen.isNil()) screen = $.NSScreen.screens.firstObject;
223
+ var v = screen.visibleFrame;
224
+ var at = $.NSMakePoint(Math.max(v.origin.x, v.origin.x + v.size.width - Number(item.menu.size.width) - 8), v.origin.y + v.size.height);
220
225
  app.activateIgnoringOtherApps(true);
221
- item.menu.popUpMenuPositioningItemAtLocationInView(null, $.NSEvent.mouseLocation, null);
226
+ // nil, not null: the bridge turns null into NSNull, which AppKit asks for its window and throws.
227
+ item.menu.popUpMenuPositioningItemAtLocationInView($(), at, $());
222
228
  app.deactivate;
223
229
  }
224
230
  function registerHotkey() {
@@ -9,7 +9,16 @@ export interface NetworkHookDeps {
9
9
  sleep?: Sleep;
10
10
  /** Starts the detached refresh; tests replace it. */
11
11
  background?: (family: string, env: Env) => void;
12
+ /** What the Host hands the hook on stdin; without it the hook decides as if it were given nothing. */
13
+ input?: AsyncIterable<string | Uint8Array> | string;
14
+ /** Whether the Host that started the hook is gone (`ppid` 1 by default): nothing is left to wake. */
15
+ parentGone?: () => boolean;
12
16
  }
17
+ /** `Held` asks again after these waits, then every `HELD_EVERY_MS`: one request each time. */
18
+ export declare const HELD_DELAYS_MS: readonly [15000, 30000];
19
+ export declare const HELD_EVERY_MS = 60000;
20
+ /** `Held` ends by itself after this long, two minutes before the 5 hours Claude Code gives it (core/network.ts). */
21
+ export declare const HELD_BUDGET_MS: number;
13
22
  /** Returns the exit code: 0 lets the Host go on, 2 blocks (the reason is written to `err`). */
14
23
  export declare function runNetworkHook(argv: readonly string[], env: Env, err: {
15
24
  write(s: string): unknown;
@@ -2,13 +2,146 @@
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
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
+ // about 30 seconds. A prompt the Host made itself (a background task's notification) is not sent again once blocked,
6
+ // so Claude Code also runs the `Held` entry in the background: it keeps such a prompt in memory while the exit is not
7
+ // allowed, and wakes the session with it (exit 2) once a new check passes.
6
8
  import { spawn } from 'node:child_process';
7
- import { blockMessage, inCi, NETWORK_ENV, prefersChinese, readNetworkConfig, refresh, verdict, } from '../core/egress.js';
9
+ import { lstat, readdir, unlink } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { setTimeout as delay } from 'node:timers/promises';
12
+ import { blockMessage, inCi, judge, NETWORK_ENV, prefersChinese, readNetworkConfig, refresh, verdict, } from '../core/egress.js';
13
+ import { ownedFolder, readSmallFile, sha256, writeFileAtomic } from '../core/fs-safe.js';
8
14
  import { resolvePaths } from '../core/paths.js';
9
15
  export const NETWORK_HOOK_COMMAND = 'sideby network-hook';
10
16
  /** The Host events this entry answers, and when each happens; `Refresh` is its own detached refresh. */
11
17
  const MOMENTS = { UserPromptSubmit: 'prompt', PreToolUse: 'tool' };
18
+ /** A prompt larger than this is not read: the hook then decides as if it were given nothing. */
19
+ const STDIN_MAX = 1024 * 1024;
20
+ /** Input that has not ended after this long is not waited for: the hook then decides as if it were given nothing. */
21
+ const STDIN_WAIT_MS = 5000;
22
+ /** A wake-up Claude Code makes from a background hook's exit 2 starts like this; only such a prompt carries a held message. */
23
+ const WAKE_UP = /^<task-notification>\s*<summary>Stop hook feedback<\/summary>/;
24
+ /** A prompt Claude Code made itself starts with this (a background task's notification, a hook's wake-up). */
25
+ const HOST_MADE = '<task-notification>';
26
+ /** `Held` asks again after these waits, then every `HELD_EVERY_MS`: one request each time. */
27
+ export const HELD_DELAYS_MS = [15_000, 30_000];
28
+ export const HELD_EVERY_MS = 60_000;
29
+ /** `Held` ends by itself after this long, two minutes before the 5 hours Claude Code gives it (core/network.ts). */
30
+ export const HELD_BUDGET_MS = 5 * 3600_000 - 120_000;
31
+ /**
32
+ * How long `Held` waits for the decision of the hook that checks the same prompt: the 60 seconds Claude Code gives
33
+ * that hook (`CLAUDE_NETWORK_HOOK_TIMEOUT_S`, core/network.ts) and a little more.
34
+ */
35
+ const DECISION_WAIT_MS = 65_000;
36
+ const DECISION_POLL_MS = 200;
37
+ /** A decision nobody read (a session started before `Held` existed) is removed after this long. */
38
+ const DECISION_KEPT_MS = 3600_000;
39
+ /** The most of a held message that is handed over. */
40
+ const HELD_MAX_CHARS = 8000;
41
+ const HELD_OPEN = '<sideby-held-message>';
42
+ const HELD_CLOSE = '</sideby-held-message>';
43
+ async function readInput(input) {
44
+ if (input === undefined)
45
+ return '';
46
+ if (typeof input === 'string')
47
+ return input;
48
+ const read = (async () => {
49
+ const chunks = [];
50
+ let size = 0;
51
+ for await (const chunk of input) {
52
+ const b = Buffer.from(chunk);
53
+ size += b.length;
54
+ if (size > STDIN_MAX)
55
+ return '';
56
+ chunks.push(b);
57
+ }
58
+ return Buffer.concat(chunks).toString('utf8');
59
+ })();
60
+ read.catch(() => { });
61
+ // A Host that never ends the input must not keep the check from starting.
62
+ let timer;
63
+ const late = new Promise((resolve) => {
64
+ timer = setTimeout(() => {
65
+ // Let go of the stream too: an open stdin would keep the process alive after the hook has decided.
66
+ ;
67
+ input.destroy?.();
68
+ resolve('');
69
+ }, STDIN_WAIT_MS);
70
+ });
71
+ try {
72
+ return await Promise.race([read, late]);
73
+ }
74
+ finally {
75
+ clearTimeout(timer);
76
+ }
77
+ }
78
+ /** The prompt and its id when the Host made the prompt itself; undefined for a typed prompt or unreadable input. */
79
+ async function hostMadePrompt(input) {
80
+ try {
81
+ const v = JSON.parse(await readInput(input));
82
+ if (!v || typeof v.prompt !== 'string' || typeof v.prompt_id !== 'string' || !v.prompt_id)
83
+ return undefined;
84
+ return v.prompt.trimStart().startsWith(HOST_MADE) ? { id: v.prompt_id, prompt: v.prompt } : undefined;
85
+ }
86
+ catch {
87
+ return undefined;
88
+ }
89
+ }
90
+ /** The file that tells `Held` what the checking hook decided for one prompt: named by a hash of the prompt's id. */
91
+ const decisionName = (id) => sha256(id).slice(0, 32);
92
+ /**
93
+ * Keeps the decision for a prompt the Host made (`ok` or `blocked`, nothing of the prompt) where `Held` finds it, and
94
+ * removes decisions nobody read. A failure changes nothing: `Held` then hands nothing over, as before it existed.
95
+ */
96
+ async function keepDecision(dir, id, decision, now) {
97
+ try {
98
+ const folder = (await ownedFolder(dir, ['held'], { create: true, private: true }));
99
+ for (const name of await readdir(folder)) {
100
+ const st = await lstat(join(folder, name)).catch(() => null);
101
+ if (st && now - st.mtimeMs > DECISION_KEPT_MS)
102
+ await unlink(join(folder, name)).catch(() => { });
103
+ }
104
+ await writeFileAtomic(join(folder, decisionName(id)), decision, 0o600);
105
+ }
106
+ catch {
107
+ // no decision kept
108
+ }
109
+ }
110
+ /** Reads the decision for a prompt and removes it; undefined while there is none. */
111
+ async function takeDecision(dir, id) {
112
+ try {
113
+ const folder = await ownedFolder(dir, ['held'], { create: false });
114
+ if (!folder)
115
+ return undefined;
116
+ const file = join(folder, decisionName(id));
117
+ const text = await readSmallFile(file, 16);
118
+ if (text === undefined)
119
+ return undefined;
120
+ await unlink(file).catch(() => { });
121
+ return text === 'ok' ? 'ok' : 'blocked';
122
+ }
123
+ catch {
124
+ return undefined;
125
+ }
126
+ }
127
+ /** What the session is woken with: why the message is late, and the message between the two tags. */
128
+ function heldMessage(prompt, zh) {
129
+ // A wake-up that was blocked again carries the first message inside the tags: hand over that one alone.
130
+ const from = prompt.indexOf(HELD_OPEN);
131
+ const to = prompt.lastIndexOf(HELD_CLOSE);
132
+ const inner = WAKE_UP.test(prompt.trimStart()) && from !== -1 && to > from;
133
+ const whole = (inner ? prompt.slice(from + HELD_OPEN.length, to) : prompt).trim();
134
+ const text = whole.slice(0, HELD_MAX_CHARS);
135
+ const cut = whole.length > HELD_MAX_CHARS
136
+ ? zh
137
+ ? `\n(原文在 ${HELD_MAX_CHARS} 个字符处截断。)`
138
+ : `\n(The message was cut at ${HELD_MAX_CHARS} characters.)`
139
+ : '';
140
+ const why = zh
141
+ ? 'sideby 的网络检查在网络出口不被允许或查不出期间,扣住了一条 Claude Code 自己生成的消息(例如后台任务的结果)。现在可以送达了,原文如下:'
142
+ : "sideby's Network Guard held back a message Claude Code made itself (such as a background task's result) while this network's exit was not allowed or could not be told. It can go through now. The message as it was:";
143
+ return `${why}\n${HELD_OPEN}\n${text}\n${HELD_CLOSE}${cut}\n`;
144
+ }
12
145
  function startRefresh(family, env) {
13
146
  try {
14
147
  const entry = process.argv[1];
@@ -40,7 +173,9 @@ export async function runNetworkHook(argv, env, err, deps = {}) {
40
173
  // The switch and the list as config says now, so turning the check off or allowing a country in the Panel or with
41
174
  // `sideby network` reaches sessions already running. When config cannot be read, the list the session started with.
42
175
  const current = await readNetworkConfig(resolvePaths(env).configFile);
43
- if (current && !current.guard)
176
+ // `Held` goes on when the check is off: a prompt blocked a moment before the switch still has to be handed over.
177
+ const off = Boolean(current && !current.guard);
178
+ if (off && event !== 'Held')
44
179
  return 0;
45
180
  const allow = current?.allow ?? (env[NETWORK_ENV.allow] ?? '').split(',').filter(Boolean);
46
181
  const common = {
@@ -55,9 +190,56 @@ export async function runNetworkHook(argv, env, err, deps = {}) {
55
190
  await refresh(common);
56
191
  return 0;
57
192
  }
193
+ const clock = () => (deps.now?.() ?? new Date()).getTime();
194
+ if (event === 'Held') {
195
+ const made = await hostMadePrompt(deps.input);
196
+ if (!made)
197
+ return 0;
198
+ const sleep = deps.sleep ?? delay;
199
+ // The hook that checks this prompt says what it decided; no answer in time means it let the prompt through.
200
+ const asked = clock();
201
+ let decision;
202
+ while (true) {
203
+ decision = await takeDecision(dir, made.id);
204
+ if (decision || clock() - asked >= DECISION_WAIT_MS)
205
+ break;
206
+ await sleep(DECISION_POLL_MS);
207
+ }
208
+ if (decision !== 'blocked')
209
+ return 0;
210
+ const deliver = () => {
211
+ err.write(heldMessage(made.prompt, prefersChinese(env)));
212
+ return 2;
213
+ };
214
+ if (off)
215
+ return deliver();
216
+ const parentGone = deps.parentGone ?? (() => process.ppid === 1);
217
+ for (let i = 0;; i++) {
218
+ const wait = HELD_DELAYS_MS[i] ?? HELD_EVERY_MS;
219
+ if (clock() - asked + wait > HELD_BUDGET_MS)
220
+ return 0;
221
+ await sleep(wait);
222
+ if (parentGone())
223
+ return 0;
224
+ // As for every check: config as it is now, and the session's own list when config cannot be read.
225
+ const now = await readNetworkConfig(resolvePaths(env).configFile);
226
+ if (now && !now.guard)
227
+ return deliver();
228
+ const list = now?.allow ?? allow;
229
+ // Only a new answer that passes hands the message over; `refresh` never throws.
230
+ if (judge((await refresh(common)).entry, list) === 'ok')
231
+ return deliver();
232
+ }
233
+ }
58
234
  const moment = MOMENTS[event];
59
235
  if (!moment)
60
236
  return 0;
237
+ // A prompt the Host made itself is not sent again once blocked: tell `Held` what is decided for it.
238
+ const made = event === 'UserPromptSubmit' ? await hostMadePrompt(deps.input) : undefined;
239
+ const decided = async (d) => {
240
+ if (made)
241
+ await keepDecision(dir, made.id, d, clock());
242
+ };
61
243
  try {
62
244
  const v = await verdict({
63
245
  ...common,
@@ -66,12 +248,16 @@ export async function runNetworkHook(argv, env, err, deps = {}) {
66
248
  ...(deps.sleep ? { sleep: deps.sleep } : {}),
67
249
  background: () => (deps.background ?? startRefresh)(family, env),
68
250
  });
69
- if (v.status === 'ok')
251
+ if (v.status === 'ok') {
252
+ await decided('ok');
70
253
  return 0;
254
+ }
255
+ await decided('blocked');
71
256
  err.write(`${blockMessage(v, allow, { ref: env.SIDEBY_LABEL || env.SIDEBY_ACCOUNT, at: moment, zh: prefersChinese(env) })}\n`);
72
257
  return 2;
73
258
  }
74
259
  catch {
260
+ await decided('blocked');
75
261
  err.write(`${prefersChinese(env)
76
262
  ? '已拦截:sideby 的网络检查出错,没能确认网络出口。重新发送试试;一直出错就运行 `sideby network check`。'
77
263
  : "Blocked: sideby's network check failed and could not tell this network's exit. Try again; if it keeps failing, run `sideby network check`."}\n`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.38.0",
3
+ "version": "0.38.1",
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.38.0"
5
+ version: "0.38.1"
6
6
  requires:
7
7
  bins: [sideby, node]
8
8
  cliHelp: sideby --help
@@ -34,4 +34,4 @@ The Panel's **Let AI help** (in the Network check dialog and on the wrong-networ
34
34
 
35
35
  ## When something was blocked
36
36
 
37
- A blocked Launch exits 1 with `code` `network-blocked` (wrong country) or `network-unknown` (could not tell). Inside a session the prompt or tool call is stopped with the same reason. Help the user check their proxy (is it running, which node), then run `sideby network check --json` to confirm. To go on once anyway, the user runs `sideby run <account> --ignore-network` (or `sideby next <family> --ignore-network`); never add it yourself without their say-so. When the user wants the check gone, show `sideby network off --json` (exit 10, a preview), then run it with `--yes` once they agree; sessions already running follow config at once, so no restart is needed.
37
+ A blocked Launch exits 1 with `code` `network-blocked` (wrong country) or `network-unknown` (could not tell). Inside a session the prompt or tool call is stopped with the same reason. In a Claude session, a message Claude Code made itself (a background task's result) that was stopped is kept and handed to the session once the network is right again, between `<sideby-held-message>` tags; a typed message is not, the user sends it again. Help the user check their proxy (is it running, which node), then run `sideby network check --json` to confirm. To go on once anyway, the user runs `sideby run <account> --ignore-network` (or `sideby next <family> --ignore-network`); never add it yourself without their say-so. When the user wants the check gone, show `sideby network off --json` (exit 10, a preview), then run it with `--yes` once they agree; sessions already running follow config at once, so no restart is needed.