sideby 0.24.0 → 0.26.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/README.md +3 -1
- package/ai-tasks.json +17 -0
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +14 -0
- package/dist/src/cli/commands.js +120 -12
- package/dist/src/cli/json-schemas.js +47 -0
- package/dist/src/cli/main.js +41 -6
- package/dist/src/core/ask.d.ts +10 -6
- package/dist/src/core/ask.js +52 -9
- package/dist/src/core/config.d.ts +16 -0
- package/dist/src/core/config.js +16 -0
- package/dist/src/core/egress.d.ts +103 -0
- package/dist/src/core/egress.js +333 -0
- package/dist/src/core/handoff-run.d.ts +4 -2
- package/dist/src/core/handoff-run.js +18 -11
- package/dist/src/core/launch.d.ts +5 -1
- package/dist/src/core/launch.js +5 -0
- package/dist/src/core/network.d.ts +131 -0
- package/dist/src/core/network.js +317 -0
- package/dist/src/families/agy/index.js +4 -1
- package/dist/src/families/claude/index.js +4 -1
- package/dist/src/families/codex/index.js +8 -1
- package/dist/src/families/grok/index.js +4 -1
- package/dist/src/families/pi/index.js +4 -1
- package/dist/src/network/hook.d.ts +15 -0
- package/dist/src/network/hook.js +69 -0
- package/dist/src/panel/handler.d.ts +3 -0
- package/dist/src/panel/handler.js +33 -1
- package/dist/src/panel/i18n.d.ts +51 -0
- package/dist/src/panel/i18n.js +102 -0
- package/dist/src/panel/page-logic.d.ts +23 -1
- package/dist/src/panel/page-logic.js +33 -0
- package/dist/src/panel/page-script.js +130 -2
- package/dist/src/panel/page-styles.js +11 -3
- package/dist/src/runtime.d.ts +18 -1
- package/dist/src/runtime.js +78 -7
- package/dist/src/types.d.ts +7 -0
- package/package.json +2 -2
- package/schemas/config.json +20 -0
- package/schemas/network-set.json +129 -0
- package/schemas/network.json +199 -0
- package/schemas/try.json +4 -0
- package/skills/sideby/SKILL.md +3 -2
- package/skills/sideby/references/ai-tasks.md +2 -1
- package/skills/sideby/references/network.md +37 -0
package/dist/src/core/config.js
CHANGED
|
@@ -200,6 +200,15 @@ export const ConfigSchema = Type.Object({
|
|
|
200
200
|
description: "Keep a local History Index of every Session's title, Project, typed prompts and model replies (never tool output) in sideby's state folder, so Session History opens and searches at once. On by default; false stops it and deletes the index.",
|
|
201
201
|
})),
|
|
202
202
|
}, { additionalProperties: false, description: 'Session History (spec §3.33, ADR-0042).' })),
|
|
203
|
+
network: Type.Optional(Type.Object({
|
|
204
|
+
guard: Type.Optional(Type.Boolean({
|
|
205
|
+
description: "Network Guard: before a Launch and before each prompt and tool call in a session sideby starts, check the country Claude Code's and Codex's requests leave from, and stop when it is not in `allow` or cannot be told. Asks the vendor's own `/cdn-cgi/trace` through the Host's proxy settings, with no credential. Off by default.",
|
|
206
|
+
})),
|
|
207
|
+
allow: Type.Optional(Type.Array(Type.String({ pattern: '^[A-Z]{2}$' }), {
|
|
208
|
+
uniqueItems: true,
|
|
209
|
+
description: 'Countries (ISO 3166-1 alpha-2, such as `US` or `JP`) a Host may send requests from. Network Guard cannot be turned on while it is empty.',
|
|
210
|
+
})),
|
|
211
|
+
}, { additionalProperties: false, description: 'Network Guard (spec §3.35, ADR-0053).' })),
|
|
203
212
|
browser: Type.Optional(Type.Object({
|
|
204
213
|
signIns: Type.Optional(Type.Boolean({
|
|
205
214
|
description: "Look in Google Chrome's local data for which browser user signed in to each Account's website (key names only, never cookies or passwords; nothing leaves this computer). Off by default.",
|
|
@@ -411,6 +420,13 @@ export function editConfigHandoff(file, edit, opts = {}) {
|
|
|
411
420
|
export function editConfigUpdate(file, edit, opts = {}) {
|
|
412
421
|
return editConfigKey(file, 'update', 'change the setting', (current) => edit(current ?? {}), opts);
|
|
413
422
|
}
|
|
423
|
+
/**
|
|
424
|
+
* `sideby network on|off|allow` and the Panel's network check (spec §3.35): changes the config `network` key with
|
|
425
|
+
* `edit` (see `editConfigKey` for how the file is written). With `dryRun`, shows the change without writing.
|
|
426
|
+
*/
|
|
427
|
+
export function editConfigNetwork(file, edit, opts = {}) {
|
|
428
|
+
return editConfigKey(file, 'network', 'change the setting', (current) => edit(current ?? {}), opts);
|
|
429
|
+
}
|
|
414
430
|
/**
|
|
415
431
|
* `sideby browser --enable|--disable` and the Panel's switch (spec §3.24): changes the config `browser` key with
|
|
416
432
|
* `edit` (see `editConfigKey` for how the file is written). With `dryRun`, shows the change without writing.
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { networkInterfaces } from 'node:os';
|
|
2
|
+
/** Variables a launched Host reads for its proxy; the check uses the same ones, so it takes the same route. */
|
|
3
|
+
export declare const PROXY_VARS: readonly ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy'];
|
|
4
|
+
/** What `network-hook` reads from the session's environment; set by sideby at Launch. */
|
|
5
|
+
export declare const NETWORK_ENV: {
|
|
6
|
+
readonly url: 'SIDEBY_NETWORK_URL';
|
|
7
|
+
readonly allow: 'SIDEBY_NETWORK_ALLOW';
|
|
8
|
+
readonly dir: 'SIDEBY_NETWORK_DIR';
|
|
9
|
+
};
|
|
10
|
+
export declare const TIMEOUT_MS = 3000;
|
|
11
|
+
/** A result this young is used as it is. */
|
|
12
|
+
export declare const FRESH_MS = 60000;
|
|
13
|
+
/** Up to this age a tool call goes on while a detached process refreshes the result. */
|
|
14
|
+
export declare const STALE_MS: number;
|
|
15
|
+
export type EgressStatus = 'ok' | 'blocked' | 'unknown';
|
|
16
|
+
/** When a check happens: before a Launch, before a prompt, or before a tool call (spec §3.35 table). */
|
|
17
|
+
export type CheckMoment = 'launch' | 'prompt' | 'tool';
|
|
18
|
+
export interface EgressEntry {
|
|
19
|
+
url: string;
|
|
20
|
+
/** ISO time of the request. */
|
|
21
|
+
checkedAt: string;
|
|
22
|
+
/** Country code from `loc=`, absent when the check could not tell. */
|
|
23
|
+
loc?: string;
|
|
24
|
+
/** SHA-256 of the address; the address itself is never kept. */
|
|
25
|
+
ipHash?: string;
|
|
26
|
+
/** When a check last saw another address than the one before. */
|
|
27
|
+
ipChangedAt?: string;
|
|
28
|
+
/** Why the check could not tell, in plain words. */
|
|
29
|
+
error?: string;
|
|
30
|
+
/** Hash of the machine's network addresses at the time of the check. */
|
|
31
|
+
netPrint: string;
|
|
32
|
+
}
|
|
33
|
+
export interface Verdict {
|
|
34
|
+
status: EgressStatus;
|
|
35
|
+
entry: EgressEntry;
|
|
36
|
+
/** True when this call asked the network (not the cache). */
|
|
37
|
+
fresh: boolean;
|
|
38
|
+
/** True when this call saw the address change. */
|
|
39
|
+
ipChanged: boolean;
|
|
40
|
+
}
|
|
41
|
+
type Env = Record<string, string | undefined>;
|
|
42
|
+
export type TraceFetcher = (url: string, env: Env, timeoutMs: number) => Promise<string>;
|
|
43
|
+
/** The proxy a request to `url` goes through under `env`, or null for a direct connection. */
|
|
44
|
+
export declare function proxyFor(url: string, env: Env): string | null;
|
|
45
|
+
/** The key a cached result is kept under: the URL and the proxy settings, never their values in clear. */
|
|
46
|
+
export declare function cacheKey(url: string, env: Env): string;
|
|
47
|
+
/** A hash of the machine's own network addresses; it changes with Wi-Fi, a VPN or a TUN device. */
|
|
48
|
+
export declare function netPrint(read?: typeof networkInterfaces): string;
|
|
49
|
+
export declare function parseTrace(text: string): {
|
|
50
|
+
ip?: string;
|
|
51
|
+
loc?: string;
|
|
52
|
+
};
|
|
53
|
+
/** One GET of `url`, directly or through an `http://` proxy (CONNECT), as the Host would send it. */
|
|
54
|
+
export declare const fetchTrace: TraceFetcher;
|
|
55
|
+
export declare function readEntry(dir: string, key: string): Promise<EgressEntry | null>;
|
|
56
|
+
/** Whether `loc` passes `allow`; without a country the check could not tell. */
|
|
57
|
+
export declare function judge(entry: EgressEntry, allow: readonly string[]): EgressStatus;
|
|
58
|
+
/**
|
|
59
|
+
* What to do with a cached result at `moment` (spec §3.35): use it, use it and refresh in the background
|
|
60
|
+
* (tool calls only), or check now.
|
|
61
|
+
*/
|
|
62
|
+
export declare function plan(entry: EgressEntry | null, allow: readonly string[], moment: CheckMoment, now: number, print: string): 'use' | 'refresh' | 'check';
|
|
63
|
+
/** Asks the network once and keeps the answer (spec §3.35); never throws. */
|
|
64
|
+
export declare function refresh(opts: {
|
|
65
|
+
url: string;
|
|
66
|
+
env: Env;
|
|
67
|
+
dir: string;
|
|
68
|
+
now?: () => Date;
|
|
69
|
+
fetcher?: TraceFetcher;
|
|
70
|
+
print?: string;
|
|
71
|
+
}): Promise<{
|
|
72
|
+
entry: EgressEntry;
|
|
73
|
+
ipChanged: boolean;
|
|
74
|
+
}>;
|
|
75
|
+
/**
|
|
76
|
+
* The verdict at `moment`: from the cache when it is young enough, else from one request. `background` starts a
|
|
77
|
+
* detached refresh for the tool-call middle tier; without it that tier checks now.
|
|
78
|
+
*/
|
|
79
|
+
export declare function verdict(opts: {
|
|
80
|
+
url: string;
|
|
81
|
+
env: Env;
|
|
82
|
+
allow: readonly string[];
|
|
83
|
+
dir: string;
|
|
84
|
+
moment: CheckMoment;
|
|
85
|
+
now?: () => Date;
|
|
86
|
+
fetcher?: TraceFetcher;
|
|
87
|
+
print?: string;
|
|
88
|
+
background?: () => void;
|
|
89
|
+
}): Promise<Verdict>;
|
|
90
|
+
/** "香港(HK)" or "HK": a country for a sentence. */
|
|
91
|
+
export declare function countryLabel(code: string, zh: boolean): string;
|
|
92
|
+
/** Whether messages for a hook or a terminal should be Chinese: the user's locale says so. */
|
|
93
|
+
export declare function prefersChinese(env: Env): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* What the user reads when Network Guard stops something (spec §3.35): what happened, why, what to do.
|
|
96
|
+
* `at`: `prompt`/`tool` inside a session, `launch` before one.
|
|
97
|
+
*/
|
|
98
|
+
export declare function blockMessage(v: Pick<Verdict, 'status' | 'entry'>, allow: readonly string[], opts: {
|
|
99
|
+
ref?: string;
|
|
100
|
+
at: CheckMoment;
|
|
101
|
+
zh: boolean;
|
|
102
|
+
}): string;
|
|
103
|
+
export {};
|
|
@@ -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
|
-
|
|
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
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
return
|
|
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 =
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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[];
|
package/dist/src/core/launch.js
CHANGED
|
@@ -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
|
+
}
|