sideby 0.42.1 → 0.43.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 (58) hide show
  1. package/ai-tasks.json +10 -0
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +63 -13
  4. package/dist/src/cli/json-schemas.js +58 -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/handoff-run.js +41 -8
  11. package/dist/src/core/handoff-select.d.ts +5 -0
  12. package/dist/src/core/handoff-select.js +1 -1
  13. package/dist/src/core/handoff.d.ts +69 -1
  14. package/dist/src/core/handoff.js +90 -9
  15. package/dist/src/core/history-index.d.ts +4 -0
  16. package/dist/src/core/history-index.js +1 -1
  17. package/dist/src/core/live-sessions.d.ts +5 -0
  18. package/dist/src/core/live-sessions.js +12 -1
  19. package/dist/src/core/network.d.ts +37 -0
  20. package/dist/src/core/network.js +65 -1
  21. package/dist/src/core/pick-commands.d.ts +7 -1
  22. package/dist/src/core/pick-commands.js +15 -3
  23. package/dist/src/core/pick-records.d.ts +26 -0
  24. package/dist/src/core/pick-records.js +81 -0
  25. package/dist/src/families/agy/history.d.ts +2 -0
  26. package/dist/src/families/agy/history.js +118 -0
  27. package/dist/src/families/agy/index.js +5 -0
  28. package/dist/src/families/agy/quota.d.ts +5 -1
  29. package/dist/src/families/agy/quota.js +111 -10
  30. package/dist/src/families/history.js +2 -1
  31. package/dist/src/network/hook.js +4 -4
  32. package/dist/src/network/page-script.d.ts +40 -0
  33. package/dist/src/network/page-script.js +270 -0
  34. package/dist/src/network/page.d.ts +11 -0
  35. package/dist/src/network/page.js +189 -0
  36. package/dist/src/network/panel.d.ts +5 -0
  37. package/dist/src/network/panel.js +7 -0
  38. package/dist/src/panel/handler.d.ts +21 -1
  39. package/dist/src/panel/handler.js +174 -37
  40. package/dist/src/panel/i18n.d.ts +26 -0
  41. package/dist/src/panel/i18n.js +54 -2
  42. package/dist/src/panel/page-logic.d.ts +26 -3
  43. package/dist/src/panel/page-logic.js +95 -12
  44. package/dist/src/panel/page-script.js +86 -17
  45. package/dist/src/panel/page-styles.js +1 -0
  46. package/dist/src/runtime.d.ts +58 -5
  47. package/dist/src/runtime.js +121 -13
  48. package/dist/src/types.d.ts +3 -2
  49. package/package.json +1 -1
  50. package/schemas/network-diagnose.json +196 -0
  51. package/schemas/next.json +42 -2
  52. package/skills/sideby/SKILL.md +3 -2
  53. package/skills/sideby/references/accounts.md +1 -1
  54. package/skills/sideby/references/ai-tasks.md +1 -1
  55. package/skills/sideby/references/handoff.md +4 -2
  56. package/skills/sideby/references/network.md +6 -1
  57. package/skills/sideby/references/quota.md +1 -1
  58. package/skills/sideby/references/sessions.md +1 -1
@@ -1236,8 +1236,9 @@ export function loginKey(refs) {
1236
1236
  * 16 capitals or digits), and a JWT (three base64url parts joined by dots, the first starting `eyJ`). Then any run of
1237
1237
  * 32 or more letters, digits, `_`, `-` or `+` that mixes letters and digits, unless the whitespace-free word it sits
1238
1238
  * in is a URL or a file path (it has a `/`); a 40-character git SHA is such a run. Everything else, whitespace and
1239
- * newlines included, stays as it was. `removed` says whether anything was taken out, so the caller can point the
1240
- * user to the key box.
1239
+ * newlines included, stays as it was, except a URL with userinfo is reduced to scheme and host (credentials, path,
1240
+ * query and fragment removed). `removed` says whether anything was taken out, so the caller can point the user to the
1241
+ * key box.
1241
1242
  */
1242
1243
  export function stripSecrets(text) {
1243
1244
  const mark = '[key removed]';
@@ -1247,6 +1248,33 @@ export function stripSecrets(text) {
1247
1248
  removed = true;
1248
1249
  return mark;
1249
1250
  });
1251
+ // URL userinfo is a credential too. Keep only its origin, and drop path/query/fragment with it; this also covers
1252
+ // a proxy URL pasted into the fixed network diagnosis task before its prompt is previewed or written to disk.
1253
+ w = w.replace(/\b[a-z][a-z\d+.-]*:\/\/\S+/gi, (value) => {
1254
+ const trailing = /[),.;!?]+$/.exec(value)?.[0] ?? '';
1255
+ try {
1256
+ const url = new URL(value.slice(0, value.length - trailing.length));
1257
+ if (!url.username && !url.password)
1258
+ return value;
1259
+ removed = true;
1260
+ return `${url.protocol}//${url.host}${trailing}`;
1261
+ }
1262
+ catch {
1263
+ return value;
1264
+ }
1265
+ });
1266
+ // Proxy environment values also allow user:password@host without a scheme. Keep only the host and port.
1267
+ w = w.replace(/(?<![A-Za-z0-9_@])[^:@\s/]+:[^@\s/]+@(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+)(?::\d{1,5})?(?:[/?#]\S*)?/g, (value) => {
1268
+ const trailing = /[),.;!?]+$/.exec(value)?.[0] ?? '';
1269
+ try {
1270
+ const url = new URL(`http://${value.slice(0, value.length - trailing.length)}`);
1271
+ removed = true;
1272
+ return `${url.host}${trailing}`;
1273
+ }
1274
+ catch {
1275
+ return value;
1276
+ }
1277
+ });
1250
1278
  if (w.includes('/'))
1251
1279
  return w;
