sideby 0.25.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +1 -0
  2. package/ai-tasks.json +17 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +14 -0
  5. package/dist/src/cli/commands.js +113 -7
  6. package/dist/src/cli/json-schemas.js +46 -0
  7. package/dist/src/cli/main.js +38 -3
  8. package/dist/src/core/ask.js +5 -0
  9. package/dist/src/core/config.d.ts +16 -0
  10. package/dist/src/core/config.js +16 -0
  11. package/dist/src/core/egress.d.ts +103 -0
  12. package/dist/src/core/egress.js +333 -0
  13. package/dist/src/core/handoff-run.d.ts +4 -2
  14. package/dist/src/core/handoff-run.js +18 -11
  15. package/dist/src/core/launch.d.ts +5 -1
  16. package/dist/src/core/launch.js +5 -0
  17. package/dist/src/core/network.d.ts +131 -0
  18. package/dist/src/core/network.js +317 -0
  19. package/dist/src/network/hook.d.ts +15 -0
  20. package/dist/src/network/hook.js +69 -0
  21. package/dist/src/panel/handler.d.ts +3 -0
  22. package/dist/src/panel/handler.js +32 -0
  23. package/dist/src/panel/i18n.d.ts +53 -0
  24. package/dist/src/panel/i18n.js +106 -0
  25. package/dist/src/panel/page-logic.d.ts +23 -1
  26. package/dist/src/panel/page-logic.js +33 -0
  27. package/dist/src/panel/page-script.js +184 -11
  28. package/dist/src/panel/page-styles.js +11 -3
  29. package/dist/src/runtime.d.ts +18 -1
  30. package/dist/src/runtime.js +78 -7
  31. package/package.json +2 -2
  32. package/schemas/config.json +20 -0
  33. package/schemas/network-set.json +129 -0
  34. package/schemas/network.json +199 -0
  35. package/skills/sideby/SKILL.md +2 -1
  36. package/skills/sideby/references/ai-tasks.md +1 -1
  37. package/skills/sideby/references/network.md +37 -0
