sideby 0.44.0 → 0.45.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 (39) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +4 -0
  3. package/dist/src/cli/commands.js +9 -8
  4. package/dist/src/cli/json-schemas.js +51 -0
  5. package/dist/src/core/ask.js +4 -3
  6. package/dist/src/core/cli-commands.js +0 -10
  7. package/dist/src/core/egress.d.ts +1 -7
  8. package/dist/src/core/egress.js +7 -36
  9. package/dist/src/core/history.d.ts +1 -1
  10. package/dist/src/core/history.js +2 -2
  11. package/dist/src/core/network.d.ts +5 -35
  12. package/dist/src/core/network.js +18 -54
  13. package/dist/src/core/task-spec.js +10 -3
  14. package/dist/src/core/themes.js +0 -7
  15. package/dist/src/core/update.d.ts +1 -1
  16. package/dist/src/core/update.js +4 -12
  17. package/dist/src/families/claude/quota-fetch.js +2 -2
  18. package/dist/src/families/claude/tuning.d.ts +0 -1
  19. package/dist/src/families/claude/tuning.js +1 -1
  20. package/dist/src/network/hook.js +1 -1
  21. package/dist/src/network/page.d.ts +1 -1
  22. package/dist/src/network/page.js +15 -181
  23. package/dist/src/panel/handler.js +57 -25
  24. package/dist/src/panel/page-logic.d.ts +11 -29
  25. package/dist/src/panel/page-logic.js +11 -33
  26. package/dist/src/panel/page-script.js +5 -34
  27. package/dist/src/panel/page-styles.js +9 -18
  28. package/dist/src/quota/claude-statusline.js +1 -1
  29. package/dist/src/runtime.d.ts +2 -1
  30. package/dist/src/runtime.js +9 -6
  31. package/dist/src/types.d.ts +2 -2
  32. package/dist/src/unattended/hook.js +0 -1
  33. package/dist/testing/index.js +1 -1
  34. package/package.json +2 -1
  35. package/schemas/network-diagnose.json +239 -0
  36. package/skills/sideby/SKILL.md +1 -1
  37. package/skills/sideby/references/network.md +5 -3
  38. package/dist/src/network/page-script.d.ts +0 -40
  39. package/dist/src/network/page-script.js +0 -270
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261123T103613-7b7f5c"}
1
+ {"id":"20261124T100816-3f80d3"}
@@ -202,4 +202,8 @@ export declare function cmdTrust(a: ParsedArgs, io: Io): Promise<number>;
202
202
  export declare function cmdMemory(a: ParsedArgs, io: Io): Promise<number>;
203
203
  /** `sideby unattended …` (spec §3.37, ADR-0058): status, on and off, the Schedule, Pending Decisions and `defer`. */
204
204
  export declare function cmdUnattended(a: ParsedArgs, io: Io): Promise<number>;
205
+ /**
206
+ * `sideby commands <words>` (spec §3.36, ADR-0054): the Search Catalog the Panel's Command Palette searches, read-only.
207
+ * Titles and places are in English, as every other command prints; the words may be English or Chinese.
208
+ */
205
209
  export declare function cmdCommands(a: ParsedArgs, io: Io): number;
@@ -44,8 +44,10 @@ async function whileRunning(rt, fn) {
44
44
  await done().catch(() => { });
45
45
  }
46
46
  }
47
- /** Runs the Account with Auto Handoff when it applies (spec §3.17), else the Host as usual. */
48
- /** `opts.aiTask`: an AI Task's Host, started without permission bypasses (ADR-0031); `sideby run` leaves it out. */
47
+ /**
48
+ * Runs the Account with Auto Handoff when it applies (spec §3.17), else the Host as usual. `opts.aiTask`: an AI Task's
49
+ * Host, started without permission bypasses (ADR-0031); `sideby run` leaves it out.
50
+ */
49
51
  async function runAccount(rt, ref, args, io, opts = {}) {
50
52
  return whileRunning(rt, () => runAccountNow(rt, ref, args, io, opts));
51
53
  }
@@ -132,7 +134,6 @@ function displayOrdered(accounts, rt) {
132
134
  const ids = inDisplayOrder([...new Set(accounts.map((x) => x.family))], (id) => id, d.families);
133
135
  return ids.flatMap((id) => withPinned(inDisplayOrder(accounts.filter((x) => x.family === id), (x) => x.name, d.accounts?.[id]), d.pinned?.[id]));
134
136
  }
