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,13 +2,15 @@
2
2
  // only network request sideby makes on its own: one GET for the `latest` dist-tag, carrying nothing about the user.
3
3
  // Everything it learns goes to one state file shared by the CLI and every Panel.
4
4
  import { spawn } from 'node:child_process';
5
- import { readFileSync } from 'node:fs';
6
- import { access, constants, mkdir, open, readdir, readFile, realpath, rm, stat } from 'node:fs/promises';
5
+ import { access, constants, mkdir, readdir, readFile, realpath, rm } from 'node:fs/promises';
7
6
  import { dirname, join, sep } from 'node:path';
8
7
  import { fileURLToPath } from 'node:url';
8
+ import { afterInstall, runSkillUpdate } from './after-install.js';
9
9
  import { writeFileAtomic } from './fs-safe.js';
10
+ import { processAlive, takeFileLock } from './lock.js';
10
11
  import { installedSkills, SKILL_UPDATE, SKILL_UPDATE_SHOWN, skillOwnerRepo } from './skill-check.js';
11
12
  import { localBuild, packageVersion, parseLocalBuild } from './version.js';
13
+ export { isZombieStat } from './lock.js';
12
14
  export const DEFAULT_REGISTRY = 'https://registry.npmjs.org';
13
15
  export const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
14
16
  export const NOTICE_INTERVAL_MS = 24 * 60 * 60 * 1000;
@@ -18,9 +20,20 @@ export const RETRY_INTERVAL_MS = 60 * 60 * 1000;
18
20
  export const AUTO_RETRY_MS = 24 * 60 * 60 * 1000;
19
21
  const FETCH_TIMEOUT_MS = 5000;
20
22
  export const RELEASE_NOTES = (v) => `https://github.com/Adonis0123/sideby/releases/tag/v${v}`;