@@ -0,0 +1,333 @@
1
+ // The Egress check behind Network Guard (spec §3.35, ADR-0053). A leaf module: `network-hook` runs it on every prompt
2
+ // and tool call, so it imports only Node built-ins and core/fs-safe.ts. It asks the vendor's own
3
+ // `/cdn-cgi/trace` through the Host's proxy settings, keeps the country and a hash of the address, and decides.
4
+ import { createHash } from 'node:crypto';
5
+ import { mkdir, readFile } from 'node:fs/promises';
6
+ import { request as httpRequest } from 'node:http';
7
+ import { request as httpsRequest } from 'node:https';
8
+ import { networkInterfaces } from 'node:os';
9
+ import { join } from 'node:path';
10
+ import { connect as tlsConnect } from 'node:tls';
11
+ import { writeFileAtomic } from './fs-safe.js';
12
+ /** Variables a launched Host reads for its proxy; the check uses the same ones, so it takes the same route. */
13
+ export const PROXY_VARS = [
14
+ 'HTTPS_PROXY',
15
+ 'https_proxy',
16
+ 'HTTP_PROXY',
17
+ 'http_proxy',
18
+ 'ALL_PROXY',
19
+ 'all_proxy',
20
+ 'NO_PROXY',
21
+ 'no_proxy',
22
+ ];
23
+ /** What `network-hook` reads from the session's environment; set by sideby at Launch. */
24
+ export const NETWORK_ENV = {
25
+ url: 'SIDEBY_NETWORK_URL',
26
+ allow: 'SIDEBY_NETWORK_ALLOW',
27
+ dir: 'SIDEBY_NETWORK_DIR',
28
+ };
29
+ export const TIMEOUT_MS = 3000;
30
+ /** A result this young is used as it is. */
31
+ export const FRESH_MS = 60_000;
32
+ /** Up to this age a tool call goes on while a detached process refreshes the result. */
33
+ export const STALE_MS = 5 * 60_000;
34
+ const sha = (s) => createHash('sha256').update(s).digest('hex');
35
+ /** The proxy a request to `url` goes through under `env`, or null for a direct connection. */
36
+ export function proxyFor(url, env) {
37
+ const host = new URL(url).hostname.toLowerCase();
38
+ const no = env.NO_PROXY ?? env.no_proxy ?? '';
39
+ for (const raw of no.split(',')) {
40
+ const p = raw.trim().toLowerCase().replace(/:\d+$/, '');
41
+ if (!p)
42
+ continue;
43
+ if (p === '*')
44
+ return null;
45
+ const bare = p.replace(/^\*?\./, '');
46
+ if (host === bare || host.endsWith(`.${bare}`))
47
+ return null;
48
+ }
49
+ const v = env.HTTPS_PROXY || env.https_proxy || env.ALL_PROXY || env.all_proxy;
50
+ return v ? v.trim() : null;
51
+ }
52
+ /** The key a cached result is kept under: the URL and the proxy settings, never their values in clear. */
53
+ export function cacheKey(url, env) {
54
+ return sha(JSON.stringify([url, ...PROXY_VARS.map((k) => env[k] ?? '')])).slice(0, 32);
55
+ }
56
+ /** A hash of the machine's own network addresses; it changes with Wi-Fi, a VPN or a TUN device. */
57
+ export function netPrint(read = networkInterfaces) {
58
+ const all = [];
59
+ try {
60
+ for (const [name, list] of Object.entries(read())) {
61
+ for (const a of list ?? [])
62
+ if (!a.internal)
63
+ all.push(`${name}/${a.address}`);
64
+ }
65
+ }
66
+ catch {
67
+ // no interfaces readable: one constant print
68
+ }
69
+ return sha(all.sort().join('\n')).slice(0, 32);
70
+ }
71
+ export function parseTrace(text) {
72
+ const out = {};
73
+ for (const line of text.split('\n')) {
74
+ const [k, v] = line.split('=', 2);
75
+ if (k === 'ip' && v)
76
+ out.ip = v.trim();
77
+ if (k === 'loc' && v && /^[A-Z]{2}$/.test(v.trim()))
78
+ out.loc = v.trim();
79
+ }
80
+ return out;
81
+ }
82
+ /** One GET of `url`, directly or through an `http://` proxy (CONNECT), as the Host would send it. */
83
+ export const fetchTrace = (url, env, timeoutMs) => new Promise((resolve, reject) => {
84
+ const target = new URL(url);
85
+ const proxy = proxyFor(url, env);
86
+ let done = false;
87
+ const finish = (err, body) => {
88
+ if (done)
89
+ return;
90
+ done = true;
91
+ clearTimeout(timer);
92
+ if (err)
93
+ reject(err);
94
+ else
95
+ resolve(body ?? '');
96
+ };
97
+ const timer = setTimeout(() => finish(new Error('timeout')), timeoutMs);
98
+ const read = (res) => {
99
+ if ((res.statusCode ?? 0) >= 400) {
100
+ res.resume();
101
+ return finish(new Error(`HTTP ${res.statusCode}`));
102
+ }
103
+ let body = '';
104
+ res.setEncoding('utf8');
105
+ res.on('data', (c) => {
106
+ if (body.length < 4096)
107
+ body += c;
108
+ });
109
+ res.on('end', () => finish(null, body));
110
+ res.on('error', (e) => finish(e));
111
+ };
112
+ const get = (socket) => {
113
+ const req = httpsRequest({
114
+ host: target.hostname,
115
+ path: target.pathname,
116
+ method: 'GET',
117
+ headers: { 'user-agent': 'sideby-network-guard' },
118
+ ...(socket ? { createConnection: () => socket } : {}),
119
+ }, read);
120
+ req.on('error', (e) => finish(e));
121
+ req.end();
122
+ };
123
+ if (!proxy)
124
+ return get();
125
+ let p;
126
+ try {
127
+ p = new URL(proxy.includes('://') ? proxy : `http://${proxy}`);
128
+ }
129
+ catch {
130
+ return finish(new Error('the proxy address is not a URL'));
131
+ }
132
+ if (p.protocol !== 'http:')
133
+ return finish(new Error(`a ${p.protocol.replace(':', '')} proxy is not supported`));
134
+ const headers = { host: `${target.hostname}:443` };
135
+ if (p.username)
136
+ headers['proxy-authorization'] =
137
+ `Basic ${Buffer.from(`${decodeURIComponent(p.username)}:${decodeURIComponent(p.password)}`).toString('base64')}`;
138
+ const req = httpRequest({
139
+ host: p.hostname,
140
+ port: Number(p.port) || 80,
141
+ method: 'CONNECT',
142
+ path: `${target.hostname}:443`,
143
+ headers,
144
+ });
145
+ req.on('connect', (res, socket) => {
146
+ if (res.statusCode !== 200) {
147
+ socket.destroy();
148
+ return finish(new Error(`the proxy answered ${res.statusCode}`));
149
+ }
150
+ const tls = tlsConnect({ socket, servername: target.hostname });
151
+ tls.on('error', (e) => finish(e));
152
+ get(tls);
153
+ });
154
+ req.on('error', (e) => finish(e));
155
+ req.end();
156
+ });
157
+ /** Plain words for a failed request; never the proxy address or its password. */
158
+ function failure(err) {
159
+ const e = err;
160
+ if (e?.message === 'timeout')
161
+ return 'no answer within 3 seconds';
162
+ if (e?.code === 'ECONNREFUSED')
163
+ return 'the connection was refused (is the proxy running?)';
164
+ if (e?.code === 'ENOTFOUND' || e?.code === 'EAI_AGAIN')
165
+ return 'the address could not be looked up (offline?)';
166
+ if (e?.message?.startsWith('HTTP ') || e?.message?.startsWith('the proxy') || e?.message?.startsWith('a '))
167
+ return e.message;
168
+ return 'the request failed';
169
+ }
170
+ const entryFile = (dir, key) => join(dir, `${key}.json`);
171
+ export async function readEntry(dir, key) {
172
+ try {
173
+ const v = JSON.parse(await readFile(entryFile(dir, key), 'utf8'));
174
+ return typeof v?.checkedAt === 'string' && typeof v.netPrint === 'string' ? v : null;
175
+ }
176
+ catch {
177
+ return null;
178
+ }
179
+ }
180
+ /** Whether `loc` passes `allow`; without a country the check could not tell. */
181
+ export function judge(entry, allow) {
182
+ if (!entry.loc)
183
+ return 'unknown';
184
+ return allow.includes(entry.loc) ? 'ok' : 'blocked';
185
+ }
186
+ /**
187
+ * What to do with a cached result at `moment` (spec §3.35): use it, use it and refresh in the background
188
+ * (tool calls only), or check now.
189
+ */
190
+ export function plan(entry, allow, moment, now, print) {
191
+ if (!entry || entry.netPrint !== print || judge(entry, allow) !== 'ok')
192
+ return 'check';
193
+ const age = now - Date.parse(entry.checkedAt);
194
+ if (!(age >= 0))
195
+ return 'check';
196
+ if (age <= FRESH_MS)
197
+ return 'use';
198
+ if (moment === 'tool' && age <= STALE_MS)
199
+ return 'refresh';
200
+ return 'check';
201
+ }
202
+ /** Asks the network once and keeps the answer (spec §3.35); never throws. */
203
+ export async function refresh(opts) {
204
+ const key = cacheKey(opts.url, opts.env);
205
+ const before = await readEntry(opts.dir, key);
206
+ const print = opts.print ?? netPrint();
207
+ let entry;
208
+ let ipChanged = false;
209
+ try {
210
+ const t = parseTrace(await (opts.fetcher ?? fetchTrace)(opts.url, opts.env, TIMEOUT_MS));
211
+ const at = (opts.now?.() ?? new Date()).toISOString();
212
+ const ipHash = t.ip ? sha(t.ip) : undefined;
213
+ ipChanged = Boolean(ipHash && before?.ipHash && before.ipHash !== ipHash);
214
+ const changedAt = ipChanged ? at : before?.ipChangedAt;
215
+ entry = {
216
+ url: opts.url,
217
+ checkedAt: at,
218
+ ...(t.loc ? { loc: t.loc } : { error: 'the answer named no country' }),
219
+ ...(ipHash ? { ipHash } : before?.ipHash ? { ipHash: before.ipHash } : {}),
220
+ ...(changedAt ? { ipChangedAt: changedAt } : {}),
221
+ netPrint: print,
222
+ };
223
+ }
224
+ catch (err) {
225
+ entry = {
226
+ url: opts.url,
227
+ checkedAt: (opts.now?.() ?? new Date()).toISOString(),
228
+ error: failure(err),
229
+ ...(before?.ipHash ? { ipHash: before.ipHash } : {}),
230
+ ...(before?.ipChangedAt ? { ipChangedAt: before.ipChangedAt } : {}),
231
+ netPrint: print,
232
+ };
233
+ }
234
+ try {
235
+ await mkdir(opts.dir, { recursive: true, mode: 0o700 });
236
+ await writeFileAtomic(entryFile(opts.dir, key), `${JSON.stringify(entry)}\n`, 0o600);
237
+ }
238
+ catch {
239
+ // an unwritable cache only costs the next call another request
240
+ }
241
+ return { entry, ipChanged };
242
+ }
243
+ /**
244
+ * The verdict at `moment`: from the cache when it is young enough, else from one request. `background` starts a
245
+ * detached refresh for the tool-call middle tier; without it that tier checks now.
246
+ */
247
+ export async function verdict(opts) {
248
+ const key = cacheKey(opts.url, opts.env);
249
+ const cached = await readEntry(opts.dir, key);
250
+ const print = opts.print ?? netPrint();
251
+ const now = (opts.now?.() ?? new Date()).getTime();
252
+ const what = plan(cached, opts.allow, opts.moment, now, print);
253
+ if (cached && (what === 'use' || (what === 'refresh' && opts.background))) {
254
+ if (what === 'refresh')
255
+ opts.background?.();
256
+ return { status: judge(cached, opts.allow), entry: cached, fresh: false, ipChanged: false };
257
+ }
258
+ const { entry, ipChanged } = await refresh({ ...opts, print });
259
+ return { status: judge(entry, opts.allow), entry, fresh: true, ipChanged };
260
+ }
261
+ const NAMES_ZH = {
262
+ US: '美国',
263
+ JP: '日本',
264
+ SG: '新加坡',
265
+ HK: '香港',
266
+ TW: '台湾',
267
+ KR: '韩国',
268
+ GB: '英国',
269
+ DE: '德国',
270
+ FR: '法国',
271
+ CA: '加拿大',
272
+ AU: '澳大利亚',
273
+ CN: '中国大陆',
274
+ MO: '澳门',
275
+ NL: '荷兰',
276
+ IN: '印度',
277
+ RU: '俄罗斯',
278
+ };
279
+ /** "香港(HK)" or "HK": a country for a sentence. */
280
+ export function countryLabel(code, zh) {
281
+ return zh && NAMES_ZH[code] ? `${NAMES_ZH[code]}(${code})` : code;
282
+ }
283
+ /** Whether messages for a hook or a terminal should be Chinese: the user's locale says so. */
284
+ export function prefersChinese(env) {
285
+ return /^zh/i.test(env.LC_ALL || env.LC_MESSAGES || env.LANG || '');
286
+ }
287
+ /** A failure reason from `refresh` in the user's language (the cache keeps the English one). */
288
+ function reasonZh(reason) {
289
+ const m = /^(?:the proxy answered|HTTP) (\d+)$/.exec(reason);
290
+ if (m)
291
+ return reason.startsWith('HTTP') ? `服务器返回 ${m[1]}` : `代理返回 ${m[1]}`;
292
+ const p = /^a (\w+) proxy is not supported$/.exec(reason);
293
+ if (p)
294
+ return `不支持 ${p[1]} 代理`;
295
+ return ({
296
+ 'no answer within 3 seconds': '3 秒内没有回应',
297
+ 'the connection was refused (is the proxy running?)': '连接被拒绝,代理开着吗',
298
+ 'the address could not be looked up (offline?)': '域名解析失败,断网了吗',
299
+ 'the answer named no country': '回应里没有国家或地区',
300
+ 'the proxy address is not a URL': '代理地址写得不对',
301
+ 'the request failed': '请求失败',
302
+ }[reason] ?? reason);
303
+ }
304
+ /**
305
+ * What the user reads when Network Guard stops something (spec §3.35): what happened, why, what to do.
306
+ * `at`: `prompt`/`tool` inside a session, `launch` before one.
307
+ */
308
+ export function blockMessage(v, allow, opts) {
309
+ const ref = opts.ref || '<account>';
310
+ const allowed = allow.map((c) => countryLabel(c, opts.zh)).join(opts.zh ? '、' : ', ');
311
+ const skip = `sideby run ${ref} --ignore-network`;
312
+ const reason = v.entry.error ?? 'no answer within 3 seconds';
313
+ if (opts.zh) {
314
+ const what = v.status === 'unknown'
315
+ ? `已拦截:没能确认网络出口(${reasonZh(reason)}),可能是代理没开或断网。`
316
+ : `已拦截:现在的网络出口在${countryLabel(v.entry.loc ?? '?', true)},不在允许的地区(${allowed})里。`;
317
+ const next = opts.at === 'launch'
318
+ ? '检查代理是否开着、节点是否正确,然后再启动。'
319
+ : opts.at === 'prompt'
320
+ ? '检查代理是否开着、节点是否正确,然后重新发送这条消息。'
321
+ : '检查代理是否开着、节点是否正确,然后让它继续。';
322
+ return `${what}${next}临时跳过:\`${skip}\`。`;
323
+ }
324
+ const what = v.status === 'unknown'
325
+ ? `Blocked: sideby could not tell this network's exit (${reason}); the proxy may be off or the network down.`
326
+ : `Blocked: this network exits in ${v.entry.loc}, which is not an allowed country (${allowed}).`;
327
+ const next = opts.at === 'launch'
328
+ ? 'Check that the proxy is on and the node is right, then start again.'
329
+ : opts.at === 'prompt'
330
+ ? 'Check that the proxy is on and the node is right, then send the message again.'
331
+ : 'Check that the proxy is on and the node is right, then let it continue.';
332
+ return `${what} ${next} To skip once: \`${skip}\`.`;
333
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Runtime } from '../runtime.ts';
2
2
  import type { Env } from '../types.ts';
