sideby 0.42.2 → 0.44.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.
Files changed (66) hide show
  1. package/ai-tasks.json +10 -0
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +54 -13
  4. package/dist/src/cli/json-schemas.js +65 -1
  5. package/dist/src/cli/main.js +11 -4
  6. package/dist/src/core/ask.d.ts +8 -14
  7. package/dist/src/core/ask.js +66 -30
  8. package/dist/src/core/egress.d.ts +5 -0
  9. package/dist/src/core/egress.js +32 -2
  10. package/dist/src/core/file-memo.d.ts +2 -0
  11. package/dist/src/core/file-memo.js +20 -0
  12. package/dist/src/core/handoff-run.js +41 -8
  13. package/dist/src/core/handoff-select.d.ts +5 -0
  14. package/dist/src/core/handoff-select.js +1 -1
  15. package/dist/src/core/handoff.d.ts +78 -1
  16. package/dist/src/core/handoff.js +100 -9
  17. package/dist/src/core/history-index.d.ts +4 -0
  18. package/dist/src/core/history-index.js +1 -1
  19. package/dist/src/core/live-sessions.d.ts +5 -0
  20. package/dist/src/core/live-sessions.js +12 -1
  21. package/dist/src/core/memo-store.js +32 -8
  22. package/dist/src/core/network.d.ts +37 -0
  23. package/dist/src/core/network.js +65 -1
  24. package/dist/src/core/pick-commands.d.ts +7 -1
  25. package/dist/src/core/pick-commands.js +15 -3
  26. package/dist/src/core/pick-records.d.ts +26 -0
  27. package/dist/src/core/pick-records.js +81 -0
  28. package/dist/src/families/agy/history.d.ts +2 -0
  29. package/dist/src/families/agy/history.js +118 -0
  30. package/dist/src/families/agy/index.js +5 -0
  31. package/dist/src/families/agy/quota.d.ts +5 -1
  32. package/dist/src/families/agy/quota.js +111 -10
  33. package/dist/src/families/history.js +2 -1
  34. package/dist/src/families/quota-watch.d.ts +12 -0
  35. package/dist/src/families/quota-watch.js +24 -0
  36. package/dist/src/network/hook.js +4 -4
  37. package/dist/src/network/page-script.d.ts +40 -0
  38. package/dist/src/network/page-script.js +270 -0
  39. package/dist/src/network/page.d.ts +11 -0
  40. package/dist/src/network/page.js +189 -0
  41. package/dist/src/network/panel.d.ts +5 -0
  42. package/dist/src/network/panel.js +7 -0
  43. package/dist/src/panel/changes.d.ts +57 -0
  44. package/dist/src/panel/changes.js +178 -0
  45. package/dist/src/panel/handler.d.ts +59 -1
  46. package/dist/src/panel/handler.js +374 -99
  47. package/dist/src/panel/i18n.d.ts +49 -0
  48. package/dist/src/panel/i18n.js +100 -2
  49. package/dist/src/panel/page-logic.d.ts +37 -3
  50. package/dist/src/panel/page-logic.js +106 -12
  51. package/dist/src/panel/page-script.js +194 -27
  52. package/dist/src/panel/page-styles.js +18 -8
  53. package/dist/src/panel/page.js +3 -1
  54. package/dist/src/runtime.d.ts +55 -5
  55. package/dist/src/runtime.js +105 -12
  56. package/dist/src/types.d.ts +3 -2
  57. package/package.json +1 -1
  58. package/schemas/network-diagnose.json +196 -0
  59. package/schemas/next.json +67 -2
  60. package/skills/sideby/SKILL.md +3 -2
  61. package/skills/sideby/references/accounts.md +1 -1
  62. package/skills/sideby/references/ai-tasks.md +1 -1
  63. package/skills/sideby/references/handoff.md +6 -2
  64. package/skills/sideby/references/network.md +6 -1
  65. package/skills/sideby/references/quota.md +1 -1
  66. package/skills/sideby/references/sessions.md +1 -1
package/ai-tasks.json CHANGED
@@ -143,6 +143,16 @@
143
143
  { "en": "A message was blocked; help me check the proxy", "zh": "消息被拦了,帮我查查代理" }
144
144
  ]
145
145
  },
146
+ {
147
+ "id": "network-diagnose",
148
+ "native": true,
149
+ "title": { "en": "Let AI diagnose", "zh": "让 AI 诊断" },
150
+ "placeholder": {
151
+ "en": "No added text; the current diagnosis is included automatically",
152
+ "zh": "无需补充;会自动带上当前诊断"
153
+ },
154
+ "examples": []
155
+ },
146
156
  {
147
157
  "id": "update",
148
158
  "native": true,
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261122T154741-dff236"}
1
+ {"id":"20261123T103613-7b7f5c"}
@@ -29,7 +29,7 @@ import { SEARCH_CATALOG, searchCatalog } from '../core/search-catalog.js';
29
29
  import { SHELLS } from '../core/shell-init.js';
30
30
  import { clockText, daysText } from '../core/unattended-state.js';
31
31
  import { MODEL_NAME } from '../families/shared/model-args.js';
32
- import { AI_TASK_KINDS, hiddenIn, inDisplayOrder, pinnedIn, resetWhen, suggestAlias, suggestName, vendorAlias, withPinned, } from '../panel/page-logic.js';
32
+ import { AI_TASK_KINDS, hiddenIn, inDisplayOrder, networkDiagnoseTaskFacts, pinnedIn, resetWhen, suggestAlias, suggestName, vendorAlias, withPinned, } from '../panel/page-logic.js';
33
33
  import { createRuntime, UnknownFamilyError } from '../runtime.js';
34
34
  import { UsageError } from './args.js';
35
35
  import { ago, c, clock, compactNumber, quotaText, table, truncate, tuningLines, usageText } from './format.js';
@@ -659,7 +659,7 @@ async function runPick(rt, name, args, io, opts = {}) {
659
659
  : `sideby: session ${target.sessionId} is in ${target.account.ref}; starting it there`));
