sideby 0.19.1 → 0.20.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 (159) hide show
  1. package/README.md +7 -4
  2. package/ai-tasks.json +28 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +22 -1
  5. package/dist/src/cli/commands.js +815 -21
  6. package/dist/src/cli/format.d.ts +4 -0
  7. package/dist/src/cli/format.js +42 -4
  8. package/dist/src/cli/json-schemas.js +334 -4
  9. package/dist/src/cli/main.js +159 -13
  10. package/dist/src/core/accounts.d.ts +6 -0
  11. package/dist/src/core/accounts.js +12 -0
  12. package/dist/src/core/autostart.d.ts +11 -0
  13. package/dist/src/core/autostart.js +32 -5
  14. package/dist/src/core/browser-profiles.d.ts +23 -2
  15. package/dist/src/core/browser-profiles.js +148 -37
  16. package/dist/src/core/claude-settings-file.d.ts +18 -0
  17. package/dist/src/core/claude-settings-file.js +52 -3
  18. package/dist/src/core/config.d.ts +5 -0
  19. package/dist/src/core/config.js +12 -1
  20. package/dist/src/core/edit-settings.d.ts +7 -0
  21. package/dist/src/core/edit-settings.js +10 -5
  22. package/dist/src/core/history-group.d.ts +28 -0
  23. package/dist/src/core/history-group.js +47 -0
  24. package/dist/src/core/history-index.d.ts +145 -0
  25. package/dist/src/core/history-index.js +447 -0
  26. package/dist/src/core/history-project.d.ts +13 -0
  27. package/dist/src/core/history-project.js +87 -0
  28. package/dist/src/core/history.d.ts +210 -0
  29. package/dist/src/core/history.js +952 -0
  30. package/dist/src/core/inbound.d.ts +62 -0
  31. package/dist/src/core/inbound.js +215 -0
  32. package/dist/src/core/launch.d.ts +9 -1
  33. package/dist/src/core/launch.js +58 -24
  34. package/dist/src/core/live-sessions-copy.d.ts +5 -0
  35. package/dist/src/core/live-sessions-copy.js +46 -0
  36. package/dist/src/core/live-sessions-procs.d.ts +89 -0
  37. package/dist/src/core/live-sessions-procs.js +296 -0
  38. package/dist/src/core/live-sessions-title.d.ts +28 -0
  39. package/dist/src/core/live-sessions-title.js +80 -0
  40. package/dist/src/core/live-sessions.d.ts +68 -0
  41. package/dist/src/core/live-sessions.js +163 -0
  42. package/dist/src/core/login-check.d.ts +15 -0
  43. package/dist/src/core/login-check.js +32 -0
  44. package/dist/src/core/messages.d.ts +83 -0
  45. package/dist/src/core/messages.js +433 -0
  46. package/dist/src/core/project-categories.d.ts +14 -0
  47. package/dist/src/core/project-categories.js +48 -0
  48. package/dist/src/core/quota-fetch.d.ts +3 -3
  49. package/dist/src/core/quota-fetch.js +5 -5
  50. package/dist/src/core/quota-levels.d.ts +5 -0
  51. package/dist/src/core/quota-levels.js +5 -0
  52. package/dist/src/core/remote-control.d.ts +2 -0
  53. package/dist/src/core/remote-control.js +34 -59
  54. package/dist/src/core/run-link.d.ts +76 -0
  55. package/dist/src/core/run-link.js +245 -0
  56. package/dist/src/core/same-login.d.ts +4 -3
  57. package/dist/src/core/same-login.js +10 -7
  58. package/dist/src/core/session-select.d.ts +31 -0
  59. package/dist/src/core/session-select.js +44 -0
  60. package/dist/src/families/browser.d.ts +7 -18
  61. package/dist/src/families/browser.js +19 -8
  62. package/dist/src/families/claude/deliver.d.ts +2 -0
  63. package/dist/src/families/claude/deliver.js +43 -0
  64. package/dist/src/families/claude/history.d.ts +2 -0
  65. package/dist/src/families/claude/history.js +192 -0
  66. package/dist/src/families/claude/live-sessions.d.ts +13 -0
  67. package/dist/src/families/claude/live-sessions.js +117 -0
  68. package/dist/src/families/claude/messaging.d.ts +69 -0
  69. package/dist/src/families/claude/messaging.js +165 -0
  70. package/dist/src/families/claude/mod.d.ts +26 -0
  71. package/dist/src/families/claude/mod.js +105 -0
  72. package/dist/src/families/claude/session-files.d.ts +21 -0
  73. package/dist/src/families/claude/session-files.js +54 -0
  74. package/dist/src/families/codex/deliver.d.ts +5 -0
  75. package/dist/src/families/codex/deliver.js +76 -0
  76. package/dist/src/families/codex/history.d.ts +7 -0
  77. package/dist/src/families/codex/history.js +174 -0
  78. package/dist/src/families/codex/index.js +2 -0
  79. package/dist/src/families/codex/live-sessions.d.ts +12 -0
  80. package/dist/src/families/codex/live-sessions.js +193 -0
  81. package/dist/src/families/codex/quota.d.ts +3 -0
  82. package/dist/src/families/codex/quota.js +123 -0
  83. package/dist/src/families/codex/rate-limits.js +2 -0
  84. package/dist/src/families/codex/rollout.js +1 -1
  85. package/dist/src/families/grok/browser.d.ts +3 -0
  86. package/dist/src/families/grok/browser.js +5 -0
  87. package/dist/src/families/grok/history.d.ts +2 -0
  88. package/dist/src/families/grok/history.js +157 -0
  89. package/dist/src/families/grok/live-sessions.d.ts +4 -0
  90. package/dist/src/families/grok/live-sessions.js +80 -0
  91. package/dist/src/families/grok/login-key.d.ts +14 -0
  92. package/dist/src/families/grok/login-key.js +37 -0
  93. package/dist/src/families/history.d.ts +20 -0
  94. package/dist/src/families/history.js +81 -0
  95. package/dist/src/families/live-sessions.d.ts +26 -0
  96. package/dist/src/families/live-sessions.js +9 -0
  97. package/dist/src/families/login-keys.js +5 -1
  98. package/dist/src/families/messaging.d.ts +27 -0
  99. package/dist/src/families/messaging.js +6 -0
  100. package/dist/src/families/pi/history.d.ts +2 -0
  101. package/dist/src/families/pi/history.js +124 -0
  102. package/dist/src/families/pi/live-sessions.d.ts +2 -0
  103. package/dist/src/families/pi/live-sessions.js +70 -0
  104. package/dist/src/families/shared/history-text.d.ts +65 -0
  105. package/dist/src/families/shared/history-text.js +261 -0
  106. package/dist/src/menubar/hotkey.d.ts +86 -0
  107. package/dist/src/menubar/hotkey.js +159 -0
  108. package/dist/src/menubar/script.d.ts +2 -0
  109. package/dist/src/menubar/script.js +118 -22
  110. package/dist/src/menubar/snapshot.d.ts +8 -4
  111. package/dist/src/menubar/snapshot.js +45 -13
  112. package/dist/src/menubar/strings.d.ts +24 -6
  113. package/dist/src/menubar/strings.js +24 -6
  114. package/dist/src/panel/handler.d.ts +69 -0
  115. package/dist/src/panel/handler.js +686 -15
  116. package/dist/src/panel/i18n.d.ts +304 -3
  117. package/dist/src/panel/i18n.js +620 -18
  118. package/dist/src/panel/orca.d.ts +48 -0
  119. package/dist/src/panel/orca.js +153 -0
  120. package/dist/src/panel/page-logic.d.ts +255 -13
  121. package/dist/src/panel/page-logic.js +483 -1
  122. package/dist/src/panel/page-script.js +2260 -204
  123. package/dist/src/panel/page-styles.js +404 -32
  124. package/dist/src/panel/page.js +1 -0
  125. package/dist/src/plugins/check.js +16 -4
  126. package/dist/src/plugins/loader.d.ts +8 -1
  127. package/dist/src/plugins/loader.js +72 -7
  128. package/dist/src/runtime.d.ts +5 -0
  129. package/dist/src/runtime.js +27 -5
  130. package/dist/src/types.d.ts +116 -1
  131. package/dist/testing/index.d.ts +5 -0
  132. package/dist/testing/index.js +5 -0
  133. package/mods/claude/.claude-plugin/plugin.json +7 -0
  134. package/mods/claude/hooks/hooks.json +1 -0
  135. package/mods/claude/hooks/register.js +261 -0
  136. package/package.json +5 -2
  137. package/schemas/autostart.json +74 -1
  138. package/schemas/browser-set.json +110 -0
  139. package/schemas/browser.json +22 -2
  140. package/schemas/config.json +26 -1
  141. package/schemas/history-index.json +209 -0
  142. package/schemas/history-projects.json +133 -0
  143. package/schemas/history-show.json +275 -0
  144. package/schemas/history.json +410 -0
  145. package/schemas/menubar-hotkey.json +139 -0
  146. package/schemas/menubar-snapshot.json +36 -2
  147. package/schemas/menubar.json +74 -1
  148. package/schemas/messages-inbound.json +258 -0
  149. package/schemas/messages.json +164 -0
  150. package/schemas/send.json +165 -0
  151. package/schemas/sessions-copy.json +113 -0
  152. package/schemas/sessions-open-run.json +97 -0
  153. package/schemas/sessions.json +237 -0
  154. package/skills/sideby/SKILL.md +10 -5
  155. package/skills/sideby/references/accounts.md +11 -0
  156. package/skills/sideby/references/ai-tasks.md +17 -1
  157. package/skills/sideby/references/panel.md +6 -4
  158. package/skills/sideby/references/quota.md +2 -2
  159. package/skills/sideby/references/sessions.md +79 -0