3
3
  import type { HandoffDecision } from './handoff-select.ts';
4
+ import { beforeDashes } from './launch.ts';
4
5
  export interface HandoffIo {
5
6
  err(line: string): void;
6
7
  stdin: NodeJS.ReadableStream & {
@@ -13,8 +14,7 @@ export declare const EXIT_GRACE_MS = 10000;
13
14
  /** Accounts the decision left out and why (spec §3.21), as `; skipped claude:main (…)`, or ''. */
14
15
  export declare function skippedText(d: HandoffDecision): string;
15
16
  export declare function explain(d: HandoffDecision): string;
16
- /** `args` with `extra` before the first `--`, so a user's own `--` cannot turn sideby's options into prompt text. */
17
- export declare function beforeDashes(args: readonly string[], extra: readonly string[]): string[];
17
+ export { beforeDashes };
18
18
  /** Whether the `sideby` on PATH has the hook entry: an older install would fail every hook call. */
19
19
  export declare function hookEntryWorks(env: Env): Promise<boolean>;
20
20
  /**
@@ -26,6 +26,8 @@ export declare function runWithHandoff(rt: Runtime, ref: string, userArgs: reado
26
26
  exitGraceMs?: number;
27
27
  /** An AI Task (ADR-0031): every Account it hands over to starts without permission bypasses too. */
28
28
  aiTask?: boolean;
29
+ /** `--ignore-network` (spec §3.35): no Launch of this run is checked. */
30
+ ignoreNetwork?: boolean;
29
31
  }): Promise<number | null>;