135
- /** Drop deleted accounts and unloaded Families only when saving a display change. */
136
137
  /**
137
138
  * Groups the Display Order may name (spec §3.25): every Family, and every desktop app with windows of its own (Grok
138
139
  * Bot, `grok-bot`), each with the names it holds.
@@ -147,6 +148,7 @@ async function orderGroups(rt, accounts) {
147
148
  }
148
149
  return out;
149
150
  }
151
+ /** Drop deleted accounts and unloaded Families only when saving a display change. */
150
152
  function cleanDisplay(rt, groups) {
151
153
  const d = rt.displayOrder();
152
154
  const clean = (lists) => Object.fromEntries(Object.entries(lists ?? {})
@@ -4098,7 +4100,6 @@ export async function cmdHistory(a, io) {
4098
4100
  io.out(c.dim('Read one, and get the command that continues it in its folder: sideby history show <id>'));
4099
4101
  return 0;
4100
4102
  }
4101
- /** The most Sessions one `sideby history` page lists. */
4102
4103
  const HISTORY_PAGE_MAX = 500;
4103
4104
  /** What to try when a search lists nothing, by what the search was narrowed by. */
4104
4105
  function historyEmptyHint(r, q, tools, hasAccounts) {
@@ -5496,10 +5497,6 @@ export async function cmdUnattended(a, io) {
5496
5497
  }
5497
5498
  throw new UsageError('usage: sideby unattended [status|on|off|schedule|wait|pending|defer]; run `sideby unattended --help`');
5498
5499
  }
5499
- /**
5500
- * `sideby commands <words>` (spec §3.36, ADR-0054): the Search Catalog the Panel's Command Palette searches, read-only.
5501
- * Titles and places are in English, as every other command prints; the words may be English or Chinese.
5502
- */
5503
5500
  /** One command of the Command List as `sideby commands --json` gives it (spec §3.38). */
5504
5501
  function commandOut(cmd) {
5505
5502
  const place = cmd.feature ? SEARCH_CATALOG.find((e) => e.id === cmd.feature) : undefined;
@@ -5544,6 +5541,10 @@ function listCommands(a, io) {
5544
5541
  io.out(out.join('\n'));
5545
5542
  return 0;
5546
5543
  }
5544
+ /**
5545
+ * `sideby commands <words>` (spec §3.36, ADR-0054): the Search Catalog the Panel's Command Palette searches, read-only.
5546
+ * Titles and places are in English, as every other command prints; the words may be English or Chinese.
5547
+ */
5547
5548
  export function cmdCommands(a, io) {
5548
5549
  const query = a.positionals.join(' ').trim();
5549
5550
  if (!query)
@@ -8,6 +8,11 @@ const ReasonCode = Type.Union(['local-build', 'npx', 'volta', 'not-writable', 'p
8
8
  const Level = Type.Union([Type.Literal('ok'), Type.Literal('warn'), Type.Literal('fail')]);
9
9
  const Kind = Type.Union([Type.Literal('subscription'), Type.Literal('api')]);
10
10
  const Version = Type.Literal(1);
11
+ const NetworkProbeStatus = Type.Union([
12
+ Type.Literal('available'),
13
+ Type.Literal('unavailable'),
14
+ Type.Literal('error'),
15
+ ]);
11
16
  /** One Pending Decision of Unattended Mode (spec §3.37). */
12
17
  const PendingDecision = Type.Object({
13
18
  id: Str,
@@ -1498,6 +1503,52 @@ export const OUTPUT_SCHEMAS = {
1498
1503
  checkedAt: Type.String({
1499
1504
  description: 'When this offline diagnosis ran (ISO), not the Guard cache time.',
1500
1505
  }),
1506
+ system: Type.Object({
1507
+ warp: Type.Object({
1508
+ status: NetworkProbeStatus,
1509
+ state: Type.Union([
1510
+ Type.Literal('connected'),
1511
+ Type.Literal('disconnected'),
1512
+ Type.Literal('unknown'),
1513
+ ]),
1514
+ networkHealthy: Type.Optional(Type.Boolean()),
1515
+ error: Type.Optional(Str),
1516
+ }),
1517
+ proxy: Type.Object({
1518
+ status: NetworkProbeStatus,
1519
+ pacEnabled: Type.Boolean(),
1520
+ autoDiscoveryEnabled: Type.Boolean(),
1521
+ protocols: Type.Array(Type.Object({
1522
+ protocol: Type.Union([Type.Literal('http'), Type.Literal('https'), Type.Literal('socks')]),
1523
+ enabled: Type.Boolean(),
1524
+ host: Type.Optional(Type.String({ description: 'Loopback only; every other host is redacted.' })),
1525
+ port: Type.Optional(Type.Integer()),
1526
+ })),
1527
+ exceptionCount: Type.Optional(Type.Integer()),
1528
+ error: Type.Optional(Str),
1529
+ }),
1530
+ dns: Type.Object({
1531
+ status: NetworkProbeStatus,
1532
+ nameservers: Type.Array(Str),
1533
+ error: Type.Optional(Str),
1534
+ }),
1535
+ route: Type.Object({
1536
+ status: NetworkProbeStatus,
1537
+ interface: Type.Optional(Str),
1538
+ gateway: Type.Optional(Str),
1539
+ error: Type.Optional(Str),
1540
+ }),
1541
+ }),
1542
+ localProxyCandidates: Type.Array(Type.Object({
1543
+ label: Type.String({
1544
+ description: 'The common configuration for this port, not an identified process.',
1545
+ }),
1546
+ protocol: Str,
1547
+ host: Str,
1548
+ port: Type.Integer(),
1549
+ reachable: Type.Boolean({ description: 'TCP connect only; not proof of upstream connectivity.' }),
1550
+ error: Type.Optional(Str),
1551
+ })),
1501
1552
  targets: Type.Array(Type.Object({
1502
1553
  url: Type.String({
1503
1554
  description: 'The Guard trace address whose cached result is shown; it is not requested.',
@@ -26,13 +26,14 @@ export async function pickTaskAccount(rt, opts = {}) {
26
26
  const a = await rt.resolve(opts.account);
27
27
  if (opts.family && a.family !== opts.family)
28
28
  throw new UserError('Choose an account of the requested family; run `sideby list`.');
29
- if (a.kind === 'api' || (await rt.status(a)).login === 'logged-in')
29
+ // A named Account runs unless known to be signed out: an `unknown` one (a Keychain sign-in) asks in its Host.
30
+ if (a.kind === 'api' || (await rt.status(a)).login !== 'logged-out')
30
31
  return { account: a };
31
32
  return { reason: 'none-signed-in' };
32
33
  }
33
- // A remembered choice may be an API Account; only the automatic pick below skips them.
34
+ // A remembered choice may be an API Account or one of unknown sign-in; only the automatic pick below skips them.
34
35
  const preferred = all.find((a) => a.ref === rt.config.ask?.account);
35
- if (preferred && (preferred.kind === 'api' || (await rt.status(preferred)).login === 'logged-in'))
36
+ if (preferred && (preferred.kind === 'api' || (await rt.status(preferred)).login !== 'logged-out'))
36
37
  return { account: preferred };
37
38
  if (!all.length)
38
39
  return { reason: 'no-accounts' };
@@ -17,7 +17,6 @@ export const COMMAND_GROUPS = [
17
17
  { id: 'help', title: { en: 'Help, AI and plugins', zh: '帮助、AI 与插件' } },
18
18
  ];
19
19
  export const CLI_COMMANDS = [
20
- // ---------- Accounts ----------
21
20
  {
22
21
  id: 'list',
23
22
  group: 'accounts',
@@ -203,7 +202,6 @@ export const CLI_COMMANDS = [
203
202
  zh: '恢复默认顺序,保留置顶和隐藏',
204
203
  },
205
204
  },
206
- // ---------- Start and open ----------
207
205
  {
208
206
  id: 'run',
209
207
  group: 'start',
@@ -280,7 +278,6 @@ export const CLI_COMMANDS = [
280
278
  zh: '自己指定 Chrome 用户,或让 sideby 重新找',
281
279
  },
282
280
  },
283
- // ---------- Short commands ----------
284
281
  {
285
282
  id: 'alias.add',
286
283
  group: 'shortcuts',
@@ -342,7 +339,6 @@ export const CLI_COMMANDS = [
342
339
  summary: { en: 'Make new terminals load your short commands', zh: '让新开的终端自动加载短命令' },
343
340
  example: 'sideby shell-init setup',
344
341
  },
345
- // ---------- Quota and usage ----------
346
342
  {
347
343
  id: 'quota',
348
344
  group: 'quota',
@@ -400,7 +396,6 @@ export const CLI_COMMANDS = [
400
396
  example: 'sideby tune claude',
401
397
  feature: 'page.tuning',
402
398
  },
403
- // ---------- Auto Handoff ----------
404
399
  {
405
400
  id: 'handoff.status',
406
401
  group: 'handoff',
@@ -460,7 +455,6 @@ export const CLI_COMMANDS = [
460
455
  help: 'remove it',
461
456
  summary: { en: "Remove Grok's handoff hook file", zh: '删掉 Grok 的接力 hook 文件' },
462
457
  },
463
- // ---------- Sessions and messages ----------
464
458
  {
465
459
  id: 'sessions',
466
460
  group: 'sessions',
@@ -556,7 +550,6 @@ export const CLI_COMMANDS = [
556
550
  example: 'sideby progress on --every 10',
557
551
  feature: 'setting.progress',
558
552
  },
559
- // ---------- Health and safety ----------
560
553
  {
561
554
  id: 'doctor',
562
555
  group: 'health',
@@ -615,7 +608,6 @@ export const CLI_COMMANDS = [
615
608
  example: 'sideby unattended wait 30',
616
609
  feature: 'action.unattended-wait',
617
610
  },
618
- // ---------- Panel and app ----------
619
611
  {
620
612
  id: 'ui',
621
613
  group: 'panel',
@@ -705,7 +697,6 @@ export const CLI_COMMANDS = [
705
697
  help: 'your own Themes (JSON, colors only)',
706
698
  summary: { en: 'Import, export or remove your own themes', zh: '导入、导出或删除自己的主题' },
707
699
  },
708
- // ---------- Settings and updates ----------
709
700
  {
710
701
  id: 'config.get',
711
702
  group: 'settings',
@@ -782,7 +773,6 @@ export const CLI_COMMANDS = [
782
773
  zh: '给 sideby 开发者:在本地构建和 npm 包之间切换',
783
774
  },
784
775
  },
785
- // ---------- Help, AI and plugins ----------
786
776
  {
787
777
  id: 'commands',
788
778
  group: 'help',
@@ -1,4 +1,5 @@
1
1
  import { networkInterfaces } from 'node:os';
2
+ export { proxyFor, redactedProxy, routeLabel } from 'network-portal/proxy';
2
3
  /** Variables a launched Host reads for its proxy; the check uses the same ones, so it takes the same route. */
3
4
  export declare const PROXY_VARS: readonly ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy'];
4
5
  /** What `network-hook` reads from the session's environment; set by sideby at Launch. */
@@ -68,12 +69,6 @@ export interface Verdict {
68
69
  type Env = Record<string, string | undefined>;
69
70
  export type TraceFetcher = (url: string, env: Env, timeoutMs: number) => Promise<string>;
70
71
  export type Sleep = (ms: number) => Promise<unknown>;
71
- /** The proxy a request to `url` goes through under `env`, or null for a direct connection. */
72
- export declare function proxyFor(url: string, env: Env): string | null;
73
- /** The selected route safe to show: scheme, hostname and port only, or `direct`; never credentials or a path. */
74
- export declare function redactedProxy(proxy: string | null): string;
75
- /** The route `url` selects under `env`, safe for an error, diagnostic result or AI fact. */
76
- export declare const routeLabel: (url: string, env: Env) => string;
77
72
  /** The key a cached result is kept under: the URL and the proxy settings, never their values in clear. */
78
73
  export declare function cacheKey(url: string, env: Env): string;
79
74
  /** A hash of the machine's own network addresses; it changes with Wi-Fi, a VPN or a TUN device. */
@@ -140,4 +135,3 @@ export declare function blockMessage(v: Pick<Verdict, 'status' | 'entry' | 'atte
140
135
  zh: boolean;
141
136
  proxy?: string;
142
137
  }): string;
143
- export {};
@@ -1,6 +1,7 @@
1
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.
2
+ // and tool call, so it imports only Node built-ins, network-portal/proxy (zero runtime dependencies) and core/fs-safe.ts.
3
+ // It asks the vendor's own `/cdn-cgi/trace` through the Host's proxy settings, keeps the country and a hash of the
4
+ // address, and decides.
4
5
  import { createHash } from 'node:crypto';
5
6
  import { mkdir, readFile } from 'node:fs/promises';
6
7
  import { request as httpRequest } from 'node:http';
@@ -9,7 +10,9 @@ import { networkInterfaces } from 'node:os';
9
10
  import { join } from 'node:path';
10
11
  import { setTimeout as delay } from 'node:timers/promises';
11
12
  import { connect as tlsConnect } from 'node:tls';
13
+ import { proxyFor } from 'network-portal/proxy';
12
14
  import { writeFileAtomic } from './fs-safe.js';
15
+ export { proxyFor, redactedProxy, routeLabel } from 'network-portal/proxy';
13
16
  /** Variables a launched Host reads for its proxy; the check uses the same ones, so it takes the same route. */
14
17
  export const PROXY_VARS = [
15
18
  'HTTPS_PROXY',
@@ -74,42 +77,10 @@ export const FRESH_MS = 60_000;
74
77
  /** Up to this age a tool call goes on while a detached process refreshes the result. */
75
78
  export const STALE_MS = 5 * 60_000;
76
79
  const sha = (s) => createHash('sha256').update(s).digest('hex');
77
- /** The proxy a request to `url` goes through under `env`, or null for a direct connection. */
78
- export function proxyFor(url, env) {
79
- const host = new URL(url).hostname.toLowerCase();
80
- const no = env.NO_PROXY ?? env.no_proxy ?? '';
81
- for (const raw of no.split(',')) {
82
- const p = raw.trim().toLowerCase().replace(/:\d+$/, '');
83
- if (!p)
84
- continue;
85
- if (p === '*')
86
- return null;
87
- const bare = p.replace(/^\*?\./, '');
88
- if (host === bare || host.endsWith(`.${bare}`))
89
- return null;
90
- }
91
- const v = env.HTTPS_PROXY || env.https_proxy || env.ALL_PROXY || env.all_proxy;
92
- return v ? v.trim() : null;
93
- }
94
- /** The selected route safe to show: scheme, hostname and port only, or `direct`; never credentials or a path. */
95
- export function redactedProxy(proxy) {
96
- if (!proxy)
97
- return 'direct';
98
- try {
99
- const p = new URL(proxy.includes('://') ? proxy : `http://${proxy}`);
100
- if (!p.hostname)
101
- return 'invalid';
102
- return `${p.protocol}//${p.host}`;
103
- }
104
- catch {
105
- return 'invalid';
106
- }
107
- }
108
- /** The route `url` selects under `env`, safe for an error, diagnostic result or AI fact. */
109
- export const routeLabel = (url, env) => redactedProxy(proxyFor(url, env));
110
80
  /** The key a cached result is kept under: the URL and the proxy settings, never their values in clear. */
111
81
  export function cacheKey(url, env) {
112
- return sha(JSON.stringify([url, ...PROXY_VARS.map((k) => env[k] ?? '')])).slice(0, 32);
82
+ // Version the routing algorithm: an older direct result must not authorize a route the new rules send through a proxy.
83
+ return sha(JSON.stringify(['proxy-selection-v2', url, ...PROXY_VARS.map((k) => env[k] ?? '')])).slice(0, 32);
113
84
  }
114
85
  /** A hash of the machine's own network addresses; it changes with Wi-Fi, a VPN or a TUN device. */
115
86
  export function netPrint(read = networkInterfaces) {
@@ -137,7 +137,7 @@ export declare const recency: (ageMs: number) => number;
137
137
  /** The words of a search; `"two words"` in double quotes is one phrase, matched as written. */
138
138
  export declare const splitWords: (q: string | undefined) => string[];
139
139
  /**
140
- * Sessions matching `q`, best first (relevance times a recency boost that halves every 7 days), or newest first
140
+ * Sessions matching `q`, best first (relevance times a recency boost that is half at 30 days), or newest first
141
141
  * without words. Answers from what is built; `wait` waits for the current sync first (the CLI's first run).
142
142
  * `live` names Sessions running now, as `<account>\0<sessionId>`.
143
143
  */
@@ -251,9 +251,9 @@ export async function syncHistory(rt, opts = {}) {
251
251
  if (s.retired)
252
252
  return;
253
253
  let input;
254
- // A Session id goes into a resume command the user may run, so only plain ids are kept.
255
254
  if (parsed)
256
255
  parsed.parent ??= file.parent;
256
+ // A Session id goes into a resume command the user may run, so only plain ids are kept.
257
257
  if (parsed && SAFE_ID.test(parsed.sessionId) && (!parsed.parent || SAFE_ID.test(parsed.parent))) {
258
258
  const p = await projects.resolve(parsed.cwd, parsed.gitRoot);
259
259
  input = {
@@ -600,7 +600,7 @@ function toSession(rt, r, labels, names, extra) {
600
600
  /** The words of a search; `"two words"` in double quotes is one phrase, matched as written. */
601
601
  export const splitWords = (q) => [...(q ?? '').matchAll(/"([^"]*)"?|(\S+)/g)].map((m) => (m[1] ?? m[2] ?? '').trim()).filter(Boolean);
602
602
  /**
603
- * Sessions matching `q`, best first (relevance times a recency boost that halves every 7 days), or newest first
603
+ * Sessions matching `q`, best first (relevance times a recency boost that is half at 30 days), or newest first
604
604
  * without words. Answers from what is built; `wait` waits for the current sync first (the CLI's first run).
605
605
  * `live` names Sessions running now, as `<account>\0<sessionId>`.
606
606
  */
@@ -1,7 +1,9 @@
1
+ import { type ListenerProbe, type NetworkDiagnosis, type NetworkSystemDeps } from 'network-portal';
1
2
  import type { Account, Env } from '../types.ts';
2
3
  import type { Config } from './config.ts';
3
4
  import { type EgressStatus, type TraceFetcher, type Verdict } from './egress.ts';
4
5
  import { type SessionHookPart } from './session-hooks.ts';
6
+ export { type ListenerProbe, type NetworkCommandRunner, type NetworkDiagnoseTarget, type NetworkDiagnosis, type NetworkGuardFact, type NetworkGuardStatus, type NetworkLocalProxyCandidate, type NetworkProbeStatus, type NetworkProxyProtocol, type NetworkSystemDeps, type NetworkSystemInfo, probeListener, readNetworkSystem, } from 'network-portal';
5
7
  /** Families Network Guard covers in v1. */
6
8
  export declare const GUARDED_FAMILIES: readonly ['claude', 'codex'];
7
9
  export declare const TRACE: {
@@ -84,7 +86,7 @@ export declare function withClaudeNetworkHooks(hookArgs: readonly string[], stat
84
86
  export declare function withoutArgs(args: readonly string[], drop: readonly string[]): string[];
85
87
  /**
86
88
  * Where one Account is checked, or why not: an API Account (`api`), or an endpoint set to a third party.
87
- * `at-launch` is no longer given (API Accounts were once checked at Launch); it stays in the type for readers.
89
+ * `at-launch` is never given (API Accounts are not checked, ADR-0079); it stays in the type for `--json` readers.
88
90
  */
89
91
  export interface NetworkAccountRow {
90
92
  ref: string;
@@ -125,42 +127,10 @@ export declare function networkOverview(opts: {
125
127
  accounts: NetworkAccountRow[];
126
128
  }>;
127
129
  export type NetworkOverview = Awaited<ReturnType<typeof networkOverview>>;
128
- export type ListenerProbe = (host: string, port: number, timeoutMs: number) => Promise<{
129
- reachable: boolean;
130
- error?: string;
131
- }>;
132
- /** A local TCP connection attempt; its result says nothing about the proxy protocol or upstream connectivity. */
133
- export declare const probeListener: ListenerProbe;
134
- export interface NetworkDiagnosis {
135
- /** When this offline diagnosis was made (ISO), not when the cached Guard entries were checked. */
136
- checkedAt: string;
137
- targets: {
138
- url: string;
139
- /** The current process's selected proxy with credentials/path removed, or `direct`. */
140
- proxy: string;
141
- /** Whether Network Guard can use this route: HTTP CONNECT only; direct needs no proxy protocol. */
142
- guardSupport: 'direct' | 'http-connect' | 'unsupported' | 'invalid';
143
- /** Null for direct, a remote proxy, an unreadable address, or a non-HTTP proxy without an explicit port. */
144
- listener: null | {
145
- host: string;
146
- port: number;
147
- reachable: boolean;
148
- error?: string;
149
- };
150
- guard: {
151
- status: NetworkTargetStatus['status'];
152
- loc?: string;
153
- checkedAt?: string;
154
- error?: string;
155
- };
156
- }[];
157
- }
158
- /**
159
- * Offline, read-only diagnosis: cached Guard state plus the route visible to this sideby process and a local TCP probe.
160
- * Unlike `networkOverview({check:true})`, it never calls a trace fetcher, resolves a remote proxy, or writes a cache entry.
161
- */
130
+ /** The package owns generic probes; sideby supplies only its accounts and cached Guard state. */
162
131
  export declare function networkDiagnose(opts: Parameters<typeof networkOverview>[0] & {
163
132
  probe?: ListenerProbe;
133
+ system?: NetworkSystemDeps;
164
134
  }): Promise<NetworkDiagnosis>;
165
135
  export interface NetworkChange {
166
136
  guard?: boolean;
@@ -1,13 +1,14 @@
1
1
  // Network Guard (spec §3.35, ADR-0053): which address each Account's Egress is checked at, the check before a
2
2
  // Launch, and the hooks that keep checking inside a session sideby starts. The check itself is core/egress.ts.
3
3
  import { mkdir, readFile } from 'node:fs/promises';
4
- import { createConnection } from 'node:net';
5
4
  import { join } from 'node:path';
6
- import { blockMessage, cacheKey, judge, NETWORK_ENV, prefersChinese, proxyFor, readEntry, refresh, routeLabel, verdict, } from './egress.js';
5
+ import { diagnoseNetwork, } from 'network-portal';
6
+ import { blockMessage, cacheKey, judge, NETWORK_ENV, prefersChinese, readEntry, refresh, routeLabel, verdict, } from './egress.js';
7
7
  import { UserError } from './errors.js';
8
8
  import { writeFileAtomic } from './fs-safe.js';
9
9
  import { sessionHookArgs, sidebyHookCommand, withClaudeHooks } from './session-hooks.js';
10
10
  import { inCi } from './update.js';
11
+ export { probeListener, readNetworkSystem, } from 'network-portal';
11
12
  /** Families Network Guard covers in v1. */
12
13
  export const GUARDED_FAMILIES = ['claude', 'codex'];
13
14
  export const TRACE = {
@@ -266,67 +267,30 @@ export async function networkOverview(opts) {
266
267
  accounts,
267
268
  };
268
269
  }
269
- /** A local TCP connection attempt; its result says nothing about the proxy protocol or upstream connectivity. */
270
- export const probeListener = (host, port, timeoutMs) => new Promise((resolve) => {
271
- const socket = createConnection({ host, port });
272
- let done = false;
273
- const finish = (reachable, error) => {
274
- if (done)
275
- return;
276
- done = true;
277
- socket.destroy();
278
- resolve({ reachable, ...(error ? { error } : {}) });
279
- };
280
- socket.setTimeout(timeoutMs);
281
- socket.once('connect', () => finish(true));
282
- socket.once('timeout', () => finish(false, 'timeout'));
283
- socket.once('error', (e) => finish(false, e.code || 'failed'));
284
- });
285
- /**
286
- * Offline, read-only diagnosis: cached Guard state plus the route visible to this sideby process and a local TCP probe.
287
- * Unlike `networkOverview({check:true})`, it never calls a trace fetcher, resolves a remote proxy, or writes a cache entry.
288
- */
270
+ /** The package owns generic probes; sideby supplies only its accounts and cached Guard state. */
289
271
  export async function networkDiagnose(opts) {
290
272
  const overview = await networkOverview({ ...opts, check: false });
291
- const targets = [];
292
- for (const target of overview.targets) {
293
- const raw = proxyFor(target.url, opts.env);
294
- const proxy = routeLabel(target.url, opts.env);
295
- let guardSupport = raw ? 'invalid' : 'direct';
296
- let listener = null;
297
- if (raw && proxy !== 'invalid') {
298
- // `proxy` is already redacted; parse this rather than the raw environment value at the output boundary.
299
- const parsed = new URL(proxy.includes('://') ? proxy : `http://${proxy}`);
300
- guardSupport = parsed.protocol === 'http:' ? 'http-connect' : 'unsupported';
301
- // Offline diagnosis never resolves or connects to a remote proxy. URL keeps IPv6 brackets in `hostname`;
302
- // `createConnection` needs the bare address. Only HTTP has a defined default port for this check.
303
- const host = parsed.hostname.startsWith('[') ? parsed.hostname.slice(1, -1) : parsed.hostname;
304
- const local = host === 'localhost' || host === '::1' || /^127(?:\.\d{1,3}){3}$/.test(host);
305
- const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'http:' ? 80 : null;
306
- if (local && port !== null)
307
- listener = {
308
- host,
309
- port,
310
- ...(await (opts.probe ?? probeListener)(host, port, 1000).catch(() => ({
311
- reachable: false,
312
- error: 'failed',
313
- }))),
314
- };
315
- }
316
- targets.push({
273
+ const diagnosis = await diagnoseNetwork({
274
+ env: opts.env,
275
+ targets: overview.targets.map((target) => ({
317
276
  url: target.url,
318
- proxy,
319
- guardSupport,
320
- listener,
321
277
  guard: {
322
278
  status: target.status,
323
279
  ...(target.loc ? { loc: target.loc } : {}),
324
280
  ...(target.checkedAt ? { checkedAt: target.checkedAt } : {}),
325
281
  ...(target.error ? { error: target.error } : {}),
326
282
  },
327
- });
328
- }
329
- return { checkedAt: (opts.now?.() ?? new Date()).toISOString(), targets };
283
+ })),
284
+ ...(opts.now ? { now: opts.now } : {}),
285
+ ...(opts.probe ? { probe: opts.probe } : {}),
286
+ ...(opts.system ? { system: opts.system } : {}),
287
+ });
288
+ // The generic package exposes origins only; sideby v1 keeps the exact Guard trace URLs its CLI callers correlate.
289
+ const traceUrls = new Map(overview.targets.map((target) => [new URL(target.url).origin, target.url]));
290
+ return {
291
+ ...diagnosis,
292
+ targets: diagnosis.targets.map((target) => ({ ...target, url: traceUrls.get(target.url) ?? target.url })),
293
+ };
330
294
  }
331
295
  /** Country codes as config keeps them: upper case, two letters, each once, in the order given. */
332
296
  export function normalizeAllow(codes) {
@@ -185,13 +185,20 @@ export async function taskChoices(rt) {
185
185
  const pick = await pickTaskAccount(rt);
186
186
  const signedIn = [];
187
187
  const api = [];
188
+ // `unknown`: the sign-in is in the Keychain, which sideby never reads (agy); offered, since only the Host can tell.
189
+ const unknown = [];
188
190
  const signedOut = [];
189
191
  const all = [...(await rt.accounts())].sort((a, b) => (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));
190
192
  for (const a of all) {
191
- if (a.kind === 'api')
193
+ if (a.kind === 'api') {
192
194
  api.push({ ref: a.ref, label: `${a.ref} · API`, signedIn: true });
193
- else if ((await rt.status(a)).login === 'logged-in')
195
+ continue;
196
+ }
197
+ const login = (await rt.status(a)).login;
198
+ if (login === 'logged-in')
194
199
  signedIn.push({ ref: a.ref, label: a.ref, signedIn: true });
200
+ else if (login === 'unknown')
201
+ unknown.push({ ref: a.ref, label: a.ref, signedIn: true });
195
202
  else
196
203
  signedOut.push({ ref: a.ref, label: a.ref, signedIn: false });
197
204
  }
@@ -200,7 +207,7 @@ export async function taskChoices(rt) {
200
207
  return {
201
208
  schemaVersion: 1,
202
209
  account: 'account' in pick ? pick.account.ref : null,
203
- accounts: [...signedIn, ...api, ...signedOut],
210
+ accounts: [...signedIn, ...api, ...unknown, ...signedOut],
204
211
  terminal: t.guess.id,
205
212
  terminals: t.installed.map((i) => ({ id: i.id, label: name(i.id) })),
206
213
  reason: 'reason' in pick ? pick.reason : null,
@@ -22,7 +22,6 @@ const builtin = (id) => BUILTIN_THEMES.find((t) => t.id === (Object.hasOwn(RENAM
22
22
  export const NO_THEME = 'default';
23
23
  const reserved = (id) => Boolean(builtin(id)) || id === NO_THEME;
24
24
  const DEFAULT = builtin(DEFAULT_THEME_ID);
25
- // ---- Reading and checking a Theme File
26
25
  /** Checks parsed JSON as a Theme File. Problems make it unusable; warnings are keys that were ignored. */
27
26
  export function checkThemeData(data) {
28
27
  const problems = [];
@@ -102,7 +101,6 @@ export async function readThemeFile(path) {
102
101
  return { problems: [`cannot be read (${e.code ?? 'error'})`], warnings: [] };
103
102
  }
104
103
  }
105
- // ---- Listing
106
104
  export async function listThemes(paths) {
107
105
  const out = BUILTIN_THEMES.map((t) => ({
108
106
  id: t.id,
@@ -151,7 +149,6 @@ export async function listThemes(paths) {
151
149
  return out;
152
150
  }
153
151
  const swatchesOf = (l, d) => [l.bg, l.accentSoft, l.primary, d.bg].filter((c) => typeof c === 'string');
154
- // ---- Resolving a Theme to tokens
155
152
  /** A Theme File's colors before the contrast check: base, then accent roles, then the file's own tokens. */
156
153
  export function themeColors(theme) {
157
154
  const base = builtin(theme.base ?? DEFAULT_THEME_ID);
@@ -192,7 +189,6 @@ function adjust(id, c) {
192
189
  }
193
190
  return { id, light, dark, adjusted };
194
191
  }
195
- // ---- Accent roles from one color
196
192
  // Lightness and chroma of the maintainer's leaf scales, step 1 to 12; step 9 becomes the accent itself.
197
193
  const SCALE_LIGHT = [
198
194
  [0.988, 0.014],
@@ -324,7 +320,6 @@ function passing(fg, bg, min) {
324
320
  }
325
321
  return darker ? '#000000' : '#ffffff';
326
322
  }
327
- // ---- Switching
328
323
  /** Sets `panel.colorTheme`, keeping what it was so `undo` can put it back. */
329
324
  export async function useTheme(paths, id) {
330
325
  id = builtin(id)?.id ?? id;
@@ -360,7 +355,6 @@ export async function undoTheme(paths) {
360
355
  await rm(undoFile(paths), { force: true });
361
356
  return { before: now, after: rec.before };
362
357
  }
363
- // ---- Files
364
358
  /** Writes a checked Theme File into the themes folder. */
365
359
  export async function saveThemeFile(paths, id, theme) {
366
360
  if (!THEME_ID_RE.test(id) || reserved(id))
@@ -417,7 +411,6 @@ export async function previewColors(paths) {
417
411
  return undefined;
418
412
  }
419
413
  }
420
- // ---- OKLCH and WCAG contrast
421
414
  const lin = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
422
415
  const unlin = (c) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
423
416
  const rgb = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16) / 255);
@@ -69,12 +69,12 @@ export interface InstallMethod {
69
69
  /** npm only: the prefix whose `lib/node_modules` holds sideby. */
70
70
  prefix?: string;
71
71
  }
72
- /** Swapped in tests through `bindUpdateDeps`; the real machine otherwise. */
73
72
  /**
74
73
  * Whether `sideby autostart --refresh --json` rewrote the login item: it exits 0 also when nothing changed or the
75
74
  * rewrite was refused, so only its `changed: true` counts.
76
75
  */
77
76
  export declare function autostartRefreshed(code: number | null, stdout: string): boolean;
77
+ /** Swapped in tests through `bindUpdateDeps`; the real machine otherwise. */
78
78
  export interface UpdateDeps {
79
79
  fetch: typeof fetch;
80
80
  now: () => Date;