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
@@ -2,10 +2,14 @@
2
2
  import { randomBytes, timingSafeEqual } from 'node:crypto';
3
3
  import { aliasesByAccount } from '../core/accounts.js';
4
4
  import { listAppProfiles, openAppProfile, removeAppProfile, } from '../core/app-profiles.js';
5
+ import { openLoginInTerminal, pickTaskAccount, previewAttachments, promptForTask, setCustomTerminal, setPreferredTerminal, startAiTask, taskContext, terminals, tryAccount, } from '../core/ask.js';
6
+ import { MAX_ATTACHMENTS, MAX_UPLOAD_BYTES, removeStaged, stageUpload } from '../core/attachments.js';
7
+ import { applyAutostart, autostartStatus, PANEL_AGENT, planAutostart, } from '../core/autostart.js';
5
8
  import { FAVICON_SVG, ICON_SVG } from '../core/brand-mark.js';
6
9
  import { browserReport, openInBrowser, setBrowserSignIns, } from '../core/browser-profiles.js';
7
- import { aliasArgs, aliasRefs, editConfigUpdate, } from '../core/config.js';
10
+ import { aliasArgs, aliasRefs, editConfigPanel, editConfigTerminal, editConfigUpdate, } from '../core/config.js';
8
11
  import { openDesktopApp, withDesktopApps } from '../core/desktop-app.js';
12
+ import { editSettings } from '../core/edit-settings.js';
9
13
  import { UserError } from '../core/errors.js';
10
14
  import { planHandoff } from '../core/handoff.js';
11
15
  import { applyHandoffEnable, planHandoffEnable } from '../core/handoff-enable.js';
@@ -13,17 +17,32 @@ import { handoffOverview } from '../core/handoff-overview.js';
13
17
  import { configureHandoff, handoffStatus } from '../core/handoff-status.js';
14
18
  import { accountModel, setAccountModel } from '../core/model-choice.js';
15
19
  import { tildify } from '../core/paths.js';
20
+ import { SECRET_VAR_NAME, secretVarFor, setSecret } from '../core/secret-file.js';
16
21
  import { SKILL_INSTALL } from '../core/skill-check.js';
22
+ import { launchArgs, TERMINALS } from '../core/terminal.js';
17
23
  import { MIN_CALLS } from '../core/tuning.js';
18
24
  import * as update from '../core/update.js';
19
25
  import { buildId, localBuild, packageVersion } from '../core/version.js';
20
26
  import { HOOK_FAMILIES } from '../handoff/hook.js';
27
+ import { MENUBAR_AGENT } from '../menubar/agent.js';
28
+ import { MENUBAR_SCRIPT } from '../menubar/script.js';
21
29
  import { renderPage } from './page.js';
30
+ import { AI_TASK_KINDS } from './page-logic.js';
22
31
  import { resolveTheme } from './theme.js';
23
32
  export const PANEL_VERSION = packageVersion();
24
33
  export const MAX_BODY_BYTES = 64 * 1024;
25
34
  /** Write requests allowed to wait behind the running one; more get 409. */
26
35
  export const MAX_QUEUED_WRITES = 4;
36
+ function resolveAsk(ask) {
37
+ if (ask === undefined)
38
+ return undefined;
39
+ if (!ask ||
40
+ typeof ask !== 'object' ||
41
+ ask.bridge !== 'postMessage' ||
42
+ Object.keys(ask).length !== 1)
43
+ throw new TypeError('panel ask must be { bridge: "postMessage" } or left out');
44
+ return { bridge: 'postMessage' };
45
+ }
27
46
  const PANEL_LANGS = ['auto', 'en', 'zh'];
28
47
  function resolveLang(lang) {
29
48
  if (lang === undefined)
@@ -44,6 +63,66 @@ export function healthByAccount(history) {
44
63
  });
45
64
  return out;
46
65
  }
