sideby 0.16.1 → 0.18.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 (128) hide show
  1. package/README.md +7 -3
  2. package/ai-tasks.json +90 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +25 -1
  5. package/dist/src/cli/commands.js +802 -15
  6. package/dist/src/cli/json-schemas.js +252 -1
  7. package/dist/src/cli/main.js +143 -4
  8. package/dist/src/core/after-install.d.ts +54 -0
  9. package/dist/src/core/after-install.js +78 -0
  10. package/dist/src/core/ask.d.ts +222 -0
  11. package/dist/src/core/ask.js +465 -0
  12. package/dist/src/core/attachments.d.ts +50 -0
  13. package/dist/src/core/attachments.js +442 -0
  14. package/dist/src/core/autostart.d.ts +118 -0
  15. package/dist/src/core/autostart.js +302 -0
  16. package/dist/src/core/brand-mark.d.ts +49 -11
  17. package/dist/src/core/brand-mark.js +116 -38
  18. package/dist/src/core/config.d.ts +102 -0
  19. package/dist/src/core/config.js +289 -11
  20. package/dist/src/core/desktop-app.d.ts +1 -1
  21. package/dist/src/core/desktop-app.js +2 -2
  22. package/dist/src/core/edit-settings.d.ts +24 -0
  23. package/dist/src/core/edit-settings.js +97 -0
  24. package/dist/src/core/handoff-brief.d.ts +4 -2
  25. package/dist/src/core/handoff-brief.js +6 -1
  26. package/dist/src/core/handoff-chain.d.ts +24 -0
  27. package/dist/src/core/handoff-chain.js +2 -0
  28. package/dist/src/core/handoff-run.d.ts +4 -3
  29. package/dist/src/core/handoff-run.js +14 -9
  30. package/dist/src/core/launch.d.ts +17 -4
  31. package/dist/src/core/launch.js +32 -24
  32. package/dist/src/core/local-build.d.ts +17 -5
  33. package/dist/src/core/local-build.js +61 -23
  34. package/dist/src/core/lock.d.ts +30 -0
  35. package/dist/src/core/lock.js +143 -0
  36. package/dist/src/core/probe.d.ts +78 -0
  37. package/dist/src/core/probe.js +127 -0
  38. package/dist/src/core/quota-levels.d.ts +6 -1
  39. package/dist/src/core/quota-levels.js +16 -5
  40. package/dist/src/core/same-login.d.ts +9 -4
  41. package/dist/src/core/same-login.js +9 -4
  42. package/dist/src/core/secret-file.d.ts +26 -0
  43. package/dist/src/core/secret-file.js +126 -7
  44. package/dist/src/core/task-spec.d.ts +95 -0
  45. package/dist/src/core/task-spec.js +209 -0
  46. package/dist/src/core/terminal.d.ts +93 -0
  47. package/dist/src/core/terminal.js +376 -0
  48. package/dist/src/core/update.d.ts +34 -12
  49. package/dist/src/core/update.js +96 -84
  50. package/dist/src/desktop/icon.js +12 -15
  51. package/dist/src/families/claude/ai-task.d.ts +8 -0
  52. package/dist/src/families/claude/ai-task.js +38 -0
  53. package/dist/src/families/claude/handoff-hook.js +4 -4
  54. package/dist/src/families/claude/index.js +6 -0
  55. package/dist/src/families/claude/quota-cache.d.ts +24 -7
  56. package/dist/src/families/claude/quota-cache.js +72 -21
  57. package/dist/src/families/codex/handoff-hook.js +4 -4
  58. package/dist/src/families/codex/index.js +16 -0
  59. package/dist/src/families/codex/login-key.d.ts +8 -0
  60. package/dist/src/families/codex/login-key.js +33 -0
  61. package/dist/src/families/grok/handoff-hook.js +4 -4
  62. package/dist/src/families/grok/index.js +4 -0
  63. package/dist/src/families/login-keys.d.ts +6 -0
  64. package/dist/src/families/login-keys.js +6 -0
  65. package/dist/src/families/pi/index.js +5 -0
  66. package/dist/src/handoff/hook.js +51 -30
  67. package/dist/src/handoff/levels.d.ts +24 -0
  68. package/dist/src/handoff/levels.js +70 -0
  69. package/dist/src/handoff/messages.d.ts +6 -3
  70. package/dist/src/handoff/messages.js +20 -7
  71. package/dist/src/handoff/reader.d.ts +6 -3
  72. package/dist/src/menubar/agent.d.ts +3 -0
  73. package/dist/src/menubar/agent.js +21 -0
  74. package/dist/src/menubar/script.d.ts +8 -0
  75. package/dist/src/menubar/script.js +457 -0
  76. package/dist/src/menubar/snapshot.d.ts +115 -0
  77. package/dist/src/menubar/snapshot.js +255 -0
  78. package/dist/src/menubar/strings.d.ts +87 -0
  79. package/dist/src/menubar/strings.js +88 -0
  80. package/dist/src/panel/background.js +15 -21
  81. package/dist/src/panel/handler.d.ts +41 -2
  82. package/dist/src/panel/handler.js +394 -10
  83. package/dist/src/panel/i18n.d.ts +205 -2
  84. package/dist/src/panel/i18n.js +441 -35
  85. package/dist/src/panel/page-logic.d.ts +301 -0
  86. package/dist/src/panel/page-logic.js +532 -0
  87. package/dist/src/panel/page-script.js +1135 -185
  88. package/dist/src/panel/page-styles.js +111 -32
  89. package/dist/src/panel/page.d.ts +12 -0
  90. package/dist/src/panel/page.js +7 -0
  91. package/dist/src/panel/server.d.ts +16 -2
  92. package/dist/src/panel/server.js +41 -13
  93. package/dist/src/plugins/check.d.ts +47 -0
  94. package/dist/src/plugins/check.js +544 -0
  95. package/dist/src/plugins/scaffold.d.ts +21 -0
  96. package/dist/src/plugins/scaffold.js +123 -0
  97. package/dist/src/quota/statusline-tap.js +1 -1
  98. package/dist/src/runtime.d.ts +19 -1
  99. package/dist/src/runtime.js +53 -14
  100. package/dist/src/types.d.ts +33 -0
  101. package/package.json +4 -3
  102. package/schemas/ask-choices.json +168 -0
  103. package/schemas/ask-print.json +87 -0
  104. package/schemas/ask.json +180 -0
  105. package/schemas/autostart.json +165 -0
  106. package/schemas/config-get.json +132 -0
  107. package/schemas/config-set.json +107 -0
  108. package/schemas/config.json +90 -7
  109. package/schemas/edit.json +119 -0
  110. package/schemas/error.json +4 -0
  111. package/schemas/families.json +4 -0
  112. package/schemas/key.json +93 -0
  113. package/schemas/list.json +4 -0
  114. package/schemas/local.json +1 -1
  115. package/schemas/menubar-snapshot.json +646 -0
  116. package/schemas/menubar-start.json +112 -0
  117. package/schemas/menubar.json +165 -0
  118. package/schemas/plugins-check.json +113 -0
  119. package/schemas/plugins-new.json +87 -0
  120. package/schemas/terminal.json +152 -0
  121. package/schemas/try.json +109 -0
  122. package/schemas/update.json +4 -0
  123. package/skills/sideby/SKILL.md +16 -6
  124. package/skills/sideby/references/accounts.md +1 -1
  125. package/skills/sideby/references/ai-tasks.md +126 -0
  126. package/skills/sideby/references/handoff.md +3 -1
  127. package/skills/sideby/references/panel.md +20 -0
  128. package/skills/sideby/references/update.md +1 -1
