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
@@ -9,6 +9,7 @@ import { codexModelChoice } from './model.js';
9
9
  import { readCodexQuota, readCodexUsage } from './rollout.js';
10
10
  import { readCodexTuning } from './tuning.js';
11
11
  const FILE_STORE_KEY = 'cli_auth_credentials_store';
12
+ const CODEX_BYPASS = ['--dangerously-bypass-approvals-and-sandbox', '--yolo'];
12
13
  async function readModel(account) {
13
14
  try {
14
15
  return topLevelTomlString(await readFile(join(account.dir, 'config.toml'), 'utf8'), 'model');
@@ -31,6 +32,21 @@ export const codexFamily = {
31
32
  layout: { main: '.codex', account: '.codex-<name>' },
32
33
  hijackVars: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'CODEX_API_BASE_URL'],
33
34
  apiVars: ['OPENAI_BASE_URL', 'OPENAI_API_KEY'],
35
+ secretVar: 'OPENAI_API_KEY',
36
+ // `exec` refuses to run outside a git repo unless this flag is set (Codex 0.163.0 --help:
37
+ // allow running outside a Git repository). The probe's cwd is a temp directory.
38
+ probe: { args: ['exec', '--skip-git-repo-check', 'Reply with OK'] },
39
+ // `-i, --image <FILE>...` takes several values (Codex 0.163.0 --help); AI Tasks pass `--image=<path>`, one value
40
+ // per flag, so the prompt after it stays a positional argument.
41
+ imageArg: '--image',
42
+ // An AI Task keeps Codex's approvals and sandbox (ADR-0031): the one flag that turns both off, and its `--yolo`
43
+ // alias, are dropped before `--`. Codex has no mode that blocks only risky actions, so nothing is added.
44
+ aiTaskArgs(args) {
45
+ const end = args.indexOf('--');
46
+ const options = end === -1 ? args : args.slice(0, end);
47
+ return [...options.filter((a) => !CODEX_BYPASS.includes(a)), ...(end === -1 ? [] : args.slice(end))];
48
+ },
49
+ settingsFile: 'config.toml',
34
50
  sharedItems: [
35
51
  { path: 'AGENTS.md', mode: 'link' },
36
52
  { path: 'hooks.json', mode: 'link' },
@@ -0,0 +1,8 @@
1
+ import type { Account } from '../../types.ts';
2
+ /**
3
+ * A hash of `chatgpt_account_id` (the workspace) and `chatgpt_user_id` under the auth claim of `tokens.id_token`,
4
+ * cut to 16 hex characters, only for comparing two Accounts while the Runtime groups a Same Login. The payload is
5
+ * decoded as for the email (core/identity.ts); the token, both ids and every other claim are dropped at once.
6
+ * Undefined on any problem: the Account then simply does not group.
7
+ */
8
+ export declare function codexLoginKey(account: Account): Promise<string | undefined>;
@@ -0,0 +1,33 @@
1
+ // Codex's Login Key (ADR-0028): which ChatGPT workspace and user an Account is signed in as, kept only as a hash.
2
+ import { createHash } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ const AUTH_CLAIM = 'https://api.openai.com/auth';
6
+ // The shapes Codex writes; anything else gives no key rather than a key built from an unexpected value.
7
+ const ACCOUNT_ID = /^[A-Za-z0-9-]{8,64}$/;
8
+ const USER_ID = /^user-[A-Za-z0-9]{8,64}$/;
9
+ /**
10
+ * A hash of `chatgpt_account_id` (the workspace) and `chatgpt_user_id` under the auth claim of `tokens.id_token`,
11
+ * cut to 16 hex characters, only for comparing two Accounts while the Runtime groups a Same Login. The payload is
12
+ * decoded as for the email (core/identity.ts); the token, both ids and every other claim are dropped at once.
13
+ * Undefined on any problem: the Account then simply does not group.
14
+ */
15
+ export async function codexLoginKey(account) {
16
+ try {
17
+ const token = JSON.parse(await readFile(join(account.dir, 'auth.json'), 'utf8'))?.tokens?.id_token;
18
+ if (typeof token !== 'string')
19
+ return undefined;
20
+ const parts = token.split('.');
21
+ if (parts.length !== 3 || !parts[1])
22
+ return undefined;
23
+ const auth = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'))?.[AUTH_CLAIM];
24
+ const ws = auth?.chatgpt_account_id;
25
+ const user = auth?.chatgpt_user_id;
26
+ if (typeof ws !== 'string' || !ACCOUNT_ID.test(ws) || typeof user !== 'string' || !USER_ID.test(user))
27
+ return undefined;
28
+ return createHash('sha256').update(`codex\0${ws}\0${user}`).digest('hex').slice(0, 16);
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
@@ -1,11 +1,11 @@
1
- // Grok Build for the handoff hook (spec §3.17, §3.26): Quota Pressure from the kept answer of its CLI and the billing
1
+ // Grok Build for the handoff hook (spec §3.17, §3.26): the Quota windows from the kept answer of its CLI and the billing
2
2
  // lines it writes to its log, and a turn that failed at the limit. Leaf module: the hook runs on every tool call. The
3
3
  // wording comes from the grok 1.0.50 binary; check it again when Grok changes.
4
4
  import { homedir } from 'node:os';
5
5
  import { basename, join, resolve } from 'node:path';
6
6
  import { ACCOUNT_NAME } from '../../core/account-name.js';
7
7
  import { resolvePaths } from '../../core/paths.js';
8
- import { quotaPressure } from '../../core/quota-levels.js';
8
+ import { openWindows } from '../../core/quota-levels.js';
9
9
  import { quotaStoreFile, readQuotaStore } from '../../core/quota-store.js';
10
10
  import { field } from '../../handoff/reader.js';
11
11
  import { grokLogFile, HOOK_LOG_READ_BYTES, lastGrokBilling } from './quota-log.js';
@@ -37,7 +37,7 @@ export const GROK_USED_UP = [
37
37
  'status 402',
38
38
  ];
39
39
  export const grokHookReader = {
40
- async pressure(_input, env, now) {
40
+ async windows(_input, env, now) {
41
41
  const account = grokAccountFromEnv(env);
42
42
  if (!account)
43
43
  return null;
@@ -52,7 +52,7 @@ export const grokHookReader = {
52
52
  ? log
53
53
  : fetched
54
54
  : (log ?? fetched);
55
- return newer ? quotaPressure(newer, now) : null;
55
+ return newer ? openWindows(newer, now) : null;
56
56
  }
57
57
  catch {
58
58
  return null;
@@ -49,6 +49,10 @@ export const grokFamily = {
49
49
  layout: { main: '.grok', account: '.grok-<name>' },
50
50
  hijackVars: ['XAI_API_KEY', 'GROK_MODELS_BASE_URL'],
51
51
  apiVars: ['GROK_MODELS_BASE_URL', 'XAI_API_KEY'],
52
+ secretVar: 'XAI_API_KEY',
53
+ // `-p` is one non-interactive prompt (Grok Build 1.0.60 --help, 2026-10-17).
54
+ probe: { args: ['-p', 'Reply with OK'] },
55
+ settingsFile: 'config.toml',
52
56
  sharedItems: [
53
57
  { path: 'skills', mode: 'link' },
54
58
  { path: 'installed-plugins', mode: 'link' },
@@ -0,0 +1,6 @@
1
+ import type { Account } from '../types.ts';
2
+ /**
3
+ * Family id → its Login Key reader. Must list exactly the Families of `LOGIN_KEY_FAMILIES` (core/same-login.ts);
4
+ * a test keeps the two in step.
5
+ */
6
+ export declare const LOGIN_KEY_READERS: ReadonlyMap<string, (account: Account) => Promise<string | undefined>>;
@@ -0,0 +1,6 @@
1
+ import { codexLoginKey } from './codex/login-key.js';
2
+ /**
3
+ * Family id → its Login Key reader. Must list exactly the Families of `LOGIN_KEY_FAMILIES` (core/same-login.ts);
4
+ * a test keeps the two in step.
5
+ */
6
+ export const LOGIN_KEY_READERS = new Map([['codex', codexLoginKey]]);
@@ -41,6 +41,11 @@ export const piFamily = {
41
41
  'OPENAI_BASE_URL',
42
42
  ],
43
43
  apiVars: ['ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL'],
44
+ // First key in the proxy.env template `new --api` writes. The OpenAI key is still set with `--var`.
45
+ secretVar: 'ANTHROPIC_API_KEY',
46
+ // `-p` is one non-interactive prompt (pi 1.3.0 --help, 2026-10-17).
47
+ probe: { args: ['-p', 'Reply with OK'] },
48
+ settingsFile: 'settings.json',
44
49
  sharedItems: [
45
50
  { path: 'AGENTS.md', mode: 'link' },
46
51
  { path: 'auth.json', mode: 'info', credential: true },
@@ -1,12 +1,13 @@
1
1
  // Entry for `sideby handoff-hook <family> <event>` (spec §3.17). A Host runs it on PostToolUse, Stop and
2
2
  // StopFailure, so it imports only Node built-ins and leaf modules: never the Runtime, a Family index or
3
3
  // core/accounts.ts. It never fails the Host: any problem means no output and exit 0.
4
- import { rm, stat } from 'node:fs/promises';
4
+ import { readFile, rm, stat } from 'node:fs/promises';
5
5
  import { join } from 'node:path';
6
- import { FILES, HANDOFF_ENV, readJsonFile, writeJsonFile, } from '../core/handoff-chain.js';
6
+ import { BRIEF_DONE, FILES, HANDOFF_ENV, readJsonFile, writeJsonFile, } from '../core/handoff-chain.js';
7
7
  import { claudeHookReader } from '../families/claude/handoff-hook.js';
8
8
  import { codexHookReader } from '../families/codex/handoff-hook.js';
9
9
  import { grokHookReader } from '../families/grok/handoff-hook.js';
10
+ import { crossedWindow, firstMark, fullestWindow, recordTurn } from './levels.js';
10
11
  import { endTurnMessage, notifySequence, prepareMessage, sessionStartMessage, stopMessage, thresholdMessage, waitNotice, } from './messages.js';
11
12
  import { field } from './reader.js';
12
13
  export const HOOK_COMMAND = 'sideby handoff-hook';
@@ -33,12 +34,15 @@ const contextOutput = (text, hookEventName = 'PostToolUse') => ({
33
34
  hookSpecificOutput: { hookEventName, additionalContext: text },
34
35
  });
35
36
  const blockOutput = (reason) => ({ decision: 'block', reason });
36
- async function mtimeMs(path) {
37
+ /** The session's Brief was written after `since` and ends finished (`BRIEF_DONE`, ADR-0032). */
38
+ async function briefFinished(path, since) {
37
39
  try {
38
- return (await stat(path)).mtimeMs;
40
+ if ((await stat(path)).mtimeMs <= since)
41
+ return false;
42
+ return (await readFile(path, 'utf8')).includes(BRIEF_DONE);
39
43
  }
40
44
  catch {
41
- return null;
45
+ return false;
42
46
  }
43
47
  }
44
48
  /** What one hook call decided: output for the Host, and files to write. Separate from I/O for the tests. */
@@ -76,20 +80,28 @@ export async function decide(opts) {
76
80
  : {};
77
81
  }
78
82
  const threshold = usable?.threshold ?? 95;
79
- const pressure = reader.pressure ? await reader.pressure(input, env, now) : null;
83
+ const levels = usable ?? { prepareAt: 80, threshold };
84
+ const windows = reader.windows ? await reader.windows(input, env, now) : null;
85
+ const pressure = windows ? Math.max(0, ...windows.map((w) => w.usedPercent)) : null;
80
86
  const ref = env.SIDEBY_ACCOUNT ?? family;
81
87
  const waiting = usable?.decision === 'wait' && usable.until ? usable.until : undefined;
88
+ let st = state;
89
+ const keep = async (next) => {
90
+ st = next;
91
+ await save(next);
92
+ };
82
93
  // Once per run, shown to the user (not the model): sideby will wait for the reset, and how to move on now.
83
94
  const waitOutput = async () => {
84
- if (!waiting || pressure === null || pressure < threshold || state.waitNoticeSentAt)
95
+ if (!waiting || pressure === null || pressure < threshold || st.waitNoticeSentAt)
85
96
  return undefined;
86
- await save({ ...state, waitNoticeSentAt: now.toISOString() });
97
+ await keep({ ...st, waitNoticeSentAt: now.toISOString() });
87
98
  return { systemMessage: waitNotice(ref, waiting, pressure) };
88
99
  };
89
100
  if (event === 'StopFailure') {
90
101
  if (!reader.limitHit?.(input, pressure, threshold))
91
102
  return {};
92
- await ready({ trigger: 'limit' });
103
+ const window = windows ? fullestWindow(windows) : undefined;
104
+ await ready({ trigger: 'limit', ...(window ? { window } : {}) });
93
105
  // The Host keeps only `terminalSequence` of a StopFailure hook's output.
94
106
  return waiting ? { output: { terminalSequence: notifySequence(waitNotice(ref, waiting)) } } : {};
95
107
  }
@@ -106,52 +118,61 @@ export async function decide(opts) {
106
118
  }
107
119
  if (!usable)
108
120
  return {};
121
+ // The turn that just ended joins the window's recent turns before anything is judged (ADR-0032).
122
+ if (windows)
123
+ await keep(recordTurn(st, windows));
109
124
  const notice = await waitOutput();
110
125
  if (notice)
111
126
  return { output: notice };
112
- if (state.thresholdSentAt && usable.agentBrief === false) {
113
- await ready({ trigger: 'threshold' });
127
+ const window = st.thresholdWindow ? { window: st.thresholdWindow } : {};
128
+ if (st.thresholdSentAt && usable.agentBrief === false) {
129
+ await ready({ trigger: 'threshold', ...window });
114
130
  return {};
115
131
  }
116
- if (state.thresholdSentAt) {
117
- const written = await mtimeMs(usable.brief);
118
- if (written !== null && written > Date.parse(state.thresholdSentAt))
119
- await ready({ trigger: 'threshold', brief: usable.brief, briefSource: 'agent' });
120
- else if (!state.stopBlocked && input.stop_hook_active !== true && input.stopHookActive !== true) {
121
- await save({ ...state, stopBlocked: true });
132
+ if (st.thresholdSentAt) {
133
+ if (await briefFinished(usable.brief, Date.parse(st.thresholdSentAt)))
134
+ await ready({ trigger: 'threshold', brief: usable.brief, briefSource: 'agent', ...window });
135
+ else if (!st.stopBlocked && input.stop_hook_active !== true && input.stopHookActive !== true) {
136
+ await keep({ ...st, stopBlocked: true });
122
137
  return { output: blockOutput(stopMessage(usable.brief)) };
123
138
  }
124
139
  else
125
- await ready({ trigger: 'threshold' });
140
+ await ready({ trigger: 'threshold', ...window });
126
141
  return {};
127
142
  }
128
- // A turn without tool calls: the threshold is first seen here.
129
- if (pressure !== null && pressure >= threshold && usable.decision === 'pick') {
143
+ // A turn without tool calls: the level is first reached here.
144
+ const crossed = windows ? crossedWindow(windows, levels, st) : undefined;
145
+ if (crossed && usable.decision === 'pick') {
130
146
  if (usable.agentBrief === false) {
131
- await ready({ trigger: 'threshold' });
147
+ await ready({ trigger: 'threshold', window: crossed });
132
148
  return {};
133
149
  }
134
- await save({ ...state, thresholdSentAt: now.toISOString(), stopBlocked: true });
135
- return { output: blockOutput(thresholdMessage(usable.brief, pressure)) };
150
+ await keep({ ...st, thresholdSentAt: now.toISOString(), thresholdWindow: crossed, stopBlocked: true });
151
+ return { output: blockOutput(thresholdMessage(usable.brief, crossed)) };
136
152
  }
137
153
  return {};
138
154
  }
139
155
  // PostToolUse
140
- if (!usable || pressure === null)
156
+ if (!usable || windows === null || pressure === null)
141
157
  return {};
158
+ const first = firstMark(st, windows);
159
+ if (first)
160
+ await keep(first);
142
161
  const notice = await waitOutput();
143
162
  if (notice)
144
163
  return { output: notice };
145
- if (pressure >= usable.threshold && usable.decision === 'pick' && !state.thresholdSentAt) {
146
- await save({ ...state, thresholdSentAt: now.toISOString() });
147
- const text = usable.agentBrief === false ? endTurnMessage(pressure) : thresholdMessage(usable.brief, pressure);
164
+ const crossed = crossedWindow(windows, levels, st);
165
+ if (crossed && usable.decision === 'pick' && !st.thresholdSentAt) {
166
+ await keep({ ...st, thresholdSentAt: now.toISOString(), thresholdWindow: crossed });
167
+ const text = usable.agentBrief === false ? endTurnMessage(crossed) : thresholdMessage(usable.brief, crossed);
148
168
  return { output: contextOutput(text) };
149
169
  }
150
170
  if (usable.agentBrief === false)
151
171
  return {};
152
- if (pressure >= usable.prepareAt && !state.prepareSentAt && !state.thresholdSentAt) {
153
- await save({ ...state, prepareSentAt: now.toISOString() });
154
- return { output: contextOutput(prepareMessage(usable.brief, pressure)) };
172
+ const top = fullestWindow(windows);
173
+ if (top && pressure >= usable.prepareAt && !st.prepareSentAt && !st.thresholdSentAt) {
174
+ await keep({ ...st, prepareSentAt: now.toISOString() });
175
+ return { output: contextOutput(prepareMessage(usable.brief, top)) };
155
176
  }
156
177
  return {};
157
178
  }
@@ -0,0 +1,24 @@
1
+ import type { PlanFile, RunState, WindowReading } from '../core/handoff-chain.ts';
2
+ import type { QuotaWindow } from '../types.ts';
3
+ /** Finished turns kept per window. */
4
+ export declare const TURNS_KEPT = 5;
5
+ /** How many of the largest recent turn the window must still have room for. */
6
+ export declare const HEADROOM = 1.5;
7
+ /** Never later than this: at 100 the limit is already hit. */
8
+ export declare const LEVEL_MAX = 99;
9
+ type Levels = Pick<PlanFile, 'prepareAt' | 'threshold' | 'adaptive'>;
10
+ /** The used percent at which `label` hands over in this run. */
11
+ export declare function handOverLevel(label: string, plan: Levels, state: RunState): number;
12
+ export declare const reading: (w: QuotaWindow) => WindowReading;
13
+ /** The window that reached its level, the one furthest past it when several have; undefined when none has. */
14
+ export declare function crossedWindow(windows: readonly QuotaWindow[], plan: Levels, state: RunState): WindowReading | undefined;
15
+ /** The fullest window, to name in a message when none is past its level (the preparing step, a limit hit). */
16
+ export declare function fullestWindow(windows: readonly QuotaWindow[]): WindowReading | undefined;
17
+ /** The readings a run starts measuring from, when no `Stop` has set them yet. */
18
+ export declare function firstMark(state: RunState, windows: readonly QuotaWindow[]): RunState | undefined;
19
+ /**
20
+ * At a `Stop`: each window's growth since the last one joins its recent turns (growth across a reset, or none at
21
+ * all, is not a turn's use), and today's readings become the next turn's starting point.
22
+ */
23
+ export declare function recordTurn(state: RunState, windows: readonly QuotaWindow[]): RunState;
24
+ export {};
@@ -0,0 +1,70 @@
1
+ /** Finished turns kept per window. */
2
+ export const TURNS_KEPT = 5;
3
+ /** How many of the largest recent turn the window must still have room for. */
4
+ export const HEADROOM = 1.5;
5
+ /** Never later than this: at 100 the limit is already hit. */
6
+ export const LEVEL_MAX = 99;
7
+ /** The used percent at which `label` hands over in this run. */
8
+ export function handOverLevel(label, plan, state) {
9
+ const used = state.turnUse?.[label];
10
+ if (plan.adaptive !== true || !used?.length)
11
+ return plan.threshold;
12
+ const level = Math.floor(100 - HEADROOM * Math.max(...used));
13
+ return Math.max(plan.prepareAt, Math.min(LEVEL_MAX, level));
14
+ }
15
+ export const reading = (w) => ({
16
+ label: w.label,
17
+ usedPercent: w.usedPercent,
18
+ resetsAt: w.resetsAt,
19
+ });
20
+ /** The window that reached its level, the one furthest past it when several have; undefined when none has. */
21
+ export function crossedWindow(windows, plan, state) {
22
+ let best;
23
+ for (const w of windows) {
24
+ const past = w.usedPercent - handOverLevel(w.label, plan, state);
25
+ if (past >= 0 && (!best || past > best.past))
26
+ best = { w, past };
27
+ }
28
+ return best && reading(best.w);
29
+ }
30
+ /** The fullest window, to name in a message when none is past its level (the preparing step, a limit hit). */
31
+ export function fullestWindow(windows) {
32
+ let top;
33
+ for (const w of windows)
34
+ if (!top || w.usedPercent > top.usedPercent)
35
+ top = w;
36
+ return top && reading(top);
37
+ }
38
+ /**
39
+ * Two readings belong to one window when their reset times are within 10 minutes: Codex derives the time from a
40
+ * relative `resets_in_seconds`, so it moves a little between readings.
41
+ */
42
+ function sameWindow(a, b) {
43
+ const d = Math.abs(Date.parse(a) - Date.parse(b));
44
+ return Number.isFinite(d) && d < 10 * 60_000;
45
+ }
46
+ /** The readings a run starts measuring from, when no `Stop` has set them yet. */
47
+ export function firstMark(state, windows) {
48
+ if (state.turnMark || windows.length === 0)
49
+ return undefined;
50
+ return {
51
+ ...state,
52
+ turnMark: Object.fromEntries(windows.map((w) => [w.label, { usedPercent: w.usedPercent, resetsAt: w.resetsAt }])),
53
+ };
54
+ }
55
+ /**
56
+ * At a `Stop`: each window's growth since the last one joins its recent turns (growth across a reset, or none at
57
+ * all, is not a turn's use), and today's readings become the next turn's starting point.
58
+ */
59
+ export function recordTurn(state, windows) {
60
+ const turnUse = { ...state.turnUse };
61
+ const turnMark = {};
62
+ for (const w of windows) {
63
+ const before = state.turnMark?.[w.label];
64
+ const grew = before && sameWindow(before.resetsAt, w.resetsAt) ? w.usedPercent - before.usedPercent : 0;
65
+ if (grew > 0)
66
+ turnUse[w.label] = [...(turnUse[w.label] ?? []), grew].slice(-TURNS_KEPT);
67
+ turnMark[w.label] = { usedPercent: w.usedPercent, resetsAt: w.resetsAt };
68
+ }
69
+ return { ...state, turnMark, turnUse };
70
+ }
@@ -1,7 +1,10 @@
1
- export declare function prepareMessage(brief: string, pressure: number): string;
2
- export declare function thresholdMessage(brief: string, pressure: number): string;
1
+ import { type WindowReading } from '../core/handoff-chain.ts';
2
+ /** Which window, how full and when it resets, so nobody mistakes the weekly window for the 5-hour one (ADR-0032). */
3
+ export declare function windowText(w: WindowReading): string;
4
+ export declare function prepareMessage(brief: string, window: WindowReading): string;
5
+ export declare function thresholdMessage(brief: string, window: WindowReading): string;
3
6
  /** At the threshold when the session cannot write a Brief: sideby puts one together from its records. */
4
- export declare function endTurnMessage(pressure: number): string;
7
+ export declare function endTurnMessage(window: WindowReading): string;
5
8
  export declare function stopMessage(brief: string): string;
6
9
  /** At session start (Claude): this session may hand its task to another account when the user asks. */
7
10
  export declare function sessionStartMessage(ref: string, brief: string): string;
@@ -1,5 +1,6 @@
1
1
  // Text the handoff hook puts in front of the model, and the first prompt of the next session (spec §3.17).
2
2
  // English, since Hosts and models read it; complete in itself, so it works without any skill installed.
3
+ import { BRIEF_DONE } from '../core/handoff-chain.js';
3
4
  const TEMPLATE = [
4
5
  'the goal of the task',
5
6
  'what is done',
@@ -7,16 +8,28 @@ const TEMPLATE = [
7
8
  'key decisions and why',
8
9
  'the files that matter',
9
10
  ].join('; ');
10
- const RULES = 'Reference specs, ADRs, commits and diffs by path instead of repeating them, list the skills the next agent should use, and never include keys, passwords or personal data.';
11
- export function prepareMessage(brief, pressure) {
12
- return `sideby: this account's quota is at ${Math.round(pressure)}%. Write a handoff brief to ${brief} now (${TEMPLATE}). ${RULES} Keep it current after each step, then go on with the task. Do not tell the user that the work will move to another account: sideby decides that and tells them itself.`;
11
+ const RULES = `Reference specs, ADRs, commits and diffs by path instead of repeating them, list the skills the next agent should use, and never include keys, passwords or personal data. End the brief with the line ${BRIEF_DONE} once it covers all of this.`;
12
+ const WINDOW_NAMES = { '5h': '5-hour', '7d': 'weekly' };
13
+ const when = (iso) => {
14
+ const t = new Date(iso);
15
+ if (Number.isNaN(t.getTime()))
16
+ return 'an unknown time';
17
+ return t.toLocaleString(undefined, { weekday: 'short', hour: '2-digit', minute: '2-digit' });
18
+ };
19
+ /** Which window, how full and when it resets, so nobody mistakes the weekly window for the 5-hour one (ADR-0032). */
20
+ export function windowText(w) {
21
+ const name = WINDOW_NAMES[w.label] ? `${WINDOW_NAMES[w.label]} (${w.label})` : w.label;
22
+ return `${name} quota is at ${Math.round(w.usedPercent)}%, back at ${when(w.resetsAt)}`;
23
+ }
24
+ export function prepareMessage(brief, window) {
25
+ return `sideby: this account's ${windowText(window)}. Write a handoff brief to ${brief} now (${TEMPLATE}). ${RULES} Keep it current after each step, then go on with the task. Do not tell the user that the work will move to another account: sideby decides that and tells them itself.`;
13
26
  }
14
- export function thresholdMessage(brief, pressure) {
15
- return `sideby: this account's quota is at ${Math.round(pressure)}%. Finish the current step, update the handoff brief at ${brief} (${TEMPLATE}; ${RULES}), then end your turn. sideby will start the next account from that brief.`;
27
+ export function thresholdMessage(brief, window) {
28
+ return `sideby: this account's ${windowText(window)}. Finish the current step, update the handoff brief at ${brief} (${TEMPLATE}; ${RULES}), then end your turn. sideby will start the next account from that brief.`;
16
29
  }
17
30
  /** At the threshold when the session cannot write a Brief: sideby puts one together from its records. */
18
- export function endTurnMessage(pressure) {
19
- return `sideby: this account's quota is at ${Math.round(pressure)}%. Finish the current step and end your turn; sideby will start the next account and tell it what you did.`;
31
+ export function endTurnMessage(window) {
32
+ return `sideby: this account's ${windowText(window)}. Finish the current step and end your turn; sideby will start the next account and tell it what you did.`;
20
33
  }
21
34
  export function stopMessage(brief) {
22
35
  return `sideby: before you stop, update the handoff brief at ${brief} (${TEMPLATE}; ${RULES}), then end your turn.`;
@@ -1,9 +1,12 @@
1
- import type { Env } from '../types.ts';
1
+ import type { Env, QuotaWindow } from '../types.ts';
2
2
  /** The hook's stdin, parsed: field names differ per Host (snake_case for Claude and Codex, camelCase for Grok). */
3
3
  export type HookInput = Record<string, unknown>;
4
4
  export interface HookReader {
5
- /** Quota Pressure in percent now, or null when unknown. Families without a Quota source leave it out. */
6
- pressure?(input: HookInput, env: Env, now: Date): Promise<number | null>;
5
+ /**
6
+ * The windows that count toward Quota Pressure and have not reset (`openWindows`), or null when unknown. Families
7
+ * without a Quota source leave it out.
8
+ */
9
+ windows?(input: HookInput, env: Env, now: Date): Promise<QuotaWindow[] | null>;
7
10
  /** Whether a `StopFailure` means the Quota is used up, not a transient rate limit or an overloaded server. */
8
11
  limitHit?(input: HookInput, pressure: number | null, threshold: number): boolean;
9
12
  }
@@ -0,0 +1,3 @@
1
+ import type { LoginAgent } from '../core/autostart.ts';
2
+ export declare const MENUBAR_LABEL = "dev.sideby.menubar";
3
+ export declare const MENUBAR_AGENT: LoginAgent;
@@ -0,0 +1,21 @@
1
+ import { MENUBAR_SCRIPT } from './script.js';
2
+ export const MENUBAR_LABEL = 'dev.sideby.menubar';
3
+ export const MENUBAR_AGENT = {
4
+ label: MENUBAR_LABEL,
5
+ marker: 'Written by `sideby menubar`',
6
+ command: 'menubar',
7
+ comment: 'shows sideby quota in the menu bar from login',
8
+ programArguments: (l) => ['/usr/bin/osascript', '-l', 'JavaScript', '-e', MENUBAR_SCRIPT, l.node, l.entry],
9
+ launcherPaths: (args) => args.slice(-2),
10
+ later: 'the menu bar item appears at your next login',
11
+ restartOnCrash: true,
12
+ // The Hosts `menubar snapshot` asks for Quota (Grok's CLI) are found on the PATH of whoever turned it on, and the
13
+ // config and state folders stay the ones that person uses.
14
+ environment: (env) => {
15
+ const out = { PATH: env.PATH || '/usr/bin:/bin:/usr/sbin:/sbin' };
16
+ for (const k of ['XDG_CONFIG_HOME', 'XDG_STATE_HOME'])
17
+ if (env[k])
18
+ out[k] = env[k];
19
+ return out;
20
+ },
21
+ };
@@ -0,0 +1,8 @@
1
+ /** Seconds between two snapshots, and between two looks at a running one. */
2
+ export declare const SNAPSHOT_SECONDS = 120;
3
+ export declare const TICK_SECONDS = 5;
4
+ /** A snapshot older than this greys the title. */
5
+ export declare const STALE_SECONDS: number;
6
+ /** A snapshot still running after this is ended, so a stuck one cannot stop the refreshes. */
7
+ export declare const SNAPSHOT_TIMEOUT_SECONDS = 60;
8
+ export declare const MENUBAR_SCRIPT: string;