66
+ function keyFacts(def) {
67
+ let keyVar = null;
68
+ try {
69
+ keyVar = secretVarFor(def);
70
+ }
71
+ catch { }
72
+ return {
73
+ keyVar,
74
+ ...(def.secretFileMeansApi === false ? { keyAlways: true } : {}),
75
+ ...(def.probe ? { tryCommand: [def.bin, ...def.probe.args] } : {}),
76
+ ...(def.aiTaskArgs ? { aiTaskSafe: true } : {}),
77
+ };
78
+ }
79
+ let autostartOverride = {};
80
+ /**
81
+ * Internal, for tests: replaces parts of the machine the Panel's start-at-login switch uses (platform, launcher,
82
+ * `exec`, login home). Not part of the plugin or Portal contract.
83
+ */
84
+ export function bindPanelAutostart(ctx) {
85
+ const before = autostartOverride;
86
+ autostartOverride = { ...autostartOverride, ...ctx };
87
+ return () => {
88
+ autostartOverride = before;
89
+ };
90
+ }
91
+ const autostartCtx = (rt) => ({
92
+ home: rt.paths.home,
93
+ env: rt.env,
94
+ ...autostartOverride,
95
+ });
96
+ /**
97
+ * The start-at-login state as the page shows it (spec §3.29): the agent's path and what it starts, with the home
98
+ * folder as `~`, and nothing else of the machine.
99
+ */
100
+ export function autostartView(s, home) {
101
+ const t = shownArg(home);
102
+ return {
103
+ supported: s.supported,
104
+ ...(s.reason ? { reason: s.reason } : {}),
105
+ state: s.state,
106
+ path: t(s.path),
107
+ current: s.current,
108
+ ...(s.programArguments ? { programArguments: s.programArguments.map(t) } : {}),
109
+ ...(s.missing ? { missing: s.missing.map(t) } : {}),
110
+ };
111
+ }
112
+ /** A program argument as the page shows it: the home folder as `~`, and the menu bar script by name only. */
113
+ const shownArg = (home) => (a) => a === MENUBAR_SCRIPT ? '(menu bar script)' : tildify(a, home);
114
+ function autostartPlanView(p, home) {
115
+ return {
116
+ action: p.action,
117
+ changed: p.changed,
118
+ path: tildify(p.path, home),
119
+ ...(p.programArguments ? { programArguments: p.programArguments.map(shownArg(home)) } : {}),
120
+ ...(p.blocked ? { blocked: p.blocked } : {}),
121
+ status: autostartView(p.status, home),
122
+ };
123
+ }
124
+ const PANEL_THEMES = ['system', 'light', 'dark'];
125
+ const PANEL_LANGUAGES = ['auto', 'en', 'zh'];
47
126
  // One Update Check at a time per process, started by a state read when one is due (the cache also keeps a failed
48
127
  // one from being tried again within the hour, though the page asks every 20 s).
49
128
  let checking = null;
@@ -312,9 +391,10 @@ async function buildState(rt, opts) {
312
391
  readOnly: opts.readOnly,
313
392
  generatedAt: ctx.now.toISOString(),
314
393
  families: families.map((f) => {
315
- const logo = rt.families.get(f.id)?.logo;
394
+ const def = rt.families.get(f.id);
395
+ const logo = def?.logo;
316
396
  const g = f.brokenBin ? { ...f, brokenBin: tildify(f.brokenBin, ctx.home) } : f;
317
- return logo ? { ...g, logo } : g;
397
+ return { ...g, ...(logo ? { logo } : {}), ...(def ? keyFacts(def) : {}) };
318
398
  }),
319
399
  accounts: list,
320
400
  pluginErrors: rt.pluginErrors.map((e) => ({ where: e.where, message: e.message })),
@@ -338,6 +418,7 @@ async function buildState(rt, opts) {
338
418
  ...(showBrowser ? { browser } : {}),
339
419
  display: rt.displayOrder(),
340
420
  ...(rt.quotaChecks().length ? { quotaChecks: rt.quotaChecks() } : {}),
421
+ ...(rt.config.panel && Object.keys(rt.config.panel).length ? { panel: rt.config.panel } : {}),
341
422
  };
342
423
  }
343
424
  /** The `display` of a /api/display-order body: null, or string lists only; anything else is refused. */
@@ -405,6 +486,60 @@ function handoffChange(body) {
405
486
  }
406
487
  return out;
407
488
  }