21
- /** Whether a Linux `/proc/<pid>/stat` line is of a zombie: the state after the parenthesised command name is `Z`. */
22
- export function isZombieStat(stat) {
23
- return /\)\s+Z\s/.test(stat.slice(stat.lastIndexOf(')')));
23
+ /** Swapped in tests through `bindUpdateDeps`; the real machine otherwise. */
24
+ /**
25
+ * Whether `sideby autostart --refresh --json` rewrote the login item: it exits 0 also when nothing changed or the
26
+ * rewrite was refused, so only its `changed: true` counts.
27
+ */
28
+ export function autostartRefreshed(code, stdout) {
29
+ if (code !== 0)
30
+ return false;
31
+ try {
32
+ return JSON.parse(stdout)?.changed === true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
24
37
  }
25
38
  /** The folder of the sideby package this module belongs to: two levels above src/, three above dist/src/. */
26
39
  async function ownPackageDir() {
@@ -43,22 +56,7 @@ const realDeps = {
43
56
  now: () => new Date(),
44
57
  packageDir: ownPackageDir,
45
58
  writable: (dir) => access(dir, constants.W_OK).then(() => true, () => false),
46
- alive(pid) {
47
- try {
48
- process.kill(pid, 0);
49
- }
50
- catch (err) {
51
- return err.code === 'EPERM';
52
- }
53
- // An exited process nobody waited for (its parent went first) still answers signal 0 on Linux: a zombie holds
54
- // no lock and runs no session.
55
- try {
56
- return !isZombieStat(readFileSync(`/proc/${pid}/stat`, 'utf8'));
57
- }
58
- catch {
59
- return true; // no /proc (macOS): signal 0 is the answer
60
- }
61
- },
59
+ alive: processAlive,
62
60
  exec: (file, args, opts) => new Promise((resolve) => {
63
61
  let output = '';
64
62
  const child = spawn(file, args, {
@@ -111,6 +109,28 @@ const realDeps = {
111
109
  child.once('error', () => resolve(false));
112
110
  child.once('close', (code) => resolve(code === 0));
113
111
  }),
112
+ autostartInstalled: async (home, command = 'autostart') => {
113
+ const { autostartInstalled } = await import('./autostart.js');
114
+ if (command === 'autostart')
115
+ return autostartInstalled(home);
116
+ const { MENUBAR_AGENT } = await import('../menubar/agent.js');
117
+ return autostartInstalled(home, MENUBAR_AGENT);
118
+ },
119
+ refreshAutostart: (env, command = 'autostart') => new Promise((resolve) => {
120
+ // By name, like refreshApp: the new code records its own Node and entry; it never creates a login item.
121
+ const child = spawn('sideby', [command, '--refresh', '--json'], {
122
+ env: env,
123
+ stdio: ['ignore', 'pipe', 'ignore'],
124
+ timeout: 60_000,
125
+ });
126
+ let out = '';
127
+ child.stdout?.on('data', (d) => {
128
+ if (out.length < 65_536)
129
+ out += d.toString();
130
+ });
131
+ child.once('error', () => resolve(false));
132
+ child.once('close', (code) => resolve(autostartRefreshed(code, out)));
133
+ }),
114
134
  };
115
135
  let override = {};
116
136
  /** Internal, for tests: replaces parts of the machine. Not part of the plugin or Portal contract. */
@@ -124,14 +144,8 @@ export function bindUpdateDeps(deps) {
124
144
  const deps = () => ({ ...realDeps, ...override });
125
145
  /** Runs a program through the swappable machine (tests bind `exec`); a Local Build switch installs with it. */
126
146
  export const runProgram = (file, args, opts) => deps().exec(file, args, opts);
127
- /** Starts the background Panel again from the code `sideby` now names; see `UpdateDeps.restartPanel`. */
128
- export const restartPanelByName = (env, port) => deps()
129
- .restartPanel(env, port)
130
- .catch(() => false);
131
- /** Starts a program detached through the swappable machine; see `UpdateDeps.startDetached`. */
132
- export const startDetached = (file, args, env) => deps()
133
- .startDetached(file, args, env)
134
- .catch(() => false);
147
+ /** The machine in use: the real one, or the parts tests bound. Internal, for after-install.ts and local-build.ts. */
148
+ export const updateMachine = () => deps();
135
149
  /** The lock every install shares (`update-install.lock`), so a Local Build switch never races an Update. */
136
150
  export const takeInstallLock = (paths) => takeLock(paths, 'update-install.lock').catch(() => null);
137
151
  // Build metadata is limited to what semver allows, so a version never carries a terminal escape into the notice.
@@ -342,41 +356,28 @@ export async function refreshUpdateCheck(paths, env) {
342
356
  const LOCK_MAX_MS = 60 * 60 * 1000;
343
357
  /** A lock file another process has just created and not yet written to. */
344
358
  const LOCK_WRITE_GRACE_MS = 60 * 1000;
359
+ /** How often a holder touches its lock, and how long a lock nobody touched counts as held. */
360
+ const LOCK_BEAT_MS = 15 * 1000;
361
+ const LOCK_STALE_MS = 2 * 60 * 1000;
345
362
  /**
346
- * An exclusive lock file in the state directory holding `<pid> <ms since epoch>`. It is held while that pid runs and
347
- * the lock is under an hour old, however long an install takes on a slow mirror; an empty or unreadable lock is held
348
- * for a minute (its owner may still be writing it). Null when held: the second caller fails at once instead of
349
- * waiting. Release removes the file only while it still names this process.
363
+ * An exclusive lock file in the state directory holding `<pid> <ms since epoch>`. It is held while that pid runs, the
364
+ * lock is under an hour old and its holder still touches it (every 15 s), however long an install takes on a slow
365
+ * mirror. A lock not touched for two minutes is free even when its pid runs: a Portal's worker thread that was ended
366
+ * mid-install leaves it behind in a process that lives on. An empty or unreadable lock is held for a minute (its owner
367
+ * may still be writing it). Null when held: the second caller fails at once instead of waiting. Release removes the
368
+ * file only while it still names this process.
350
369
  */
351
370
  async function takeLock(paths, name) {
352
- const file = join(paths.stateDir, name);
353
371
  const d = deps();
354
- const me = `${process.pid} ${d.now().getTime()}`;
355
372
  await mkdir(paths.stateDir, { recursive: true, mode: 0o700 });
356
- for (let attempt = 0; attempt < 2; attempt++) {
357
- try {
358
- const fh = await open(file, 'wx', 0o600);
359
- await fh.writeFile(me);
360
- await fh.close();
361
- return async () => {
362
- if ((await readFile(file, 'utf8').catch(() => '')) === me)
363
- await rm(file, { force: true });
364
- };
365
- }
366
- catch (err) {
367
- if (err.code !== 'EEXIST')
368
- return null;
369
- const text = await readFile(file, 'utf8').catch(() => '');
370
- const m = /^(\d+) (\d+)$/.exec(text);
371
- const held = m
372
- ? d.alive(Number(m[1])) && d.now().getTime() - Number(m[2]) < LOCK_MAX_MS
373
- : d.now().getTime() - ((await stat(file).catch(() => null))?.mtimeMs ?? 0) < LOCK_WRITE_GRACE_MS;
374
- if (held)
375
- return null;
376
- await rm(file, { force: true });
377
- }
378
- }
379
- return null;
373
+ return takeFileLock(join(paths.stateDir, name), {
374
+ alive: d.alive,
375
+ now: () => d.now().getTime(),
376
+ maxMs: LOCK_MAX_MS,
377
+ staleMs: LOCK_STALE_MS,
378
+ beatMs: LOCK_BEAT_MS,
379
+ writeGraceMs: LOCK_WRITE_GRACE_MS,
380
+ }).catch(() => null);
380
381
  }
381
382
  // ---- the notice
382
383
  /**
@@ -709,17 +710,20 @@ export async function planUpdate(paths, env) {
709
710
  const skill = await skillUpdatePlan(paths.home, plan.available ? latest : plan.current).catch(() => null);
710
711
  return skill ? { ...plan, skill } : plan;
711
712
  }
713
+ /**
714
+ * The plan of `sideby update --skill`: the installed skill toward this version, never the CLI. Asks no registry: what
715
+ * it says of a newer CLI comes from the last Update Check.
716
+ */
717
+ export async function planSkillUpdate(paths, env) {
718
+ const current = packageVersion();
719
+ const cache = await readUpdateCache(paths).catch(() => ({}));
720
+ const plan = planFrom(await installMethod(env), current, cache.latest ?? current, env);
721
+ const skill = await skillUpdatePlan(paths.home, current).catch(() => null);
722
+ return skill ? { ...plan, skill } : plan;
723
+ }
712
724
  /** Updates the installed sideby skill when the plan says it is outdated and sideby may; null when it did nothing. */
713
725
  export async function applySkillUpdate(plan, env, onOutput) {
714
- if (!plan?.outdated || !plan.canRun)
715
- return null;
716
- const [file, ...args] = SKILL_UPDATE;
717
- const r = await deps()
718
- .exec(file, args, { env, ...(onOutput ? { onOutput } : {}) })
719
- .catch((e) => ({ code: 1, output: e instanceof Error ? e.message : String(e) }));
720
- return r.code === 0
721
- ? { ok: true, message: 'updated the sideby skill' }
722
- : { ok: false, message: `\`${plan.command}\` failed (exit ${r.code}); run it yourself to see why` };
726
+ return runSkillUpdate(deps(), plan, env, onOutput);
723
727
  }
724
728
  /**
725
729
  * Updates only the sideby skill, for a CLI that is already current (`sideby update`, the Panel, Auto Update). Holds
@@ -743,11 +747,12 @@ export async function applySkillOnly(paths, plan, env, onOutput) {
743
747
  }
744
748
  }
745
749
  /**
746
- * Runs the Update the plan names, then starts a running background Panel again from the new code and, when the
747
- * desktop app is installed, runs `sideby app install` again from the new code. The caller has
748
- * shown the plan and got a confirmation (or this is an Auto Update). One Update runs at a time on this machine (the
749
- * CLI, a Panel and an Auto Update share the lock). `panelPort` gives the port of the background Panel to restart, or
750
- * null when none runs. A successful Update is recorded as said, so no notice for it follows.
750
+ * Runs the Update the plan names, then what follows an install (after-install.ts): the desktop app and the login item
751
+ * are written again from the new code where installed, the skill follows, and a running background Panel starts again
752
+ * from the new code, last. The caller has shown the plan and got a confirmation (or this is an Auto Update). One
753
+ * Update runs at a time on this machine (the CLI, a Panel and an Auto Update share the lock). `panelPort` gives the
754
+ * port of the background Panel to restart, or null when none runs. A successful Update is recorded as said, so no
755
+ * notice for it follows.
751
756
  */
752
757
  export async function applyUpdate(paths, plan, env, opts = {}) {
753
758
  const cmd = updateCommand(plan.method, plan.latest, env);
@@ -766,6 +771,13 @@ export async function applyUpdate(paths, plan, env, opts = {}) {
766
771
  return fail('another sideby update is running; wait for it to finish, then run `sideby update` again', {
767
772
  busy: true,
768
773
  });
774
+ let released = false;
775
+ const free = async () => {
776
+ if (released)
777
+ return;
778
+ released = true;
779
+ await release().catch(() => { });
780
+ };
769
781
  try {
770
782
  const d = deps();
771
783
  const r = await d.exec(cmd.run.file, cmd.run.args, {
@@ -777,26 +789,26 @@ export async function applyUpdate(paths, plan, env, opts = {}) {
777
789
  await updateUpdateCache(paths, {
778
790
  notified: { version: plan.latest, at: d.now().toISOString() },
779
791
  }).catch(() => { });
780
- const port = opts.panelPort ? await opts.panelPort().catch(() => null) : null;
781
- const restarted = port !== null && (await d.restartPanel(env, port).catch(() => false));
782
- // The desktop app records the Node and entry it starts and carries the icon of the version that wrote it, so
783
- // the new code writes it again. Only where one is installed; a failure here never fails the Update.
784
- const installed = await d.appInstalled(paths.home, env).catch(() => false);
785
- const refreshed = installed && (await d.refreshApp(env).catch(() => false));
786
792
  // The skill teaches agents this version's commands, so it follows the CLI; a failure there keeps the Update.
787
- const skill = await applySkillUpdate(plan.skill, env, opts.onOutput);
793
+ const after = await afterInstall(d, env, {
794
+ home: paths.home,
795
+ release: free,
796
+ app: true,
797
+ skill: { plan: plan.skill },
798
+ ...(opts.skillSync ? { skillSync: opts.skillSync } : {}),
799
+ ...(opts.panelPort ? { panelPort: opts.panelPort } : {}),
800
+ ...(opts.onOutput ? { onOutput: opts.onOutput } : {}),
801
+ });
788
802
  return {
789
803
  ok: true,
790
804
  code: 0,
791
805
  output: r.output,
792
806
  message: `updated sideby from ${plan.current} to ${plan.latest}`,
793
- restartedPanel: restarted,
794
- refreshedApp: refreshed,
795
- ...(skill ? { skillUpdated: skill.ok, skillMessage: skill.message } : {}),
807
+ ...after,
796
808
  };
797
809
  }
798
810
  finally {
799
- await release().catch(() => { });
811
+ await free();
800
812
  }
801
813
  }
802
814
  /** What keeps an Auto Update from installing `plan` until the user acts (an install it cannot update, a major version). */
@@ -4,7 +4,7 @@
4
4
  // polylines (distance to a segment), ellipses use an analytic distance. Each shape is computed only inside its own
5
5
  // bounding box and composited back to front, fill before outline, as an SVG renderer would.
6
6
  import { deflateSync } from 'node:zlib';
7
- import { BUDDY, highlights, MARK, MARK_COLORS, MARK_VIEWBOX, markSvgBody, } from '../core/brand-mark.js';
7
+ import { buddyShapes, MARK, MARK_COLORS, MARK_VIEWBOX, markSvgBody, } from '../core/brand-mark.js';
8
8
  /** Text stored in every generated file, so `sideby app uninstall` deletes only what it wrote. */
9
9
  export const APP_MARKER = 'sideby-app-install';
10
10
  // The Panel's logo tile (page-styles.ts: .logo 40×40, radius 10); MARK_VIEWBOX maps onto the whole tile square.
@@ -246,23 +246,19 @@ function roundedRectMask(size, s) {
246
246
  }
247
247
  return m;
248
248
  }
249
- /** The shapes of one placed buddy, back to front, each with its colour. */
249
+ /** The shapes of one placed buddy, back to front, each with its colour (core/brand-mark.ts buddyShapes). */
250
250
  function buddyLayers(size, b) {
251
251
  const { k, map } = placement(size, b);
252
- const ink = rgb(MARK_COLORS.ink);
253
- const fills = {
254
- body: b.colors.body,
255
- shade: b.colors.shade,
256
- };
252
+ const { paths, dots, above } = buddyShapes(b);
257
253
  const layers = [];
258
- for (const p of BUDDY.paths) {
259
- const polys = flatten(p.d, map);
260
- if (p.fill !== 'none')
261
- layers.push({ mask: fillMask(size, polys), color: rgb(fills[p.fill]) });
262
- const stroke = p.stroke === 'chevron' ? rgb(b.colors.chevron) : ink;
263
- layers.push({ mask: strokeMask(size, polys, (p.width ?? MARK.placedLine) * k), color: stroke });
264
- }
265
- const dots = [...BUDDY.eyes, ...highlights(b.look)];
254
+ const shape = (s) => {
255
+ const polys = flatten(s.d, map);
256
+ if (s.fill && s.fill !== 'none')
257
+ layers.push({ mask: fillMask(size, polys), color: rgb(s.fill) });
258
+ if (s.stroke !== 'none')
259
+ layers.push({ mask: strokeMask(size, polys, (s.width ?? MARK.placedLine) * k), color: rgb(s.stroke) });
260
+ };
261
+ paths.forEach(shape);
266
262
  for (const e of dots) {
267
263
  const [cx, cy] = map(e.cx, e.cy);
268
264
  layers.push({
@@ -270,6 +266,7 @@ function buddyLayers(size, b) {
270
266
  color: rgb(e.fill === 'ink' ? MARK_COLORS.ink : MARK_COLORS.light),
271
267
  });
272
268
  }
269
+ above.forEach(shape);
273
270
  return layers;
274
271
  }
275
272
  /** RGBA pixels (straight alpha) of the icon at `size`×`size`. */
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `args` without any argument that skips Claude Code's permission checks: the two bypass flags and a
3
+ * `--permission-mode bypassPermissions` (either form). Unless the arguments still pick another permission mode,
4
+ * `--permission-mode auto` comes first: no routine prompts, while auto mode's classifier blocks risky actions. It also
5
+ * outranks a settings file's `permissions.defaultMode`, and a session where auto mode is unavailable starts in Manual.
6
+ * Text after `--` is the Host's own and stays as it is.
7
+ */
8
+ export declare function claudeAiTaskArgs(args: readonly string[]): string[];
@@ -0,0 +1,38 @@
1
+ // How an AI Task starts Claude Code (spec §3.28 "权限检查", ADR-0031), checked against the permission modes page of
2
+ // the Claude Code docs on 2026-10-18 (Claude Code 2.1.301).
3
+ const BYPASS_FLAGS = ['--dangerously-skip-permissions', '--allow-dangerously-skip-permissions'];
4
+ const MODE = '--permission-mode';
5
+ const isBypass = (mode) => mode.toLowerCase() === 'bypasspermissions';
6
+ /**
7
+ * `args` without any argument that skips Claude Code's permission checks: the two bypass flags and a
8
+ * `--permission-mode bypassPermissions` (either form). Unless the arguments still pick another permission mode,
9
+ * `--permission-mode auto` comes first: no routine prompts, while auto mode's classifier blocks risky actions. It also
10
+ * outranks a settings file's `permissions.defaultMode`, and a session where auto mode is unavailable starts in Manual.
11
+ * Text after `--` is the Host's own and stays as it is.
12
+ */
13
+ export function claudeAiTaskArgs(args) {
14
+ const end = args.indexOf('--');
15
+ const options = end === -1 ? args : args.slice(0, end);
16
+ const out = [];
17
+ let picked = false;
18
+ for (let i = 0; i < options.length; i++) {
19
+ const arg = options[i];
20
+ if (BYPASS_FLAGS.includes(arg))
21
+ continue;
22
+ if (arg.startsWith(`${MODE}=`)) {
23
+ if (isBypass(arg.slice(MODE.length + 1)))
24
+ continue;
25
+ picked = true;
26
+ }
27
+ else if (arg === MODE && i + 1 < options.length) {
28
+ const mode = options[++i];
29
+ if (isBypass(mode))
30
+ continue;
31
+ picked = true;
32
+ out.push(arg, mode);
33
+ continue;
34
+ }
35
+ out.push(arg);
36
+ }
37
+ return [...(picked ? [] : [MODE, 'auto']), ...out, ...(end === -1 ? [] : args.slice(end))];
38
+ }
@@ -1,12 +1,12 @@
1
- // Claude Code for the handoff hook (spec §3.17): Quota Pressure from the status line tap's cache, and a used-up
1
+ // Claude Code for the handoff hook (spec §3.17): the Quota windows from the status line tap's cache, and a used-up
2
2
  // Quota told apart from a transient rate limit. Leaf module: the hook runs on every tool call.
3
- import { quotaPressure } from '../../core/quota-levels.js';
3
+ import { openWindows } from '../../core/quota-levels.js';
4
4
  import { field } from '../../handoff/reader.js';
5
5
  import { accountNameFromEnv, cacheStateDir, readQuotaCache } from './quota-cache.js';
6
6
  /** Claude Code's wording when a subscription window is used up (as opposed to an overloaded server). */
7
7
  const USED_UP = /usage limit|limit reached|out of (extra )?usage/i;
8
8
  export const claudeHookReader = {
9
- async pressure(_input, env, now) {
9
+ async windows(_input, env, now) {
10
10
  const name = accountNameFromEnv(env);
11
11
  if (!name)
12
12
  return null;
@@ -14,7 +14,7 @@ export const claudeHookReader = {
14
14
  const cache = await readQuotaCache(cacheStateDir(env), name);
15
15
  if (cache.status !== 'ok')
16
16
  return null;
17
- return quotaPressure({ ...cache, source: 'statusline' }, now);
17
+ return openWindows({ ...cache, source: 'statusline' }, now);
18
18
  }
19
19
  catch {
20
20
  return null;
@@ -6,6 +6,7 @@ import { readSecretFile } from '../../core/secret-file.js';
6
6
  import { claudeStatusline } from '../../quota/claude-statusline.js';
7
7
  import { BUILTIN_LOGOS } from '../logos.js';
8
8
  import { dirWrittenAt, groupedEntryWrittenAt, resumeFlagSession, withoutResumeFlag, } from '../shared/sessions.js';
9
+ import { claudeAiTaskArgs } from './ai-task.js';
9
10
  import { claudeHandoff } from './handoff.js';
10
11
  import { CLAUDE_LAYOUT } from './layout.js';
11
12
  import { claudeModelChoice } from './model.js';
@@ -105,6 +106,11 @@ export const claudeFamily = {
105
106
  'ANTHROPIC_DEFAULT_OPUS_MODEL',
106
107
  ],
107
108
  apiVars: ['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL'],
109
+ secretVar: 'ANTHROPIC_AUTH_TOKEN',
110
+ // `-p` is one non-interactive prompt (Claude Code 2.1.301 --help, 2026-10-17).
111
+ probe: { args: ['-p', 'Reply with OK'] },
112
+ aiTaskArgs: claudeAiTaskArgs,
113
+ settingsFile: 'settings.json',
108
114
  sharedItems: [
109
115
  ...LINKED.map((path) => ({ path, mode: 'link' })),
110
116
  { path: '.claude.json', mode: 'json-key', key: 'mcpServers', mainPath: '.claude.json', credential: true },
@@ -4,27 +4,44 @@ export interface ClaudeQuotaCache {
4
4
  /** When the status line last reported these windows. */
5
5
  observedAt: string;
6
6
  windows: QuotaWindow[];
7
+ /**
8
+ * Per status line session id: a hash of the windows it last reported and when that changed. Only these two values
9
+ * are kept for a session (at most {@link MAX_SESSIONS}, none older than {@link SESSION_DAYS} days). Files written
10
+ * before sessions were tracked have none.
11
+ */
12
+ sessions?: Record<string, SessionSeen>;
13
+ }
14
+ export interface SessionSeen {
15
+ hash: string;
16
+ seenAt: string;
17
+ }
18
+ /** A status line reading: the cache fields and, when Claude Code sent one, the session that reported it. */
19
+ export interface QuotaReading extends ClaudeQuotaCache {
20
+ sessionId?: string;
7
21
  }
8
22
  export declare function claudeQuotaCacheFile(stateDir: string, name: string): string;
9
23
  /** sideby's state directory for this environment (same rule as the Runtime). */
10
24
  export declare function cacheStateDir(env: Env): string;
11
25
  /** Account name from CLAUDE_CONFIG_DIR: unset or `~/.claude` is `main`, `.claude-<name>` is `<name>`, else null. */
12
26
  export declare function accountNameFromEnv(env: Env): string | null;
13
- /** Extracts the 5h and 7d windows from status line JSON; null when there is nothing usable. */
14
- export declare function parseRateLimits(input: string, observedAt: Date): ClaudeQuotaCache | null;
27
+ /** Extracts the 5h and 7d windows and the session id from status line JSON; null when there is nothing usable. */
28
+ export declare function parseRateLimits(input: string, observedAt: Date): QuotaReading | null;
15
29
  /**
16
- * Merges a status line reading into the cached windows. Each session reports the Quota of its own last request, so an
17
- * idle session of the same Account reports older numbers, sometimes of a window that has already reset: within one
18
- * window the higher use wins, otherwise the later reset; a window the reading lacks is kept. Null when the reading
19
- * only repeats older numbers, so nothing is written and `observedAt` keeps the time of the newer reading.
30
+ * Merges a status line reading into the cache (spec §3.7). Each session reports the Quota of its own last request, so
31
+ * an idle session of the same Account keeps repeating older numbers. A reading whose session reported exactly these
32
+ * windows before carries nothing new: null, so nothing is written. A reading that changed, or the first of a session,
33
+ * is a fresh request result and wins for every window it has, the vendor's resets included; a window it lacks is
34
+ * kept. A reading without a session id falls back to: within one window the higher use wins, otherwise the reading
35
+ * wins; null when that only repeats the cache.
20
36
  */
21
- export declare function mergeQuotaCache(cached: readonly QuotaWindow[], next: ClaudeQuotaCache): ClaudeQuotaCache | null;
37
+ export declare function mergeQuotaCache(cached: Pick<ClaudeQuotaCache, 'windows' | 'sessions'> | null, next: QuotaReading): ClaudeQuotaCache | null;
22
38
  /** Writes the cache atomically; creates the private parent directory first (writeFileAtomic does not). */
23
39
  export declare function writeQuotaCache(stateDir: string, name: string, cache: ClaudeQuotaCache): Promise<void>;
24
40
  export type CacheRead = {
25
41
  status: 'ok';
26
42
  observedAt: string;
27
43
  windows: QuotaWindow[];
44
+ sessions?: Record<string, SessionSeen>;
28
45
  } | {
29
46
  status: 'missing';
30
47
  } | {
@@ -1,6 +1,7 @@
1
1
  // The Claude Quota cache: one module owns where it lives, how the Account is named, and how it is written,
2
2
  // read and validated. The status line tap writes it on every refresh, so this module imports only leaf
3
3
  // modules and Node built-ins (never the Family index, the Runtime or core/accounts.ts).
4
+ import { createHash } from 'node:crypto';
4
5
  import { mkdir, readFile } from 'node:fs/promises';
5
6
  import { homedir } from 'node:os';
6
7
  import { basename, dirname, join, resolve } from 'node:path';
@@ -8,6 +9,9 @@ import { ACCOUNT_NAME } from '../../core/account-name.js';
8
9
  import { writeFileAtomic } from '../../core/fs-safe.js';
9
10
  import { resolvePaths } from '../../core/paths.js';
10
11
  import { CLAUDE_ACCOUNT_PREFIX, CLAUDE_MAIN_DIR } from './layout.js';
12
+ const MAX_SESSIONS = 32;
13
+ const SESSION_DAYS = 8;
14
+ const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/;
11
15
  const WINDOWS = [
12
16
  { key: 'five_hour', label: '5h', minutes: 300 },
13
17
  { key: 'seven_day', label: '7d', minutes: 10_080 },
@@ -32,7 +36,7 @@ export function accountNameFromEnv(env) {
32
36
  const name = base.slice(CLAUDE_ACCOUNT_PREFIX.length);
33
37
  return name !== 'main' && ACCOUNT_NAME.test(name) ? name : null;
34
38
  }
35
- /** Extracts the 5h and 7d windows from status line JSON; null when there is nothing usable. */
39
+ /** Extracts the 5h and 7d windows and the session id from status line JSON; null when there is nothing usable. */
36
40
  export function parseRateLimits(input, observedAt) {
37
41
  let data;
38
42
  try {
@@ -62,7 +66,15 @@ export function parseRateLimits(input, observedAt) {
62
66
  resetsAt: new Date(resets * 1000).toISOString(),
63
67
  });
64
68
  }
65
- return windows.length ? { version: 1, observedAt: observedAt.toISOString(), windows } : null;
69
+ if (!windows.length)
70
+ return null;
71
+ const id = data.session_id;
72
+ return {
73
+ version: 1,
74
+ observedAt: observedAt.toISOString(),
75
+ windows,
76
+ ...(typeof id === 'string' && SESSION_ID.test(id) ? { sessionId: id } : {}),
77
+ };
66
78
  }
67
79
  /** Two readings belong to one window when their resets are less than a quarter of the window apart. */
68
80
  function sameWindow(a, b) {
@@ -76,33 +88,56 @@ const order = (label) => {
76
88
  const i = WINDOWS.findIndex((w) => w.label === label);
77
89
  return i < 0 ? WINDOWS.length : i;
78
90
  };
91
+ /** What a session reported, as a short hash: equal hashes mean the session has made no request since. */
92
+ function windowsHash(windows) {
93
+ const key = windows.map((w) => [w.label, w.usedPercent, w.resetsAt]);
94
+ return createHash('sha256').update(JSON.stringify(key)).digest('hex').slice(0, 16);
95
+ }
96
+ /** The newest {@link MAX_SESSIONS} sessions seen in the last {@link SESSION_DAYS} days before `now`. */
97
+ function pruneSessions(sessions, now) {
98
+ const oldest = Date.parse(now) - SESSION_DAYS * 86_400_000;
99
+ const kept = Object.entries(sessions)
100
+ .filter(([, s]) => Date.parse(s.seenAt) >= oldest)
101
+ .sort((a, b) => Date.parse(b[1].seenAt) - Date.parse(a[1].seenAt))
102
+ .slice(0, MAX_SESSIONS);
103
+ return Object.fromEntries(kept);
104
+ }
79
105
  /**
80
- * Merges a status line reading into the cached windows. Each session reports the Quota of its own last request, so an
81
- * idle session of the same Account reports older numbers, sometimes of a window that has already reset: within one
82
- * window the higher use wins, otherwise the later reset; a window the reading lacks is kept. Null when the reading
83
- * only repeats older numbers, so nothing is written and `observedAt` keeps the time of the newer reading.
106
+ * Merges a status line reading into the cache (spec §3.7). Each session reports the Quota of its own last request, so
107
+ * an idle session of the same Account keeps repeating older numbers. A reading whose session reported exactly these
108
+ * windows before carries nothing new: null, so nothing is written. A reading that changed, or the first of a session,
109
+ * is a fresh request result and wins for every window it has, the vendor's resets included; a window it lacks is
110
+ * kept. A reading without a session id falls back to: within one window the higher use wins, otherwise the reading
111
+ * wins; null when that only repeats the cache.
84
112
  */
85
113
  export function mergeQuotaCache(cached, next) {
114
+ const { sessionId, ...reading } = next;
115
+ const before = cached?.windows ?? [];
116
+ const keepLacking = (windows) => {
117
+ for (const c of before)
118
+ if (!windows.some((w) => w.label === c.label))
119
+ windows.push(c);
120
+ return windows.sort((a, b) => order(a.label) - order(b.label));
121
+ };
122
+ if (sessionId) {
123
+ const hash = windowsHash(reading.windows);
124
+ if (cached?.sessions?.[sessionId]?.hash === hash)
125
+ return null;
126
+ const sessions = pruneSessions({ ...cached?.sessions, [sessionId]: { hash, seenAt: reading.observedAt } }, reading.observedAt);
127
+ return { ...reading, windows: keepLacking([...reading.windows]), sessions };
128
+ }
86
129
  let older = false;
87
- const windows = next.windows.map((w) => {
88
- const c = cached.find((x) => x.label === w.label);
89
- if (!c)
90
- return w;
91
- const keep = sameWindow(c, w)
92
- ? c.usedPercent > w.usedPercent
93
- : Date.parse(c.resetsAt) > Date.parse(w.resetsAt);
130
+ const windows = keepLacking(reading.windows.map((w) => {
131
+ const c = before.find((x) => x.label === w.label);
132
+ const keep = !!c && sameWindow(c, w) && c.usedPercent > w.usedPercent;
94
133
  if (keep)
95
134
  older = true;
96
135
  return keep ? c : w;
97
- });
98
- for (const c of cached)
99
- if (!windows.some((w) => w.label === c.label))
100
- windows.push(c);
101
- windows.sort((a, b) => order(a.label) - order(b.label));
102
- const unchanged = windows.length === cached.length && windows.every((w) => cached.some((c) => sameReading(c, w)));
136
+ }));
137
+ const unchanged = windows.length === before.length && windows.every((w) => before.some((c) => sameReading(c, w)));
103
138
  if (older && unchanged)
104
139
  return null;
105
- return { ...next, windows };
140
+ return { ...reading, windows, ...(cached?.sessions ? { sessions: cached.sessions } : {}) };
106
141
  }
107
142
  /** Writes the cache atomically; creates the private parent directory first (writeFileAtomic does not). */
108
143
  export async function writeQuotaCache(stateDir, name, cache) {
@@ -147,5 +182,21 @@ export async function readQuotaCache(stateDir, name) {
147
182
  !Number.isFinite(Date.parse(cache.observedAt)) ||
148
183
  !windows.length)
149
184
  return { status: 'unrecognized', detail: `${file} has no usable quota windows` };
150
- return { status: 'ok', observedAt: cache.observedAt, windows };
185
+ const sessions = validSessions(cache.sessions);
186
+ return { status: 'ok', observedAt: cache.observedAt, windows, ...(sessions ? { sessions } : {}) };
187
+ }
188
+ /** The well-formed session entries of a cache file; undefined when it has none (older files). */
189
+ function validSessions(raw) {
190
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
191
+ return undefined;
192
+ const out = {};
193
+ for (const [id, v] of Object.entries(raw)) {
194
+ const s = v;
195
+ if (SESSION_ID.test(id) &&
196
+ typeof s?.hash === 'string' &&
197
+ typeof s.seenAt === 'string' &&
198
+ Number.isFinite(Date.parse(s.seenAt)))
199
+ out[id] = { hash: s.hash, seenAt: s.seenAt };
200
+ }
201
+ return Object.keys(out).length ? out : undefined;
151
202
  }
@@ -1,16 +1,16 @@
1
- // Codex for the handoff hook (spec §3.17): Quota Pressure from the current session's rollout. Codex has no hook
1
+ // Codex for the handoff hook (spec §3.17): the Quota windows from the current session's rollout. Codex has no hook
2
2
  // for a failed turn, so it starts a Handoff only before its limit. Leaf module: the hook runs on every tool call.
3
- import { quotaPressure } from '../../core/quota-levels.js';
3
+ import { openWindows } from '../../core/quota-levels.js';
4
4
  import { field } from '../../handoff/reader.js';
5
5
  import { lastRateLimits } from './rate-limits.js';
6
6
  export const codexHookReader = {
7
- async pressure(input, _env, now) {
7
+ async windows(input, _env, now) {
8
8
  const file = field(input, 'transcript_path');
9
9
  if (!file)
10
10
  return null;
11
11
  const windows = await lastRateLimits(file);
12
12
  return windows
13
- ? quotaPressure({ status: 'ok', windows, observedAt: now.toISOString(), source: file }, now)
13
+ ? openWindows({ status: 'ok', windows, observedAt: now.toISOString(), source: file }, now)
14
14
  : null;
15
15
  },
16
16
  };