30
32
  /**
31
33
  * For `sideby handoff ready`: where a Handoff from the session running under `env` would go now, using the chain's
@@ -11,7 +11,8 @@ import { aliasArgs } from './config.js';
11
11
  import { UserError } from './errors.js';
12
12
  import { finishBrief } from './handoff-brief.js';
13
13
  import { briefPath, chainDir, ensureChainDir, FILES, HANDOFF_ENV, newId, readJsonFile, writeJsonFile, } from './handoff-chain.js';
14
- import { runHost, sidebyBinProblem, spawnHost } from './launch.js';
14
+ import { beforeDashes, runHost, sidebyBinProblem, spawnHost } from './launch.js';
15
+ import { withClaudeNetworkHooks, withoutArgs } from './network.js';
15
16
  import { quotaPressure } from './quota-levels.js';
16
17
  /** How long the Host gets to exit after SIGTERM (time for its SessionEnd hooks) before sideby gives up. */
17
18
  export const EXIT_GRACE_MS = 10_000;
@@ -120,10 +121,10 @@ async function codexTrustNotice(rt, account, io) {
120
121
  await ensureChainDir(join(rt.paths.stateDir, 'handoff'));
121
122
  await writeJsonFile(file, { refs: [...seen, account.ref] });
122
123
  }