489
+ /** The terminals for Settings and the confirm area: installed paths stay on the server. */
490
+ async function terminalsView(rt) {
491
+ const r = await terminals(rt);
492
+ return {
493
+ installed: r.installed.map((t) => t.id),
494
+ preferred: r.preferred,
495
+ guess: r.guess,
496
+ custom: rt.config.terminal?.custom ?? null,
497
+ terminals: r.terminals.map((t) => ({ id: t.id, name: t.name, installed: t.installed })),
498
+ };
499
+ }
500
+ const AI_TASKS = AI_TASK_KINDS;
501
+ /** The `context` of an AI Task body (spec §3.28): only the strings and findings a Task Prompt shows. */
502
+ function askContext(body) {
503
+ return taskContext(body.context, (message) => new HttpError(400, message));
504
+ }
505
+ /** Task, text, context, language and account of an /api/ask body; unknown tasks are refused. */
506
+ function askInput(body) {
507
+ const task = optString(body, 'task') ?? 'free';
508
+ if (!AI_TASKS.includes(task))
509
+ throw new HttpError(400, `"task" must be one of ${AI_TASKS.join(', ')}`);
510
+ const text = optString(body, 'text');
511
+ if (text && text.length > 8000)
512
+ throw new HttpError(400, '"text" is too long; keep it under 8000 characters');
513
+ const lang = optString(body, 'lang');
514
+ if (lang && lang !== 'en' && lang !== 'zh')
515
+ throw new HttpError(400, '"lang" must be "en" or "zh"');
516
+ const account = optString(body, 'account');
517
+ const terminal = optString(body, 'terminal');
518
+ if (terminal && !TERMINALS.some((t) => t.id === terminal))
519
+ throw new HttpError(400, 'unknown terminal; pick one from the list');
520
+ const context = askContext(body);
521
+ const uploads = body.attachments;
522
+ if (uploads !== undefined &&
523
+ !(Array.isArray(uploads) &&
524
+ uploads.length <= MAX_ATTACHMENTS &&
525
+ uploads.every((u) => typeof u === 'string' && /^[a-f0-9]{16}$/.test(u))))
526
+ throw new HttpError(400, `"attachments" must list at most ${MAX_ATTACHMENTS} upload ids`);
527
+ return {
528
+ ...(uploads?.length ? { uploads: uploads } : {}),
529
+ task,
530
+ ...(text ? { text } : {}),
531
+ ...(context ? { context } : {}),
532
+ ...(lang ? { lang } : {}),
533
+ ...(account ? { account } : {}),
534
+ ...(terminal ? { terminal } : {}),
535
+ };
536
+ }
537
+ /** A terminal open result as the page needs it: macOS refusing Automation gets its own flag (spec §3.28). */
538
+ function opened(r) {
539
+ return { ...r, automation: !r.opened && r.reason === 'automation-denied' };
540
+ }
541
+ /** The AI Task upload route; its body is a file, not a JSON object, so it sits outside the route table. */
542
+ const ATTACH_ROUTE = '/api/ask/attach';
408
543
  /** Runs write requests one at a time; a few may wait, the rest are told to retry. */