@@ -2,7 +2,7 @@ import { StringDecoder } from 'node:string_decoder';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { aliasesByAccount } from '../core/accounts.js';
4
4
  import { listAppProfiles, openAppProfile, parseProfileRef, removeAppProfile } from '../core/app-profiles.js';
5
- import { browserReport, openInBrowser, setBrowserSignIns } from '../core/browser-profiles.js';
5
+ import { browserReport, openInBrowser, setBrowserChoice, setBrowserSignIns, } from '../core/browser-profiles.js';
6
6
  import { aliasAccount, aliasArgs, aliasRefs, editConfigUpdate } from '../core/config.js';
7
7
  import { openDesktopApp, withDesktopApps } from '../core/desktop-app.js';
8
8
  import { editSettings } from '../core/edit-settings.js';
@@ -12,16 +12,17 @@ import { handoffOverview } from '../core/handoff-overview.js';
12
12
  import { explain, readyDecision, runWithHandoff } from '../core/handoff-run.js';
13
13
  import { configureHandoff, handoffHint, handoffStatus } from '../core/handoff-status.js';
14
14
  import { installHint, runHost } from '../core/launch.js';
15
+ import { loginAfterLine, loginBeforeLine } from '../core/login-check.js';
15
16
  import { accountModel, setAccountModel } from '../core/model-choice.js';
16
17
  import { resolvePaths, tildify } from '../core/paths.js';
17
18
  import { USAGE_DAYS } from '../core/quota-levels.js';
18
- import { groupsToTurnOff, groupsToTurnOn, groupsToUndo, } from '../core/remote-control.js';
19
+ import { groupsToTurnOff, groupsToTurnOn, groupsToUndo, remoteControlNothingToDo, } from '../core/remote-control.js';
19
20
  import { SHELLS } from '../core/shell-init.js';
20
21
  import { MODEL_NAME } from '../families/shared/model-args.js';
21
22
  import { AI_TASK_KINDS, inDisplayOrder, pinnedIn, suggestAlias, suggestName, withPinned, } from '../panel/page-logic.js';
22
23
  import { createRuntime, UnknownFamilyError } from '../runtime.js';
23
24
  import { UsageError } from './args.js';
24
- import { c, clock, compactNumber, quotaText, table, tuningLines, usageText } from './format.js';
25
+ import { c, clock, compactNumber, quotaText, table, truncate, tuningLines, usageText } from './format.js';
25
26
  /** Runs `fn` while a record under the state directory says a Host runs (also for `login`), so an Auto Update waits (spec §3.23). */