@@ -1,9 +1,11 @@
1
+ import { StringDecoder } from 'node:string_decoder';
1
2
  import { fileURLToPath } from 'node:url';
2
3
  import { aliasesByAccount } from '../core/accounts.js';
3
4
  import { listAppProfiles, openAppProfile, parseProfileRef, removeAppProfile } from '../core/app-profiles.js';
4
5
  import { browserReport, openInBrowser, setBrowserSignIns } from '../core/browser-profiles.js';
5
6
  import { aliasRefs, editConfigUpdate } from '../core/config.js';
6
7
  import { openDesktopApp, withDesktopApps } from '../core/desktop-app.js';
8
+ import { editSettings } from '../core/edit-settings.js';
7
9
  import { UserError } from '../core/errors.js';
8
10
  import { requestHandoff } from '../core/handoff-chain.js';
9
11
  import { handoffOverview } from '../core/handoff-overview.js';
@@ -15,7 +17,8 @@ import { resolvePaths, tildify } from '../core/paths.js';
15
17
  import { USAGE_DAYS } from '../core/quota-levels.js';
16
18
  import { groupsToTurnOff, groupsToTurnOn, groupsToUndo, } from '../core/remote-control.js';
17
19
  import { SHELLS } from '../core/shell-init.js';
18
- import { inDisplayOrder, pinnedIn, suggestAlias, suggestName, withPinned } from '../panel/page-logic.js';
20
+ import { MODEL_NAME } from '../families/shared/model-args.js';
21
+ import { AI_TASK_KINDS, inDisplayOrder, pinnedIn, suggestAlias, suggestName, withPinned, } from '../panel/page-logic.js';
19
22
  import { createRuntime, UnknownFamilyError } from '../runtime.js';
20
23
  import { UsageError } from './args.js';
21
24
  import { c, clock, compactNumber, quotaText, table, tuningLines, usageText } from './format.js';
@@ -31,17 +34,15 @@ async function whileRunning(rt, fn) {
31
34
  }
32
35
  }
33
36
  /** Runs the Account with Auto Handoff when it applies (spec §3.17), else the Host as usual. */