660
660
  return runAccount(rt, target.account.ref, target.args, io, opts);
661
661
  }
662
- const { choice, family } = await rt.pickChoice(name);
662
+ const { choice, family } = await rt.pickChoice(name, { record: true });
663
663
  if (choice.ref === null) {
664
664
  const now = rt.readContext().now;
665
665
  const why = choice.earliestReset
@@ -712,7 +712,12 @@ export async function cmdNext(a, io) {
712
712
  throw new UsageError('usage: sideby next <family> [--dry-run] [--include-api] [--ignore-network] [--unattended] [-- host args]');
713
713
  const includeApi = a.flags.has('include-api');
714
714
  const rt = await createRuntime();
715
- const plan = await rt.handoff(family, { includeApi });
715
+ // A preview (`--json`, `--dry-run`) reads the Pick Records; a start writes one for its pick (ADR-0083).
716
+ const preview = a.flags.has('json') || a.flags.has('dry-run');
717
+ const plan = await rt.handoff(family, {
718
+ includeApi,
719
+ picks: preview ? 'read' : (p) => (p.pick && p.hasQuota ? p.pick : null),
720
+ });
716
721
  if (a.flags.has('json')) {
717
722
  json(io, plan);
718
723
  return plan.pick && plan.hasQuota ? 0 : 1;
@@ -726,15 +731,17 @@ export async function cmdNext(a, io) {
726
731
  const closest = (e) => e.window
727
732
  ? `${e.window.label} ${e.window.usedPercent}% of ${e.window.limit}%`
728
733
  : `${Math.round(e.pressure ?? 0)}%`;
734
+ // Live Sessions of its login, Pick Records included: picks spread by the room each one leaves (ADR-0083).
735
+ const running = (e) => (e.liveSessions ? `; ${e.liveSessions} running` : '');
729
736
  const note = (e) => {
730
737
  if (e.sameLoginAs)
731
738
  return `same login as ${e.sameLoginAs}, which shares its quota; skipped`;
732
739
  if (e.skip?.reason === 'login-expired')
733
740
  return `sign-in expired; skipped, sign in with \`${e.skip.command}\``;
734
741
  if (e.state === 'ready')
735
- return `closest to its limit: ${closest(e)}`;
742
+ return `closest to its limit: ${closest(e)}${running(e)}`;
736
743
  if (e.state === 'unknown')
737
- return 'no quota data yet';
744
+ return `no quota data yet${running(e)}`;
738
745
  if (e.state === 'api')
739
746
  return includeApi ? 'API account, pay per use' : 'left out; add --include-api to use it';
740
747
  if (low(e)) {
@@ -783,13 +790,17 @@ export async function cmdNext(a, io) {
783
790
  io.err(c.yellow(`\nno ${family} account has quota data yet, so sideby cannot tell which one has room; ${setup ? `turn it on with \`sideby quota setup ${family}\`, or ` : ''}start one yourself, for example \`${runCmd}\`.`));
784
791
  return 1;
785
792
  }
786
- const reason = picked.state === 'ready'
787
- ? `furthest from its limits, ${closest(picked)}`
788
- : plan.tight
789
- ? `every ${family} account is past its limit (${plan.tight.limit}% of a 5-hour window, ${plan.tight.longLimit}% of a weekly one); this one has the most left, ${closest(picked)}`
790
- : picked.state === 'unknown'
791
- ? 'no account with known room; this one has no quota data yet'
792
- : 'API account, pay per use';
793
+ // A weekly window "7d" reads as "weekly"; any other Long Window by its label.
794
+ const longName = (label) => (label === '7d' ? 'weekly' : label);
795
+ const reason = plan.reason === 'expiring' && picked.expiring
796
+ ? `its ${longName(picked.expiring.label)} quota resets ${resetWhen(picked.expiring.resetsAt, now.getTime(), 'en')} with ${100 - picked.expiring.usedPercent}% left, so it goes first`
797
+ : picked.state === 'ready'
798
+ ? `the most room per running session, ${closest(picked)}${picked.liveSessions ? ` with ${picked.liveSessions} running` : ''}`
799
+ : plan.tight
800
+ ? `every ${family} account is past its limit (${plan.tight.limit}% of a 5-hour window, ${plan.tight.longLimit}% of a weekly one); this one has the most left, ${closest(picked)}`
801
+ : picked.state === 'unknown'
802
+ ? 'no account with known room; this one has no quota data yet'
803
+ : 'API account, pay per use';
793
804
  io.out(`\nNext: ${c.bold(plan.pick)} (${reason}).`);
794
805
  if (a.flags.has('dry-run')) {
795
806
  io.out(`Start it with \`${runCmd}\`.`);
@@ -2843,6 +2854,9 @@ export async function cmdAsk(a, io, runtime) {
2843
2854
  account: a.flags.get('account'),
2844
2855
  terminal: a.flags.get('terminal'),
2845
2856
  files: a.attach ?? [],
2857
+ ...(task === 'network-diagnose'
2858
+ ? { context: { networkDiagnose: networkDiagnoseTaskFacts(await rt.networkDiagnose()) } }
2859
+ : {}),
2846
2860
  };
2847
2861
  // The files are checked before anything else; `--print` lists them where they are and copies nothing.
2848
2862
  const preview = promptForTask(rt, input, await previewAttachments(rt, input));
@@ -4636,6 +4650,33 @@ export async function cmdNetwork(a, io) {
4636
4650
  const { setNetwork } = await import('../core/network.js');
4637
4651
  const rt = await createRuntime();
4638
4652
  const asJson = a.flags.has('json');
4653
+ if (sub === 'diagnose') {
4654
+ if (rest.length || a.rest.length)
4655
+ throw new UsageError('usage: sideby network diagnose [--json]');
4656
+ const d = await rt.networkDiagnose();
4657
+ if (asJson) {
4658
+ json(io, d);
4659
+ return 0;
4660
+ }
4661
+ io.out(`Offline diagnosis: checked ${clock(d.checkedAt, rt.readContext().now)}; no online trace was sent.`);
4662
+ for (const t of d.targets) {
4663
+ io.out(`${new URL(t.url).hostname}: ${t.proxy}`);
4664
+ if (t.listener)
4665
+ io.out(` TCP listener ${t.listener.reachable ? c.green('reachable') : c.red('not reachable')} (${t.listener.host}:${t.listener.port}${t.listener.error ? `, ${t.listener.error}` : ''}).`);
4666
+ else if (t.guardSupport !== 'direct')
4667
+ io.out(' No local TCP listener probe (remote proxy, invalid address, or no explicit port).');
4668
+ if (t.guardSupport === 'unsupported')
4669
+ io.out(c.yellow(' Network Guard supports HTTP CONNECT only; this proxy scheme is not supported. Configure an HTTP proxy or direct connection, then run `sideby network check`.'));
4670
+ else if (t.guardSupport === 'invalid')
4671
+ io.out(c.yellow(' The proxy address is invalid; correct it in the environment, then start a new session.'));
4672
+ io.out(` Guard cache: ${t.guard.status}${t.guard.loc ? `, ${t.guard.loc}` : ''}${t.guard.checkedAt ? `, checked ${clock(t.guard.checkedAt, rt.readContext().now)}` : ', not checked yet'}${t.guard.error ? `, ${t.guard.error}` : ''}.`);
4673
+ }
4674
+ if (!d.targets.length)
4675
+ io.out('No Claude or Codex trace target is configured.');
4676
+ io.out(c.dim('A reachable TCP listener does not prove that HTTP CONNECT, SOCKS or the upstream proxy works.'));
4677
+ io.out(c.cyan('For a fresh online country check, run `sideby network check`.'));
4678
+ return 0;
4679
+ }
4639
4680
  if (sub === 'on' || sub === 'off' || sub === 'allow') {
4640
4681
  if (sub !== 'allow' && rest.length)
4641
4682
  throw new UsageError(`usage: sideby network ${sub} [--yes]`);
@@ -4659,7 +4700,7 @@ export async function cmdNetwork(a, io) {
4659
4700
  return r.changed && !r.applied ? 10 : 0;
4660
4701
  }
4661
4702
  if ((sub !== undefined && sub !== 'check') || rest.length || a.rest.length)
4662
- throw new UsageError('usage: sideby network [check] | sideby network on|off [--yes] | sideby network allow <country>... [--yes]');
4703
+ throw new UsageError('usage: sideby network [check|diagnose] | sideby network on|off [--yes] | sideby network allow <country>... [--yes]');
4663
4704
  const s = await rt.networkStatus(sub === 'check' ? { check: true } : {});
4664
4705
  if (asJson) {
4665
4706
  json(io, s);
@@ -885,13 +885,30 @@ export const OUTPUT_SCHEMAS = {
885
885
  description: 'Used percent of the fullest window not reset yet; null without quota.',
886
886
  }),
887
887
  limitUse: Type.Union([Type.Number(), Type.Null()], {
888
- description: 'Limit Use: the percent of its own Takeover Limit that the closest window has used (a weekly 87% under 95 is 91.6); null without quota. Ready accounts rank by it, lowest first.',
888
+ description: 'Limit Use: the percent of its own Takeover Limit that the closest window has used (a weekly 87% under 95 is 91.6); null without quota. Ready accounts rank by the room it leaves per running session, (100 - limitUse) / (liveSessions + 1), highest first; a Last Resort by it, lowest first.',
889
889
  }),
890
+ liveSessions: Type.Number({
891
+ description: "The Live Sessions of the account's Same Login group, plus Pick Records: starts sideby made in the last 2 minutes that have not shown up as a Live Session yet (ADR-0083).",
892
+ }),
893
+ expiring: Type.Optional(Type.Object({
894
+ label: Type.String({ description: 'Such as `7d`.' }),
895
+ usedPercent: Type.Number({ description: 'Rounded.' }),
896
+ resetsAt: Str,
897
+ }, {
898
+ description: 'For ready: its counted weekly (or longer) window that resets within 24 hours; such an account ranks before every other ready one, since that room is lost at the reset (ADR-0083).',
899
+ })),
890
900
  window: Type.Optional(Type.Object({
891
901
  label: Type.String({ description: 'Such as `5h` or `7d`.' }),
892
902
  usedPercent: Type.Number({ description: 'Rounded.' }),
893
903
  limit: Type.Number({ description: "This window's Takeover Limit in percent." }),
894
904
  }, { description: 'The window closest to its own Takeover Limit; absent when none is open.' })),
905
+ windows: Type.Optional(Type.Array(Type.Object({
906
+ label: Type.String({ description: 'Such as `5h` or `7d`.' }),
907
+ usedPercent: Type.Number({ description: 'Rounded; what is left is 100 minus it.' }),
908
+ resetsAt: Str,
909
+ }), {
910
+ description: 'Every counted window (no model name) that has not reset yet, so a caller can show what the pick has left; absent when none is open.',
911
+ })),
895
912
  resetsAt: Type.Optional(Type.String({
896
913
  description: 'For full: when it is usable again. With a window used up, when those windows reset; otherwise when every window is under its Takeover Limit again.',
897
914
  })),
@@ -925,6 +942,9 @@ export const OUTPUT_SCHEMAS = {
925
942
  earliestReset: Type.Optional(Type.Object({ ref: Str, at: Str }, {
926
943
  description: 'Set when nothing can be picked and some accounts are full (every one has a window used up): the first to come back.',
927
944
  })),
945
+ reason: Type.Optional(Type.Union([Type.Literal('expiring'), Type.Literal('room')], {
946
+ description: 'Why a ready pick goes first (ADR-0083): expiring, its weekly room resets within 24 hours; room, it has the most room per running session.',
947
+ })),
928
948
  }, { title: 'sideby next --json' }),
929
949
  'quota-setup': Type.Object({ schemaVersion: Version, family: Str, applied: Type.Boolean(), plan: QuotaSetupPlan }, { title: 'sideby quota setup --json' }),
930
950
  'quota-reset': Type.Object({
@@ -1473,6 +1493,50 @@ export const OUTPUT_SCHEMAS = {
1473
1493
  })),
1474
1494
  })),
1475
1495
  }, { title: 'sideby network [check] --json' }),
1496
+ 'network-diagnose': Type.Object({
1497
+ schemaVersion: Version,
1498
+ checkedAt: Type.String({
1499
+ description: 'When this offline diagnosis ran (ISO), not the Guard cache time.',
1500
+ }),
1501
+ targets: Type.Array(Type.Object({
1502
+ url: Type.String({
1503
+ description: 'The Guard trace address whose cached result is shown; it is not requested.',
1504
+ }),
1505
+ proxy: Type.String({
1506
+ description: 'Selected proxy reduced to scheme, hostname and port, or direct/invalid.',
1507
+ }),
1508
+ guardSupport: Type.Union([
1509
+ Type.Literal('direct'),
1510
+ Type.Literal('http-connect'),
1511
+ Type.Literal('unsupported'),
1512
+ Type.Literal('invalid'),
1513
+ ], { description: 'Guard supports direct and HTTP CONNECT; SOCKS/HTTPS proxies are unsupported.' }),
1514
+ listener: Type.Union([
1515
+ Type.Null(),
1516
+ Type.Object({
1517
+ host: Str,
1518
+ port: Type.Integer(),
1519
+ reachable: Type.Boolean({
1520
+ description: 'TCP connect only; not proof that the proxy protocol works.',
1521
+ }),
1522
+ error: Type.Optional(Str),
1523
+ }),
1524
+ ], {
1525
+ description: 'Local loopback TCP listener only; null for direct, remote or invalid proxies, and non-HTTP proxies without an explicit port.',
1526
+ }),
1527
+ guard: Type.Object({
1528
+ status: Type.Union([
1529
+ Type.Literal('ok'),
1530
+ Type.Literal('blocked'),
1531
+ Type.Literal('unknown'),
1532
+ Type.Literal('not-checked'),
1533
+ ]),
1534
+ loc: Type.Optional(Str),
1535
+ checkedAt: Type.Optional(Type.String({ description: 'When the cached Guard check ran (ISO).' })),
1536
+ error: Type.Optional(Str),
1537
+ }),
1538
+ })),
1539
+ }, { title: 'sideby network diagnose --json' }),
1476
1540
  'network-set': Type.Object({
1477
1541
  schemaVersion: Version,
1478
1542
  changed: Type.Boolean(),
@@ -316,7 +316,7 @@ Examples:
316
316
  sideby config unset panel.language --yes
317
317
  Exit: 0 shown, saved or nothing to change; 10 a change was shown and waits for --yes; 1 not a key, a value the key
318
318
  does not take, or the file changed meanwhile; 2 malformed command line.`,
319
- network: `sideby network [check] [--json]
319
+ network: `sideby network [check|diagnose] [--json]
320
320
  sideby network allow <country>... [--yes] [--json]
321
321
  sideby network on|off [--yes] [--json]
322
322
 
@@ -332,13 +332,17 @@ claude or codex directly) are not checked. API accounts are never checked.
332
332
 
333
333
  network shows the setting and the newest result per address (no request)
334
334
  network check asks every address now
335
+ network diagnose offline and read-only: redacted proxy or direct, local TCP listener, and cached Guard state
335
336
  allow sets the allowed countries (two letters, such as US JP); on and off turn it on and off
337
+ Only a loopback listener is probed; remote proxies are not resolved or connected.
338
+ A reachable TCP listener does not prove the proxy protocol works. SOCKS is shown but Guard supports HTTP CONNECT only.
336
339
  To skip it once: sideby run <account> --ignore-network (also sideby next --ignore-network).
337
340
 
338
341
  Examples:
339
342
  sideby network allow US JP --yes
340
343
  sideby network on --yes
341
344
  sideby network check
345
+ sideby network diagnose --json
342
346
  Exit: 0 shown or changed; 10 a change was shown and waits for --yes; 1 a country code that is not one, or on with
343
347
  no country allowed; 2 malformed command line.`,
344
348
  unattended: `sideby unattended [status] [--json]
@@ -797,19 +801,22 @@ export async function main(argv) {
797
801
  parsed.attach = repeatedValues(own, 'attach');
798
802
  if (cmd === 'send')
799
803
  parsed.images = repeatedValues(own, 'image');
804
+ // Offline diagnosis has no command-wide notification side effects: no ended checkpoint, update request/cache,
805
+ // or after-command work. Other commands keep the usual behavior.
806
+ const offlineDiagnose = cmd === 'network' && parsed.positionals[0] === 'diagnose';
800
807
  // A stretch of Unattended Mode that ended is noticed when a command starts (spec §3.37); its plugin event runs
801
808
  // alongside the command and is waited for before exiting.
802
- if (cmd !== 'update-check' && !(cmd === 'ui' && parsed.flags.has('serve-detached'))) {
809
+ if (!offlineDiagnose && cmd !== 'update-check' && !(cmd === 'ui' && parsed.flags.has('serve-detached'))) {
803
810
  const { noticeUnattendedEnded } = await import('../core/unattended-ended.js');
804
811
  ended = await noticeUnattendedEnded(process.env);
805
812
  }
806
813
  const cmds = await import('./commands.js');
807
- if (wantsJson && noticeAllowed(cmd, parsed)) {
814
+ if (!offlineDiagnose && wantsJson && noticeAllowed(cmd, parsed)) {
808
815
  notice = await jsonNoticeFor();
809
816
  cmds.setJsonNotice(notice);
810
817
  }
811
818
  const code = await dispatch(cmd, parsed, io, cmds);
812
- if (!wantsJson && noticeAllowed(cmd, parsed))
819
+ if (!offlineDiagnose && !wantsJson && noticeAllowed(cmd, parsed))
813
820
  await afterCommand();
814
821
  return code;
815
822
  }
@@ -3,12 +3,20 @@ import type { Runtime } from '../runtime.ts';
3
3
  import type { Account, Env, FamilyDef } from '../types.ts';
4
4
  import { type Attachment } from './attachments.ts';
5
5
  import { UserError } from './errors.ts';
6
+ import { type PickRecord } from './handoff.ts';
6
7
  import { type Paths } from './paths.ts';
7
8
  import { type ProbeDeps } from './probe.ts';
8
9
  import { type TerminalId } from './terminal.ts';
10
+ /**
11
+ * The Account an AI Task starts in: the one named, the remembered one, else the pick `sideby next` would make across
12
+ * Families. `record`: the caller starts the automatic pick, so a Pick Record is written for it (ADR-0083) and given
13
+ * to `recorded`, the token that takes it back.
14
+ */
9
15
  export declare function pickTaskAccount(rt: Runtime, opts?: {
10
16
  family?: string;
11
17
  account?: string;
18
+ record?: boolean;
19
+ recorded?: (rec: PickRecord) => void;
12
20
  }): Promise<{
13
21
  account: Account;
14
22
  } | {
@@ -203,20 +211,6 @@ export declare function openRunInTerminal(rt: Runtime, ref: string): Promise<{
203
211
  reason?: AiTaskReason | undefined;
204
212
  detail?: string | undefined;
205
213
  }>;
206
- /**
207
- * Starts a Pick Command in the Preferred Terminal (spec §3.13): the terminal runs it as `sideby run <name>` does, so it
208
- * picks the Account when it starts and says which there.
209
- */
210
- export declare function openPickInTerminal(rt: Runtime, name: string): Promise<{
211
- schemaVersion: 1;
212
- task: string;
213
- account: string;
214
- terminal: string;
215
- opened: boolean;
216
- command: string;
217
- reason?: AiTaskReason | undefined;
218
- detail?: string | undefined;
219
- }>;
220
214
  /**
221
215
  * What `try` will run for an Account, computed as `sideby run` would (Family defaults, config arguments, a short
222
216
  * command's arguments) but without reading its Secret File or running `launch.before` hooks: nothing runs before the
@@ -15,6 +15,11 @@ import { resolvePaths } from './paths.js';
15
15
  import { runProbe, spawnProbe } from './probe.js';
16
16
  import { takeoverLimits } from './quota-levels.js';
17
17
  import { askLauncher, askRunCommand, guessTerminal, installedTerminals, launcherProblem, openTerminal, TERMINALS, validateCustomTemplate, wslDistro, } from './terminal.js';
18
+ /**
19
+ * The Account an AI Task starts in: the one named, the remembered one, else the pick `sideby next` would make across
20
+ * Families. `record`: the caller starts the automatic pick, so a Pick Record is written for it (ADR-0083) and given
21
+ * to `recorded`, the token that takes it back.
22
+ */
18
23
  export async function pickTaskAccount(rt, opts = {}) {
19
24
  const all = (await rt.accounts()).filter((a) => !opts.family || a.family === opts.family);
20
25
  if (opts.account) {
@@ -35,15 +40,26 @@ export async function pickTaskAccount(rt, opts = {}) {
35
40
  for (const a of all) {
36
41
  if (a.kind !== 'subscription' || (await rt.status(a)).login !== 'logged-in')
37
42
  continue;
38
- candidates.push({ ...a, login: 'logged-in', quota: await rt.quota(a, { fetch: 'never' }) });
43
+ candidates.push({
44
+ ...a,
45
+ login: 'logged-in',
46
+ quota: await rt.quota(a, { fetch: 'never' }),
47
+ sameLogin: await rt.sameLogin(a),
48
+ });
39
49
  }
40
50
  if (!candidates.length)
41
51
  return { reason: 'none-signed-in' };
42
- // As `sideby next`: past the Takeover Limits, the Account closest to room with no window used up (a Last Resort, §3.13).
43
- const plan = planHandoff('', candidates, rt.readContext().now, {
44
- limits: takeoverLimits(rt.handoffSettings().threshold),
45
- lastResort: true,
46
- });
52
+ // As `sideby next`: by Room per Session (ADR-0083); past the Takeover Limits, the Account closest to room with no
53
+ // window used up (a Last Resort, §3.13).
54
+ const plan = await rt.pickLoad(opts.record === true, (live, picks) => {
55
+ const counted = candidates.map((c) => ({ ...c, liveSessions: live.get(c.ref) ?? 0 }));
56
+ const result = planHandoff('', counted, rt.readContext().now, {
57
+ limits: takeoverLimits(rt.handoffSettings().threshold),
58
+ lastResort: true,
59
+ picks,
60
+ });
61
+ return { result, candidates: counted };
62
+ }, (p) => p.pick, opts.recorded);
47
63
  const account = all.find((a) => a.ref === plan.pick);
48
64
  return account ? { account } : { reason: 'all-full' };
49
65
  }
@@ -295,10 +311,10 @@ export function taskContext(c, fail) {
295
311
  throw fail('"context.handoff" must be a list');
296
312
  out.handoff = v.map((x) => str(x, 'each of "context.handoff"'));
297
313
  }
298
- else if (k === 'network') {
314
+ else if (k === 'network' || k === 'networkDiagnose') {
299
315
  if (!Array.isArray(v) || v.length > 100)
300
- throw fail('"context.network" must be a list');
301
- out.network = v.map((x) => str(x, 'each of "context.network"'));
316
+ throw fail(`"context.${k}" must be a list`);
317
+ out[k] = v.map((x) => str(x, `each of "context.${k}"`));
302
318
  }
303
319
  else if (k === 'findings') {
304
320
  if (!Array.isArray(v) || v.length > 100)
@@ -320,8 +336,16 @@ export function taskContext(c, fail) {
320
336
  }
321
337
  return out;
322
338
  }
339
+ function refuseFixedTaskExtras(input, attachments = []) {
340
+ if (input.task !== 'network-diagnose')
341
+ return;
342
+ const unsafeFacts = input.context?.networkDiagnose?.some((fact) => fact.includes('@'));
343
+ if (input.text?.trim() || input.uploads?.length || input.files?.length || attachments.length || unsafeFacts)
344
+ throw new UserError('The fixed network diagnosis uses only its current redacted diagnostic facts; remove added text and attachments, then try again.', { code: 'fixed-task-input' });
345
+ }
323
346
  /** The attachments a prompt shown before the task exists lists: uploads still staged, the user's files in place. */
324
347
  export async function previewAttachments(rt, input) {
348
+ refuseFixedTaskExtras(input);
325
349
  if (input.uploads?.length)
326
350
  return stagedAttachments(rt.paths, input.uploads);
327
351
  if (input.files?.length)
@@ -340,6 +364,7 @@ export function taskLang(rt, lang) {
340
364
  return lang ?? (/^zh/i.test(rt.env.LC_ALL || rt.env.LC_MESSAGES || rt.env.LANG || '') ? 'zh' : 'en');
341
365
  }
342
366
  export function promptForTask(rt, input, attachments = []) {
367
+ refuseFixedTaskExtras(input, attachments);
343
368
  if (input.task && !AI_TASK_KINDS.includes(input.task))
344
369
  throw new UserError(`Choose a task: ${AI_TASK_KINDS.join(', ')}; rerun \`sideby ask\`.`);
345
370
  let removedSecrets = false;
@@ -421,7 +446,15 @@ export async function startAiTask(rt, input) {
421
446
  */
422
447
  export async function openPromptTask(rt, input, written) {
423
448
  const { taskId, prompt, removedSecrets, attachments } = written;
424
- const pick = await pickTaskAccount(rt, input);
449
+ // Only an automatic pick writes a record; a named or remembered account has none to take back.
450
+ let rec;
451
+ const pick = await pickTaskAccount(rt, {
452
+ ...input,
453
+ record: true,
454
+ recorded: (r) => {
455
+ rec = r;
456
+ },
457
+ });
425
458
  // Without an account the prompt is copied instead; the saved attachments stay where it says, until the cleanup.
426
459
  if ('reason' in pick)
427
460
  return {
@@ -437,13 +470,21 @@ export async function openPromptTask(rt, input, written) {
437
470
  removedSecrets,
438
471
  attachments,
439
472
  };
440
- if (input.remember && input.account && rt.config.ask?.account !== pick.account.ref) {
441
- const saved = await editConfigAsk(rt.paths.configFile, pick.account.ref);
442
- rt.config.ask = saved.after;
473
+ try {
474
+ if (input.remember && input.account && rt.config.ask?.account !== pick.account.ref) {
475
+ const saved = await editConfigAsk(rt.paths.configFile, pick.account.ref);
476
+ rt.config.ask = saved.after;
477
+ }
478
+ // A terminal the person picked is kept as their preferred one, as `sideby terminal --set` would.
479
+ if (input.remember && input.terminal && rt.config.terminal?.preferred !== input.terminal)
480
+ await setPreferredTerminal(rt, input.terminal);
481
+ }
482
+ catch (err) {
483
+ // Nothing starts, so the pick's record is taken back (ADR-0083).
484
+ if (rec)
485
+ await rt.cancelPick(rec);
486
+ throw err;
443
487
  }
444
- // A terminal the person picked is kept as their preferred one, as `sideby terminal --set` would.
445
- if (input.remember && input.terminal && rt.config.terminal?.preferred !== input.terminal)
446
- await setPreferredTerminal(rt, input.terminal);
447
488
  const task = {
448
489
  kind: 'prompt',
449
490
  account: pick.account.ref,
@@ -453,11 +494,15 @@ export async function openPromptTask(rt, input, written) {
453
494
  };
454
495
  if (attachments.length)
455
496
  task.attachments = attachments.map(({ path, kind }) => ({ path, kind }));
456
- return {
457
- ...(await openTask(rt, task, input.terminal, undefined, taskId)),
458
- removedSecrets,
459
- attachments,
460
- };
497
+ // A terminal that did not open starts nothing: the pick's record is taken back (ADR-0083).
498
+ const opened = await openTask(rt, task, input.terminal, undefined, taskId).catch(async (err) => {
499
+ if (rec)
500
+ await rt.cancelPick(rec);
501
+ throw err;
502
+ });
503
+ if (!opened.opened && rec)
504
+ await rt.cancelPick(rec);
505
+ return { ...opened, removedSecrets, attachments };
461
506
  }
462
507
  export async function openLoginInTerminal(rt, ref) {
463
508
  const account = await rt.resolve(ref);
@@ -468,15 +513,6 @@ export async function openRunInTerminal(rt, ref) {
468
513
  const account = await rt.resolve(ref);
469
514
  return openTask(rt, { kind: 'run', account: account.ref, cwd: rt.paths.home });
470
515
  }
471
- /**
472
- * Starts a Pick Command in the Preferred Terminal (spec §3.13): the terminal runs it as `sideby run <name>` does, so it
473
- * picks the Account when it starts and says which there.
474
- */
475
- export async function openPickInTerminal(rt, name) {
476
- if (rt.pickCommandFamily(name) === undefined)
477
- throw new UserError(`No short command "${name}" picks an account; add one in the Panel or with \`sideby alias add ${name} --pick <family>\`.`);
478
- return openTask(rt, { kind: 'run', account: name, cwd: rt.paths.home });
479
- }
480
516
  /** The probe arguments for `model`, or the plain probe; refuses a model the Family cannot choose or a malformed name. */
481
517
  function probeArgs(family, model) {
482
518
  const probe = family.probe;
@@ -70,6 +70,10 @@ export type TraceFetcher = (url: string, env: Env, timeoutMs: number) => Promise
70
70
  export type Sleep = (ms: number) => Promise<unknown>;
71
71
  /** The proxy a request to `url` goes through under `env`, or null for a direct connection. */
72
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;
73
77
  /** The key a cached result is kept under: the URL and the proxy settings, never their values in clear. */
74
78
  export declare function cacheKey(url: string, env: Env): string;
75
79
  /** A hash of the machine's own network addresses; it changes with Wi-Fi, a VPN or a TUN device. */
@@ -134,5 +138,6 @@ export declare function blockMessage(v: Pick<Verdict, 'status' | 'entry' | 'atte
134
138
  ref?: string;
135
139
  at: CheckMoment;
136
140
  zh: boolean;
141
+ proxy?: string;
137
142
  }): string;
138
143
  export {};
@@ -91,6 +91,22 @@ export function proxyFor(url, env) {
91
91
  const v = env.HTTPS_PROXY || env.https_proxy || env.ALL_PROXY || env.all_proxy;
92
92
  return v ? v.trim() : null;
93
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));
94
110
  /** The key a cached result is kept under: the URL and the proxy settings, never their values in clear. */
95
111
  export function cacheKey(url, env) {
96
112
  return sha(JSON.stringify([url, ...PROXY_VARS.map((k) => env[k] ?? '')])).slice(0, 32);
@@ -393,6 +409,11 @@ export function blockMessage(v, allow, opts) {
393
409
  const reason = v.entry.error ?? 'no answer within 3 seconds';
394
410
  const tries = v.attempts ?? 1;
395
411
  const secs = Math.max(1, Math.round((v.triedMs ?? 0) / 1000));
412
+ const route = opts.proxy ?? 'direct';
413
+ const routeZh = route === 'direct' ? '本次检查使用直连(direct)。' : `本次检查使用代理 \`${route}\`。`;
414
+ const unsupported = /^(?!http:)[a-z][a-z\d+.-]*:\/\//i.test(route);
415
+ const protocolNextZh = unsupported ? '当前 Guard 只支持 HTTP CONNECT;请配置 HTTP 代理或直连后再重试。' : '';
416
+ const restartZh = opts.at === 'launch' ? '' : '如果刚改过代理环境,旧会话可能要重开才能继承。';
396
417
  if (opts.zh) {
397
418
  const tried = tries > 1 ? `试了 ${tries} 次(约 ${secs} 秒)仍` : '';
398
419
  const what = v.status === 'unknown'
@@ -407,7 +428,7 @@ export function blockMessage(v, allow, opts) {
407
428
  const skipZh = opts.at === 'launch'
408
429
  ? `临时跳过:\`${skip}\`。`
409
430
  : `不想检查了:运行 \`sideby network off --yes\`,正在运行的会话也会马上放行;只跳过一次就新开会话:\`${skip}\`。`;
410
- return `${what}${next}${skipZh}`;
431
+ return `${what}${routeZh}${next}${protocolNextZh}${restartZh}${skipZh}`;
411
432
  }
412
433
  const tried = tries > 1 ? ` after ${tries} tries in about ${secs} s` : '';
413
434
  const what = v.status === 'unknown'
@@ -418,8 +439,17 @@ export function blockMessage(v, allow, opts) {
418
439
  : opts.at === 'prompt'
419
440
  ? 'Check that the proxy is on and the node is right, then send the message again.'
420
441
  : 'Check that the proxy is on and the node is right, then let it continue.';
442
+ const routeEn = route === 'direct'
443
+ ? 'This check used a direct connection (direct).'
444
+ : `This check used proxy \`${route}\`.`;
445
+ const protocolNextEn = unsupported
446
+ ? ' Network Guard supports HTTP CONNECT only; configure an HTTP proxy or a direct connection, then retry.'
447
+ : '';
448
+ const restartEn = opts.at === 'launch'
449
+ ? ''
450
+ : ' If you just changed the proxy environment, an older session may need restarting to inherit it.';
421
451
  const skipEn = opts.at === 'launch'
422
452
  ? `To skip once: \`${skip}\`.`
423
453
  : `To stop checking, run \`sideby network off --yes\`; sessions already running follow it at once. To skip once, start a new session: \`${skip}\`.`;
424
- return `${what} ${next} ${skipEn}`;
454
+ return `${what} ${routeEn} ${next}${protocolNextEn}${restartEn} ${skipEn}`;
425
455
  }
@@ -36,6 +36,8 @@ export declare class FileMemo<T> {
36
36
  pass(scope: string): MemoPass<T>;
37
37
  /** What is remembered, for the cache file; clears `dirty`. */
38
38
  dump(): MemoDump;
39
+ /** The scopes a pass ended in since the last call, for merging into the cache file; clears `dirty`. */
40
+ takeFresh(): MemoDump;
39
41
  /**
40
42
  * Takes remembered parses from the cache file for scopes this process has not read yet. The values are trusted
41
43
  * to have the shape `persist.version` stands for; a stale one never matches, because its signature differs.
@@ -14,6 +14,12 @@ export class FileMemo {
14
14
  stats = { hits: 0, misses: 0 };
15
15
  /** True when a pass changed what is remembered since the last `dump`. */
16
16
  dirty = false;
17
+ /**
18
+ * Scopes a pass ended in since the last `takeFresh`. Only these are this process's own news: the others hold what
19
+ * the cache file had when this process started, which another sideby process sharing the state directory may since
20
+ * have replaced with newer parses.
21
+ */
22
+ #fresh = new Set();
17
23
  persist;
18
24
  constructor(persist) {
19
25
  if (!persist)
@@ -61,6 +67,7 @@ export class FileMemo {
61
67
  if (!before || before.size !== seen.size || [...seen].some(([k, v]) => before.get(k) !== v))
62
68
  this.dirty = true;
63
69
  this.#scopes.set(scope, seen);
70
+ this.#fresh.add(scope);
64
71
  },
65
72
  };
66
73
  }
@@ -72,6 +79,18 @@ export class FileMemo {
72
79
  out[scope] = Object.fromEntries([...files].map(([path, e]) => [path, [e.sig, e.value]]));
73
80
  return out;
74
81
  }
82
+ /** The scopes a pass ended in since the last call, for merging into the cache file; clears `dirty`. */
83
+ takeFresh() {
84
+ this.dirty = false;
85
+ const out = {};
86
+ for (const scope of this.#fresh) {
87
+ const files = this.#scopes.get(scope);
88
+ if (files)
89
+ out[scope] = Object.fromEntries([...files].map(([path, e]) => [path, [e.sig, e.value]]));
90
+ }
91
+ this.#fresh.clear();
92
+ return out;
93
+ }
75
94
  /**
76
95
  * Takes remembered parses from the cache file for scopes this process has not read yet. The values are trusted
77
96
  * to have the shape `persist.version` stands for; a stale one never matches, because its signature differs.
@@ -93,6 +112,7 @@ export class FileMemo {
93
112
  }
94
113
  clear() {
95
114
  this.#scopes.clear();
115
+ this.#fresh.clear();
96
116
  this.dirty = false;
97
117
  this.stats.hits = 0;
98
118
  this.stats.misses = 0;