26
27
  async function whileRunning(rt, fn) {
27
28
  const { markRunning } = await import('../core/update.js');
@@ -412,10 +413,41 @@ export async function cmdRun(a, io, command) {
412
413
  return runPick(rt, ref, [...extra, ...a.rest], io);
413
414
  if (command === 'run')
414
415
  return runAccount(rt, ref, [...extra, ...a.rest], io);
415
- const prepared = await rt.prepareLaunch(ref, [...extra, ...a.rest], command);
416
+ return runLogin(rt, ref, io);
417
+ }
418
+ /** Who an Account is signed in as, for `runLogin`; identity fields and Same Login peers only, never a credential. */
419
+ async function loginSnapshot(rt, account) {
420
+ const s = await rt.status(account);
421
+ return {
422
+ login: s.login,
423
+ ...(s.identity?.email ? { email: s.identity.email } : {}),
424
+ sameLogin: s.sameLogin ?? [],
425
+ };
426
+ }
427
+ /**
428
+ * `sideby login` and the Panel's sign-in (spec §3.21 "换个账号登录"): the Host's own sign-in, with a line before on how
429
+ * to choose another login and a line after on whether the Account now has a login of its own. Exits as the Host does.
430
+ */
431
+ async function runLogin(rt, ref, io) {
432
+ const account = await rt.resolve(ref);
433
+ // pi signs in inside the app (`login.args` null), so there is no sign-in of its own to compare around.
434
+ const before = rt.families.get(account.family)?.login.args
435
+ ? await loginSnapshot(rt, account).catch(() => undefined)
436
+ : undefined;
437
+ const prepared = await rt.prepareLaunch(account.ref, [], 'login');
416
438
  if (prepared.notice)
417
439
  io.err(c.cyan(prepared.notice));
418
- return whileRunning(rt, () => runHost(prepared));
440
+ const hint = before && loginBeforeLine(account.ref, before);
441
+ if (hint)
442
+ io.err(c.dim(`sideby: ${hint}`));
443
+ const code = await whileRunning(rt, () => runHost(prepared));
444
+ if (!before)
445
+ return code;
446
+ const after = await loginSnapshot(rt, account).catch(() => undefined);
447
+ const result = after && loginAfterLine(account.ref, before, after);
448
+ if (result)
449
+ io.err((result.ok ? c.green : c.yellow)(`sideby: ${result.line}`));
450
+ return code;
419
451
  }
420
452
  /** A Pick Command (spec §3.13, ADR-0035): start the Account with the most room, else the Main Account, and say which. */
421
453
  async function runPick(rt, name, args, io) {
@@ -685,13 +717,13 @@ function rcGroupLine(g, home) {
685
717
  * `sideby remote-control [on|off|undo] [--yes] [--json]` (spec §3.22, ADR-0017): whether Claude sessions connect to
686
718
  * claude.ai by themselves, and turning that on or off for every Account (a preview with exit 10 until --yes).
687
719
  */
688
- export async function cmdRemoteControl(a, io) {
720
+ export async function cmdRemoteControl(a, io, runtime) {
689
721
  const [action, extra] = a.positionals;
690
722
  if (extra !== undefined ||
691
723
  (action !== undefined && action !== 'on' && action !== 'off' && action !== 'undo'))
692
724
  throw new UsageError('usage: sideby remote-control [on|off|undo] [--yes] [--json]');
693
725
  const wantJson = a.flags.has('json');
694
- const rt = await createRuntime();
726
+ const rt = runtime ?? (await createRuntime());
695
727
  const home = rt.paths.home;
696
728
  const show = (gs) => gs.map((g) => ({ ...g, file: tildify(g.file, home) }));
697
729
  const out = (data) => json(io, { action: action ?? 'status', ...data });
@@ -721,12 +753,13 @@ export async function cmdRemoteControl(a, io) {
721
753
  : groupsToUndo(groups);
722
754
  const verb = action === 'off' ? 'turn it off' : action === 'on' ? 'turn it on' : 'undo';
723
755
  if (todo.length === 0) {
724
- const r = await apply();
756
+ // Only what was read: writing here would act on a file the user never saw in a preview.
757
+ const r = remoteControlNothingToDo(action, groups);
725
758
  if (wantJson)
726
759
  out({ applied: false, groups: show(groups), message: r.message });
727
760
  else
728
761
  io.out(tilde(r.message, home));
729
- return r.ok ? 0 : 1;
762
+ return 1;
730
763
  }
731
764
  if (!a.flags.has('yes')) {
732
765
  if (wantJson)
@@ -1203,7 +1236,7 @@ export async function cmdPlugins(a, io) {
1203
1236
  c.bold(p.name),
1204
1237
  p.version,
1205
1238
  p.source === 'builtin' ? 'built-in' : tildify(p.source, rt.paths.home),
1206
- p.families.join(', ') || c.dim('hooks'),
1239
+ [...p.families, ...(p.name === rt.projectCategoriesFrom ? ['project categories'] : [])].join(', ') || c.dim('hooks'),
1207
1240
  ]), ['PLUGIN', 'VERSION', 'SOURCE', 'PROVIDES']));
1208
1241
  for (const e of rt.pluginErrors)
1209
1242
  io.err(c.red(`✗ ${e.where}: ${e.message}`));
@@ -1758,8 +1791,24 @@ export async function cmdBrowser(a, io) {
1758
1791
  io.out(`${c.green('✓')} opened ${r.url} in Chrome as ${c.bold(r.profile.name)} for ${c.bold(r.ref)}`);
1759
1792
  return 0;
1760
1793
  }
1794
+ if (sub === 'set') {
1795
+ const auto = a.flags.has('auto');
1796
+ const [profile, ...more] = extra;
1797
+ if (!ref || more.length || a.rest.length || auto === (profile !== undefined))
1798
+ throw new UsageError('usage: sideby browser set <account> <folder|name> | sideby browser set <account> --auto');
1799
+ const r = await setBrowserChoice(rt, await rt.resolve(ref), auto ? null : profile);
1800
+ if (a.flags.has('json'))
1801
+ json(io, r);
1802
+ else if (r.profile)
1803
+ io.out(`${c.green('✓')} ${c.bold(r.ref)} now opens in ${c.bold(r.profile.name)} (${r.profile.dir})${r.changed ? '' : '; it already did'}.`);
1804
+ else
1805
+ io.out(r.changed
1806
+ ? `${c.green('✓')} sideby finds the browser user of ${c.bold(r.ref)} by itself again.`
1807
+ : `Nothing was chosen for ${r.ref}; sideby already finds its browser user by itself.`);
1808
+ return 0;
1809
+ }
1761
1810
  if (sub !== undefined || a.rest.length)
1762
- throw new UsageError('usage: sideby browser [--enable|--disable] [--yes] | sideby browser open <account>');
1811
+ throw new UsageError('usage: sideby browser [--enable|--disable] [--yes] | sideby browser open <account> | sideby browser set <account> <folder|name>');
1763
1812
  const enable = a.flags.has('enable');
1764
1813
  if (enable || a.flags.has('disable')) {
1765
1814
  if (enable && a.flags.has('disable'))
@@ -1807,16 +1856,17 @@ export async function cmdBrowser(a, io) {
1807
1856
  p.name,
1808
1857
  p.email ?? c.dim('-'),
1809
1858
  p.dir,
1810
- p.signIns.join(', ') || c.dim('-'),
1859
+ p.signIns.map((x) => (r.choices[x] ? `${x} (chosen)` : x)).join(', ') || c.dim('-'),
1811
1860
  p.changedAt ? clock(p.changedAt, now) : '-',
1812
1861
  ]), ['Browser user', 'Google account', 'Folder', 'Signed in to', 'Changed']));
1813
1862
  const missing = accounts.filter((x) => r.families.matched.includes(x.family) && x.kind !== 'api' && !signedIn.has(x.ref));
1814
1863
  if (missing.length)
1815
1864
  io.out(c.dim(`\nNo browser user found for: ${missing.map((x) => x.ref).join(', ')}`));
1816
1865
  if (r.families.openOnly.length)
1817
- io.out(c.dim(`${r.families.openOnly.join(', ')}: the website keeps no id to match; open it with --profile.`));
1866
+ io.out(c.dim(`${r.families.openOnly.join(', ')}: the website keeps no id to match, so only the login email can find it; choose one with \`sideby browser set\`.`));
1818
1867
  io.out(c.dim('\nRead from Chrome on this computer only; a browser user that signed out may still show.'));
1819
1868
  io.out(c.dim('Open one: sideby browser open <account> [--profile <name>]'));
1869
+ io.out(c.dim('Wrong one? sideby browser set <account> <folder|name>; --auto finds it again'));
1820
1870
  return 0;
1821
1871
  }
1822
1872
  export async function cmdAlias(a, io) {
@@ -1972,10 +2022,7 @@ export async function cmdAsk(a, io, runtime) {
1972
2022
  return rt.pickCommandFamily(task.account) !== undefined
1973
2023
  ? await runPick(rt, task.account, [], io)
1974
2024
  : await runAccount(rt, task.account, [], io);
1975
- const prepared = await rt.prepareLaunch(task.account, [], 'login');
1976
- if (prepared.notice)
1977
- io.err(prepared.notice);
1978
- return await whileRunning(rt, () => runHost(prepared));
2025
+ return await runLogin(rt, task.account, io);
1979
2026
  }
1980
2027
  finally {
1981
2028
  process.chdir(cwd);
@@ -2353,12 +2400,40 @@ export async function cmdMenubar(a, io) {
2353
2400
  const [action, extra] = a.positionals;
2354
2401
  const wantJson = a.flags.has('json');
2355
2402
  if (action === 'snapshot') {
2356
- if (extra !== undefined)
2357
- throw new UsageError('usage: sideby menubar snapshot [--lang en|zh] [--json]');
2403
+ const reported = a.flags.get('hotkey');
2404
+ const icon = a.flags.get('icon');
2405
+ if (extra !== undefined ||
2406
+ (reported !== undefined && reported !== 'ok' && reported !== 'taken') ||
2407
+ (icon !== undefined && icon !== 'visible' && icon !== 'hidden'))
2408
+ throw new UsageError('usage: sideby menubar snapshot [--refresh] [--lang en|zh] [--hotkey ok|taken [--hotkey-label <label>]] [--icon visible|hidden] [--json]');
2358
2409
  const { menubarHotkey, menubarLang, menubarSnapshot } = await import('../menubar/snapshot.js');
2359
2410
  const rt = await createRuntime();
2411
+ const hotkey = menubarHotkey(rt.config.menubar?.hotkey);
2412
+ // The menu bar script says whether it could register the shortcut; the Panel and `menubar hotkey` show it.
2413
+ // The script says whether macOS shows its icon now; the Panel says where it went when it does not.
2414
+ if (icon) {
2415
+ const { writeMenubarState } = await import('../menubar/hotkey.js');
2416
+ await writeMenubarState(rt.paths.stateDir, {
2417
+ icon: { visible: icon === 'visible', at: rt.readContext().now.toISOString() },
2418
+ }).catch(() => { });
2419
+ }
2420
+ // The script names the shortcut it registered; config may have changed since, and the Panel then shows nothing.
2421
+ const label = a.flags.get('hotkey-label') ?? hotkey?.label;
2422
+ if (reported && label) {
2423
+ const { readHotkeyState, writeHotkeyState } = await import('../menubar/hotkey.js');
2424
+ const before = await readHotkeyState(rt.paths.stateDir);
2425
+ const registered = reported === 'ok';
2426
+ if (before?.label !== label || before.registered !== registered)
2427
+ await writeHotkeyState(rt.paths.stateDir, {
2428
+ label,
2429
+ registered,
2430
+ at: rt.readContext().now.toISOString(),
2431
+ }).catch(() => { });
2432
+ }
2360
2433
  const lang = menubarLang(rt.config.panel?.language, a.flags.get('lang') ?? rt.env.LANG);
2361
- const snap = menubarSnapshot(await menubarFamilies(rt), rt.readContext().now, lang, menubarHotkey(rt.config.menubar?.hotkey));
2434
+ if (a.flags.has('refresh'))
2435
+ await rt.refreshQuota();
2436
+ const snap = menubarSnapshot(await menubarFamilies(rt), rt.readContext().now, lang, hotkey);
2362
2437
  if (wantJson)
2363
2438
  json(io, snap);
2364
2439
  else {
@@ -2377,6 +2452,44 @@ export async function cmdMenubar(a, io) {
2377
2452
  }
2378
2453
  return 0;
2379
2454
  }
2455
+ if (action === 'hotkey') {
2456
+ if (a.positionals.length > 2)
2457
+ throw new UsageError('usage: sideby menubar hotkey [<keys>|off|default] [--json]');
2458
+ const { hotkeyView, readHotkeyState, setMenubarHotkey } = await import('../menubar/hotkey.js');
2459
+ const paths = resolvePaths();
2460
+ if (extra === undefined) {
2461
+ const { loadConfig } = await import('../core/config.js');
2462
+ const v = hotkeyView((await loadConfig(paths.configFile)).menubar?.hotkey, await readHotkeyState(paths.stateDir));
2463
+ if (wantJson)
2464
+ json(io, v);
2465
+ else {
2466
+ io.out(!v.enabled
2467
+ ? 'Menu bar shortcut: off.'
2468
+ : `Menu bar shortcut: ${v.label}${v.isDefault ? ' (default)' : ''}${v.registered === false ? ', but macOS did not accept it (something else uses it)' : ''}.`);
2469
+ if (v.registered === false)
2470
+ io.out(c.dim('Pick another: sideby menubar hotkey ctrl+opt+s (or free it in System Settings › Keyboard › Keyboard Shortcuts)'));
2471
+ if (v.problem)
2472
+ io.out(c.dim(`It works, but a new choice would be refused: ${v.problem.message}.`));
2473
+ io.out(c.dim('Change it: sideby menubar hotkey <keys>|off|default, such as opt+x (one hand)'));
2474
+ }
2475
+ return 0;
2476
+ }
2477
+ const r = await setMenubarHotkey({
2478
+ configFile: paths.configFile,
2479
+ stateDir: paths.stateDir,
2480
+ value: extra,
2481
+ ctx: { home: paths.home },
2482
+ });
2483
+ if (wantJson)
2484
+ json(io, r);
2485
+ else if (!r.changed)
2486
+ io.out('Nothing to change.');
2487
+ else
2488
+ io.out(r.hotkey.enabled
2489
+ ? `Menu bar shortcut: ${r.hotkey.label}.${r.nudged ? ' The menu bar item takes it within seconds.' : ''}`
2490
+ : 'Menu bar shortcut turned off.');
2491
+ return 0;
2492
+ }
2380
2493
  if (action === 'start') {
2381
2494
  if (!extra || a.positionals.length > 2)
2382
2495
  throw new UsageError('usage: sideby menubar start <account> [--json]');
@@ -2416,8 +2529,18 @@ export async function cmdMenubar(a, io) {
2416
2529
  }
2417
2530
  if (!action) {
2418
2531
  const s = await autostartStatus(ctx, MENUBAR_AGENT);
2532
+ const { hotkeyView, iconView, readMenubarState } = await import('../menubar/hotkey.js');
2533
+ const { loadConfig } = await import('../core/config.js');
2534
+ const paths = resolvePaths();
2535
+ const kept = await readMenubarState(paths.stateDir);
2536
+ const hotkey = hotkeyView((await loadConfig(paths.configFile)).menubar?.hotkey, kept.hotkey ?? null);
2537
+ const icon = iconView(kept.icon, new Date());
2419
2538
  if (wantJson)
2420
- json(io, { ...s, path: tilde(s.path, home) });
2539
+ json(io, {
2540
+ ...s,
2541
+ path: tilde(s.path, home),
2542
+ ...(s.supported ? { hotkey, ...(s.state === 'on' ? { icon } : {}) } : {}),
2543
+ });
2421
2544
  else if (!s.supported)
2422
2545
  io.out('The menu bar item is only available on macOS for now.');
2423
2546
  else if (s.state === 'off')
@@ -2426,10 +2549,18 @@ export async function cmdMenubar(a, io) {
2426
2549
  io.out(`${tilde(s.path, home)} is not sideby's, so sideby leaves it alone; remove or rename it yourself if it is not needed.`);
2427
2550
  else if (s.state === 'stale')
2428
2551
  io.out('Menu bar item: points to a sideby or Node that is no longer there. Run `sideby menubar on` to fix it.');
2552
+ else if (s.loaded === false)
2553
+ io.out('Menu bar item: on, but not running, so no icon shows. Run `sideby menubar on --yes` to start it again.');
2429
2554
  else {
2430
2555
  io.out('Menu bar item: on.');
2556
+ if (icon.visible === false)
2557
+ io.out('Its icon is hidden right now: click « in the menu bar to see it, or set it to always show in System Settings › Menu Bar.');
2431
2558
  if (!s.current)
2432
2559
  io.out(c.dim('It runs another sideby than this one; `sideby menubar on` points it here.'));
2560
+ if (hotkey.registered === false)
2561
+ io.out(`macOS did not accept its shortcut ${hotkey.label}; pick another with \`sideby menubar hotkey <keys>\`.`);
2562
+ else if (hotkey.enabled)
2563
+ io.out(c.dim(`Open it from anywhere with ${hotkey.label} (sideby menubar hotkey to change).`));
2433
2564
  io.out(c.dim('Turn it off: sideby menubar off'));
2434
2565
  }
2435
2566
  return 0;
@@ -2584,3 +2715,666 @@ export async function cmdConfig(a, io) {
2584
2715
  }
2585
2716
  return r.changed && !yes ? 10 : 0;
2586
2717
  }
2718
+ const SESSION_STATUS = {
2719
+ 'needs-you': 'needs you',
2720
+ busy: 'running',
2721
+ idle: 'idle',
2722
+ unknown: '—',
2723
+ };
2724
+ /** The language of a copied Session Reference: `--lang`, else the user's locale. */
2725
+ function copyLang(a, env) {
2726
+ const flag = a.flags.get('lang');
2727
+ if (flag !== undefined) {
2728
+ if (flag !== 'en' && flag !== 'zh')
2729
+ throw new UsageError('--lang takes en or zh');
2730
+ return flag;
2731
+ }
2732
+ return /^zh/i.test(env.LC_ALL || env.LC_MESSAGES || env.LANG || '') ? 'zh' : 'en';
2733
+ }
2734
+ /**
2735
+ * `sideby sessions [<account>|<family>]`: the Live Sessions of every Account (spec §3.32);
2736
+ * `sideby sessions copy <account|session-id> [--as reference|id|resume]` copies one of them for another AI;
2737
+ * `sideby sessions open-run <account|session-id>` opens the Run Board of one (spec §3.32 step 2b).
2738
+ */
2739
+ export async function cmdSessions(a, io, runtime) {
2740
+ const [first, ...more] = a.positionals;
2741
+ if (first === 'copy')
2742
+ return sessionsCopy(a, more, io, runtime);
2743
+ if (first === 'open-run')
2744
+ return sessionsOpenRun(a, more, io, runtime);
2745
+ if (more.length || a.rest.length)
2746
+ throw new UsageError('usage: sideby sessions [<account>|<family>] | sideby sessions copy <account|session-id> | sideby sessions open-run <account|session-id>');
2747
+ const rt = runtime ?? (await createRuntime());
2748
+ const { listLiveSessions, sessionLabel } = await import('../core/live-sessions.js');
2749
+ const { withRuns } = await import('../core/run-link.js');
2750
+ const r = await listLiveSessions(rt, first ? { only: first } : {});
2751
+ const sessions = await withRuns(rt.env, rt.paths.home, r.sessions);
2752
+ if (a.flags.has('json')) {
2753
+ json(io, { sessions, problems: r.problems });
2754
+ return 0;
2755
+ }
2756
+ for (const p of r.problems)
2757
+ io.err(c.yellow(`sideby: ${p}`));
2758
+ if (!sessions.length) {
2759
+ io.out(first
2760
+ ? `${first} has no running session now. Start one with \`sideby run <account>\` and it shows up here.`
2761
+ : 'No sessions are running now. Start an account with `sideby run <account>` and it shows up here.');
2762
+ return 0;
2763
+ }
2764
+ const now = rt.readContext().now;
2765
+ const home = rt.paths.home;
2766
+ // A long title (often in Chinese, two columns a character) is cut so the table stays readable.
2767
+ // The RUN column shows only when an orchestrator's Session Index ties a Session to a Run (spec §3.32 step 2b).
2768
+ const anyRun = sessions.some((s) => s.run);
2769
+ const rows = sessions.map((s) => [
2770
+ c.bold(sessionLabel(s.accountLabel, truncate(s.title, 40), s.sessionId)),
2771
+ s.status === 'needs-you' ? c.yellow(SESSION_STATUS[s.status]) : SESSION_STATUS[s.status],
2772
+ s.cwd ? tildify(s.cwd, home) : '',
2773
+ s.startedAt ? clock(s.startedAt, now) : '',
2774
+ ...(anyRun
2775
+ ? [s.run ? truncate(s.run.title, 30) + (s.run.others ? ` +${s.run.others.length}` : '') : '']
2776
+ : []),
2777
+ s.guessed ? c.dim('newest session (guessed)') : '',
2778
+ ]);
2779
+ io.out(table(rows, ['SESSION', 'STATUS', 'DIRECTORY', 'STARTED', ...(anyRun ? ['RUN'] : []), '']));
2780
+ // One line per Run board (each checked one, once), so the user can open it.
2781
+ const boards = new Map();
2782
+ for (const s of sessions)
2783
+ for (const r of s.run ? [s.run, ...(s.run.others ?? [])] : [])
2784
+ if (!boards.has(r.board))
2785
+ boards.set(r.board, r.title);
2786
+ for (const [board, title] of boards)
2787
+ io.out(c.dim(`Run: ${title} ${tildify(board, home)}`));
2788
+ if (boards.size)
2789
+ io.out(c.dim('Open its run report: sideby sessions open-run <account|session-id>'));
2790
+ io.out(c.dim('Copy one for another AI: sideby sessions copy <account|session-id>'));
2791
+ return 0;
2792
+ }
2793
+ /** Prints the listing's problems to stderr unless the output is JSON. */
2794
+ const listedProblems = (a, io) => (l) => {
2795
+ if (!a.flags.has('json'))
2796
+ for (const p of l.problems)
2797
+ io.err(c.yellow(`sideby: ${p}`));
2798
+ };
2799
+ async function sessionsOpenRun(a, args, io, runtime) {
2800
+ const [target, ...extra] = args;
2801
+ if (!target || extra.length || a.rest.length)
2802
+ throw new UsageError('usage: sideby sessions open-run <account|session-id>');
2803
+ const rt = runtime ?? (await createRuntime());
2804
+ const { selectSession } = await import('../core/session-select.js');
2805
+ const { openRunBoard } = await import('../core/run-link.js');
2806
+ const { session: s } = await selectSession(rt, target, {
2807
+ next: { verb: 'open the run report of', command: (id) => `sideby sessions open-run ${id}` },
2808
+ onListed: listedProblems(a, io),
2809
+ });
2810
+ // The same checks and opener as the Panel's "Open run report": the board comes only from the Session Index.
2811
+ const r = await openRunBoard(rt, s.sessionId);
2812
+ const board = tildify(r.board, rt.paths.home);
2813
+ if (a.flags.has('json')) {
2814
+ json(io, { opened: true, board, sessionId: s.sessionId, label: s.label });
2815
+ return 0;
2816
+ }
2817
+ io.out(`${c.green('✓')} opened the run report of ${c.bold(s.label)}`);
2818
+ io.out(c.dim(` ${board}`));
2819
+ return 0;
2820
+ }
2821
+ async function sessionsCopy(a, args, io, runtime) {
2822
+ const [target, ...extra] = args;
2823
+ if (!target || extra.length || a.rest.length)
2824
+ throw new UsageError('usage: sideby sessions copy <account|session-id> [--as reference|id|resume]');
2825
+ const as = (a.flags.get('as') ?? 'reference');
2826
+ if (as !== 'reference' && as !== 'id' && as !== 'resume')
2827
+ throw new UsageError('--as takes reference, id or resume');
2828
+ const rt = runtime ?? (await createRuntime());
2829
+ const lang = copyLang(a, rt.env);
2830
+ const { sessionCopyText } = await import('../core/live-sessions.js');
2831
+ const { copyToClipboard } = await import('../core/live-sessions-copy.js');
2832
+ const { selectSession } = await import('../core/session-select.js');
2833
+ const { session: s } = await selectSession(rt, target, { onListed: listedProblems(a, io) });
2834
+ const text = sessionCopyText(s, as, lang);
2835
+ const program = await copyToClipboard(text, rt.env);
2836
+ if (a.flags.has('json')) {
2837
+ json(io, { copied: program !== null, as, text, sessionId: s.sessionId, label: s.label });
2838
+ return 0;
2839
+ }
2840
+ const what = as === 'reference' ? 'a reference to' : as === 'id' ? 'the id of' : 'the resume command of';
2841
+ if (program) {
2842
+ io.out(`${c.green('✓')} copied ${what} ${c.bold(s.label)}; paste it into the other AI`);
2843
+ io.out(c.dim(text));
2844
+ }
2845
+ else {
2846
+ io.out(text);
2847
+ io.err(c.yellow('sideby: no clipboard program found (pbcopy on macOS, wl-copy or xclip on Linux); copy the text above yourself'));
2848
+ }
2849
+ return 0;
2850
+ }
2851
+ const HISTORY_USAGE = 'usage: sideby history [<words>...] [--project <p>] [--family <id>] [--account <a>] [--since today|7d|30d|all] [--category <c>] [--group project|category|account|family|day|none] [--scripts] [--tools] [--limit <n>] [--offset <n>] | sideby history show <id> [--account <a>] | sideby history projects [--family <id>] [--account <a>] [--since <s>] [--scripts] | sideby history index [--clear]';
2852
+ function positiveInt(a, name) {
2853
+ const v = a.flags.get(name);
2854
+ if (v === undefined)
2855
+ return undefined;
2856
+ const n = Number(v);
2857
+ if (!Number.isInteger(n) || n < 1)
2858
+ throw new UsageError(`--${name} takes a whole number of 1 or more`);
2859
+ return n;
2860
+ }
2861
+ /** Prints how far the first build of the History Index is, on stderr, while `work` runs. */
2862
+ async function withIndexProgress(rt, io, quiet, work) {
2863
+ const { historyBuilt, historyIndexInfo } = await import('../core/history.js');
2864
+ if (quiet || historyBuilt(rt) || !process.stderr.isTTY)
2865
+ return work;
2866
+ const timer = setInterval(() => {
2867
+ historyIndexInfo(rt)
2868
+ .then((i) => {
2869
+ if (i.progress.total)
2870
+ io.err(c.dim(`Building the History Index: ${i.progress.done}/${i.progress.total} files…`));
2871
+ })
2872
+ .catch(() => { });
2873
+ }, 2_000);
2874
+ try {
2875
+ return await work;
2876
+ }
2877
+ finally {
2878
+ clearInterval(timer);
2879
+ }
2880
+ }
2881
+ /**
2882
+ * `sideby history [<words>...]` (spec §3.33, ADR-0042): every Session of every Account, newest or best match first;
2883
+ * `history show <id>` reads one, `history projects` lists Projects, `history index [--clear]` shows or deletes the
2884
+ * History Index.
2885
+ */
2886
+ const HISTORY_FLAGS = {
2887
+ search: [
2888
+ 'json',
2889
+ 'project',
2890
+ 'category',
2891
+ 'group',
2892
+ 'family',
2893
+ 'account',
2894
+ 'since',
2895
+ 'scripts',
2896
+ 'tools',
2897
+ 'limit',
2898
+ 'offset',
2899
+ ],
2900
+ show: ['json', 'account', 'before', 'limit'],
2901
+ projects: ['json', 'family', 'account', 'since', 'scripts'],
2902
+ index: ['json', 'clear'],
2903
+ };
2904
+ /** The filters `history` and `history projects` share, from their flags. */
2905
+ function historyFilters(a) {
2906
+ const since = a.flags.get('since');
2907
+ if (since !== undefined && !['today', '7d', '30d', 'all'].includes(since))
2908
+ throw new UsageError('--since takes today, 7d, 30d or all');
2909
+ return {
2910
+ ...(a.flags.has('family') ? { family: a.flags.get('family') } : {}),
2911
+ ...(a.flags.has('account') ? { account: a.flags.get('account') } : {}),
2912
+ ...(since ? { since: since } : {}),
2913
+ ...(a.flags.has('scripts') ? { scripts: true } : {}),
2914
+ };
2915
+ }
2916
+ export async function cmdHistory(a, io) {
2917
+ const [first, ...more] = a.positionals;
2918
+ const sub = first === 'show' || first === 'projects' || first === 'index' ? first : 'search';
2919
+ const allowed = HISTORY_FLAGS[sub];
2920
+ const extra = [...a.flags.keys()].find((f) => !allowed.includes(f));
2921
+ if (extra)
2922
+ throw new UsageError(`${sub === 'search' ? 'sideby history' : `sideby history ${sub}`} does not take --${extra}. ${HISTORY_USAGE}`);
2923
+ if (first === 'show')
2924
+ return historyShowCmd(a, more, io);
2925
+ if (first === 'projects' || first === 'index') {
2926
+ if (more.length || a.rest.length)
2927
+ throw new UsageError(HISTORY_USAGE);
2928
+ return first === 'projects' ? historyProjectsCmd(a, io) : historyIndexCmd(a, io);
2929
+ }
2930
+ const words = [...a.positionals, ...a.rest].join(' ');
2931
+ const limit = positiveInt(a, 'limit') ?? 30;
2932
+ if (limit > HISTORY_PAGE_MAX)
2933
+ throw new UsageError(`--limit is at most ${HISTORY_PAGE_MAX}; page on with --offset ${HISTORY_PAGE_MAX}`);
2934
+ const offset = a.flags.has('offset') ? Number(a.flags.get('offset')) : 0;
2935
+ if (!Number.isInteger(offset) || offset < 0)
2936
+ throw new UsageError('--offset takes a whole number of 0 or more');
2937
+ const asJson = a.flags.has('json');
2938
+ const filters = historyFilters(a);
2939
+ const rt = await createRuntime();
2940
+ const { scanToolOutput, searchHistory } = await import('../core/history.js');
2941
+ const { listLiveSessions, liveKey } = await import('../core/live-sessions.js');
2942
+ const group = a.flags.get('group');
2943
+ if (group !== undefined && !['project', 'category', 'account', 'family', 'day', 'none'].includes(group))
2944
+ throw new UsageError('--group takes project, category, account, family, day or none');
2945
+ if (group && group !== 'none' && a.flags.has('tools'))
2946
+ throw new UsageError('--tools lists its finds ungrouped; leave out --group to use it');
2947
+ const query = {
2948
+ q: words,
2949
+ limit,
2950
+ ...(offset ? { offset } : {}),
2951
+ ...(a.flags.has('project') ? { project: a.flags.get('project') } : {}),
2952
+ ...(a.flags.has('category') ? { category: a.flags.get('category') } : {}),
2953
+ ...(group ? { group: group } : {}),
2954
+ ...filters,
2955
+ };
2956
+ const [live, r] = await Promise.all([
2957
+ listLiveSessions(rt, { deadlineMs: 3_000 }).catch(() => ({ sessions: [], problems: [] })),
2958
+ withIndexProgress(rt, io, asJson, searchHistory(rt, query, { wait: true })),
2959
+ ]);
2960
+ // The live list is read alongside the search, not before it, so the mark is set here rather than in the query.
2961
+ const running = new Set(live.sessions.map((s) => liveKey(s.account, s.sessionId)));
2962
+ for (const s of r.sessions)
2963
+ s.live = running.has(liveKey(s.account, s.sessionId));
2964
+ let toolHits = 0;
2965
+ let toolsMore = false;
2966
+ // Tool output is read only to fill a page the index left short; a full page needs none of it. It is searched as
2967
+ // the records are now and not paged, so the first page that is short gets its finds and later pages none.
2968
+ if (a.flags.has('tools') &&
2969
+ words.trim() &&
2970
+ r.sessions.length < limit &&
2971
+ offset + r.sessions.length >= r.total) {
2972
+ const skip = new Set(r.sessions.map((s) => liveKey(s.account, s.sessionId)));
2973
+ for await (const hit of scanToolOutput(rt, query, { skip, live: running })) {
2974
+ if (r.sessions.length >= limit) {
2975
+ toolsMore = true;
2976
+ break;
2977
+ }
2978
+ r.sessions.push({ ...hit.session, foundIn: 'tools' });
2979
+ toolHits++;
2980
+ }
2981
+ r.total += toolHits;
2982
+ }
2983
+ if (asJson) {
2984
+ json(io, {
2985
+ sessions: r.sessions,
2986
+ total: r.total,
2987
+ ...(r.groups ? { groups: r.groups } : {}),
2988
+ ...(r.categories ? { categories: r.categories } : {}),
2989
+ ...(toolsMore ? { toolOutputMore: true } : {}),
2990
+ index: { state: r.state, progress: r.progress },
2991
+ sources: r.sources,
2992
+ problems: r.problems,
2993
+ });
2994
+ return 0;
2995
+ }
2996
+ for (const p of r.problems)
2997
+ io.err(c.yellow(`sideby: ${p}`));
2998
+ if (!r.sessions.length) {
2999
+ io.out(historyEmptyHint(r, query, a.flags.has('tools'), (await rt.accounts()).length > 0));
3000
+ return 0;
3001
+ }
3002
+ const now = rt.readContext().now;
3003
+ const home = rt.paths.home;
3004
+ const rows = r.sessions.map((s) => [
3005
+ s.updatedAt ? clock(s.updatedAt, now) : '',
3006
+ s.accountLabel,
3007
+ c.bold(truncate(s.title || '(no title)', 50)) +
3008
+ (s.live ? c.green(' ●') : '') +
3009
+ (s.children ? c.dim(` +${s.children}`) : ''),
3010
+ truncate(s.projectName ? s.projectName : tildify(s.cwd, home), 24) + (s.cwdGone ? c.dim(' (gone)') : ''),
3011
+ s.branch ? truncate(s.branch, 20) : '',
3012
+ c.dim(s.sessionId.slice(0, 8)),
3013
+ ]);
3014
+ // A snippet goes on its own line under its row, so it does not widen the table; a group header goes above the
3015
+ // first row of its group.
3016
+ const lines = table(rows, ['UPDATED', 'ACCOUNT', 'SESSION', 'PROJECT', 'BRANCH', 'ID']).split('\n');
3017
+ const headers = new Map((r.groups ?? []).map((g) => [g.key, g]));
3018
+ io.out([
3019
+ lines[0],
3020
+ ...r.sessions.flatMap((s, i) => {
3021
+ const g = s.group !== undefined && s.group !== r.sessions[i - 1]?.group ? headers.get(s.group) : undefined;
3022
+ return [
3023
+ ...(g ? [c.bold(`${g.label} (${g.sessions})`)] : []),
3024
+ lines[i + 1] ?? '',
3025
+ ...(s.snippet ? [c.dim(` ${truncate(s.snippet, 100)}`)] : []),
3026
+ ];
3027
+ }),
3028
+ ].join('\n'));
3029
+ const legend = [
3030
+ r.sessions.some((s) => s.live) ? `${c.green('●')} running now` : '',
3031
+ r.sessions.some((s) => s.children) ? '+n subagents it started' : '',
3032
+ ].filter(Boolean);
3033
+ if (legend.length)
3034
+ io.out(c.dim(legend.join('; ')));
3035
+ const shown = r.sessions.length;
3036
+ const next = offset + shown;
3037
+ if (r.total > next)
3038
+ io.out(c.dim(`Sessions ${offset + 1}-${next} of ${r.total}; --offset ${next} shows the next ${Math.min(limit, r.total - next)}.`));
3039
+ else if (offset)
3040
+ io.out(c.dim(`Sessions ${offset + 1}-${next} of ${r.total}.`));
3041
+ if (toolsMore)
3042
+ io.out(c.dim(`More sessions match in tool output; --limit ${Math.min(limit * 2, HISTORY_PAGE_MAX)} shows more of them.`));
3043
+ if (r.state === 'building')
3044
+ io.out(c.dim(`The History Index is still being built (${r.progress.done}/${r.progress.total} files); run again for the rest.`));
3045
+ if (toolHits)
3046
+ io.out(c.dim(`${toolHits} found only in tool output.`));
3047
+ io.out(c.dim('Read one, and get the command that continues it in its folder: sideby history show <id>'));
3048
+ return 0;
3049
+ }
3050
+ /** The most Sessions one `sideby history` page lists. */
3051
+ const HISTORY_PAGE_MAX = 500;
3052
+ /** What to try when a search lists nothing, by what the search was narrowed by. */
3053
+ function historyEmptyHint(r, q, tools, hasAccounts) {
3054
+ if (!r.sources.some((s) => s.sessions)) {
3055
+ if (r.state === 'building')
3056
+ return 'The search index is still being built; run this again in a moment.';
3057
+ return hasAccounts
3058
+ ? 'No session records yet. Start an account with `sideby run <account>`, chat a little, and it shows up here.'
3059
+ : 'No accounts yet. Add one with `sideby new <family>` (see `sideby families`), then start it with `sideby run`.';
3060
+ }
3061
+ if (q.offset)
3062
+ return `No sessions after the first ${q.offset}; leave out --offset to see the first page.`;
3063
+ const narrowed = [
3064
+ q.project !== undefined ? '--project' : '',
3065
+ q.category !== undefined ? '--category' : '',
3066
+ q.family ? '--family' : '',
3067
+ q.account ? '--account' : '',
3068
+ ].filter(Boolean);
3069
+ const tries = [
3070
+ q.since && q.since !== 'all' ? '--since all' : '',
3071
+ narrowed.length ? `without ${narrowed.join(', ')}` : '',
3072
+ q.q?.trim() ? 'fewer or shorter words' : '',
3073
+ q.q?.trim() && !tools ? '--tools to search tool output too' : '',
3074
+ ].filter(Boolean);
3075
+ const words = q.q?.trim() ?? '';
3076
+ // Words the user already quoted as a phrase are shown as they typed them.
3077
+ return `Nothing found${words ? ` for ${words.startsWith('"') ? words : `"${words}"`}` : ''}.${tries.length ? ` Try ${tries.join('; ')}.` : ''}`;
3078
+ }
3079
+ async function historyShowCmd(a, args, io) {
3080
+ const [id, ...extra] = args;
3081
+ if (!id || extra.length || a.rest.length)
3082
+ throw new UsageError('usage: sideby history show <session-id> [--account <a>] [--before <n>] [--limit <n>]');
3083
+ const rt = await createRuntime();
3084
+ const { historyShow } = await import('../core/history.js');
3085
+ const before = positiveInt(a, 'before');
3086
+ const limit = positiveInt(a, 'limit');
3087
+ const r = await historyShow(rt, id, {
3088
+ ...(a.flags.has('account') ? { account: a.flags.get('account') } : {}),
3089
+ ...(before !== undefined ? { before } : {}),
3090
+ ...(limit !== undefined ? { limit } : {}),
3091
+ });
3092
+ if (a.flags.has('json')) {
3093
+ json(io, r);
3094
+ return 0;
3095
+ }
3096
+ const s = r.session;
3097
+ const home = rt.paths.home;
3098
+ io.out(c.bold(s.title || '(no title)'));
3099
+ io.out(c.dim([s.accountLabel, s.projectName, s.branch, s.updatedAt ? clock(s.updatedAt, rt.readContext().now) : '']
3100
+ .filter(Boolean)
3101
+ .join(' · ')));
3102
+ if (s.cwd)
3103
+ io.out(c.dim(`${tildify(s.cwd, home)}${s.cwdGone ? ' (folder no longer exists)' : ''}`));
3104
+ if (r.before)
3105
+ io.out(c.dim(`Earlier messages: sideby history show ${s.sessionId} --before ${r.before}`));
3106
+ io.out('');
3107
+ for (const m of r.messages) {
3108
+ if (m.role === 'tool')
3109
+ io.out(c.dim(` · ${m.tool ?? m.text}`));
3110
+ else if (m.role === 'user')
3111
+ io.out(`${c.bold(c.green('›'))} ${m.text}\n`);
3112
+ else
3113
+ io.out(`${c.bold('‹')} ${m.text}\n`);
3114
+ }
3115
+ io.out(c.dim(`Continue it: ${s.continueCommand}`));
3116
+ return 0;
3117
+ }
3118
+ async function historyProjectsCmd(a, io) {
3119
+ const filters = historyFilters(a);
3120
+ const rt = await createRuntime();
3121
+ const { historyProjects } = await import('../core/history.js');
3122
+ const asJson = a.flags.has('json');
3123
+ const r = await withIndexProgress(rt, io, asJson, historyProjects(rt, filters, { wait: true }));
3124
+ if (asJson) {
3125
+ json(io, {
3126
+ projects: r.projects,
3127
+ ...(r.categories ? { categories: r.categories } : {}),
3128
+ ...(r.problems ? { problems: r.problems } : {}),
3129
+ });
3130
+ return 0;
3131
+ }
3132
+ for (const p of r.problems ?? [])
3133
+ io.err(c.yellow(`sideby: ${p}`));
3134
+ if (!r.projects.length) {
3135
+ io.out('No session records yet. Start an account with `sideby run <account>`, chat a little, and it shows up here.');
3136
+ return 0;
3137
+ }
3138
+ const now = rt.readContext().now;
3139
+ io.out(table(r.projects.map((p) => [
3140
+ c.bold(p.name || '(no folder)'),
3141
+ ...(r.categories ? [p.category ?? ''] : []),
3142
+ String(p.sessions),
3143
+ p.updatedAt ? clock(p.updatedAt, now) : '',
3144
+ tildify(p.project, rt.paths.home) + (p.gone ? c.dim(' (gone)') : ''),
3145
+ ]), [
3146
+ 'PROJECT',
3147
+ ...(r.categories ? [(r.categories.label || 'Category').toUpperCase()] : []),
3148
+ 'SESSIONS',
3149
+ 'UPDATED',
3150
+ 'PATH',
3151
+ ]));
3152
+ io.out(c.dim(`Sessions of one: sideby history --project <name>${r.categories ? '; of a category: --category <name>' : ''}`));
3153
+ return 0;
3154
+ }
3155
+ async function historyIndexCmd(a, io) {
3156
+ const rt = await createRuntime();
3157
+ const { historyIndexInfo } = await import('../core/history.js');
3158
+ const clear = a.flags.has('clear');
3159
+ const asJson = a.flags.has('json');
3160
+ const r = await withIndexProgress(rt, io, asJson, historyIndexInfo(rt, { clear, wait: !clear, rebuild: !clear }));
3161
+ if (asJson) {
3162
+ json(io, r);
3163
+ return 0;
3164
+ }
3165
+ if (clear)
3166
+ io.out(r.cleared
3167
+ ? `${c.green('✓')} deleted the History Index; it is built again from the hosts' files the next time you look`
3168
+ : 'There was no History Index to delete.');
3169
+ if (!r.enabled)
3170
+ io.out('The History Index is off (config history.index false): searches look at titles and folders only.');
3171
+ else if (!clear) {
3172
+ io.out(`${tildify(r.path, rt.paths.home)} ${(r.bytes / 1e6).toFixed(1)} MB`);
3173
+ io.out(r.state === 'building'
3174
+ ? `Building: ${r.progress.done}/${r.progress.total} files read`
3175
+ : `${r.sessions} sessions from ${r.files} files`);
3176
+ }
3177
+ if (!clear)
3178
+ for (const s of r.sources)
3179
+ io.out(` ${s.accountLabel.padEnd(14)} ${String(s.sessions).padStart(5)} sessions${s.failed ? c.yellow(`, ${s.failed} unreadable`) : ''}${s.note ? c.dim(` ${s.note}`) : ''}`);
3180
+ return 0;
3181
+ }
3182
+ /**
3183
+ * `sideby send <account|session> "<text>" [--image <path>]...` (spec §3.32 step 2, ADR-0040): keeps the Message as a
3184
+ * file, delivers it through the Host's own channel where it has one (Claude Code), else copies the line to paste.
3185
+ */
3186
+ export async function cmdSend(a, io) {
3187
+ const [target, ...words] = a.positionals;
3188
+ const text = [...words, ...a.rest].join(' ');
3189
+ if (!target || (!text.trim() && !a.images?.length))
3190
+ throw new UsageError('usage: sideby send <account|session> "<text>" [--image <path>]... [--json]');
3191
+ const rt = await createRuntime();
3192
+ const lang = copyLang(a, rt.env);
3193
+ const { sendMessage } = await import('../core/messages.js');
3194
+ const { copyToClipboard } = await import('../core/live-sessions-copy.js');
3195
+ const r = await sendMessage(rt, target, { text, images: a.images ?? [], lang });
3196
+ const copied = r.status === 'paste-needed' ? (await copyToClipboard(r.pasteText, rt.env)) !== null : false;
3197
+ if (a.flags.has('json')) {
3198
+ json(io, { message: r, copied });
3199
+ return 0;
3200
+ }
3201
+ const home = rt.paths.home;
3202
+ if (r.status === 'delivered') {
3203
+ io.out(`${c.green('✓')} delivered to ${c.bold(r.to)} (message ${r.id})`);
3204
+ if (r.note)
3205
+ io.out(c.yellow(` ${r.note}`));
3206
+ if (r.needsApproval)
3207
+ io.out(` To receive messages without approving each one: ${c.bold('sideby messages inbound accept')}`);
3208
+ }
3209
+ else {
3210
+ io.out(`${c.yellow('●')} kept message ${r.id} for ${c.bold(r.to)}; it needs a paste`);
3211
+ if (r.note)
3212
+ io.out(` ${r.note}`);
3213
+ io.out(` Paste this into the tab of ${c.bold(r.to)}${copied ? ' (it is on the clipboard)' : ''}:`);
3214
+ io.out(` ${r.pasteText}`);
3215
+ }
3216
+ io.out(c.dim(` Kept at ${tildify(r.file, home)}${r.attachments.length ? ` with ${r.attachments.length} screenshot(s)` : ''}`));
3217
+ return 0;
3218
+ }
3219
+ const MESSAGE_STATUS = {
3220
+ stored: 'kept',
3221
+ delivered: 'delivered',
3222
+ read: 'read',
3223
+ 'paste-needed': 'needs paste',
3224
+ };
3225
+ /**
3226
+ * `sideby messages [--to <account|session>] [--limit <n>]`: the Messages sideby kept and how far each got;
3227
+ * `sideby messages inbound [accept|undo] [--yes]`: whether Claude sessions show them at once.
3228
+ */
3229
+ export async function cmdMessages(a, io, runtime) {
3230
+ const [first, ...more] = a.positionals;
3231
+ if (first === 'inbound')
3232
+ return messagesInbound(a, more, io, runtime);
3233
+ if (first !== undefined || a.rest.length)
3234
+ throw new UsageError('usage: sideby messages [--to <account|session>] [--limit <n>] | sideby messages inbound [accept|undo] [--yes]');
3235
+ const to = a.flags.get('to');
3236
+ const limitFlag = a.flags.get('limit');
3237
+ const limit = limitFlag === undefined ? undefined : Number(limitFlag);
3238
+ if (limit !== undefined && !(Number.isInteger(limit) && limit > 0))
3239
+ throw new UsageError('--limit takes a whole number above 0');
3240
+ const rt = runtime ?? (await createRuntime());
3241
+ const { listMessages } = await import('../core/messages.js');
3242
+ const list = await listMessages(rt, {
3243
+ ...(typeof to === 'string' ? { to } : {}),
3244
+ ...(limit ? { limit } : {}),
3245
+ });
3246
+ if (a.flags.has('json')) {
3247
+ json(io, { messages: list });
3248
+ return 0;
3249
+ }
3250
+ if (!list.length) {
3251
+ io.out('No messages yet. Send one with `sideby send <account|session> "<text>"`.');
3252
+ return 0;
3253
+ }
3254
+ const now = rt.readContext().now;
3255
+ const rows = list.map((m) => [
3256
+ clock(m.sentAt, now),
3257
+ c.bold(m.to),
3258
+ m.status === 'paste-needed'
3259
+ ? c.yellow(MESSAGE_STATUS[m.status])
3260
+ : m.needsApproval
3261
+ ? c.yellow('waits for approval')
3262
+ : MESSAGE_STATUS[m.status],
3263
+ m.id,
3264
+ m.from ?? c.dim('you'),
3265
+ ]);
3266
+ io.out(table(rows, ['SENT', 'TO', 'STATUS', 'ID', 'FROM']));
3267
+ // A session whose latest Message waits for a paste gets the line to paste and why, newest first.
3268
+ const seen = new Set();
3269
+ const waiting = list.filter((m) => !seen.has(m.toSessionId) && seen.add(m.toSessionId) && m.status === 'paste-needed');
3270
+ for (const m of waiting.slice(0, 5)) {
3271
+ io.out('');
3272
+ io.out(`${c.yellow('Paste this line into')} ${c.bold(m.to)}${m.note ? c.dim(` (${m.note})`) : ''}:`);
3273
+ io.out(` ${m.pasteText}`);
3274
+ }
3275
+ if (list.some((m) => m.needsApproval)) {
3276
+ io.out('');
3277
+ io.out(`${c.yellow('Some messages wait for approval')} in the target's terminal and are dropped after about 5 minutes. To receive them directly: ${c.bold('sideby messages inbound accept')}`);
3278
+ }
3279
+ return 0;
3280
+ }
3281
+ const INBOUND_WORDS = {
3282
+ accept: 'accept',
3283
+ hold: 'hold',
3284
+ refuse: 'refuse',
3285
+ default: 'not set',
3286
+ other: 'unknown value',
3287
+ missing: 'no settings',
3288
+ blocked: 'blocked',
3289
+ };
3290
+ async function messagesInbound(a, args, io, runtime) {
3291
+ const [action, extra] = args;
3292
+ if (extra !== undefined || (action !== undefined && action !== 'accept' && action !== 'undo'))
3293
+ throw new UsageError('usage: sideby messages inbound [accept|undo] [--yes] [--json]');
3294
+ const wantJson = a.flags.has('json');
3295
+ const rt = runtime ?? (await createRuntime());
3296
+ const home = rt.paths.home;
3297
+ const inbound = await import('../core/inbound.js');
3298
+ const accounts = await rt.accounts();
3299
+ const ctx = rt.readContext();
3300
+ const groups = await inbound.inboundGroups(accounts, ctx);
3301
+ const show = (gs) => gs.map((g) => ({ ...g, file: tildify(g.file, home) }));
3302
+ const out = (data) => json(io, { action: action ?? 'status', ...data });
3303
+ if (!action) {
3304
+ if (wantJson) {
3305
+ out({ groups: show(groups) });
3306
+ return 0;
3307
+ }
3308
+ if (!groups.length) {
3309
+ io.out('No Claude accounts found.');
3310
+ return 0;
3311
+ }
3312
+ io.out('Messages from other sessions: whether Claude sessions show them at once');
3313
+ for (const g of groups) {
3314
+ const word = INBOUND_WORDS[g.state];
3315
+ const paint = g.state === 'accept' ? c.green : g.state === 'blocked' ? c.red : c.yellow;
3316
+ io.out(` ${paint(word)} ${c.bold(g.accounts.join(', '))} ${c.dim(g.reason ? tilde(g.reason, home) : tildify(g.file, home))}`);
3317
+ }
3318
+ io.out(c.dim(' accept: shown at once; hold or not set: a session in bypass permission mode waits for you to approve each one, and drops it after about 5 minutes; refuse: dropped'));
3319
+ if (inbound.groupsToAccept(groups).length)
3320
+ io.out(c.cyan('\nRun `sideby messages inbound accept` so they are shown at once (it shows the change first).'));
3321
+ return 0;
3322
+ }
3323
+ const todo = action === 'accept' ? inbound.groupsToAccept(groups) : inbound.inboundGroupsToUndo(groups);
3324
+ const apply = () => action === 'accept' ? inbound.acceptInbound(accounts, ctx) : inbound.undoInbound(accounts, ctx);
3325
+ const verb = action === 'accept' ? 'set it' : 'undo';
3326
+ if (todo.length === 0) {
3327
+ // Only from what was read: a run without --yes never writes, even if a file changed since (exit 1).
3328
+ const r = inbound.inboundNothingToDo(action, groups);
3329
+ if (wantJson)
3330
+ out({ applied: false, groups: show(groups), message: r.message });
3331
+ else
3332
+ io.out(tilde(r.message, home));
3333
+ return 1;
3334
+ }
3335
+ if (!a.flags.has('yes')) {
3336
+ if (wantJson) {
3337
+ // The same facts as the text preview: the key and value each file gets, and what is left alone and why.
3338
+ const preview = action === 'accept'
3339
+ ? show(todo).map((g) => ({
3340
+ ...g,
3341
+ change: {
3342
+ key: inbound.INBOUND_KEY,
3343
+ from: g.state === 'default' ? null : g.state,
3344
+ to: 'accept',
3345
+ },
3346
+ }))
3347
+ : show(todo);
3348
+ const leftAlone = inbound
3349
+ .inboundLeftAlone(groups)
3350
+ .map((g) => ({ ...g, file: tildify(g.file, home), reason: tilde(g.reason ?? '', home) }));
3351
+ out({ applied: false, groups: preview, leftAlone, message: `Run again with --yes to ${verb}.` });
3352
+ }
3353
+ else {
3354
+ io.out(action === 'accept'
3355
+ ? 'Show messages from other sessions at once?'
3356
+ : 'Put back the setting sideby replaced?');
3357
+ for (const g of todo) {
3358
+ const from = g.state === 'default' ? 'not set' : `"${g.state}"`;
3359
+ io.out(` ${tildify(g.file, home)}: crossSessionInbound ${action === 'accept' ? `${from} -> "accept"` : '-> what it was before'}`);
3360
+ io.out(c.dim(` used by ${g.accounts.join(', ')}`));
3361
+ }
3362
+ for (const g of inbound.inboundLeftAlone(groups))
3363
+ io.out(c.dim(` left alone, ${g.accounts.join(', ')}: ${tilde(g.reason ?? '', home)}`));
3364
+ if (action === 'accept')
3365
+ io.out('A session then shows a message from another session of yours as soon as it arrives, also in bypass permission mode. Only your own sessions on this computer can send one. Undo it with `sideby messages inbound undo`.');
3366
+ io.out(`Run again with --yes to ${verb}.`);
3367
+ }
3368
+ return 10;
3369
+ }
3370
+ const r = await apply();
3371
+ const results = r.results.map((x) => ({ ...x, file: tildify(x.file, home) }));
3372
+ if (wantJson)
3373
+ out({ applied: r.ok, results, message: r.message });
3374
+ else {
3375
+ for (const x of results)
3376
+ io.out(` ${x.ok ? c.green('ok') : c.red('failed')} ${x.file}: ${x.message}`);
3377
+ io.out(r.message);
3378
+ }
3379
+ return r.ok ? 0 : 1;
3380
+ }