1252
1280
  w = w.replace(/[A-Za-z0-9_+-]{32,}=*/g, (run) => {
@@ -1280,6 +1308,30 @@ export function networkTaskFacts(n) {
1280
1308
  out.push(`${a.ref}: not checked here (${a.skip})`);
1281
1309
  return out;
1282
1310
  }
1311
+ export function networkDiagnoseTaskFacts(d) {
1312
+ const out = [`diagnosed: ${d.checkedAt} (offline; no trace sent)`];
1313
+ for (const t of d.targets) {
1314
+ let host = t.url;
1315
+ try {
1316
+ host = new URL(t.url).hostname;
1317
+ }
1318
+ catch {
1319
+ /* keep the URL */
1320
+ }
1321
+ const listener = t.listener
1322
+ ? `TCP ${t.listener.host}:${t.listener.port} ${t.listener.reachable ? 'reachable' : 'not reachable'}${t.listener.error ? ` (${t.listener.error})` : ''}; this does not prove the proxy protocol works`
1323
+ : t.guardSupport === 'direct'
1324
+ ? 'direct; no proxy TCP listener to test'
1325
+ : 'no local TCP listener probe (remote proxy, invalid address, or no explicit port)';
1326
+ const support = t.guardSupport === 'unsupported'
1327
+ ? '; Guard does not support this proxy scheme; configure HTTP CONNECT or direct before an online check'
1328
+ : t.guardSupport === 'invalid'
1329
+ ? '; proxy address invalid; correct it and start a new session'
1330
+ : '';
1331
+ out.push(`${host}: proxy ${t.proxy}; ${listener}${support}; Guard ${t.guard.status}${t.guard.loc ? `, country ${t.guard.loc}` : ''}${t.guard.checkedAt ? `, checked ${t.guard.checkedAt}` : ', not checked yet'}${t.guard.error ? `, ${t.guard.error}` : ''}`);
1332
+ }
1333
+ return out;
1334
+ }
1283
1335
  /** The kinds of AI Task (spec §3.28); anything else is refused. */
1284
1336
  export const AI_TASK_KINDS = [
1285
1337
  'free',
@@ -1294,6 +1346,7 @@ export const AI_TASK_KINDS = [
1294
1346
  'menubar',
1295
1347
  'hotkey',
1296
1348
  'network',
1349
+ 'network-diagnose',
1297
1350
  'update',
1298
1351
  ];
1299
1352
  /**
@@ -1450,11 +1503,14 @@ export function taskPrompt(input, strip) {
1450
1503
  pMenubar: '先运行 `sideby menubar --json`。`state` 为 `off`:它被关掉了(常见于菜单里的「从状态栏隐藏…」),给我看 `sideby menubar on` 的预览,我同意后加 `--yes`。`state` 为 `on` 但 `loaded` 为 `false`:macOS 没在运行它,`sideby menubar on --yes` 只是重新启动,不改文件。`loaded` 为 `true`:它在运行但被挡住了,依次查:状态栏是否太满或被刘海挡住(按住 ⌘ 拖动图标);有没有 Ice、Bartender、Hidden Bar 这类菜单栏整理工具把它收起来了(查 `/Applications`,告诉我去它的设置里把 sideby(显示为 osascript)挪出来);macOS 26 及以上要在「系统设置 › 菜单栏」里允许 osascript(`sideby menubar --json` 里的快捷键 `hotkey.label` 可以在任何地方打开菜单,用来确认它在运行)。不要结束或重启任何不是 sideby 的进程。',
1451
1504
  cHandoff: '自动接力现在的设置(来自 `sideby handoff status --json`):',
1452
1505
  network: '帮我设置 sideby 的网络检查:请求要从我没允许的国家或地区发出时(比如代理断了、节点切错了),拦下 Claude 和 Codex。',
1506
+ 'network-diagnose': '根据下面的离线诊断 facts,向我解释当前网络异常和最可能的下一步。',
1453
1507
  cNetwork: '网络检查现在的情况(来自 `sideby network --json`):',
1508
+ cNetworkDiagnose: '离线诊断(来自 `sideby network diagnose --json`):',
1454
1509
  update: '帮我把 sideby 和它的 skill 更新到最新版:面板检查更新或更新时出错了,请找出原因并修好。',
1455
1510
  cUpdate: '面板上的报错:',
1456
1511
  pUpdate: '先运行 `sideby update --json`,看它能不能连上 npm、最新版是多少、是哪种安装方式(`canRun`)。连不上时先查网络:要走代理的话,看启动 sideby 的终端里有没有 `HTTPS_PROXY`、代理开没开;在中国大陆可以用镜像 `SIDEBY_UPDATE_REGISTRY=https://registry.npmmirror.com`,要写进 shell 配置文件前先问我。能更新时,`sideby update --json` 已经给出预览(退出码 10),我同意后再跑 `sideby update --yes --json`。`canRun` 为 `false` 时(npx、项目依赖、没有写权限的全局目录),把输出里的 `command` 给我,告诉我在哪里运行。skill 比 sideby 新不是问题,更新 sideby 就好。最后再跑一次 `sideby update --json`,确认 sideby 和 skill 都已是最新。',
1457
1512
  pNetwork: '先运行 `sideby network check --json`,告诉我现在每个地址的请求从哪里发出。问我允许哪些国家或地区;不要替我决定,也不要因为现在在哪就把它加进去(网络不对时那正是错的地区)。我说了以后,先不加 `--yes` 跑 `sideby network allow <代码>... --json` 和 `sideby network on --json` 给我看预览,我同意后再加 `--yes`。告诉我:只检查 sideby 启动的会话;Codex 要在 `/hooks` 里信任一次 `network-hook`;临时跳过一次用 `sideby run <账号> --ignore-network`。被拦过的话,先帮我查代理(开没开、哪个节点),再跑 `sideby network check --json` 确认。它只防代理出意外,不会让在不支持的地区使用变得合规;不要帮我隐藏所在地(时区、指纹之类)。',
1513
+ pNetworkDiagnose: '只解释这些 facts。TCP listener 可连接不代表 HTTP CONNECT、SOCKS 或上游代理可用。看到 SOCKS 或 HTTPS 代理时,明确说当前 Guard 只支持 HTTP CONNECT,建议我配置 HTTP 代理或直连。需要新的出口国家结果时,让我自己运行 `sideby network check --json`。不要修改网络、配置、代码或文件,不要切换出口,也不要运行任何写入命令。',
1458
1514
  pHandoff: '先运行 `sideby handoff status --json` 和 `sideby quota --json`,看清每个账号的额度来源和用量。只用 `sideby handoff enable …` 或 `sideby config set handoff.<键> <值>` 改设置;先不加 `--yes` 给我看预览,我同意后再加 `--yes`。没有额度数据的账号排在顺序后面,并告诉我怎么让它显示额度。',
1459
1515
  cAccount: '账号:',
1460
1516
  cFamily: '家族:',
@@ -1467,7 +1523,9 @@ export function taskPrompt(input, strip) {
1467
1523
  cNoTerminals: '本机没找到 sideby 支持的终端',
1468
1524
  cLang: '面板语言:中文(请用中文和我交流)',
1469
1525
  r1: '先用 sideby skill,怎么做见它的 references/ai-tasks.md。没装 skill 就先问我,我同意后运行 `npx skills add Adonis0123/sideby -g`。',
1526
+ r1ReadOnly: '装了 sideby skill 就看它的 references/ai-tasks.md;没装就只说明,不安装,也不运行其他写入命令。',
1470
1527
  r2: '会改文件的命令先给我看预览,我同意后才加 `--yes`。',
1528
+ rReadOnly: '这是固定只读任务:不得修改网络、配置、代码或文件,不得切换出口,不得自动运行在线检查。',
1471
1529
  r3: '不要替我登录,也不要让我把密钥发给你:密钥由我自己用 `sideby key <账号>` 输入。',
1472
1530
  pFix: '先运行 `sideby doctor --json` 看清问题;能自动修的交给 `sideby doctor --fix`。修完再跑一次 `sideby doctor`,告诉我还剩什么。',
1473
1531
  pQuota: '用 `sideby quota --json` 和 `sideby doctor --json` 看原因。',
@@ -1502,11 +1560,14 @@ export function taskPrompt(input, strip) {
1502
1560
  pMenubar: 'Run `sideby menubar --json` first. `state` is `off`: it was turned off (often with "Hide from Menu Bar…" in its menu); show me the preview of `sideby menubar on`, and add `--yes` after I agree. `state` is `on` with `loaded: false`: macOS is not running it; `sideby menubar on --yes` only starts it again and changes no file. `loaded: true`: it runs but is hidden; check in turn whether the menu bar is too full or the notch covers it (hold ⌘ and drag icons), whether a menu bar organizer such as Ice, Bartender or Hidden Bar tucked it away (look in /Applications, and tell me where in its settings to move sideby, shown as osascript, out), and, on macOS 26 and later, whether osascript is allowed under System Settings › Menu Bar. The shortcut in `hotkey.label` opens the menu from anywhere, which shows it is running. Never end or restart a process that is not sideby\'s.',
1503
1561
  cHandoff: 'Auto Handoff now (from `sideby handoff status --json`):',
1504
1562
  network: "Help me set up sideby's network check: stop Claude and Codex when my requests would leave from a country I did not allow (for example when the proxy stopped or a node in the wrong country is picked).",
1563
+ 'network-diagnose': 'Explain the current network problem and the most likely next step from the offline diagnosis facts below.',
1505
1564
  cNetwork: 'Network check now (from `sideby network --json`):',
1565
+ cNetworkDiagnose: 'Offline diagnosis (from `sideby network diagnose --json`):',
1506
1566
  update: 'Bring sideby and its skill up to date: the Panel showed an error while checking for or installing an update. Find out why and fix it.',
1507
1567
  cUpdate: 'The error the Panel showed: ',
1508
1568
  pUpdate: 'Run `sideby update --json` first to see whether it reaches npm, the latest version and how sideby is installed (`canRun`). When it cannot reach npm, check the network: behind a proxy, whether the terminal that starts sideby has `HTTPS_PROXY` and the proxy is on; in mainland China the mirror `SIDEBY_UPDATE_REGISTRY=https://registry.npmmirror.com` helps, but ask me before writing it into a shell config file. When it can update, `sideby update --json` already shows the change (exit 10); run `sideby update --yes --json` after I agree. When `canRun` is false (npx, a project dependency, a global folder I cannot write), give me the `command` from its output and tell me where to run it. A skill newer than sideby is fine: updating sideby is enough. Finish with `sideby update --json` again to confirm sideby and the skill are current.',
1509
1569
  pNetwork: "Run `sideby network check --json` first and tell me where each address's requests leave from now. Ask me which countries to allow; never decide for me, and never add the current country because it is current (on a wrong network that is the wrong one). Once I say, run `sideby network allow <codes>... --json` and `sideby network on --json` without `--yes` to show me the change, and add `--yes` after I agree. Tell me: only sessions sideby starts are checked; in Codex I trust `network-hook` once in `/hooks`; `sideby run <account> --ignore-network` skips it once. If something was blocked, help me check the proxy (is it on, which node) first, then run `sideby network check --json` to confirm. It guards against proxy accidents; it does not make use from an unsupported region allowed, and never help hide where I am (time zone, fingerprints).",
1570
+ pNetworkDiagnose: 'Explain these facts only. A reachable TCP listener does not prove that HTTP CONNECT, SOCKS or the upstream proxy works. For a SOCKS or HTTPS proxy, say that Guard currently supports HTTP CONNECT only and suggest configuring an HTTP proxy or a direct connection. If a fresh egress country is needed, ask me to run `sideby network check --json` myself. Do not change the network, configuration, code or files, do not switch the exit, and do not run any write command.',
1510
1571
  pHandoff: 'Run `sideby handoff status --json` and `sideby quota --json` first to see where each account gets its quota and how much is used. Change settings only with `sideby handoff enable …` or `sideby config set handoff.<key> <value>`; show me the preview without `--yes` first, and add `--yes` only after I agree. Put accounts without quota data last in the order, and tell me how to make them show it.',
1511
1572
  cAccount: 'Account: ',
1512
1573
  cFamily: 'Family: ',
@@ -1519,7 +1580,9 @@ export function taskPrompt(input, strip) {
1519
1580
  cNoTerminals: 'No supported terminal is installed here',
1520
1581
  cLang: 'Panel language: English (talk to me in English)',
1521
1582
  r1: 'Use the sideby skill; its references/ai-tasks.md says how. If the skill is not installed, ask me first, and with my yes run `npx skills add Adonis0123/sideby -g`.',
1583
+ r1ReadOnly: 'If the sideby skill is installed, read its references/ai-tasks.md. If not, just say so; do not install it or run any other write command.',
1522
1584
  r2: 'Show me the preview of any command that changes files; add `--yes` only after I agree.',
1585
+ rReadOnly: 'This is a fixed read-only task: do not change the network, configuration, code or files, switch the exit, or automatically run an online check.',
1523
1586
  r3: 'Never sign in for me and never ask me to send you an API key: I enter keys myself with `sideby key <account>`.',
1524
1587
  pFix: 'Run `sideby doctor --json` first; `sideby doctor --fix` fixes what it can by itself. When you are done, run `sideby doctor` and tell me what is left.',
1525
1588
  pQuota: 'Use `sideby quota --json` and `sideby doctor --json` to see why.',
@@ -1532,14 +1595,21 @@ export function taskPrompt(input, strip) {
1532
1595
  shareTerminal: 'When it works, ask me whether to make this terminal built into sideby. Only with my yes, add a row to the terminal table in src/core/terminal.ts of the sideby repository with tests, follow its CONTRIBUTING.md to open a pull request, and first remove my own account names, paths and emails.',
1533
1596
  };
1534
1597
  const task = AI_TASK_KINDS.indexOf(input.task) >= 0 ? input.task : 'free';
1598
+ const fixedReadOnly = task === 'network-diagnose';
1535
1599
  const sentence = L[task] || L.free;
1536
- const what = task === 'free' ? text || sentence : text ? sentence + '\n' + L.says + text : sentence;
1600
+ const what = fixedReadOnly
1601
+ ? sentence
1602
+ : task === 'free'
1603
+ ? text || sentence
1604
+ : text
1605
+ ? sentence + '\n' + L.says + text
1606
+ : sentence;
1537
1607
  const facts = [];
1538
- if (account)
1608
+ if (!fixedReadOnly && account)
1539
1609
  facts.push('- ' + L.cAccount + account);
1540
- if (family)
1610
+ if (!fixedReadOnly && family)
1541
1611
  facts.push('- ' + L.cFamily + family);
1542
- const findings = c.findings || [];
1612
+ const findings = fixedReadOnly ? [] : c.findings || [];
1543
1613
  if (findings.length) {
1544
1614
  facts.push('- ' + L.cFindings);
1545
1615
  findings.forEach((f, i) => {
@@ -1556,7 +1626,7 @@ export function taskPrompt(input, strip) {
1556
1626
  facts.push(' ' + hint);
1557
1627
  });
1558
1628
  }
1559
- const reason = clean(c.quotaReason);
1629
+ const reason = fixedReadOnly ? '' : clean(c.quotaReason);
1560
1630
  if (reason)
1561
1631
  facts.push('- ' + L.cQuota + reason);
1562
1632
  if (task === 'terminal') {
@@ -1581,24 +1651,37 @@ export function taskPrompt(input, strip) {
1581
1651
  if (lines.length)
1582
1652
  facts.push('- ' + L.cNetwork, ...lines.map((l) => ' - ' + l));
1583
1653
  }
1654
+ if (task === 'network-diagnose') {
1655
+ const lines = (c.networkDiagnose || []).map(clean).filter(Boolean);
1656
+ if (lines.length)
1657
+ facts.push('- ' + L.cNetworkDiagnose, ...lines.map((l) => ' - ' + l));
1658
+ }
1584
1659
  if (task === 'update') {
1585
1660
  const err = clean(c.updateError);
1586
1661
  if (err)
1587
1662
  facts.push('- ' + L.cUpdate + err);
1588
1663
  }
1589
- const version = clean(c.version);
1664
+ const version = fixedReadOnly ? '' : clean(c.version);
1590
1665
  if (version)
1591
1666
  facts.push('- ' + L.cVersion + version);
1592
1667
  facts.push('- ' + L.cLang);
1593
- const pointer = L['p' + task.charAt(0).toUpperCase() + task.slice(1)];
1668
+ const pointerKey = task === 'network-diagnose' ? 'pNetworkDiagnose' : 'p' + task.charAt(0).toUpperCase() + task.slice(1);
1669
+ const pointer = L[pointerKey];
1594
1670
  const parts = [L.task + '\n' + what, L.context + '\n' + facts.join('\n')];
1595
- const attached = attachedSection(input.attachments || [], input.lang);
1671
+ const attached = fixedReadOnly ? '' : attachedSection(input.attachments || [], input.lang);
1596
1672
  if (attached)
1597
1673
  parts.push(attached);
1598
- parts.push(L.rules + '\n- ' + L.r1 + '\n- ' + L.r2 + '\n- ' + L.r3);
1674
+ parts.push(L.rules +
1675
+ '\n- ' +
1676
+ (fixedReadOnly ? L.r1ReadOnly : L.r1) +
1677
+ '\n- ' +
1678
+ (fixedReadOnly ? L.rReadOnly : L.r2) +
1679
+ '\n- ' +
1680
+ L.r3);
1599
1681
  if (pointer)
1600
1682
  parts.push(L.pointers + '\n' + pointer);
1601
- parts.push(task === 'terminal' ? L.shareTerminal : L.share);
1683
+ if (task !== 'network-diagnose')
1684
+ parts.push(task === 'terminal' ? L.shareTerminal : L.share);
1602
1685
  return parts.join('\n\n');
1603
1686
  }
1604
1687
  /**
@@ -6,7 +6,7 @@ import { groupsToAccept } from '../core/inbound.js';
6
6
  import { limitResetOffer, quotaAge, quotaIsStale, windowAge } from '../core/quota-levels.js';
7
7
  import { remoteControlTodo } from '../core/remote-control.js';
8
8
  import { catalogMatchLevel, catalogNorm, searchCatalog } from '../core/search-catalog.js';
9
- import { accountTitle, advisorPick, advisorSummary, aiTaskAccounts, aliasArgsOf, aliasIssue, aliasPrefix, askBridge, askBridged, askCopy, askPermissionNote, attentionReasons, attentionWhy, autostartNote, bindingWindow, cacheHitRate, canLeaveLocal, categoryOrder, codeSwapOutcome, dateFormatter, dotsKeepKeyboard, enableOutcome, expiredLogins, fileSize, findingSentence, fixPrompt, foldSkips, foldToolCalls, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, hiddenIn, highlightParts, histFilters, historyEmpty, historyRowSig, historyWhen, historyWhenNext, hotkeyFromKey, hotkeyPressKind, inDisplayOrder, loginClusters, loginKey, longWindow, maskEmail, matchesQuery, mdBlocks, mdInline, menuPlacement, mergeDaily, mergeUsage, messageChip, messageNews, messageToCheck, networkTaskFacts, newAccountDir, nextReset, openBridge, openBridged, orderedAliases, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, portalRefresh, quotaAskable, quotaHighLevel, quotaPressure, radioStep, reloadForBuild, remoteControlSummary, reorder, resetWhen, rowBadge, runCodeSwap, saveHandoffChange, sendBlock, sendFileProblem, sendResultView, sessionAge, sessionLabelParts, sessionRowShape, shortCwd, shortSessionLabel, sortAccounts, sortMenu, sortSessions, startedFromView, steadyOrder, stripSecrets, suggestAlias, suggestName, switchFailure, tailInView, taskFindings, toastMerge, uaDayRuns, uaGroupByProject, uaGroupPending, uaOnChoices, uaParseClock, uaPickTime, uaSameSlot, uaShouldRead, uaSlotNight, uaStatusParts, uaStepClock, uaToggleDay, uaWaitingCount, uaWhen, updatedAge, vendorAlias, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
9
+ import { accountTitle, advisorPick, advisorSummary, aiTaskAccounts, aliasArgsOf, aliasIssue, aliasPrefix, askBridge, askBridged, askCopy, askPermissionNote, attentionReasons, attentionWhy, autostartNote, bindingWindow, cacheHitRate, canLeaveLocal, categoryOrder, codeSwapOutcome, dateFormatter, dotsKeepKeyboard, enableOutcome, expiredLogins, fileSize, findingSentence, fixPrompt, foldSkips, foldToolCalls, formatDuration, handoffChangeOf, handoffHintAccount, handoffTaskFacts, hiddenIn, highlightParts, histFilters, historyEmpty, historyRowSig, historyWhen, historyWhenNext, hotkeyFromKey, hotkeyPressKind, inDisplayOrder, loginClusters, loginKey, longWindow, maskEmail, matchesQuery, mdBlocks, mdInline, menuPlacement, mergeDaily, mergeUsage, messageChip, messageNews, messageToCheck, networkDiagnoseTaskFacts, networkTaskFacts, newAccountDir, nextReset, openBridge, openBridged, orderedAliases, panelFixes, panelHint, panelLang, panelMigration, panelPrefs, passedWindow, pinnedIn, portalRefresh, quotaAskable, quotaHighLevel, quotaPressure, radioStep, reloadForBuild, remoteControlSummary, reorder, resetWhen, rowBadge, runCodeSwap, saveHandoffChange, sendBlock, sendFileProblem, sendResultView, sessionAge, sessionLabelParts, sessionRowShape, shortCwd, shortSessionLabel, sortAccounts, sortMenu, sortSessions, startedFromView, steadyOrder, stripSecrets, suggestAlias, suggestName, switchFailure, tailInView, taskFindings, toastMerge, uaDayRuns, uaGroupByProject, uaGroupPending, uaOnChoices, uaParseClock, uaPickTime, uaSameSlot, uaShouldRead, uaSlotNight, uaStatusParts, uaStepClock, uaToggleDay, uaWaitingCount, uaWhen, updatedAge, vendorAlias, widthFollower, widthTier, windowState, withPinned, } from './page-logic.js';
10
10
  // The component library's dropdown menu, copied by the brand repo's add script (--html into ui/); do not edit it.
11
11
  import { CHECK, menuItem, menuScript } from './ui/dropdown-menu/dropdown-menu.html.js';
12
12
  import { cn, esc } from './ui/lib/cn.js';
@@ -59,6 +59,7 @@ const LOGIC = [
59
59
  handoffChangeOf,
60
60
  handoffHintAccount,
61
61
  handoffTaskFacts,
62
+ networkDiagnoseTaskFacts,
62
63
  networkTaskFacts,
63
64
  inDisplayOrder,
64
65
  loginClusters,
@@ -2401,11 +2402,12 @@ const MAIN = String.raw `
2401
2402
  // The Account 'sideby next <family>' would pick; the server ranks it with the CLI's rule (spec §3.13).
2402
2403
  // "Suggested": a click says what it means and offers the command, instead of copying without a word.
2403
2404
  function nextTag(a) {
2404
- const b = h('button', { class: 'tag tag-ok tag-btn', type: 'button', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', title: t('acct.nextWhy', { title: famTitle(a) }) }, t('acct.next'))
2405
+ const b = h('button', { class: 'tag tag-ok tag-btn', type: 'button', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', title: t(nextWhyKey(a), { title: famTitle(a) }) }, t('acct.next'))
2405
2406
  b.addEventListener('click', (e) => {
2406
2407
  e.stopPropagation()
2407
2408
  openPopover(b, 'next', t('acct.next'), () => [
2408
- h('p', { class: 'next-why' }, t('acct.nextWhy', { title: famTitle(a) })),
2409
+ h('p', { class: 'next-why' }, t(nextWhyKey(a), { title: famTitle(a) })),
2410
+ nextRunning(a) ? h('p', { class: 'next-why' }, tn('acct.nextRunning', nextRunning(a))) : null,
2409
2411
  h('button', { class: 'btn btn-sm', type: 'button', onclick: () => { closeMenu(true); copyText('sideby next ' + a.family) } }, icon('copy'), t('acct.nextCopy')),
2410
2412
  h('code', { class: 'next-cmd' }, 'sideby next ' + a.family),
2411
2413
  ])
@@ -2413,6 +2415,14 @@ const MAIN = String.raw `
2413
2415
  return b
2414
2416
  }
2415
2417
  function isNext(a) { return Boolean(S.state && S.state.handoff && S.state.handoff[a.family] === a.ref) }
2418
+ // Sessions already running on the Next pick's login (ADR-0083); 0 when none or not known.
2419
+ function nextRunning(a) { return (S.state && S.state.handoffRunning && S.state.handoffRunning[a.family]) || 0 }
2420
+ // Why the pick goes first, as the Panel state says (ADR-0083); the general line when it says nothing.
2421
+ function nextWhyKey(a) {
2422
+ const why = S.state && S.state.handoffReason && S.state.handoffReason[a.family]
2423
+ const keys = { expiring: 'acct.nextWhyExpiring', room: 'acct.nextWhyRoom', tight: 'acct.nextWhyTight', unknown: 'acct.nextWhyUnknown' }
2424
+ return keys[why] || 'acct.nextWhy'
2425
+ }
2416
2426
  function row(a, now, cols) {
2417
2427
  if (ui.arrange) return arrangeRow(a, [a])
2418
2428
  const open = isOpen(a)
@@ -4924,7 +4934,7 @@ const MAIN = String.raw `
4924
4934
  s.projectName && !noProject ? h('span', { class: 'hist-pname', title: s.cwd || s.project }, s.projectName) : null,
4925
4935
  s.cwdGone ? h('span', { class: 'chip chip-sm hist-gone', tabindex: '0', 'data-tip': t('hist.goneTip') }, t('hist.gone')) : null,
4926
4936
  s.branch ? h('span', { class: 'mono hist-branch' }, s.branch) : null,
4927
- tn('hist.msgs', s.messages),
4937
+ s.messages ? tn('hist.msgs', s.messages) : null,
4928
4938
  s.children ? h('span', { class: 'chip chip-sm', tabindex: '0', 'data-tip': t('hist.kidsTip') }, tn('hist.kids', s.children)) : null,
4929
4939
  s.script ? h('span', { class: 'chip chip-sm' }, t('hist.script')) : null,
4930
4940
  h('span', { class: 'hist-age', 'data-hage': s.updatedAt, title: fullWhen(s.updatedAt) }, whenText(s.updatedAt)),
@@ -5169,7 +5179,7 @@ const MAIN = String.raw `
5169
5179
  s.cwdGone ? t('hist.gone') : null,
5170
5180
  s.branch ? h('span', { class: 'mono' }, s.branch) : null,
5171
5181
  s.model ? h('span', { class: 'mono' }, s.model) : null,
5172
- tn('hist.msgs', s.messages),
5182
+ s.messages ? tn('hist.msgs', s.messages) : null,
5173
5183
  h('span', { title: fullWhen(s.updatedAt) }, whenText(s.updatedAt)),
5174
5184
  ])),
5175
5185
  h('div', { class: 'hv-msgs', tabindex: '0', 'aria-label': t('hv.messages') },
@@ -8137,7 +8147,7 @@ const MAIN = String.raw `
8137
8147
  function openNet() {
8138
8148
  const n = netState()
8139
8149
  if (!n) return
8140
- net = { guard: n.guard, allow: [...n.allow], checking: false }
8150
+ net = { guard: n.guard, allow: [...n.allow], checking: false, diagnosing: false, diagnosis: null }
8141
8151
  showDialog('net')
8142
8152
  renderNet()
8143
8153
  // Opening it answers "where am I now" at once, unless a result is fresh.
@@ -8153,6 +8163,22 @@ const MAIN = String.raw `
8153
8163
  if (dlg.kind === 'net') renderNet()
8154
8164
  renderBanners()
8155
8165
  }
8166
+ async function netDiagnose() {
8167
+ const mine = net
8168
+ if (!mine) return
8169
+ mine.diagnosing = true
8170
+ if (dlg.kind === 'net') renderNet()
8171
+ try {
8172
+ const diagnosis = await api('/api/network/diagnose', {})
8173
+ if (net !== mine) return
8174
+ mine.diagnosis = diagnosis
8175
+ } catch (e) {
8176
+ if (net !== mine) return
8177
+ toast(t('net.checkFailed', { msg: e.message }), { kind: 'fail' })
8178
+ }
8179
+ mine.diagnosing = false
8180
+ if (dlg.kind === 'net') renderNet()
8181
+ }
8156
8182
  // Every change in the dialog applies at once, like a system setting, and its toast carries the undo. Changes are
8157
8183
  // saved one after another in the order clicked; a failed one puts the dialog back to what the config holds.
8158
8184
  let netSaving = Promise.resolve()
@@ -8201,6 +8227,16 @@ const MAIN = String.raw `
8201
8227
  x.ipChanged ? h('div', { class: 'muted small' }, t('net.ipChanged')) : null)
8202
8228
  })
8203
8229
  const skipped = n.accounts.filter((a) => a.skip === 'third-party' || a.skip === 'at-launch' || a.skip === 'api')
8230
+ const diagnosis = net.diagnosis
8231
+ const diagnosisRows = diagnosis ? diagnosis.targets.map((x) => {
8232
+ const listener = x.listener
8233
+ return h('li', { class: 'rc-row', 'data-key': 'net-diagnosis-' + x.url },
8234
+ h('div', null, h('code', null, new URL(x.url).hostname), ' ', h('b', null, t('net.diagnoseRoute', { proxy: x.proxy }))),
8235
+ h('div', { class: 'muted small' }, listener ? t(listener.reachable ? 'net.diagnoseListenerUp' : 'net.diagnoseListenerDown', { host: listener.host, port: listener.port, error: listener.error || 'failed' }) : t(x.guardSupport === 'direct' ? 'net.diagnoseDirect' : 'net.diagnoseNoLocalProbe')),
8236
+ h('div', { class: 'muted small' }, [x.guard.status, x.guard.loc || null, x.guard.checkedAt ? t('net.checked', { when: ago(x.guard.checkedAt) }) : t('net.notChecked'), x.guard.error || null].filter(Boolean).join(' · ')),
8237
+ x.guardSupport === 'unsupported' ? h('div', { class: 'small warn' }, t('net.diagnoseUnsupported')) : null,
8238
+ x.guardSupport === 'invalid' ? h('div', { class: 'small warn' }, t('net.diagnoseInvalid')) : null)
8239
+ }) : []
8204
8240
  const body = [
8205
8241
  h('p', { class: 'small' }, t('net.explain')),
8206
8242
  h('div', { class: 'row-actions' },
@@ -8212,6 +8248,14 @@ const MAIN = String.raw `
8212
8248
  h('div', { class: 'set-row' }, h('span', { class: 'set-label' }, t('net.now')),
8213
8249
  h('button', { class: 'btn btn-sm', type: 'button', 'data-key': 'net-check', disabled: net.checking, 'aria-busy': net.checking ? 'true' : null, onclick: netCheck }, net.checking ? spinner() : icon('refresh'), t('net.recheck'))),
8214
8250
  rows.length ? h('ul', { class: 'rc-list', 'data-patch': '' }, rows) : h('p', { class: 'small muted' }, t('net.noTargets')),
8251
+ h('div', { class: 'set-row' }, h('span', { class: 'set-label' }, t('net.diagnose')),
8252
+ h('div', { class: 'row-actions' },
8253
+ h('button', { class: 'btn btn-sm', type: 'button', 'data-key': 'net-diagnose', disabled: net.diagnosing, 'aria-busy': net.diagnosing ? 'true' : null, onclick: netDiagnose }, net.diagnosing ? spinner() : icon('refresh'), t(diagnosis ? 'net.diagnoseRefresh' : 'net.diagnose')),
8254
+ diagnosis ? h('button', { class: 'btn btn-sm', type: 'button', 'data-key': 'net-diagnose-ask', onclick: askNetworkDiagnose }, icon('bot'), t('ask.title.network-diagnose')) : null)),
8255
+ h('p', { class: 'small muted' }, t('net.diagnoseOffline')),
8256
+ diagnosis ? h('p', { class: 'small muted' }, t('net.diagnoseChecked', { when: ago(diagnosis.checkedAt) })) : null,
8257
+ diagnosisRows.length ? h('ul', { class: 'rc-list', 'data-patch': '' }, diagnosisRows) : null,
8258
+ diagnosis ? h('p', { class: 'small muted' }, t('net.diagnoseTcpLimit')) : null,
8215
8259
  skipped.length ? h('p', { class: 'small muted' }, t('net.skipped', { refs: skipped.map((a) => a.ref).join(', ') })) : null,
8216
8260
  h('p', { class: 'small muted' }, t('net.notCovered')),
8217
8261
  BOOT.readOnly ? h('p', { class: 'small' }, t('rc.readOnlyBoth')) : null,
@@ -8228,6 +8272,10 @@ const MAIN = String.raw `
8228
8272
  if (!n) return
8229
8273
  openAsk({ task: 'network', context: { network: networkTaskFacts(n), version: BOOT.version } })
8230
8274
  }
8275
+ function askNetworkDiagnose() {
8276
+ if (!net || !net.diagnosis) return
8277
+ openAsk({ task: 'network-diagnose', context: { networkDiagnose: networkDiagnoseTaskFacts(net.diagnosis), version: BOOT.version } })
8278
+ }
8231
8279
  // Where the problem shows: a banner on every page while the guard is on and the exit is wrong or unknown.
8232
8280
  function netBanner() {
8233
8281
  const x = netProblem()
@@ -8423,13 +8471,14 @@ const MAIN = String.raw `
8423
8471
  }
8424
8472
  function askBody() {
8425
8473
  const body = { task: ak.task, lang }
8474
+ const fixed = ak.task === 'network-diagnose'
8426
8475
  const text = ak.els && ak.els.text ? ak.els.text.value.trim() : ak.text
8427
- if (text) body.text = text
8476
+ if (!fixed && text) body.text = text
8428
8477
  if (ak.context) body.context = ak.context
8429
8478
  if (ak.account && ak.accountChanged) body.account = ak.account
8430
8479
  if (ak.terminal && ak.terminalChanged) body.terminal = ak.terminal
8431
8480
  const ids = ak.files.filter((f) => f.status === 'ready').map((f) => f.id)
8432
- if (ids.length) body.attachments = ids
8481
+ if (!fixed && ids.length) body.attachments = ids
8433
8482
  return body
8434
8483
  }
8435
8484
  function openAsk(opts) {
@@ -8437,7 +8486,7 @@ const MAIN = String.raw `
8437
8486
  closeMenu()
8438
8487
  // In a Portal that offers AI Tasks itself (createPanelHandler's ask bridge), the task goes to its dialog.
8439
8488
  if (askBridge(BOOT, opts, window)) return
8440
- ak = { task: opts.task || 'free', text: opts.text || '', context: opts.context || null, account: null, accountChanged: false, terminal: null, terminalChanged: false, pick: null, reason: null, terms: null, loading: true, busy: false, result: null, error: null, removed: false, files: [], els: {} }
8489
+ ak = { task: opts.task || 'free', text: opts.text || '', context: opts.context || null, account: null, accountChanged: false, terminal: null, terminalChanged: false, pick: null, reason: null, terms: null, loading: true, busy: false, result: null, error: null, removed: false, files: [], els: {}, prompt: null, promptChanged: false }
8441
8490
  showDialog('ask')
8442
8491
  hookDrops()
8443
8492
  const mine = ak
@@ -8459,6 +8508,7 @@ const MAIN = String.raw `
8459
8508
  if (ak !== mine) return
8460
8509
  ak.pick = pick.account
8461
8510
  ak.reason = pick.reason || null
8511
+ if (ak.task === 'network-diagnose') ak.prompt = pick.prompt
8462
8512
  if (!ak.accountChanged) ak.account = pick.account
8463
8513
  ak.terms = terms
8464
8514
  if (terms && !ak.terminalChanged) ak.terminal = terms.guess.id
@@ -8489,6 +8539,12 @@ const MAIN = String.raw `
8489
8539
  h('div', { class: 'ask-chips' }, copy.chips.map((k) => h('button', { class: 'chip chip-btn', type: 'button', onclick: () => { e.text.value = t(k); ak.text = e.text.value; warnNow(); e.text.focus() } }, t(k)))))
8490
8540
  return [h('div', { class: 'field' }, label, e.warn), askAttachField(), chips]
8491
8541
  }
8542
+ function askFixedPrompt() {
8543
+ return h('div', { class: 'field' },
8544
+ h('span', null, t('ask.actualPrompt')),
8545
+ ak.promptChanged ? h('p', { class: 'note note-warn', role: 'status' }, t('ask.promptChanged')) : null,
8546
+ h('pre', { class: 'ask-prompt', id: 'ak-prompt' }, ak.prompt || ''))
8547
+ }
8492
8548
 
8493
8549
  // Attachments (spec §3.28 "附件"): pasted, dropped or picked files upload at once, one request each, so a wrong
8494
8550
  // type or a file that is too big is named right away. The page shows image thumbnails from the file itself as a
@@ -8499,7 +8555,7 @@ const MAIN = String.raw `
8499
8555
  // Which open dialog takes pasted or dropped files now: the AI Task's or "Send to it"'s, until it shows its result.
8500
8556
  function fileDropTarget() {
8501
8557
  if (BOOT.readOnly) return null
8502
- if (dlg.kind === 'ask' && ak && !ak.result) return askAddFiles
8558
+ if (dlg.kind === 'ask' && ak && ak.task !== 'network-diagnose' && !ak.result) return askAddFiles
8503
8559
  if (dlg.kind === 'send' && sd && !sd.result) return sendAddFiles
8504
8560
  return null
8505
8561
  }
@@ -8574,7 +8630,7 @@ const MAIN = String.raw `
8574
8630
  ])
8575
8631
  }
8576
8632
  function askAddFiles(list) {
8577
- if (!ak || !list.length) return
8633
+ if (!ak || ak.task === 'network-diagnose' || !list.length) return
8578
8634
  ak.attachFull = false
8579
8635
  for (const file of list) {
8580
8636
  if (ak.files.filter((f) => f.status !== 'error').length >= ATTACH_MAX) { ak.attachFull = true; break }
@@ -8717,7 +8773,7 @@ const MAIN = String.raw `
8717
8773
  body.push(askResult())
8718
8774
  if (ak.result.removedSecrets) body.push(h('p', { class: 'small muted' }, t('ask.keyRemoved')))
8719
8775
  } else {
8720
- body.push(askTextField(), askConfirm(), askYourself())
8776
+ body.push(ak.task === 'network-diagnose' ? askFixedPrompt() : askTextField(), askConfirm(), askYourself())
8721
8777
  const canOpen = !BOOT.readOnly && !ak.loading && !ak.error && ak.account
8722
8778
  if (canOpen) {
8723
8779
  const term = termName(ak.terminal || 'terminal')
@@ -8748,10 +8804,23 @@ const MAIN = String.raw `
8748
8804
  renderAsk()
8749
8805
  try {
8750
8806
  await askUploadsDone()
8751
- if (ak !== mine) return
8807
+ if (ak !== mine || dlg.kind !== 'ask') return
8752
8808
  renderAsk()
8753
- const r = await api('/api/ask', askBody())
8754
- if (ak !== mine) return
8809
+ const body = askBody()
8810
+ if (ak.task === 'network-diagnose') {
8811
+ const check = await api('/api/ask/prompt', body)
8812
+ if (ak !== mine || dlg.kind !== 'ask') return
8813
+ if (check.prompt !== ak.prompt) {
8814
+ ak.prompt = check.prompt
8815
+ ak.promptChanged = true
8816
+ ak.busy = false
8817
+ renderAsk()
8818
+ return
8819
+ }
8820
+ ak.promptChanged = false
8821
+ }
8822
+ const r = await api('/api/ask', body)
8823
+ if (ak !== mine || dlg.kind !== 'ask') return
8755
8824
  ak.busy = false
8756
8825
  if (r.opened) {
8757
8826
  toast(t('ask.opened', { terminal: termName(r.terminal), ref: r.account }))
@@ -8770,7 +8839,7 @@ const MAIN = String.raw `
8770
8839
  renderAsk()
8771
8840
  copyText(r.command, t('ask.copiedCmd'))
8772
8841
  } catch (e) {
8773
- if (ak !== mine) return
8842
+ if (ak !== mine || dlg.kind !== 'ask') return
8774
8843
  ak.busy = false
8775
8844
  toast(e.message, { kind: 'fail' })
8776
8845
  renderAsk()
@@ -9106,7 +9175,7 @@ const MAIN = String.raw `
9106
9175
  if (BOOT.readOnly) { copyText(name, name); return }
9107
9176
  try {
9108
9177
  const r = await api('/api/pick/start', { name })
9109
- const why = r.reason === 'most-room' ? t('pk.why.room', { n: String(r.pressure), w: r.window ? winTitle(r.window) + ' ' : '' }) : r.reason === 'tight' ? t('pk.why.tight', { n: String(r.pressure), w: r.window ? winTitle(r.window) + ' ' : '', limit: String(r.limit), longLimit: String(r.longLimit) }) : t(r.reason === 'others-full' ? 'pk.why.othersFull' : 'pk.why.noData')
9178
+ const why = r.reason === 'most-room' ? t(r.expiring ? 'pk.why.expiring' : r.running ? 'pk.why.roomRunning' : 'pk.why.room', { n: String(r.pressure), w: r.window ? winTitle(r.window) + ' ' : '', running: String(r.running || 0) }) : r.reason === 'tight' ? t('pk.why.tight', { n: String(r.pressure), w: r.window ? winTitle(r.window) + ' ' : '', limit: String(r.limit), longLimit: String(r.longLimit) }) : t(r.reason === 'others-full' ? 'pk.why.othersFull' : 'pk.why.noData')
9110
9179
  if (r.opened) { toast(t('pk.started', { terminal: TERM_NAMES[r.terminal] || r.terminal, ref: r.picked, why })); return }
9111
9180
  await copyText(name, name)
9112
9181
  toast(r.automation ? t('login.automation', { terminal: TERM_NAMES[r.terminal] || r.terminal }) : t('login.failed'), { kind: 'info' })
@@ -783,6 +783,7 @@ textarea.ask-text { min-height: 64px; resize: vertical; border-radius: var(--rad
783
783
  input[type=password]:focus, textarea.ask-text:focus { border-color: var(--focus); }
784
784
  textarea.ask-text:focus-visible, input[type=password]:focus-visible { outline: var(--focus-outline); outline-offset: 2px; box-shadow: var(--focus-ring); }
785
785
  textarea::placeholder { color: var(--faint); }
786
+ .ask-prompt { margin: 0; padding: 12px; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--surface-2); color: var(--text); white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; font-family: var(--mono); font-size: 12px; line-height: 1.55; }
786
787
  .ask-chips { display: flex; flex-wrap: wrap; gap: 8px; }
787
788
  .ask-chips .chip { font: inherit; font-size: 12px; text-align: left; white-space: normal; }
788
789
  .ask-attach-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
@@ -8,12 +8,12 @@ import { type DesktopDeps } from './core/desktop-app.ts';
8
8
  import { type DoctorReport } from './core/doctor.ts';
9
9
  import type { TraceFetcher } from './core/egress.ts';
10
10
  import { UserError } from './core/errors.ts';
11
- import { type HandoffPlan } from './core/handoff.ts';
11
+ import { type HandoffCandidate, type HandoffPlan, type PickRecord } from './core/handoff.ts';
12
12
  import { type HandoffDecision, type UsedAccount } from './core/handoff-select.ts';
13
13
  import { type DoctorHistory } from './core/last-doctor.ts';
14
14
  import { type HostLaunch, type PreparedLaunch } from './core/launch.ts';
15
15
  import { type LimitResetPlan, type LimitResetResult } from './core/limit-reset.ts';
16
- import { type NetworkOverview } from './core/network.ts';
16
+ import { type ListenerProbe, type NetworkDiagnosis, type NetworkOverview } from './core/network.ts';
17
17
  import { type Paths } from './core/paths.ts';
18
18
  import { type PickChoice } from './core/pick-commands.ts';
19
19
  import { type ProgressView } from './core/progress.ts';
@@ -48,6 +48,14 @@ export interface ResumeLaunch {
48
48
  args: string[];
49
49
  };
50
50
  }
51
+ /** The Account a by-id resume starts in, and the Host arguments to start it with (`Runtime.resumeTarget`). */
52
+ export interface ResumeTarget {
53
+ sessionId: string;
54
+ account: Account;
55
+ args: string[];
56
+ /** The session was never saved: `args` start a new session instead (ADR-0009). */
57
+ newSession?: true;
58
+ }
51
59
  /** What happened to the alias asked for with a new Account. */
52
60
  export interface AliasResult {
53
61
  name: string;
@@ -259,8 +267,14 @@ export interface Runtime {
259
267
  }): Promise<AliasEditResult>;
260
268
  /** The Family a Pick Command picks in, or undefined when `name` is not one. */
261
269
  pickCommandFamily(name: string): string | undefined;
262
- /** The Account the Pick Command `name` starts now, or why it starts nothing (ADR-0035). */
263
- pickChoice(name: string): Promise<{
270
+ /**
271
+ * The Account the Pick Command `name` starts now, or why it starts nothing (ADR-0035). With `record` the caller
272
+ * starts it, so a Pick Record is written for it (ADR-0083) and given to `recorded`; without, it is a preview.
273
+ */
274
+ pickChoice(name: string, opts?: {
275
+ record?: boolean;
276
+ recorded?: (rec: PickRecord) => void;
277
+ }): Promise<{
264
278
  name: string;
265
279
  family: string;
266
280
  choice: PickChoice;
@@ -297,6 +311,8 @@ export interface Runtime {
297
311
  networkStatus(opts?: {
298
312
  check?: boolean;
299
313
  }): Promise<NetworkOverview>;
314
+ /** Offline route, TCP listener and cached Guard diagnosis; never sends a trace. */
315
+ networkDiagnose(): Promise<NetworkDiagnosis>;
300
316
  /**
301
317
  * Unattended Mode (spec §3.37): whether it is on and why, until when, the Schedule, the open Pending Decisions and
302
318
  * which Families' sessions it covers. Read fresh on every call.
@@ -328,6 +344,12 @@ export interface Runtime {
328
344
  ignoreNetwork?: boolean;
329
345
  unattended?: boolean;
330
346
  }): Promise<ResumeLaunch>;
347
+ /**
348
+ * Where the Host arguments' by-id resume belongs (spec §3.13 "按 id 恢复", §3.15): the Account that holds the session
349
+ * (main included) with the arguments unchanged, or the one that started a never-saved session with the resume taken
350
+ * out; null when they resume nothing by id, the Family cannot route, or no Account has the session.
351
+ */
352
+ resumeTarget(familyId: string, userArgs: readonly string[]): Promise<ResumeTarget | null>;
331
353
  /**
332
354
  * The Account's Quota. For an Account of a Same Login (spec §3.21) it is the group's freshest reading, with `from`
333
355
  * naming the Account it was read from when that is another one.
@@ -501,10 +523,15 @@ export interface Runtime {
501
523
  * falls back to the least used Account under 100% (`tight`). Throws a UserError with code `no-quota-source`
502
524
  * when the Family cannot tell, `no-accounts` when it has none. `fetch` is as for `quota`; `never` reads only the kept
503
525
  * answers (the menu bar's cache-only snapshot, spec §3.31).
526
+ * `picks` counts Live Sessions and Pick Records into the ranking (ADR-0083): `read` for a preview; a function for a
527
+ * start, naming the Account the caller will start (or null), for which a Pick Record is written under the pick lock.
504
528
  */
505
529
  handoff(familyId: string, opts?: {
506
530
  includeApi?: boolean;
507
531
  fetch?: QuotaFetchMode;
532
+ picks?: 'read' | ((plan: HandoffPlan) => string | null);
533
+ /** Gets the Pick Record written, the token `cancelPick` takes back when the start does not happen. */
534
+ recorded?: (rec: PickRecord) => void;
508
535
  }): Promise<HandoffPlan>;
509
536
  /** The config `handoff` settings with every default filled in (spec §3.17). */
510
537
  handoffSettings(): HandoffSettings;
@@ -513,13 +540,31 @@ export interface Runtime {
513
540
  * candidate; `used` lists the chain's Accounts so far, as refs or as its hops (an Account whose hop recorded a window
514
541
  * that has reset since may be picked again, ADR-0060). `ahead` decides early what happens once the origin's fullest
515
542
  * window reaches the threshold, as plan.json and the Panel need. `to` names the only candidate (`handoff ready --to`);
516
- * `manual` (`handoff ready`) never waits for a reset.
543
+ * `manual` (`handoff ready`) never waits for a reset. `picks` counts Live Sessions and Pick Records into the ranking
544
+ * (ADR-0083); `record` also writes a Pick Record for a pick, as the real handoff that starts it does, and gives it to
545
+ * `recorded`.
517
546
  */
518
547
  handoffDecision(origin: Account, used: readonly UsedAccount[], opts?: {
519
548
  ahead?: boolean;
520
549
  to?: string;
521
550
  manual?: boolean;
551
+ picks?: 'read' | 'record';
552
+ recorded?: (rec: PickRecord) => void;
522
553
  }): Promise<HandoffDecision>;
554
+ /**
555
+ * One pick spread by Room per Session (ADR-0083): counts the Live Sessions of every Account and reads the Pick
556
+ * Records, and gives both to `rank`, which says which candidates it ranked. With `record`, `started` names the
557
+ * Account the caller will start and its Pick Record (its login's load now) is written, all under one lock; records
558
+ * that arrived or expired are dropped then. Never from a hook entry.
559
+ */
560
+ pickLoad<T>(record: boolean, rank: (live: ReadonlyMap<string, number>, picks: readonly PickRecord[]) => {
561
+ result: T;
562
+ candidates: readonly HandoffCandidate[];
563
+ }, started: (result: T) => string | null,
564
+ /** Gets the record written, if any: the token for `cancelPick`. */
565
+ recorded?: (rec: PickRecord) => void): Promise<T>;
566
+ /** Takes back exactly this Pick Record, when the start it was written for did not happen after all. */
567
+ cancelPick(rec: PickRecord): Promise<void>;
523
568
  readContext(): ReadContext;
524
569
  }
525
570
  export declare class UnknownFamilyError extends UserError {
@@ -551,6 +596,7 @@ export declare function createRuntime(opts?: {
551
596
  network?: {
552
597
  fetcher?: TraceFetcher;
553
598
  print?: string;
599
+ probe?: ListenerProbe;
554
600
  };
555
601
  /**
556
602
  * Internal, for tests: how long a Limit Reset request may take before it counts as unanswered (spec §3.40), so a
@@ -575,4 +621,11 @@ export declare function createRuntime(opts?: {
575
621
  liveRuns?: (account: Account) => Promise<LiveRuns>;
576
622
  trash?: Trash;
577
623
  };
624
+ /**
625
+ * Internal, for tests: the Live Sessions of each Account a pick counts (ADR-0083). Omitted, `listLiveSessions`
626
+ * with `ps`. Not part of the plugin or Portal contract.
627
+ */
628
+ picks?: {
629
+ liveSessions?: () => Promise<ReadonlyMap<string, number>>;
630
+ };
578
631
  }): Promise<Runtime>;