409
544
  function writeQueue() {
410
545
  let tail = Promise.resolve();
@@ -430,10 +565,153 @@ export function createPanelHandler(opts) {
430
565
  const theme = resolveTheme(opts.theme);
431
566
  const lang = resolveLang(opts.lang);
432
567
  const updates = opts.updates !== false;
568
+ const ask = resolveAsk(opts.ask);
433
569
  const token = randomBytes(32).toString('base64url');
434
570
  const serial = writeQueue();
435
571
  const getRuntime = typeof opts.runtime === 'function' ? opts.runtime : async () => opts.runtime;
572
+ /** The switch of one LaunchAgent sideby writes: the Panel's login item or the Menu Bar Item. */
573
+ const loginItemRoute = (agent) => ({
574
+ writes: (body) => body.confirm === true,
575
+ async run(body) {
576
+ if (typeof body.on !== 'boolean')
577
+ throw new HttpError(400, '"on" must be true or false');
578
+ const rt = await getRuntime();
579
+ const ctx = autostartCtx(rt);
580
+ const home = rt.paths.home;
581
+ const plan = await planAutostart(ctx, body.on ? 'on' : 'off', agent);
582
+ const shown = autostartPlanView(plan, home);
583
+ if (!optBool(body, 'confirm') || plan.blocked)
584
+ return { plan: shown, applied: false };
585
+ const saw = body.programArguments;
586
+ const want = shown.programArguments ?? [];
587
+ if (plan.action === 'on' &&
588
+ (!Array.isArray(saw) || saw.length !== want.length || saw.some((x, i) => x !== want[i])))
589
+ return { plan: shown, applied: false, changedSince: true };
590
+ const r = await applyAutostart(ctx, plan, agent);
591
+ return {
592
+ applied: true,
593
+ changed: r.changed,
594
+ loaded: r.loaded,
595
+ ...(r.note ? { note: r.note.split(home).join('~') } : {}),
596
+ status: autostartView(await autostartStatus(ctx, agent), home),
597
+ };
598
+ },
599
+ });
436
600
  const routes = {
601
+ // AI Tasks (spec §3.28, ADR-0027). The prompt and the account it would use, read only: for the confirm area,
602
+ // the copy fallback and the read-only Panel.
603
+ // Frees a staged upload the person removed from the dialog, so it stops counting toward the staging limit.
604
+ '/api/ask/attach/remove': {
605
+ async run(body) {
606
+ const ids = body.ids;
607
+ if (!Array.isArray(ids) || ids.length > MAX_ATTACHMENTS || ids.some((x) => typeof x !== 'string'))
608
+ throw new HttpError(400, `"ids" must be a list of at most ${MAX_ATTACHMENTS} upload ids`);
609
+ const rt = await getRuntime();
610
+ return { removed: await removeStaged(rt.paths, ids) };
611
+ },
612
+ },
613
+ '/api/ask/prompt': {
614
+ writes: () => false,
615
+ queued: false,
616
+ async run(body) {
617
+ const input = askInput(body);
618
+ const rt = await getRuntime();
619
+ const { prompt, removedSecrets } = promptForTask(rt, input, await previewAttachments(rt, input));
620
+ const pick = await pickTaskAccount(rt, input);
621
+ return {
622
+ prompt,
623
+ removedSecrets,
624
+ account: 'account' in pick ? pick.account.ref : null,
625
+ ...('reason' in pick ? { reason: pick.reason } : {}),
626
+ };
627
+ },
628
+ },
629
+ // Writes the task file and opens the terminal. An account the person picked, API ones too, is kept as `ask.account`.
630
+ '/api/ask': {
631
+ async run(body) {
632
+ const input = askInput(body);
633
+ const rt = await getRuntime();
634
+ return opened(await startAiTask(rt, { ...input, remember: Boolean(input.account || input.terminal) }));
635
+ },
636
+ },
637
+ // Runs `sideby login <ref>` in the person's terminal; no AI is involved (spec §3.28 "登录").
638
+ '/api/login': {
639
+ async run(body) {
640
+ const account = optString(body, 'account');
641
+ if (!account)
642
+ throw new HttpError(400, '"account" is required');
643
+ return opened(await openLoginInTerminal(await getRuntime(), account));
644
+ },
645
+ },
646
+ // The key box: writes one variable of an API Account's proxy.env. The value is never returned or logged.
647
+ '/api/key': {
648
+ async run(body) {
649
+ const account = optString(body, 'account');
650
+ if (!account)
651
+ throw new HttpError(400, '"account" is required');
652
+ const value = body.value;
653
+ if (typeof value !== 'string' || !value.trim())
654
+ throw new HttpError(400, 'enter the key');
655
+ const name = optString(body, 'var');
656
+ if (name !== undefined && !SECRET_VAR_NAME.test(name))
657
+ throw new HttpError(400, 'use an uppercase variable name such as API_KEY');
658
+ const rt = await getRuntime();
659
+ const found = await rt.resolve(account);
660
+ const family = rt.families.get(found.family);
661
+ if (!family)
662
+ throw new HttpError(400, 'unknown family');
663
+ if (found.kind !== 'api' && family.secretFileMeansApi !== false)
664
+ throw new UserError('This is a subscription account; sign in instead, or create an API account in New account.');
665
+ const v = name ?? secretVarFor(family);
666
+ const { join } = await import('node:path');
667
+ const r = await setSecret(found.secretFile ?? join(found.dir, 'proxy.env'), v, value.trim());
668
+ return { account: found.ref, var: v, written: true, path: tildify(r.path, rt.paths.home) };
669
+ },
670
+ },
671
+ // `sideby try`: the page has said it spends a few tokens. It starts a program, so it is a write; it runs beside
672
+ // the queue because the Host may take up to a minute.
673
+ '/api/try': {
674
+ queued: false,
675
+ async run(body) {
676
+ const account = optString(body, 'account');
677
+ if (!account)
678
+ throw new HttpError(400, '"account" is required');
679
+ return tryAccount(await getRuntime(), account);
680
+ },
681
+ },
682
+ // Preferred Terminal and Custom terminal command (spec §3.28): `id` null or left out goes back to the guess;
683
+ // `custom` an empty string removes the template.
684
+ '/api/terminal': {
685
+ async run(body) {
686
+ const id = body.id === undefined ? undefined : optString(body, 'id');
687
+ if (id && !TERMINALS.some((t) => t.id === id))
688
+ throw new HttpError(400, 'unknown terminal; pick one from the list');
689
+ const rt = await getRuntime();
690
+ if (body.custom !== undefined) {
691
+ // Same rules as `sideby terminal --custom`: a saved command is also the one chosen; clearing it drops that choice.
692
+ const custom = optString(body, 'custom')?.trim();
693
+ if (custom) {
694
+ try {
695
+ await setCustomTerminal(rt, custom);
696
+ }
697
+ catch (err) {
698
+ throw new HttpError(400, err.message);
699
+ }
700
+ }
701
+ else {
702
+ const wasChosen = rt.config.terminal?.preferred === 'custom';
703
+ const r = await editConfigTerminal(rt.paths.configFile, {
704
+ custom: undefined,
705
+ ...(wasChosen ? { preferred: undefined } : {}),
706
+ });
707
+ rt.config.terminal = r.after;
708
+ }
709
+ }
710
+ if (body.id !== undefined || body.custom === undefined)
711
+ await setPreferredTerminal(rt, id);
712
+ return terminalsView(rt);
713
+ },
714
+ },
437
715
  '/api/doctor': {
438
716
  // Only the record of the check is written, and a read-only Panel skips that (persist: false).
439
717
  writes: () => false,
@@ -608,6 +886,19 @@ export function createPanelHandler(opts) {
608
886
  };
609
887
  },
610
888
  },
889
+ // Opens the Account's Host settings file with the system's default program (spec §3.30, ADR-0033). It reads none
890
+ // of the file but starts a program, so a read-only Panel refuses it (writes defaults to true).
891
+ '/api/account/edit-settings': {
892
+ async run(body) {
893
+ const account = optString(body, 'account');
894
+ if (!account)
895
+ throw new HttpError(400, '"account" is required');
896
+ const rt = await getRuntime();
897
+ const r = await editSettings(rt, account);
898
+ const home = rt.paths.home;
899
+ return { ...r, path: tildify(r.path, home), ...(r.target ? { target: tildify(r.target, home) } : {}) };
900
+ },
901
+ },
611
902
  // Browser Sign-ins on or off (spec §3.24): config `browser.signIns`, shown first like every config change.
612
903
  '/api/browser/settings': {
613
904
  writes: (body) => body.confirm === true,
@@ -698,7 +989,7 @@ export function createPanelHandler(opts) {
698
989
  const shown = update.shownPlan(plan);
699
990
  if (!optBool(body, 'confirm'))
700
991
  return { ...shown, updated: false };
701
- // The CLI is current and the skill is behind: `skill: true` updates it alone, as `sideby update --yes` does.
992
+ // The CLI is current and the skill is behind: `skill: true` updates it alone, as `sideby update --skill --yes` does.
702
993
  if (optBool(body, 'skill')) {
703
994
  if (plan.available || plan.method.kind === 'local')
704
995
  return { ...shown, updated: false, changed: true };
@@ -715,6 +1006,7 @@ export function createPanelHandler(opts) {
715
1006
  const { backgroundPanelPort } = await import('./background.js');
716
1007
  const r = await update.applyUpdate(rt.paths, plan, rt.env, {
717
1008
  panelPort: () => backgroundPanelPort(rt.paths),
1009
+ skillSync: 'background',
718
1010
  });
719
1011
  if (!r.ok)
720
1012
  throw new UserError(r.message);
@@ -725,6 +1017,7 @@ export function createPanelHandler(opts) {
725
1017
  restartedPanel: r.restartedPanel,
726
1018
  refreshedApp: r.refreshedApp,
727
1019
  ...(r.skillUpdated === undefined ? {} : { skillUpdated: r.skillUpdated }),
1020
+ ...(r.skillSyncStarted === undefined ? {} : { skillSyncStarted: r.skillSyncStarted }),
728
1021
  };
729
1022
  },
730
1023
  },
@@ -810,6 +1103,36 @@ export function createPanelHandler(opts) {
810
1103
  return { family, ...(await rt.setQuotaCheck(family, body.on)) };
811
1104
  },
812
1105
  },
1106
+ // The Panel's theme and language (spec §3.29): config `panel.theme` and `panel.language`; null removes one.
1107
+ '/api/panel/settings': {
1108
+ async run(body) {
1109
+ const patch = {};
1110
+ for (const [k, v] of Object.entries(body)) {
1111
+ if (k === 'theme') {
1112
+ if (v !== null && !PANEL_THEMES.some((x) => x === v))
1113
+ throw new HttpError(400, '"theme" must be "system", "light", "dark" or null');
1114
+ patch.theme = v;
1115
+ }
1116
+ else if (k === 'language') {
1117
+ if (v !== null && !PANEL_LANGUAGES.some((x) => x === v))
1118
+ throw new HttpError(400, '"language" must be "auto", "en", "zh" or null');
1119
+ patch.language = v;
1120
+ }
1121
+ else
1122
+ throw new HttpError(400, `unknown setting "${k}"`);
1123
+ }
1124
+ if (!Object.keys(patch).length)
1125
+ throw new HttpError(400, 'send "theme" or "language"');
1126
+ const rt = await getRuntime();
1127
+ const r = await editConfigPanel(rt.paths.configFile, patch);
1128
+ return { changed: r.changed, panel: r.after ?? {} };
1129
+ },
1130
+ },
1131
+ // Start at login (spec §3.29, ADR-0029) and the Menu Bar Item (spec §3.31, ADR-0034). Without `confirm` the plan:
1132
+ // the file and what it starts, nothing is written. With it, a fresh plan runs only while it starts what the person
1133
+ // saw (`programArguments`).
1134
+ '/api/autostart': loginItemRoute(PANEL_AGENT),
1135
+ '/api/menubar': loginItemRoute(MENUBAR_AGENT),
813
1136
  // Undo for the quota setup above; the Runtime turns a teardown that throws into `{ ok: false, message }`.
814
1137
  '/api/quota/teardown': {
815
1138
  async run(body) {
@@ -821,6 +1144,29 @@ export function createPanelHandler(opts) {
821
1144
  },
822
1145
  },
823
1146
  };
1147
+ // An AI Task attachment (spec §3.28 "附件"): the body is the file itself, streamed into the staging folder rather than
1148
+ // read into memory, with its own size limit. The type comes from its first bytes; `Content-Type` is not trusted.
1149
+ const receiveAttachment = async (req) => {
1150
+ const declared = Number(req.headers['content-length']);
1151
+ if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES)
1152
+ throw new HttpError(413, 'This file is over 200 MB; attach a smaller one.');
1153
+ try {
1154
+ // Stopping early (a wrong type, too big) must not destroy the socket the answer goes out on.
1155
+ const { id, kind, bytes } = await stageUpload((await getRuntime()).paths, req.iterator({ destroyOnReturn: false }));
1156
+ return { id, kind, bytes };
1157
+ }
1158
+ catch (err) {
1159
+ const code = err.code;
1160
+ if (code === 'attachment-too-large')
1161
+ throw new HttpError(413, err.message);
1162
+ if (code === 'attachment-type')
1163
+ throw new HttpError(415, err.message);
1164
+ // The staging folder is full: the server's own limit, whatever the page allows.
1165
+ if (code === 'attachment-quota')
1166
+ throw new HttpError(507, err.message, code);
1167
+ throw err;
1168
+ }
1169
+ };
824
1170
  const handle = async (req, res) => {
825
1171
  let pathname;
826
1172
  try {
@@ -840,6 +1186,11 @@ export function createPanelHandler(opts) {
840
1186
  if (method === 'GET' || method === 'HEAD') {
841
1187
  if (sub === '/' || sub === '/index.html') {
842
1188
  const nonce = randomBytes(16).toString('base64');
1189
+ // The theme and language in config (spec §3.29), so the first paint has them; a config that cannot be
1190
+ // read leaves the defaults, and /api/state reports the problem.
1191
+ const panel = method === 'HEAD'
1192
+ ? undefined
1193
+ : await getRuntime().then((rt) => rt.config.panel, () => undefined);
843
1194
  res.writeHead(200, {
844
1195
  'content-type': 'text/html; charset=utf-8',
845
1196
  'cache-control': 'no-store',
@@ -858,7 +1209,20 @@ export function createPanelHandler(opts) {
858
1209
  });
859
1210
  res.end(method === 'HEAD'
860
1211
  ? undefined
861
- : renderPage({ basePath, token, nonce, version, build, local, readOnly, theme, lang, updates }));
1212
+ : renderPage({
1213
+ basePath,
1214
+ token,
1215
+ nonce,
1216
+ version,
1217
+ build,
1218
+ local,
1219
+ readOnly,
1220
+ theme,
1221
+ lang,
1222
+ updates,
1223
+ ...(ask ? { ask } : {}),
1224
+ ...(panel ? { panel } : {}),
1225
+ }));
862
1226
  return true;
863
1227
  }
864
1228
  // The mark, for a Portal's tab and for this page's favicon (ADR-0006 amendment).
@@ -883,18 +1247,29 @@ export function createPanelHandler(opts) {
883
1247
  send(res, 200, { token });
884
1248
  return true;
885
1249
  }
1250
+ if (sub === '/api/terminals') {
1251
+ send(res, 200, await terminalsView(await getRuntime()));
1252
+ return true;
1253
+ }
1254
+ // Start at login (spec §3.29): its state only; turning it on or off is the POST of the same path.
1255
+ if (sub === '/api/autostart' || sub === '/api/menubar') {
1256
+ const rt = await getRuntime();
1257
+ const agent = sub === '/api/menubar' ? MENUBAR_AGENT : PANEL_AGENT;
1258
+ send(res, 200, autostartView(await autostartStatus(autostartCtx(rt), agent), rt.paths.home));
1259
+ return true;
1260
+ }
886
1261
  if (sub === '/api/state') {
887
1262
  send(res, 200, await buildState(await getRuntime(), { version, build, readOnly, updates }));
888
1263
  return true;
889
1264
  }
890
- if (Object.hasOwn(routes, sub))
1265
+ if (Object.hasOwn(routes, sub) || sub === ATTACH_ROUTE)
891
1266
  throw new HttpError(405, 'use POST');
892
1267
  throw new HttpError(404, 'not found');
893
1268
  }
894
1269
  if (method !== 'POST')
895
1270
  throw new HttpError(405, 'method not allowed');
896
1271
  const route = Object.hasOwn(routes, sub) ? routes[sub] : undefined;
897
- if (!route)
1272
+ if (!route && sub !== ATTACH_ROUTE)
898
1273
  throw new HttpError(404, 'not found');
899
1274
  const origin = req.headers.origin;
900
1275
  if (!origin || origin.toLowerCase() !== `http://${host}`)
@@ -902,11 +1277,18 @@ export function createPanelHandler(opts) {
902
1277
  const given = req.headers['x-sideby-token'];
903
1278
  if (typeof given !== 'string' || !sameSecret(given, token))
904
1279
  throw new HttpError(403, 'missing or wrong x-sideby-token; reload the page', 'bad-token');
1280
+ if (!route) {
1281
+ // An upload writes a file: a read-only Panel refuses it before reading a byte.
1282
+ if (readOnly)
1283
+ throw new HttpError(403, 'this panel is read-only');
1284
+ send(res, 200, await receiveAttachment(req));
1285
+ return true;
1286
+ }
905
1287
  const body = (await readBody(req));
906
1288
  if (readOnly && (route.writes?.(body) ?? true))
907
1289
  throw new HttpError(403, 'this panel is read-only');
908
1290
  // Reads that record history (doctor) also run in this queue, so overlapping checks merge in order.
909
- send(res, 200, await serial(() => route.run(body)));
1291
+ send(res, 200, await (route.queued === false ? route.run(body) : serial(() => route.run(body))));
910
1292
  return true;
911
1293
  }
912
1294
  catch (err) {
@@ -916,8 +1298,10 @@ export function createPanelHandler(opts) {
916
1298
  }
917
1299
  if (err instanceof HttpError) {
918
1300
  const body = err.code ? { error: err.message, code: err.code } : { error: err.message };
919
- send(res, err.status, body, err.status === 413 ? { connection: 'close' } : {});
920
- if (err.status === 413)
1301
+ // A refused body (too big, or an upload stopped early) is left unread: close the connection after answering.
1302
+ const unread = err.status === 413 || (sub === ATTACH_ROUTE && !req.readableEnded);
1303
+ send(res, err.status, body, unread ? { connection: 'close' } : {});
1304
+ if (unread)
921
1305
  req.resume();
922
1306
  }
923
1307
  else if (err instanceof UserError) {