123
- /** `args` with `extra` before the first `--`, so a user's own `--` cannot turn sideby's options into prompt text. */
124
- export function beforeDashes(args, extra) {
125
- const at = args.indexOf('--');
126
- return at === -1 ? [...args, ...extra] : [...args.slice(0, at), ...extra, ...args.slice(at)];
124
+ export { beforeDashes };
125
+ /** A Launch's arguments without Network Guard's Claude `--settings`, which would read as the user's own. */
126
+ function withoutNetwork(l) {
127
+ return l.family.id === 'claude' ? withoutArgs(l.args, l.networkArgs ?? []) : [...l.args];
127
128
  }
128
129
  /** Whether the `sideby` on PATH has the hook entry: an older install would fail every hook call. */
129
130
  export function hookEntryWorks(env) {
@@ -152,13 +153,16 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
152
153
  const settings = rt.handoffSettings();
153
154
  if (!settings.auto || !io.stdin.isTTY)
154
155
  return null;
155
- const launchOpts = opts.aiTask ? { aiTask: true } : {};
156
+ const launchOpts = {
157
+ ...(opts.aiTask ? { aiTask: true } : {}),
158
+ ...(opts.ignoreNetwork ? { ignoreNetwork: true } : {}),
159
+ };
156
160
  const firstLaunch = await rt.prepareLaunch(ref, userArgs, 'run', launchOpts);
157
161
  const firstHandoff = firstLaunch.family.handoff;
158
162
  // Only built-in Families have a hook reader (spec §3.17); a Plugin Family can only take over.
159
163
  if (!firstHandoff?.starts.length || !HOOK_FAMILIES.includes(firstLaunch.family.id))
160
164
  return null;
161
- const firstElig = await firstHandoff.eligibility(firstLaunch.args, firstLaunch.account, firstLaunch.env);
165
+ const firstElig = await firstHandoff.eligibility(withoutNetwork(firstLaunch), firstLaunch.account, firstLaunch.env);
162
166
  if (!firstElig.start) {
163
167
  // A headless run is simply not part of it; an interactive one that cannot start says why.
164
168
  if (firstElig.receive && firstElig.reason)
@@ -187,7 +191,7 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
187
191
  const h = launch.family.handoff;
188
192
  if (!h)
189
193
  return runHost(launch);
190
- const elig = n === 1 ? firstElig : await h.eligibility(launch.args, account, launch.env);
194
+ const elig = n === 1 ? firstElig : await h.eligibility(withoutNetwork(launch), account, launch.env);
191
195
  const canStart = h.starts.length > 0 && elig.start && HOOK_FAMILIES.includes(account.family);
192
196
  if (!canStart && elig.reason)
193
197
  io.err(`sideby: ${account.ref} will not hand over: ${elig.reason}`);
@@ -195,8 +199,11 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
195
199
  const brief = briefPath(dir, n, account.ref);
196
200
  const extra = [...(elig.args ?? [])];
197
201
  const env = { ...launch.env };
202
+ // Claude takes one `--settings`: Network Guard's hooks (spec §3.35) go into Auto Handoff's file.
203
+ const mergeNet = canStart && account.family === 'claude' && Boolean(launch.networkArgs?.length);
198
204
  if (canStart) {
199
- extra.push(...((await h.hookArgs?.(hookCommand(account.family), rt.paths.stateDir)) ?? []));
205
+ const hookArgs = (await h.hookArgs?.(hookCommand(account.family), rt.paths.stateDir)) ?? [];
206
+ extra.push(...(mergeNet ? await withClaudeNetworkHooks(hookArgs, rt.paths.stateDir) : hookArgs));
200
207
  env[HANDOFF_ENV.run] = runId;
201
208
  env[HANDOFF_ENV.family] = account.family;
202
209
  env[HANDOFF_ENV.dir] = dir;
@@ -204,7 +211,7 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
204
211
  await codexTrustNotice(rt, account, io);
205
212
  }
206
213
  extra.push(...(h.dirArgs?.(dir) ?? []));
207
- const args = beforeDashes(launch.args, extra);
214
+ const args = beforeDashes(mergeNet ? withoutNetwork(launch) : launch.args, extra);
208
215
  // Later hops carry no `--` of their own (continueArgs drops it), so the prompt goes after a fresh one.
209
216
  if (hop.prompt)
210
217
  args.push(...h.promptArgs(hop.prompt));
@@ -336,7 +343,7 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
336
343
  const backArgs = [...h.continueArgs(hop.args), ...h.resumeArgs(ready.sessionId)];
337
344
  const back = await rt.prepareLaunch(account.ref, backArgs, 'run', launchOpts);
338
345
  // The same per-Account arguments as before (Grok's leader socket), without sideby's hooks.
339
- const backElig = await h.eligibility(back.args, account, back.env);
346
+ const backElig = await h.eligibility(withoutNetwork(back), account, back.env);
340
347
  return runHost({ ...back, args: beforeDashes(back.args, backElig.args ?? []) });
341
348
  }
342
349
  let next;
@@ -11,9 +11,11 @@ export interface PreparedLaunch {
11
11
  notice?: string;
12
12
  /** Terminal title set before the Host starts (config `accountTitle`), for example `[codex002]`. */
13
13
  title?: string;
14
+ /** The arguments Network Guard added to `args` for its session hooks (spec §3.35); Auto Handoff merges them. */
15
+ networkArgs?: string[];
14
16
  }
15
17
  /** What `runHost` needs: a prepared Account launch, or the Host run unchanged (`sideby resume`). */
16
- export type HostLaunch = Pick<PreparedLaunch, 'family' | 'bin' | 'args' | 'env' | 'title'> & {
18
+ export type HostLaunch = Pick<PreparedLaunch, 'family' | 'bin' | 'args' | 'env' | 'title' | 'notice'> & {
17
19
  /** The Account the Host runs as, when sideby chose one: its Live Session can then grow the title (spec §3.32). */
18
20
  account?: Account;
19
21
  };
@@ -89,3 +91,5 @@ export declare function spawnHost(p: HostLaunch): {
89
91
  child: ChildProcess;
90
92
  exited: Promise<number>;
91
93
  };
94
+ /** `args` with `extra` before the first `--`, so a user's own `--` cannot turn sideby's options into prompt text. */
95
+ export declare function beforeDashes(args: readonly string[], extra: readonly string[]): string[];
@@ -231,3 +231,8 @@ export function spawnHost(p) {
231
231
  });
232
232
  return { child: host, exited };
233
233
  }
234
+ /** `args` with `extra` before the first `--`, so a user's own `--` cannot turn sideby's options into prompt text. */
235
+ export function beforeDashes(args, extra) {
236
+ const at = args.indexOf('--');
237
+ return at === -1 ? [...args, ...extra] : [...args.slice(0, at), ...extra, ...args.slice(at)];
238
+ }
@@ -0,0 +1,131 @@
1
+ import type { Account, Env } from '../types.ts';
2
+ import type { Config } from './config.ts';
3
+ import { type EgressStatus, type TraceFetcher, type Verdict } from './egress.ts';
4
+ /** Families Network Guard covers in v1. */
5
+ export declare const GUARDED_FAMILIES: readonly ['claude', 'codex'];
6
+ export declare const TRACE: {
7
+ readonly anthropic: 'https://api.anthropic.com/cdn-cgi/trace';
8
+ readonly chatgpt: 'https://chatgpt.com/cdn-cgi/trace';
9
+ readonly openai: 'https://api.openai.com/cdn-cgi/trace';
10
+ };
11
+ /** Where an Account's Egress is checked, or why it is not. */
12
+ export type NetworkTarget = {
13
+ url: string;
14
+ } | {
15
+ skip: 'not-covered' | 'third-party';
16
+ };
17
+ /**
18
+ * The trace address that takes the same route as the Account's model requests: the vendor's own API domain for
19
+ * a Subscription Account or an API Account on the official endpoint; none for a third-party endpoint.
20
+ * `env` is the Launch environment (the Secret File already merged).
21
+ */
22
+ export declare function networkTarget(account: Pick<Account, 'family' | 'kind'>, env: Env): NetworkTarget;
23
+ export declare const networkDir: (stateDir: string) => string;
24
+ /** Network Guard is on: the switch, a non-empty list, and not in CI (where it makes no request). */
25
+ export declare function guardOn(config: Pick<Config, 'network'>, env: Env): boolean;
26
+ export interface LaunchGuardResult {
27
+ /** Variables `network-hook` reads, to add to the Host's environment. */
28
+ env: Record<string, string>;
29
+ verdict: Verdict;
30
+ }
31
+ /**
32
+ * The check before a Launch (spec §3.35): throws a UserError that says what to do when the Egress is outside the
33
+ * list or cannot be told; returns what the session's hooks need, or null when this Launch is not guarded.
34
+ */
35
+ export declare function guardLaunch(opts: {
36
+ account: Account;
37
+ env: Env;
38
+ config: Pick<Config, 'network'>;
39
+ stateDir: string;
40
+ label?: string;
41
+ fetcher?: TraceFetcher;
42
+ now?: () => Date;
43
+ print?: string;
44
+ }): Promise<LaunchGuardResult | null>;
45
+ /** The line a Launch prints when the check saw the address change (a notice, never a block). */
46
+ export declare function ipChangedLine(v: Verdict, env: Env): string | undefined;
47
+ /** Claude Code `hooks` entries for Network Guard, to put in a `--settings` file (alone or with Auto Handoff's). */
48
+ export declare function claudeNetworkHooks(): Record<string, unknown[]>;
49
+ /** The file holding Network Guard's Claude hooks alone. */
50
+ export declare const claudeNetworkSettings: (stateDir: string) => string;
51
+ /**
52
+ * Host arguments that add Network Guard's hooks to a session: Claude through a `--settings` file sideby writes,
53
+ * Codex through `-c hooks.*`. Nothing is written into a Host directory.
54
+ */
55
+ export declare function networkHookArgs(family: string, stateDir: string): Promise<string[]>;
56
+ /** The line a Claude Launch prints when the user's own `--settings` leaves no room for the session hooks. */
57
+ export declare function networkSettingsLine(env: Env): string;
58
+ /** Once per Codex Account: Codex runs the hooks only after the user trusts them in `/hooks`. */
59
+ export declare function codexNetworkTrustLine(stateDir: string, ref: string, env: Env): Promise<string | undefined>;
60
+ /**
61
+ * Auto Handoff's Claude hook arguments with Network Guard's hooks added to its `--settings` file, written as a new
62
+ * file next to Network Guard's own (Claude Code takes one `--settings`).
63
+ */
64
+ export declare function withClaudeNetworkHooks(hookArgs: readonly string[], stateDir: string): Promise<string[]>;
65
+ /** `args` without the Network Guard arguments `networkHookArgs` added (Auto Handoff merges them into its own). */
66
+ export declare function withoutArgs(args: readonly string[], drop: readonly string[]): string[];
67
+ /** Where one Account is checked, or why not: a third-party endpoint, or an API Account decided at Launch. */
68
+ export interface NetworkAccountRow {
69
+ ref: string;
70
+ url?: string;
71
+ skip?: 'not-covered' | 'third-party' | 'at-launch';
72
+ }
73
+ export interface NetworkTargetStatus {
74
+ url: string;
75
+ /** Accounts checked at this address. */
76
+ accounts: string[];
77
+ status: EgressStatus | 'not-checked';
78
+ loc?: string;
79
+ checkedAt?: string;
80
+ error?: string;
81
+ /** The address changed in the last day. */
82
+ ipChanged: boolean;
83
+ }
84
+ /**
85
+ * What `sideby network` and the Panel show (spec §3.35): per address, the newest cached result, and per Account
86
+ * where it is checked or why not. Reads only the cache; `check` asks every address now.
87
+ */
88
+ export declare function networkOverview(opts: {
89
+ accounts: readonly Account[];
90
+ config: Pick<Config, 'network'>;
91
+ stateDir: string;
92
+ env: Env;
93
+ envFor: (account: Account) => Promise<Env>;
94
+ check?: boolean;
95
+ fetcher?: TraceFetcher;
96
+ now?: () => Date;
97
+ print?: string;
98
+ }): Promise<{
99
+ guard: boolean;
100
+ allow: string[];
101
+ active: boolean;
102
+ ci: boolean;
103
+ targets: NetworkTargetStatus[];
104
+ accounts: NetworkAccountRow[];
105
+ }>;
106
+ export type NetworkOverview = Awaited<ReturnType<typeof networkOverview>>;
107
+ export interface NetworkChange {
108
+ guard?: boolean;
109
+ allow?: string[];
110
+ }
111
+ /** Country codes as config keeps them: upper case, two letters, each once, in the order given. */
112
+ export declare function normalizeAllow(codes: readonly string[]): string[];
113
+ /**
114
+ * `sideby network on|off|allow` and the Panel's network check (spec §3.35): changes config `network`, shown first
115
+ * (`apply: false`) and written with `apply`. Turning it on with no allowed country is refused.
116
+ */
117
+ export declare function setNetwork(configFile: string, change: NetworkChange, opts: {
118
+ apply: boolean;
119
+ }): Promise<{
120
+ changed: boolean;
121
+ applied: boolean;
122
+ file: string;
123
+ before: {
124
+ guard: boolean;
125
+ allow: string[];
126
+ };
127
+ after: {
128
+ guard: boolean;
129
+ allow: string[];
130
+ };
131
+ }>;