34
- async function runAccount(rt, ref, args, io) {
35
- return whileRunning(rt, () => runAccountNow(rt, ref, args, io));
37
+ /** `opts.aiTask`: an AI Task's Host, started without permission bypasses (ADR-0031); `sideby run` leaves it out. */
38
+ async function runAccount(rt, ref, args, io, opts = {}) {
39
+ return whileRunning(rt, () => runAccountNow(rt, ref, args, io, opts));
36
40
  }
37
- async function runAccountNow(rt, ref, args, io) {
38
- const handed = await runWithHandoff(rt, ref, args, {
39
- err: (l) => io.err(c.dim(l)),
40
- stdin: io.stdin ?? process.stdin,
41
- });
41
+ async function runAccountNow(rt, ref, args, io, opts) {
42
+ const handed = await runWithHandoff(rt, ref, args, { err: (l) => io.err(c.dim(l)), stdin: io.stdin ?? process.stdin }, opts);
42
43
  if (handed !== null)
43
44
  return handed;
44
- const prepared = await rt.prepareLaunch(ref, args, 'run');
45
+ const prepared = await rt.prepareLaunch(ref, args, 'run', opts);
45
46
  if (prepared.notice)
46
47
  io.err(c.cyan(prepared.notice));
47
48
  const code = await runHost(prepared);
@@ -235,7 +236,7 @@ export async function cmdList(a, io) {
235
236
  io.out('No accounts found yet.');
236
237
  const installed = families.filter((f) => f.installed);
237
238
  if (installed.length === 0)
238
- io.out(`Install a host first: ${families.map((f) => `${f.title} (${installHint(f)})`).join(', ')}`);
239
+ io.out(`Install a host first:\n${families.map((f) => ` ${f.title}: ${installHint(f)}`).join('\n')}`);
239
240
  else
240
241
  io.out(`Run ${installed.map((f) => f.bin).join(' or ')} once, then \`sideby new <family> <name>\`.`);
241
242
  }
@@ -270,8 +271,9 @@ export async function cmdList(a, io) {
270
271
  io.out(c.dim('\n= <account>: signed in as the same login as that account, so they share one quota.'));
271
272
  io.out(c.dim('\nsideby run <account> · sideby new <family> <name> · sideby quota · sideby ui'));
272
273
  }
273
- // App Profiles (ADR-0019): windows of an app that signs in apart from the Accounts above.
274
- for (const app of new Set(appProfiles.map((p) => p.app))) {
274
+ // App Profiles (ADR-0019): windows of an app that signs in apart from the Accounts above. Not on the first screen
275
+ // of someone without Accounts yet, where they would only distract from installing a Host; --json keeps them.
276
+ for (const app of statuses.length ? new Set(appProfiles.map((p) => p.app)) : []) {
275
277
  const list = appProfiles.filter((p) => p.app === app);
276
278
  io.out(`\n${c.bold(app)} ${c.dim('(signs in on its own, not with the accounts above)')}`);
277
279
  io.out(table(list.map((p) => [
@@ -345,8 +347,13 @@ export async function cmdNew(a, io) {
345
347
  io.out(`${c.green('✓')} created ${c.bold(res.account.ref)} at ${where}`);
346
348
  else
347
349
  io.out(`${c.yellow('!')} created ${c.bold(res.account.ref)} at ${where} with problems; see below`);
348
- for (const s of res.steps.filter((x) => !x.ok || x.action === 'skipped'))
350
+ // Items the main account does not have are normal for a new setup: one line, not one per item, so a beginner does
351
+ // not read a list of problems.
352
+ const notInMain = res.steps.filter((x) => x.ok && x.action === 'skipped' && x.message === 'not in the main account');
353
+ for (const s of res.steps.filter((x) => (!x.ok || x.action === 'skipped') && !notInMain.includes(x)))
349
354
  io.out(` ${s.ok ? c.dim('·') : c.red('✗')} ${s.item}: ${s.message ?? s.action}`);
355
+ if (notInMain.length)
356
+ io.out(` ${c.dim('·')} nothing to share yet: ${notInMain.map((x) => x.item).join(', ')} ${notInMain.length === 1 ? 'is' : 'are'} not in the main account (add ${notInMain.length === 1 ? 'it' : 'them'} there; \`sideby doctor\` then says what to do)`);
350
357
  for (const e of res.hookErrors)
351
358
  io.err(c.red(` ${e.message}`));
352
359
  if (res.alias?.added)
@@ -1103,6 +1110,42 @@ export async function cmdHandoff(a, io) {
1103
1110
  }
1104
1111
  export async function cmdPlugins(a, io) {
1105
1112
  const rt = await createRuntime();
1113
+ if (a.positionals.length) {
1114
+ const [action, target, ...extra] = a.positionals;
1115
+ if (!target || extra.length || a.rest.length || !['new', 'check'].includes(action))
1116
+ throw new UsageError('Use sideby plugins new <id> or sideby plugins check <id|path>.');
1117
+ const { join, isAbsolute } = await import('node:path');
1118
+ const { expandUserPath } = await import('../core/paths.js');
1119
+ const dirs = (rt.config.pluginDirs ?? [rt.paths.userPluginsDir]).map((p) => expandUserPath(p, rt.paths.home) ?? p);
1120
+ if (action === 'new') {
1121
+ const { scaffoldPlugin } = await import('../plugins/scaffold.js');
1122
+ const result = await scaffoldPlugin({ id: target, dir: dirs[0] ?? rt.paths.userPluginsDir });
1123
+ if (a.flags.has('json'))
1124
+ json(io, result);
1125
+ else
1126
+ io.out(`Created ${result.dir}. Fill in the TODOs, then run sideby plugins check ${target}.`);
1127
+ return 0;
1128
+ }
1129
+ const { checkPlugin } = await import('../plugins/check.js');
1130
+ const { access } = await import('node:fs/promises');
1131
+ let dir = target;
1132
+ if (!isAbsolute(target) && !target.includes('/') && !target.startsWith('.')) {
1133
+ dir = join(dirs[0] ?? rt.paths.userPluginsDir, target);
1134
+ for (const root of dirs)
1135
+ if (await access(join(root, target)).then(() => true, () => false)) {
1136
+ dir = join(root, target);
1137
+ break;
1138
+ }
1139
+ }
1140
+ const result = await checkPlugin({ dir });
1141
+ if (a.flags.has('json'))
1142
+ json(io, result);
1143
+ else {
1144
+ io.out(result.ok ? 'OK' : result.problems.map((p) => `${p.message}: ${p.fix}`).join('\n'));
1145
+ io.out('Plugins run as you, with your permissions. Only load plugins you trust.');
1146
+ }
1147
+ return result.ok ? 0 : 1;
1148
+ }
1106
1149
  if (a.flags.has('json'))
1107
1150
  // Plugin settings can hold tokens: report which keys are set, never their values.
1108
1151
  json(io, {
@@ -1213,13 +1256,73 @@ export async function cmdUi(a, io) {
1213
1256
  });
1214
1257
  return 0;
1215
1258
  }
1259
+ /**
1260
+ * `sideby update --skill [--yes] [--json]` (spec §3.23): only the installed sideby skill, toward this version. It
1261
+ * never installs the CLI, also when a newer one exists (it says that update is separate), and asks no registry. The
1262
+ * new code runs it after an install, so a registry that moved meanwhile never installs a version nobody confirmed.
1263
+ */
1264
+ async function cmdUpdateSkill(a, io) {
1265
+ if (a.positionals.length || a.rest.length)
1266
+ throw new UsageError('usage: sideby update --skill [--yes] [--json]');
1267
+ const u = await import('../core/update.js');
1268
+ const { SKILL_INSTALL } = await import('../core/skill-check.js');
1269
+ const paths = resolvePaths(process.env);
1270
+ const asJson = a.flags.has('json');
1271
+ const plan = await u.planSkillUpdate(paths, process.env);
1272
+ const shown = u.shownPlan(plan);
1273
+ const sk = plan.skill;
1274
+ // The skills tool fetches the newest skill, so a newer CLI should follow; that stays the user's own step.
1275
+ const cliLine = () => {
1276
+ if (plan.available)
1277
+ io.out(c.cyan(`sideby ${plan.latest} is available; updating sideby itself is separate: \`sideby update\`.`));
1278
+ };
1279
+ if (!sk?.outdated || !sk.canRun) {
1280
+ if (asJson)
1281
+ json(io, { ...shown, updated: false });
1282
+ else {
1283
+ if (!sk)
1284
+ io.out(`No sideby skill is installed. To install it: ${SKILL_INSTALL}`);
1285
+ else if (!sk.outdated)
1286
+ io.out(`${c.green('✓')} The sideby skill is already for sideby ${plan.current}.`);
1287
+ else
1288
+ io.out(c.yellow(`The sideby skill is not updated by sideby: ${sk.reason}.\n ${sk.command}`));
1289
+ cliLine();
1290
+ }
1291
+ return 0;
1292
+ }
1293
+ if (!a.flags.has('yes')) {
1294
+ if (asJson)
1295
+ json(io, { ...shown, updated: false });
1296
+ else {
1297
+ const from = sk.installed.map((v) => v ?? 'no version').join(', ');
1298
+ io.out(`Updating the sideby skill (for ${from}) to sideby ${plan.current} runs:\n ${sk.command}`);
1299
+ cliLine();
1300
+ io.out(c.cyan('\nRun it with `sideby update --skill --yes`.'));
1301
+ }
1302
+ return 10;
1303
+ }
1304
+ if (!asJson)
1305
+ io.out(c.dim(`$ ${sk.command}`));
1306
+ const r = await u.applySkillOnly(paths, sk, process.env, asJson ? undefined : (t) => process.stderr.write(t));
1307
+ if (asJson)
1308
+ json(io, { ...shown, updated: false, skillUpdated: r?.ok ?? false, message: r?.message ?? '' });
1309
+ else {
1310
+ if (r?.ok)
1311
+ io.out(`${c.green('✓')} ${r.message}; agents load it in their next session.`);
1312
+ else
1313
+ io.err(c.red(`✗ ${r?.message}`));
1314
+ cliLine();
1315
+ }
1316
+ return r?.ok ? 0 : 1;
1317
+ }
1216
1318
  /**
1217
1319
  * `sideby update [--yes] [--json]` (spec §3.23): asks the registry now, shows what an Update runs, and runs it with
1218
- * `--yes` (exit 10 before). An install sideby cannot update gets the command to run and exit 1.
1320
+ * `--yes` (exit 10 before). An install sideby cannot update gets the command to run and exit 1. `--skill` updates the
1321
+ * skill alone (cmdUpdateSkill).
1219
1322
  */
1220
1323
  export async function cmdUpdate(a, io) {
1221
1324
  if (a.positionals.length)
1222
- throw new UsageError('usage: sideby update [--yes] [--json]');
1325
+ throw new UsageError('usage: sideby update [--skill] [--yes] [--json]');
1223
1326
  if (a.flags.has('auto')) {
1224
1327
  if (a.rest.length)
1225
1328
  throw new UsageError('usage: sideby update --auto on|off [--json]');
@@ -1232,6 +1335,8 @@ export async function cmdUpdate(a, io) {
1232
1335
  io.out(`Auto Update ${auto ? 'on' : 'off'}${r.changed ? '.' : ' (unchanged).'}`);
1233
1336
  return 0;
1234
1337
  }
1338
+ if (a.flags.has('skill'))
1339
+ return cmdUpdateSkill(a, io);
1235
1340
  const u = await import('../core/update.js');
1236
1341
  const { SKILL_INSTALL } = await import('../core/skill-check.js');
1237
1342
  const { backgroundPanelPort } = await import('../panel/background.js');
@@ -1310,6 +1415,7 @@ export async function cmdUpdate(a, io) {
1310
1415
  message: r.message,
1311
1416
  restartedPanel: r.restartedPanel,
1312
1417
  refreshedApp: r.refreshedApp,
1418
+ ...(r.refreshedAutostart === undefined ? {} : { refreshedAutostart: r.refreshedAutostart }),
1313
1419
  skill: SKILL_INSTALL,
1314
1420
  ...(r.skillUpdated === undefined ? {} : { skillUpdated: r.skillUpdated }),
1315
1421
  ...(r.ok ? {} : { output: r.output }),
@@ -1325,6 +1431,10 @@ export async function cmdUpdate(a, io) {
1325
1431
  io.out(' The background panel is restarting with the new version; open pages reload by themselves.');
1326
1432
  if (r.refreshedApp)
1327
1433
  io.out(' The desktop app now starts the new version and shows its icon.');
1434
+ if (r.refreshedAutostart)
1435
+ io.out(' The login item now starts the new version.');
1436
+ else if (r.refreshedAutostart === false)
1437
+ io.out(' The login item could not be pointed at the new version; run `sideby autostart` to see why.');
1328
1438
  io.out(' A `sideby ui` running in a terminal and sessions already running keep the old version until you restart them.');
1329
1439
  if (r.skillUpdated)
1330
1440
  io.out(' The sideby skill was updated too; agents load it in their next session.');
@@ -1517,6 +1627,28 @@ export async function cmdDesktop(a, io) {
1517
1627
  io.err(c.cyan(n));
1518
1628
  return 0;
1519
1629
  }
1630
+ /** `sideby edit <account> [--path]`: the Account's Host settings file in the user's editor (spec §3.30, ADR-0033). */
1631
+ export async function cmdEdit(a, io) {
1632
+ const [ref, ...extra] = a.positionals;
1633
+ if (!ref || extra.length || a.rest.length)
1634
+ throw new UsageError('usage: sideby edit <account> [--path]');
1635
+ const rt = await createRuntime();
1636
+ const r = await editSettings(rt, ref, { open: !a.flags.has('path') });
1637
+ if (a.flags.has('json')) {
1638
+ json(io, r);
1639
+ return 0;
1640
+ }
1641
+ const home = rt.paths.home;
1642
+ if (!r.opened)
1643
+ io.out(r.target ?? r.path);
1644
+ else
1645
+ io.out(`${c.green('✓')} opened ${c.bold(r.ref)}'s ${r.file} with your default program`);
1646
+ if (r.opened || r.target)
1647
+ io.out(c.dim(` ${tildify(r.target ?? r.path, home)}${r.target ? ` (linked from ${tildify(r.path, home)})` : ''}`));
1648
+ if (r.sharedWith.length)
1649
+ io.out(c.dim(` shared: a change also applies to ${r.sharedWith.join(', ')}`));
1650
+ return 0;
1651
+ }
1520
1652
  /** `sideby browser [--enable|--disable] [--yes]` and `sideby browser open <account> [--profile <p>]` (spec §3.24). */
1521
1653
  export async function cmdBrowser(a, io) {
1522
1654
  const [sub, ref, ...extra] = a.positionals;
@@ -1651,3 +1783,658 @@ export async function cmdFamilies(a, io) {
1651
1783
  });
1652
1784
  return 0;
1653
1785
  }
1786
+ /** AI Task CLI; the terminal receives only an opaque task id. */
1787
+ export async function cmdAsk(a, io, runtime) {
1788
+ const { movedCwdError, previewAttachments, promptForTask, readTask, realCwdInHome, startAiTask, taskEnv, taskHostArgs, taskStateDir, } = await import('../core/ask.js');
1789
+ const run = a.flags.get('run');
1790
+ if (typeof run === 'string') {
1791
+ const stateDir = a.flags.get('state-dir');
1792
+ if (a.positionals.length ||
1793
+ a.rest.length ||
1794
+ [...a.flags.keys()].some((f) => f !== 'run' && f !== 'state-dir') ||
1795
+ stateDir === true)
1796
+ throw new UsageError('Use `sideby ask --run <id> [--state-dir <dir>]` on its own.');
1797
+ // The task names the state folder the Panel wrote it to; without it, this environment's folder is used.
1798
+ const where = typeof stateDir === 'string'
1799
+ ? { stateDir: await taskStateDir(stateDir) }
1800
+ : (runtime?.paths ?? resolvePaths());
1801
+ const task = await readTask(run, where);
1802
+ // The Host starts with the HOME, config and state the Panel used, whatever this terminal's environment says.
1803
+ const rt = task.home && (!runtime || runtime.paths.home !== task.home || runtime.paths.stateDir !== task.stateDir)
1804
+ ? await createRuntime({ env: taskEnv(task, runtime?.env ?? process.env) })
1805
+ : (runtime ?? (await createRuntime()));
1806
+ const cwd = process.cwd();
1807
+ try {
1808
+ try {
1809
+ process.chdir(task.cwd);
1810
+ }
1811
+ catch (err) {
1812
+ if (task.cwdInHome)
1813
+ throw movedCwdError('does not exist');
1814
+ throw err;
1815
+ }
1816
+ // A Portal's folder is checked where the process now is, so a link swapped in after the task was written is
1817
+ // caught, and the folder cannot change between the check and the Host start.
1818
+ if (task.cwdInHome) {
1819
+ const now = await realCwdInHome(process.cwd(), task.home ?? rt.paths.home);
1820
+ if ('why' in now)
1821
+ throw movedCwdError(now.why);
1822
+ if (now.real !== task.cwd)
1823
+ throw movedCwdError('points somewhere else');
1824
+ }
1825
+ if (task.kind === 'prompt')
1826
+ return await runAccount(rt, task.account, await taskHostArgs(rt, task), io, { aiTask: true });
1827
+ if (task.kind === 'run')
1828
+ return await runAccount(rt, task.account, [], io);
1829
+ const prepared = await rt.prepareLaunch(task.account, [], 'login');
1830
+ if (prepared.notice)
1831
+ io.err(prepared.notice);
1832
+ return await whileRunning(rt, () => runHost(prepared));
1833
+ }
1834
+ finally {
1835
+ process.chdir(cwd);
1836
+ }
1837
+ }
1838
+ if (a.flags.has('spec') || a.flags.has('choices'))
1839
+ return cmdAskSpec(a, io, runtime);
1840
+ const rt = runtime ?? (await createRuntime());
1841
+ const task = String(a.flags.get('task') ?? 'free');
1842
+ if (!AI_TASK_KINDS.includes(task))
1843
+ throw new UsageError(`Choose --task ${AI_TASK_KINDS.join('|')}.`);
1844
+ if (a.positionals.length > 1 || a.rest.length)
1845
+ throw new UsageError('Pass the text as one quoted argument: sideby ask "help me".');
1846
+ const input = {
1847
+ task,
1848
+ text: a.positionals[0],
1849
+ account: a.flags.get('account'),
1850
+ terminal: a.flags.get('terminal'),
1851
+ files: a.attach ?? [],
1852
+ };
1853
+ // The files are checked before anything else; `--print` lists them where they are and copies nothing.
1854
+ const preview = promptForTask(rt, input, await previewAttachments(rt, input));
1855
+ if (preview.removedSecrets)
1856
+ io.err('Key-shaped text was removed. Enter keys with `sideby key` or the Panel key box.');
1857
+ if (a.flags.has('print')) {
1858
+ io.out(preview.prompt);
1859
+ return 0;
1860
+ }
1861
+ // A chosen account becomes the next default, as choosing it in the Panel does.
1862
+ const result = await startAiTask(rt, { ...input, remember: Boolean(input.account || input.terminal) });
1863
+ if (a.flags.has('json'))
1864
+ json(io, result);
1865
+ else if (result.command)
1866
+ io.out(result.opened ? await openedLine(rt, result) : result.command);
1867
+ else
1868
+ io.out(result.prompt ?? preview.prompt);
1869
+ if (!result.opened)
1870
+ io.err(result.detail);
1871
+ return result.opened ? 0 : 1;
1872
+ }
1873
+ /** What `sideby ask` prints once the terminal opened; a Family with `aiTaskArgs` adds that its checks stay on. */
1874
+ async function openedLine(rt, result) {
1875
+ const line = `Opened ${result.terminal} for ${result.account}.`;
1876
+ const family = result.account
1877
+ ? await rt.resolve(result.account).then((a) => rt.families.get(a.family), () => undefined)
1878
+ : undefined;
1879
+ return family?.aiTaskArgs
1880
+ ? `${line} Its permission checks stay on, so risky actions are checked first.`
1881
+ : line;
1882
+ }
1883
+ /**
1884
+ * `sideby ask --spec - [--print]` and `sideby ask --choices` (ADR-0030): the AI Tasks a Portal starts. The Task Spec
1885
+ * comes on stdin, never through a shell. A refused spec exits 1 with its `code` (and `reason`, as the Portal reads
1886
+ * it), or 2 for a spec version this sideby does not know.
1887
+ */
1888
+ async function cmdAskSpec(a, io, runtime) {
1889
+ const { previewTaskSpec, parseTaskSpec, readSpecText, SpecError, startTaskSpec, taskChoices } = await import('../core/task-spec.js');
1890
+ const choices = a.flags.has('choices');
1891
+ const allowed = choices ? ['choices', 'json'] : ['spec', 'print', 'json'];
1892
+ if (a.positionals.length ||
1893
+ a.rest.length ||
1894
+ a.attach?.length ||
1895
+ [...a.flags.keys()].some((f) => !allowed.includes(f)))
1896
+ throw new UsageError('Use `sideby ask --spec - [--print] --json` or `sideby ask --choices --json` on their own.');
1897
+ const rt = runtime ?? (await createRuntime());
1898
+ if (choices) {
1899
+ const result = await taskChoices(rt);
1900
+ if (a.flags.has('json'))
1901
+ json(io, result);
1902
+ else {
1903
+ io.out(result.account ? `Account: ${result.account}` : `No account: ${result.detail}`);
1904
+ io.out(`Terminal: ${result.terminal}`);
1905
+ }
1906
+ return 0;
1907
+ }
1908
+ if (a.flags.get('spec') !== '-')
1909
+ throw new UsageError('Pass the Task Spec on stdin: sideby ask --spec - --json');
1910
+ const stdin = io.stdin ?? process.stdin;
1911
+ if (stdin.isTTY)
1912
+ throw new UsageError('Pipe the Task Spec into stdin: sideby ask --spec - --json < spec.json');
1913
+ try {
1914
+ const spec = parseTaskSpec(await readSpecText(stdin));
1915
+ if (a.flags.has('print')) {
1916
+ const preview = await previewTaskSpec(rt, spec);
1917
+ if (a.flags.has('json'))
1918
+ json(io, preview);
1919
+ else
1920
+ io.out(preview.prompt);
1921
+ return 0;
1922
+ }
1923
+ const result = await startTaskSpec(rt, spec);
1924
+ if (a.flags.has('json'))
1925
+ json(io, result);
1926
+ else if (result.command)
1927
+ io.out(result.opened ? await openedLine(rt, result) : result.command);
1928
+ else
1929
+ io.out(result.prompt ?? '');
1930
+ if (!result.opened)
1931
+ io.err(result.detail);
1932
+ return result.opened ? 0 : 1;
1933
+ }
1934
+ catch (err) {
1935
+ // A folder that changed between the check and the task file is refused like a bad one.
1936
+ if (!(err instanceof SpecError) && !(err instanceof UserError && err.code === 'bad-cwd'))
1937
+ throw err;
1938
+ if (a.flags.has('json'))
1939
+ json(io, { schemaVersion: 1, error: err.message, code: err.code, reason: err.code });
1940
+ else
1941
+ io.err(`sideby: ${err.message}`);
1942
+ return err.code === 'spec-version' ? 2 : 1;
1943
+ }
1944
+ }
1945
+ export async function cmdTerminal(a, io) {
1946
+ const { terminals, setCustomTerminal, setPreferredTerminal } = await import('../core/ask.js');
1947
+ const rt = await createRuntime();
1948
+ const changes = ['set', 'unset', 'custom'].filter((f) => a.flags.has(f));
1949
+ if (a.positionals.length || a.rest.length || changes.length > 1)
1950
+ throw new UsageError("Use sideby terminal [--set <id>|--custom '<program> … {cwd} … {cmd}'|--unset] [--json].");
1951
+ const custom = a.flags.get('custom');
1952
+ if (a.flags.has('custom')) {
1953
+ if (typeof custom !== 'string')
1954
+ throw new UsageError("Use sideby terminal --custom '<program> … {cwd} … {cmd}'.");
1955
+ await setCustomTerminal(rt, custom);
1956
+ }
1957
+ else if (a.flags.has('set') || a.flags.has('unset'))
1958
+ await setPreferredTerminal(rt, a.flags.get('set'));
1959
+ const result = await terminals(rt);
1960
+ if (a.flags.has('json'))
1961
+ json(io, result);
1962
+ else {
1963
+ io.out(table(result.terminals.map((t) => [t.id, t.installed ? 'yes' : 'no']), ['Terminal', 'Installed']));
1964
+ io.out(`Preferred: ${result.preferred ?? 'automatic'}; selected: ${result.guess.id} (${result.guess.source}).`);
1965
+ }
1966
+ return 0;
1967
+ }
1968
+ /** Reads a key only from an interactive terminal, restoring its original mode on every exit. */
1969
+ export function readKeyLine(input = process.stdin) {
1970
+ if (!input.isTTY || !input.setRawMode)
1971
+ throw new UserError('Run `sideby key` in a terminal or use the Panel key box.', { code: 'tty-required' });
1972
+ return new Promise((resolve, reject) => {
1973
+ const raw = input.isRaw;
1974
+ const paused = input.isPaused();
1975
+ let value = '';
1976
+ const finish = (error) => {
1977
+ input.off('data', onData);
1978
+ input.off('end', onEnd);
1979
+ input.off('error', onError);
1980
+ input.setRawMode(raw);
1981
+ if (paused)
1982
+ input.pause();
1983
+ if (error)
1984
+ reject(error);
1985
+ else
1986
+ resolve(value);
1987
+ };
1988
+ const onEnd = () => finish(new UserError('Key input ended; rerun `sideby key` in a terminal.'));
1989
+ const onError = () => finish(new UserError('Cannot read the key; use the Panel key box.'));
1990
+ // Bytes decode across chunks, so a character split by a paste arrives whole.
1991
+ const decoder = new StringDecoder('utf8');
1992
+ // An escape sequence (an arrow key: ESC [ D) is dropped whole: 0 none, 1 after ESC, 2 inside CSI, 3 inside SS3.
1993
+ let sequence = 0;
1994
+ const onData = (data) => {
1995
+ for (const ch of typeof data === 'string' ? data : decoder.write(data)) {
1996
+ // A control character (Enter, Ctrl-C) still counts inside a sequence; it also ends the sequence.
1997
+ if (sequence && ch >= ' ' && ch !== '\u007f') {
1998
+ if (sequence === 1)
1999
+ sequence = ch === '[' ? 2 : ch === 'O' ? 3 : 0;
2000
+ else if (sequence === 3 || (ch >= '@' && ch <= '~'))
2001
+ sequence = 0;
2002
+ continue;
2003
+ }
2004
+ sequence = 0;
2005
+ if (ch === '\u001b') {
2006
+ sequence = 1;
2007
+ continue;
2008
+ }
2009
+ if (ch === '\u0003') {
2010
+ finish(new UserError('Cancelled; rerun `sideby key` when ready.'));
2011
+ return;
2012
+ }
2013
+ if (ch === '\r' || ch === '\n') {
2014
+ finish();
2015
+ return;
2016
+ }
2017
+ if (ch === '\u007f' || ch === '\b')
2018
+ value = [...value].slice(0, -1).join('');
2019
+ else if (ch >= ' ')
2020
+ value += ch;
2021
+ }
2022
+ };
2023
+ input.setRawMode(true);
2024
+ input.on('data', onData);
2025
+ input.once('end', onEnd);
2026
+ input.once('error', onError);
2027
+ input.resume();
2028
+ });
2029
+ }
2030
+ export async function cmdKey(a, io, runtime) {
2031
+ const rt = runtime ?? (await createRuntime());
2032
+ const { join } = await import('node:path');
2033
+ const { setSecret, secretVarFor, SECRET_VAR_NAME } = await import('../core/secret-file.js');
2034
+ if (a.positionals.length !== 1 || a.rest.length)
2035
+ throw new UsageError('Use sideby key <account> [--var <NAME>] [--json].');
2036
+ const account = await rt.resolve(a.positionals[0]);
2037
+ const family = rt.families.get(account.family);
2038
+ if (account.kind !== 'api' && family.secretFileMeansApi !== false)
2039
+ throw new UserError('This is a subscription account; use `sideby login <account>` or create an API account with `sideby new <family> <name> --api`.');
2040
+ const name = a.flags.get('var') ?? secretVarFor(family);
2041
+ if (!SECRET_VAR_NAME.test(name))
2042
+ throw new UsageError('Use an uppercase variable name such as API_KEY.');
2043
+ const input = (io.stdin ?? process.stdin);
2044
+ if (!input.isTTY)
2045
+ throw new UserError('Run `sideby key` in a terminal or use the Panel key box.', { code: 'tty-required' });
2046
+ io.err(`Enter ${name} (hidden), then press Enter:`);
2047
+ const value = await readKeyLine(input);
2048
+ if (!value.trim())
2049
+ throw new UserError(`No key entered; nothing was written. Run \`sideby key ${account.ref}\` again.`, {
2050
+ code: 'key-empty',
2051
+ });
2052
+ const result = await setSecret(account.secretFile ?? join(account.dir, 'proxy.env'), name, value);
2053
+ if (a.flags.has('json'))
2054
+ json(io, { account: account.ref, var: name, written: true, path: result.path });
2055
+ else
2056
+ io.out(`Wrote ${name} to ${result.path}.`);
2057
+ return 0;
2058
+ }
2059
+ export async function cmdTry(a, io) {
2060
+ const { tryAccount, tryPreview } = await import('../core/ask.js');
2061
+ if (a.positionals.length !== 1 || a.rest.length)
2062
+ throw new UsageError('Use sideby try <account> [--yes] [--json].');
2063
+ const rt = await createRuntime();
2064
+ const { account, command } = await tryPreview(rt, a.positionals[0]);
2065
+ if (!a.flags.has('yes')) {
2066
+ if (a.flags.has('json'))
2067
+ json(io, { account: account.ref, command, confirmed: false });
2068
+ else
2069
+ io.out(`This spends a few tokens: ${command.map((v) => JSON.stringify(v)).join(' ')}. Run again with --yes to continue.`);
2070
+ return 10;
2071
+ }
2072
+ const { account: ref, command: _command, ...result } = await tryAccount(rt, account.ref);
2073
+ if (a.flags.has('json'))
2074
+ json(io, { account: ref, confirmed: true, ...result });
2075
+ else
2076
+ io.out(result.ok ? 'OK' : result.output || 'The Host did not reply; check the account and try again.');
2077
+ return result.ok ? 0 : 1;
2078
+ }
2079
+ /** `sideby autostart [on|off] [--yes]` (spec §3.29, ADR-0029): start the Panel in the background at login. */
2080
+ export async function cmdAutostart(a, io) {
2081
+ const { applyAutostart, autostartStatus, planAutostart, refreshAutostart } = await import('../core/autostart.js');
2082
+ const [action, extra] = a.positionals;
2083
+ if (extra !== undefined || (action !== undefined && action !== 'on' && action !== 'off'))
2084
+ throw new UsageError('usage: sideby autostart [on|off] [--yes] [--json]');
2085
+ if (a.flags.has('yes') && !action)
2086
+ throw new UsageError('--yes needs a change: sideby autostart on|off --yes');
2087
+ const paths = resolvePaths();
2088
+ const home = paths.home;
2089
+ const ctx = { home };
2090
+ const wantJson = a.flags.has('json');
2091
+ if (a.flags.has('refresh')) {
2092
+ // After an update or a local build switch: point an existing agent at this sideby; never create one.
2093
+ const r = await refreshAutostart(ctx);
2094
+ const status = await autostartStatus(ctx);
2095
+ if (wantJson)
2096
+ json(io, {
2097
+ ...status,
2098
+ path: tilde(status.path, home),
2099
+ changed: r.rewritten,
2100
+ ...(r.note ? { note: r.note } : {}),
2101
+ });
2102
+ else
2103
+ io.out(r.rewritten ? 'The login item now starts this sideby.' : (r.note ?? 'Nothing to change.'));
2104
+ return 0;
2105
+ }
2106
+ if (!action) {
2107
+ const s = await autostartStatus(ctx);
2108
+ if (wantJson)
2109
+ json(io, { ...s, path: tilde(s.path, home) });
2110
+ else if (!s.supported)
2111
+ io.out(`${s.reason}.`);
2112
+ else if (s.state === 'off')
2113
+ io.out('Off: sideby does not start at login. Turn it on: sideby autostart on');
2114
+ else if (s.state === 'foreign')
2115
+ 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.`);
2116
+ else if (s.state === 'stale')
2117
+ io.out(`Out of date: the login item starts ${s.missing.join(' and ')}, which no longer exists. Run \`sideby autostart on\` to point it at this sideby.`);
2118
+ else {
2119
+ io.out('On: the panel starts in the background at login, without opening a window.');
2120
+ if (!s.current)
2121
+ io.out(c.dim('It starts another sideby than this one; `sideby autostart on` points it here.'));
2122
+ io.out(c.dim('Turn it off: sideby autostart off'));
2123
+ }
2124
+ return 0;
2125
+ }
2126
+ const plan = await planAutostart(ctx, action);
2127
+ if (plan.blocked)
2128
+ throw new UserError(plan.blocked.message, { code: plan.blocked.code });
2129
+ const yes = a.flags.has('yes');
2130
+ const shown = {
2131
+ ...plan.status,
2132
+ path: tilde(plan.path, home),
2133
+ action,
2134
+ changed: plan.changed,
2135
+ applied: false,
2136
+ ...(plan.content ? { content: plan.content } : {}),
2137
+ ...(plan.programArguments ? { programArguments: plan.programArguments } : {}),
2138
+ commands: plan.commands,
2139
+ };
2140
+ if (!plan.changed) {
2141
+ if (wantJson)
2142
+ json(io, shown);
2143
+ else
2144
+ io.out(action === 'on' ? 'Already on.' : 'Already off.');
2145
+ return 0;
2146
+ }
2147
+ if (!yes) {
2148
+ if (wantJson)
2149
+ json(io, shown);
2150
+ else {
2151
+ if (action === 'on') {
2152
+ io.out(`Writes ${tilde(plan.path, home)}:`);
2153
+ io.out(c.dim(plan.content.trimEnd()));
2154
+ }
2155
+ else
2156
+ io.out(`Removes ${tilde(plan.path, home)}.`);
2157
+ io.out(`Then runs: ${plan.commands.map((cmd) => cmd.join(' ')).join('; ')}`);
2158
+ io.out(action === 'on'
2159
+ ? 'At login the panel starts in the background, without opening a window. Run again with --yes to turn it on.'
2160
+ : 'Run again with --yes to turn it off.');
2161
+ }
2162
+ return 10;
2163
+ }
2164
+ const r = await applyAutostart(ctx, plan);
2165
+ if (wantJson)
2166
+ json(io, {
2167
+ ...shown,
2168
+ state: r.state,
2169
+ applied: true,
2170
+ loaded: r.loaded,
2171
+ ...(r.note ? { note: r.note } : {}),
2172
+ });
2173
+ else {
2174
+ io.out(action === 'on'
2175
+ ? 'On: the panel starts in the background at login. Undo: sideby autostart off'
2176
+ : 'Off: sideby no longer starts at login.');
2177
+ if (r.note)
2178
+ io.out(c.dim(r.note));
2179
+ }
2180
+ return 0;
2181
+ }
2182
+ /** What the Menu Bar Item lists (spec §3.31): each Family's accounts in Display Order, with its Handoff ranking. */
2183
+ async function menubarFamilies(rt) {
2184
+ const accounts = displayOrdered(await rt.accounts(), rt);
2185
+ const ids = [...new Set(accounts.map((x) => x.family))];
2186
+ return Promise.all(ids.map(async (id) => {
2187
+ const f = rt.families.get(id);
2188
+ const plan = f.readQuota || f.fetchQuota ? await rt.handoff(id).catch(() => null) : null;
2189
+ const list = await Promise.all(accounts
2190
+ .filter((x) => x.family === id)
2191
+ .map(async (x) => ({
2192
+ ref: x.ref,
2193
+ name: x.name,
2194
+ kind: x.kind,
2195
+ login: x.kind === 'api' ? 'not-needed' : (await rt.status(x)).login,
2196
+ quota: await rt.quota(x),
2197
+ sameLogin: await rt.sameLogin(x),
2198
+ })));
2199
+ return { id, title: f.title, logo: f.logo ?? null, plan, accounts: list };
2200
+ }));
2201
+ }
2202
+ /**
2203
+ * `sideby menubar [on|off] [--yes]`, `menubar snapshot` and `menubar start <account>` (spec §3.31, ADR-0034): quota in
2204
+ * the macOS menu bar.
2205
+ */
2206
+ export async function cmdMenubar(a, io) {
2207
+ const [action, extra] = a.positionals;
2208
+ const wantJson = a.flags.has('json');
2209
+ if (action === 'snapshot') {
2210
+ if (extra !== undefined)
2211
+ throw new UsageError('usage: sideby menubar snapshot [--lang en|zh] [--json]');
2212
+ const { menubarHotkey, menubarLang, menubarSnapshot } = await import('../menubar/snapshot.js');
2213
+ const rt = await createRuntime();
2214
+ const lang = menubarLang(rt.config.panel?.language, a.flags.get('lang') ?? rt.env.LANG);
2215
+ const snap = menubarSnapshot(await menubarFamilies(rt), rt.readContext().now, lang, menubarHotkey(rt.config.menubar?.hotkey));
2216
+ if (wantJson)
2217
+ json(io, snap);
2218
+ else {
2219
+ io.out(snap.title ? `${snap.title} ${c.dim(snap.tooltip)}` : snap.tooltip);
2220
+ const line = (r, indent) => io.out(`${indent}${r.label}${r.recommended ? ` (${snap.labels.recommended})` : ''} ${c.dim(r.detail)}`);
2221
+ for (const s of snap.sections) {
2222
+ io.out(c.bold(s.title));
2223
+ for (const r of s.rows)
2224
+ line(r, ' ');
2225
+ if (s.more) {
2226
+ io.out(` ${s.more.title}`);
2227
+ for (const r of s.more.rows)
2228
+ line(r, ' ');
2229
+ }
2230
+ }
2231
+ }
2232
+ return 0;
2233
+ }
2234
+ if (action === 'start') {
2235
+ if (!extra || a.positionals.length > 2)
2236
+ throw new UsageError('usage: sideby menubar start <account> [--json]');
2237
+ const { openRunInTerminal } = await import('../core/ask.js');
2238
+ const rt = await createRuntime();
2239
+ const r = await openRunInTerminal(rt, extra);
2240
+ if (wantJson)
2241
+ json(io, r);
2242
+ else
2243
+ io.out(r.opened ? `Opened ${r.terminal} for ${r.account}.` : r.command);
2244
+ if (!r.opened)
2245
+ io.err(r.detail);
2246
+ return r.opened ? 0 : 1;
2247
+ }
2248
+ const { applyAutostart, autostartStatus, planAutostart, refreshAutostart } = await import('../core/autostart.js');
2249
+ const { MENUBAR_AGENT } = await import('../menubar/agent.js');
2250
+ if (extra !== undefined || (action !== undefined && action !== 'on' && action !== 'off'))
2251
+ throw new UsageError('usage: sideby menubar [on|off] [--yes] [--json]');
2252
+ if (a.flags.has('yes') && !action)
2253
+ throw new UsageError('--yes needs a change: sideby menubar on|off --yes');
2254
+ const home = resolvePaths().home;
2255
+ const ctx = { home };
2256
+ if (a.flags.has('refresh')) {
2257
+ // After an update or a local build switch: point an existing agent at this sideby; never create one.
2258
+ const r = await refreshAutostart(ctx, MENUBAR_AGENT);
2259
+ const status = await autostartStatus(ctx, MENUBAR_AGENT);
2260
+ if (wantJson)
2261
+ json(io, {
2262
+ ...status,
2263
+ path: tilde(status.path, home),
2264
+ changed: r.rewritten,
2265
+ ...(r.note ? { note: r.note } : {}),
2266
+ });
2267
+ else
2268
+ io.out(r.rewritten ? 'The menu bar item now runs this sideby.' : (r.note ?? 'Nothing to change.'));
2269
+ return 0;
2270
+ }
2271
+ if (!action) {
2272
+ const s = await autostartStatus(ctx, MENUBAR_AGENT);
2273
+ if (wantJson)
2274
+ json(io, { ...s, path: tilde(s.path, home) });
2275
+ else if (!s.supported)
2276
+ io.out('The menu bar item is only available on macOS for now.');
2277
+ else if (s.state === 'off')
2278
+ io.out('Menu bar item: off. Run `sideby menubar on` to show quota in the menu bar.');
2279
+ else if (s.state === 'foreign')
2280
+ 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.`);
2281
+ else if (s.state === 'stale')
2282
+ io.out('Menu bar item: points to a sideby or Node that is no longer there. Run `sideby menubar on` to fix it.');
2283
+ else {
2284
+ io.out('Menu bar item: on.');
2285
+ if (!s.current)
2286
+ io.out(c.dim('It runs another sideby than this one; `sideby menubar on` points it here.'));
2287
+ io.out(c.dim('Turn it off: sideby menubar off'));
2288
+ }
2289
+ return 0;
2290
+ }
2291
+ const plan = await planAutostart(ctx, action, MENUBAR_AGENT);
2292
+ if (plan.blocked)
2293
+ throw new UserError(plan.blocked.code === 'unsupported'
2294
+ ? 'The menu bar item is only available on macOS for now.'
2295
+ : plan.blocked.message, { code: plan.blocked.code });
2296
+ const shown = {
2297
+ ...plan.status,
2298
+ path: tilde(plan.path, home),
2299
+ action,
2300
+ changed: plan.changed,
2301
+ applied: false,
2302
+ ...(plan.content ? { content: plan.content } : {}),
2303
+ ...(plan.programArguments ? { programArguments: plan.programArguments } : {}),
2304
+ commands: plan.commands,
2305
+ };
2306
+ if (!plan.changed) {
2307
+ if (wantJson)
2308
+ json(io, shown);
2309
+ else
2310
+ io.out(action === 'on' ? 'Already on.' : 'Already off.');
2311
+ return 0;
2312
+ }
2313
+ const path = tilde(plan.path, home);
2314
+ if (!a.flags.has('yes')) {
2315
+ // The file holds the whole menu bar script, so only its path is printed; `--json` carries the content.
2316
+ if (wantJson)
2317
+ json(io, shown);
2318
+ else
2319
+ io.out(action === 'on'
2320
+ ? `This adds a login item at ${path} that shows your quota in the menu bar and starts at login. Run \`sideby menubar on --yes\` to turn it on.`
2321
+ : `This removes ${path} and hides the menu bar item. Run \`sideby menubar off --yes\` to turn it off.`);
2322
+ return 10;
2323
+ }
2324
+ const r = await applyAutostart(ctx, plan, MENUBAR_AGENT);
2325
+ if (wantJson)
2326
+ json(io, {
2327
+ ...shown,
2328
+ state: r.state,
2329
+ applied: true,
2330
+ loaded: r.loaded,
2331
+ ...(r.note ? { note: r.note } : {}),
2332
+ });
2333
+ else {
2334
+ io.out(action === 'on'
2335
+ ? 'The menu bar item is on and in your menu bar now. To turn it off later, run `sideby menubar off`.'
2336
+ : 'The menu bar item is off. Run `sideby menubar on` to turn it on again.');
2337
+ if (r.note)
2338
+ io.out(c.dim(r.note));
2339
+ }
2340
+ return 0;
2341
+ }
2342
+ /** The `accounts.<ref>.args` check of `sideby config set`: only the model and effort arguments, as `sideby model`. */
2343
+ function modelArgsProblem(rt) {
2344
+ return (ref, args) => {
2345
+ const family = ref.split(':')[0] ?? '';
2346
+ const f = rt.families.get(family);
2347
+ const mc = f?.modelChoice;
2348
+ if (!mc)
2349
+ return `${f?.title ?? family} has no model choice in sideby`;
2350
+ const { choice, rest } = mc.fromArgs(args);
2351
+ if (rest.length)
2352
+ return `${rest.join(' ')} is not a model or effort argument`;
2353
+ if (choice.effort && !mc.efforts.includes(choice.effort))
2354
+ return `"${choice.effort}" is not an effort level for ${f.title}; use one of: ${mc.efforts.join(', ')}`;
2355
+ if (choice.model && !MODEL_NAME.test(choice.model))
2356
+ return `"${choice.model}" is not a model name sideby passes on`;
2357
+ return null;
2358
+ };
2359
+ }
2360
+ const shownValue = (v) => (v === undefined ? '(not set)' : JSON.stringify(v));
2361
+ /** `sideby config get|set|unset` (spec §3.29): every setting has a command. */
2362
+ export async function cmdConfig(a, io) {
2363
+ const cfg = await import('../core/config.js');
2364
+ const [sub = 'get', key, value, ...more] = a.positionals;
2365
+ const wantJson = a.flags.has('json');
2366
+ const yes = a.flags.has('yes');
2367
+ const paths = resolvePaths();
2368
+ const file = paths.configFile;
2369
+ const shownFile = tilde(file, paths.home);
2370
+ if (sub === 'get') {
2371
+ if (value !== undefined || yes)
2372
+ throw new UsageError('usage: sideby config get [<key>] [--json]');
2373
+ if (key === undefined) {
2374
+ const keys = cfg.settableKeys(await cfg.loadConfig(file));
2375
+ if (wantJson)
2376
+ json(io, { file: shownFile, keys });
2377
+ else {
2378
+ for (const k of keys) {
2379
+ const now = k.value !== undefined
2380
+ ? shownValue(k.value)
2381
+ : k.entries?.length
2382
+ ? k.entries.map((e) => `${e.key}=${JSON.stringify(e.value)}`).join(', ')
2383
+ : c.dim('(not set)');
2384
+ io.out(`${k.key} = ${now}`);
2385
+ io.out(c.dim(` ${k.meaning} Takes ${k.takes}.`));
2386
+ }
2387
+ io.out(c.dim(`Change one: sideby config set <key> <value>. File: ${shownFile}`));
2388
+ }
2389
+ return 0;
2390
+ }
2391
+ const d = cfg.describeConfigKey(key);
2392
+ const r = await cfg.configGet(file, key);
2393
+ if (wantJson)
2394
+ json(io, {
2395
+ key,
2396
+ set: r.value !== undefined,
2397
+ ...(r.value !== undefined ? { value: r.value } : {}),
2398
+ meaning: d.meaning,
2399
+ takes: d.takes,
2400
+ });
2401
+ else {
2402
+ io.out(r.value === undefined ? '(not set)' : JSON.stringify(r.value, null, 2));
2403
+ io.out(c.dim(`${d.meaning} Takes ${d.takes}.`));
2404
+ }
2405
+ return 0;
2406
+ }
2407
+ if (sub !== 'set' && sub !== 'unset')
2408
+ throw new UsageError('usage: sideby config get [<key>] | set <key> <value> | unset <key> [--yes] [--json]');
2409
+ if (!key ||
2410
+ (sub === 'set' && value === undefined) ||
2411
+ (sub === 'unset' && value !== undefined) ||
2412
+ more.length)
2413
+ throw new UsageError(sub === 'set'
2414
+ ? 'usage: sideby config set <key> <value> [--yes] [--json] (quote a value with spaces)'
2415
+ : 'usage: sideby config unset <key> [--yes] [--json]');
2416
+ const next = sub === 'set' ? cfg.parseConfigValue(value) : undefined;
2417
+ const argsProblem = key.startsWith('accounts') ? modelArgsProblem(await createRuntime()) : undefined;
2418
+ const r = await cfg.editConfigPath(file, key, next, {
2419
+ dryRun: !yes,
2420
+ ...(argsProblem ? { argsProblem } : {}),
2421
+ });
2422
+ const out = {
2423
+ action: sub,
2424
+ key,
2425
+ file: shownFile,
2426
+ changed: r.changed,
2427
+ applied: r.changed && yes,
2428
+ ...(r.before !== undefined ? { before: r.before } : {}),
2429
+ ...(r.after !== undefined ? { after: r.after } : {}),
2430
+ };
2431
+ if (wantJson)
2432
+ json(io, out);
2433
+ else if (!r.changed)
2434
+ io.out('Nothing to change.');
2435
+ else {
2436
+ io.out(`${key}: ${shownValue(r.before)} → ${shownValue(r.after)}`);
2437
+ io.out(yes ? `Saved to ${shownFile}.` : 'Run again with --yes to save it.');
2438
+ }
2439
+ return r.changed && !yes ? 10 : 0;
2440
+ }