sideby 0.35.9 → 0.36.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 (66) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +12 -0
  3. package/dist/src/cli/commands.js +480 -6
  4. package/dist/src/cli/format.d.ts +12 -1
  5. package/dist/src/cli/format.js +23 -3
  6. package/dist/src/cli/json-schemas.js +166 -1
  7. package/dist/src/cli/main.js +18 -4
  8. package/dist/src/core/advisor.d.ts +176 -0
  9. package/dist/src/core/advisor.js +472 -0
  10. package/dist/src/core/browser-profiles.d.ts +16 -0
  11. package/dist/src/core/browser-profiles.js +45 -0
  12. package/dist/src/core/cli-commands.js +25 -1
  13. package/dist/src/core/config.d.ts +29 -0
  14. package/dist/src/core/config.js +25 -0
  15. package/dist/src/core/handoff-select.d.ts +13 -2
  16. package/dist/src/core/handoff-select.js +6 -2
  17. package/dist/src/core/launch.d.ts +4 -0
  18. package/dist/src/core/launch.js +7 -0
  19. package/dist/src/core/limit-reset.d.ts +198 -0
  20. package/dist/src/core/limit-reset.js +299 -0
  21. package/dist/src/core/quota-fetch.d.ts +57 -2
  22. package/dist/src/core/quota-fetch.js +291 -13
  23. package/dist/src/core/quota-levels.d.ts +70 -0
  24. package/dist/src/core/quota-levels.js +80 -0
  25. package/dist/src/core/quota-store.d.ts +15 -1
  26. package/dist/src/core/quota-store.js +26 -1
  27. package/dist/src/core/same-login.d.ts +8 -0
  28. package/dist/src/core/same-login.js +39 -2
  29. package/dist/src/core/search-catalog.js +38 -0
  30. package/dist/src/families/claude/index.js +2 -0
  31. package/dist/src/families/codex/index.js +3 -1
  32. package/dist/src/families/codex/quota.d.ts +23 -1
  33. package/dist/src/families/codex/quota.js +122 -21
  34. package/dist/src/families/grok/quota-log.d.ts +1 -0
  35. package/dist/src/menubar/script.js +70 -18
  36. package/dist/src/menubar/snapshot.d.ts +33 -1
  37. package/dist/src/menubar/snapshot.js +79 -11
  38. package/dist/src/menubar/strings.d.ts +16 -0
  39. package/dist/src/menubar/strings.js +16 -0
  40. package/dist/src/panel/handler.d.ts +21 -0
  41. package/dist/src/panel/handler.js +111 -9
  42. package/dist/src/panel/i18n.d.ts +87 -0
  43. package/dist/src/panel/i18n.js +174 -0
  44. package/dist/src/panel/page-logic.d.ts +17 -0
  45. package/dist/src/panel/page-logic.js +23 -0
  46. package/dist/src/panel/page-script.js +440 -19
  47. package/dist/src/panel/page-styles.js +38 -2
  48. package/dist/src/plugins/loader.d.ts +2 -0
  49. package/dist/src/plugins/loader.js +27 -0
  50. package/dist/src/runtime.d.ts +63 -1
  51. package/dist/src/runtime.js +529 -9
  52. package/dist/src/types.d.ts +67 -0
  53. package/package.json +1 -1
  54. package/schemas/advisor.json +332 -0
  55. package/schemas/config.json +22 -0
  56. package/schemas/error.json +4 -0
  57. package/schemas/menubar-reset.json +93 -0
  58. package/schemas/menubar-snapshot.json +70 -2
  59. package/schemas/quota-reset.json +369 -0
  60. package/schemas/quota.json +30 -0
  61. package/schemas/update.json +4 -0
  62. package/skills/sideby/SKILL.md +6 -2
  63. package/skills/sideby/references/ai-tasks.md +1 -1
  64. package/skills/sideby/references/panel.md +14 -0
  65. package/skills/sideby/references/quota.md +27 -0
  66. package/skills/sideby/references/update.md +1 -1
@@ -0,0 +1,472 @@
1
+ // Advisor (spec §3.41, ADR-0074): Claude Code's advisor lets a session ask a stronger model for advice at key moments.
2
+ // sideby reads two things of each Claude subscription Account's `settings.json` (grouped by the real file, as Remote
3
+ // Control does, ADR-0017): the top-level `advisorModel`, and whether `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` is
4
+ // true, which makes Claude Code hide the advisor. Choosing a model writes `advisorModel` and, where that variable stands
5
+ // in the way, removes it, in one confirmed write with one undo record. No other key or `env` entry is ever read into an
6
+ // output, an error or the undo record; writes go through `writeIfUnchanged`, keep every other key and `env` entry, and
7
+ // never create, replace or retarget a link. While config `advisor.unlock` is on, sideby also unlocks the advisor at
8
+ // launch with one environment variable. API Accounts that share such a file keep the variable another way: the same
9
+ // change turns config `claude.apiBetasOff` on, and sideby then sets it when it starts them (gateways often reject the
10
+ // headers experimental features send).
11
+ import { rm } from 'node:fs/promises';
12
+ import { isObj, keyRecordPath, readKeyRecord, readSettingsGroups, writeKeyRecord, writeSettingsKey, } from './claude-settings-file.js';
13
+ import { editConfigAdvisor, editConfigClaude } from './config.js';
14
+ import { UserError } from './errors.js';
15
+ export const ADVISOR_KEY = 'advisorModel';
16
+ /** The aliases Claude Code's `/advisor` takes, in the order the Panel and the CLI show them. */
17
+ export const ADVISOR_MODELS = ['fable', 'opus', 'sonnet'];
18
+ export const ADVISOR_CHOICES = [...ADVISOR_MODELS, 'off'];
19
+ export const isAdvisorChoice = (v) => typeof v === 'string' && ADVISOR_CHOICES.includes(v);
20
+ /** Set at launch while config `advisor.unlock` is on: Claude Code then offers the advisor without waiting for Anthropic's rollout. */
21
+ export const ADVISOR_UNLOCK_VAR = 'CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL';
22
+ /**
23
+ * Turns off every experimental feature of Claude Code, the advisor among them, also with `ADVISOR_UNLOCK_VAR` set
24
+ * (tried with Claude Code 2.1.322 on 2026-11-13). Users often keep it in a settings file's `env`.
25
+ */
26
+ export const BETAS_VAR = 'CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS';
27
+ /** Variables that make Claude Code hide the advisor whatever else is set. sideby never changes them in the shell. */
28
+ export const ADVISOR_OFF_VARS = ['CLAUDE_CODE_DISABLE_ADVISOR_TOOL', BETAS_VAR];
29
+ const TITLE = { fable: 'Fable', opus: 'Opus', sonnet: 'Sonnet' };
30
+ const RECORDS = 'advisor';
31
+ const ENV_NOT_OBJECT = 'settings.json has an `env` that is not a JSON object; fix it in the file, then try again';
32
+ const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:@[\]-]{0,99}$/;
33
+ function stateOf(v) {
34
+ if (v === undefined)
35
+ return { state: 'off' };
36
+ if (typeof v !== 'string')
37
+ return { state: 'other' };
38
+ const text = v.trim();
39
+ if (!text)
40
+ return { state: 'off' };
41
+ const alias = text.toLowerCase();
42
+ if (ADVISOR_MODELS.includes(alias))
43
+ return { state: alias };
44
+ return MODEL_ID.test(text) ? { state: 'other', model: text } : { state: 'other' };
45
+ }
46
+ /** Claude Code's own reading of an environment value as true. */
47
+ function truthy(v) {
48
+ if (v === true)
49
+ return true;
50
+ return typeof v === 'string' && ['1', 'true', 'yes', 'on'].includes(v.trim().toLowerCase());
51
+ }
52
+ /** The first variable of `ADVISOR_OFF_VARS` that `env` sets to a true value, or undefined. */
53
+ export function advisorOffVar(env) {
54
+ return ADVISOR_OFF_VARS.find((v) => truthy(env[v]));
55
+ }
56
+ /**
57
+ * Unlocks the advisor in `env` for a Claude subscription Account's Launch: sets `ADVISOR_UNLOCK_VAR` unless the
58
+ * environment already sets it or one of `ADVISOR_OFF_VARS`. Returns whether it set it.
59
+ */
60
+ export function unlockAdvisorEnv(env, familyId, account) {
61
+ if (familyId !== 'claude' || account.kind === 'api')
62
+ return false;
63
+ if (advisorOffVar(env) || env[ADVISOR_UNLOCK_VAR] !== undefined)
64
+ return false;
65
+ env[ADVISOR_UNLOCK_VAR] = '1';
66
+ return true;
67
+ }
68
+ /**
69
+ * Config `claude.apiBetasOff` at a Claude API Account's Launch: sets `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` unless
70
+ * the environment already sets it. Runs before the Account's Secret File is read, so `proxy.env` still decides.
71
+ * Returns whether it set it.
72
+ */
73
+ export function apiBetasEnv(env, familyId, account) {
74
+ if (familyId !== 'claude' || account.kind !== 'api' || env[BETAS_VAR] !== undefined)
75
+ return false;
76
+ env[BETAS_VAR] = '1';
77
+ return true;
78
+ }
79
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
80
+ /** Whether `obj` still holds what the record says sideby wrote (or still lacks the `advisorModel` it removed). */
81
+ function holds(obj, r) {
82
+ return r.removed ? !Object.hasOwn(obj, ADVISOR_KEY) : same(obj[ADVISOR_KEY], r.wrote);
83
+ }
84
+ async function readRecord(stateDir, file) {
85
+ const r = await readKeyRecord(stateDir, RECORDS, file);
86
+ if (!r || typeof r.hadKey !== 'boolean')
87
+ return null;
88
+ if (r.removed !== true && typeof r.wrote !== 'string')
89
+ return null;
90
+ const api = r.apiBetas;
91
+ if (api !== undefined && !(isObj(api) && (api.previous === null || typeof api.previous === 'boolean')))
92
+ delete r.apiBetas;
93
+ return r;
94
+ }
95
+ /** `obj` with `key` set to `value` at `index` among its keys (at the end without one), keeping the others' order. */
96
+ function insertAt(obj, key, value, index) {
97
+ const entries = Object.entries(obj).filter(([k]) => k !== key);
98
+ entries.splice(Math.min(index ?? entries.length, entries.length), 0, [key, value]);
99
+ return Object.fromEntries(entries);
100
+ }
101
+ /**
102
+ * Every Claude subscription Account's advisor, grouped by the file it lives in, with the API Accounts that share each
103
+ * file. Writes nothing. A file only API Accounts use is left out: the advisor needs a Claude login.
104
+ */
105
+ export async function advisorGroups(accounts, ctx) {
106
+ const claude = accounts.filter((a) => a.family === 'claude');
107
+ const api = new Set(claude.filter((a) => a.kind === 'api').map((a) => a.ref));
108
+ const out = [];
109
+ for (const g of await readSettingsGroups(claude)) {
110
+ const subs = g.accounts.filter((ref) => !api.has(ref));
111
+ if (!subs.length)
112
+ continue;
113
+ const apiAccounts = g.accounts.filter((ref) => api.has(ref));
114
+ const base = { file: g.file, accounts: subs, ...(apiAccounts.length ? { apiAccounts } : {}) };
115
+ if ('why' in g)
116
+ out.push({
117
+ ...base,
118
+ state: g.why === 'no-settings' ? 'missing' : 'blocked',
119
+ why: g.why,
120
+ reason: g.reason,
121
+ undo: false,
122
+ });
123
+ else if (g.obj.env !== undefined && !isObj(g.obj.env))
124
+ out.push({ ...base, state: 'blocked', why: 'unsafe', reason: ENV_NOT_OBJECT, undo: false });
125
+ else {
126
+ const betas = isObj(g.obj.env) ? g.obj.env[BETAS_VAR] : undefined;
127
+ const record = await readRecord(ctx.stateDir, g.file);
128
+ const undo = record !== null && holds(g.obj, record);
129
+ out.push({
130
+ ...base,
131
+ ...stateOf(g.obj[ADVISOR_KEY]),
132
+ ...(truthy(betas) ? { betasOff: true, betasValue: JSON.stringify(betas) } : {}),
133
+ undo,
134
+ ...(undo && record.apiBetas ? { undoApiBetas: true } : {}),
135
+ });
136
+ }
137
+ }
138
+ return out;
139
+ }
140
+ /**
141
+ * The groups, the two sideby settings and any variable in sideby's own environment that hides the advisor. Writes
142
+ * nothing.
143
+ */
144
+ export async function advisorStatus(accounts, ctx, cfg) {
145
+ const envOff = advisorOffVar(ctx.env);
146
+ return {
147
+ groups: await advisorGroups(accounts, ctx),
148
+ unlock: cfg.unlock,
149
+ apiBetasOff: cfg.apiBetasOff,
150
+ ...(envOff ? { envOff } : {}),
151
+ };
152
+ }
153
+ /** `account` when the advisor can be set for it; else a UserError that says what to do. */
154
+ export function checkAdvisorAccount(account) {
155
+ if (account.family !== 'claude')
156
+ throw new UserError(`${account.ref} is not a Claude Code account; the advisor is a Claude Code feature. Pick a Claude account, or leave out --account for all of them`);
157
+ if (account.kind === 'api')
158
+ throw new UserError(`${account.ref} is an API account, and the advisor needs a Claude login. Pick a Claude subscription account, or leave out --account for all of them`);
159
+ return account;
160
+ }
161
+ /** The groups `account` (a ref) uses, or every group without one. */
162
+ export function advisorScope(groups, account) {
163
+ return account ? groups.filter((g) => g.accounts.includes(account)) : [...groups];
164
+ }
165
+ /**
166
+ * What choosing `to` changes, the one rule for the CLI, the Panel's server and its page: `todo`, the groups sideby can
167
+ * write that do not hold `to` yet or, for a model, whose `env` turns experimental features off (also when they already
168
+ * name it); `unlocks`, whether config `advisor.unlock` turns on (a model, while it is off, when some group has or gets
169
+ * that model); and `apiBetas`, whether config `claude.apiBetasOff` turns on (while it is off, when the variable leaves
170
+ * a file that API Accounts also use, so they keep it). Choosing the model the files already name is still a change
171
+ * while either is set. Self-contained, so the Panel page runs this same function (page-script.ts).
172
+ */
173
+ export function advisorPending(groups, to, cfg) {
174
+ const todo = groups.filter((g) => g.state !== 'missing' &&
175
+ g.state !== 'blocked' &&
176
+ (g.state !== to || (to !== 'off' && g.betasOff === true)));
177
+ const unlocks = to !== 'off' && !cfg.unlock && (todo.length > 0 || groups.some((g) => g.state === to));
178
+ const apiBetas = to !== 'off' &&
179
+ !cfg.apiBetasOff &&
180
+ todo.some((g) => g.betasOff === true && (g.apiAccounts?.length ?? 0) > 0);
181
+ return { todo, unlocks, apiBetas };
182
+ }
183
+ /**
184
+ * What choosing `to` would do in `scope` (`advisorPending`), with the groups whose
185
+ * `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` is removed with it, the API Accounts that use those files, and the groups
186
+ * sideby cannot change. Nothing to do when there are no groups to write and no unlock.
187
+ */
188
+ export function advisorPlan(scope, to, cfg) {
189
+ const { todo, unlocks, apiBetas } = advisorPending(scope, to, cfg);
190
+ const betas = to === 'off' ? [] : todo.filter((g) => g.betasOff === true);
191
+ return {
192
+ todo,
193
+ betas,
194
+ apiAccounts: betas.flatMap((g) => g.apiAccounts ?? []),
195
+ skipped: scope.filter((g) => g.state === 'missing' || g.state === 'blocked'),
196
+ unlock: unlocks,
197
+ apiBetas,
198
+ };
199
+ }
200
+ /** What a change says when there is nothing to do: always `ok: false`, so the CLI exits 1. */
201
+ export function advisorNothingToDo(action, scope) {
202
+ const none = (message) => ({ ok: false, results: [], unlocked: false, message });
203
+ if (action === 'undo')
204
+ return none('There is nothing from sideby to undo.');
205
+ if (!scope.length)
206
+ return none('No Claude subscription accounts found, so nothing was changed. The advisor needs a Claude login; API accounts cannot use it.');
207
+ const stuck = scope.find((g) => g.state === 'blocked' || g.state === 'missing');
208
+ if (!scope.some((g) => g.state === action))
209
+ return none(`Nothing was changed: ${stuck?.reason}`);
210
+ const already = action === 'off'
211
+ ? 'The advisor is already off (nothing changed).'
212
+ : `The advisor is already ${TITLE[action]} and sideby already unlocks it at launch (nothing changed).`;
213
+ return none(stuck ? `${already} ${stuck.accounts.join(', ')} cannot be changed: ${stuck.reason}.` : already);
214
+ }
215
+ function doneMessage(to, betas, api) {
216
+ if (to === 'off')
217
+ return 'Done. New sessions no longer ask an advisor; restart sessions that are already running.';
218
+ return [
219
+ `Done. Sessions sideby starts ask ${TITLE[to]} for advice at key moments, which uses more quota; restart sessions that are already running.`,
220
+ betas ? `Removing ${BETAS_VAR} also turned Claude Code's other experimental features back on.` : '',
221
+ api.length
222
+ ? `API accounts ${api.join(', ')} still get ${BETAS_VAR}=1 from sideby when it starts them (config claude.apiBetasOff), so their gateway keeps working.`
223
+ : '',
224
+ 'Sessions started with plain `claude` get it only where Anthropic has turned the advisor on. If a session says "Advisor unavailable", Anthropic has not enabled it for that account.',
225
+ ]
226
+ .filter(Boolean)
227
+ .join(' ');
228
+ }
229
+ /**
230
+ * Puts config `claude.apiBetasOff` back to `previous` (null: not set, which removes the key and an emptied section),
231
+ * only while it still holds the `true` sideby wrote. Whether it changed it.
232
+ */
233
+ async function restoreApiBetas(configFile, previous) {
234
+ const r = await editConfigClaude(configFile, (c) => {
235
+ if (c.apiBetasOff !== true)
236
+ return null;
237
+ const { apiBetasOff: _drop, ...rest } = c;
238
+ if (previous !== null)
239
+ return { ...rest, apiBetasOff: previous };
240
+ return Object.keys(rest).length ? rest : undefined;
241
+ });
242
+ return r.changed;
243
+ }
244
+ /**
245
+ * One settings file's change: `advisorModel` set to `to` (`off` removes it) and, for a model, a true
246
+ * `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` removed (the `env` object stays, even when empty), in one write. Leaves
247
+ * an undo record of exactly those two entries, and of `apiBetas` (the earlier config `claude.apiBetasOff`) when the
248
+ * same change turned that on for this file's API Accounts.
249
+ */
250
+ async function writeGroup(stateDir, g, to, apiBetas) {
251
+ const dropBetas = to !== 'off';
252
+ const box = {};
253
+ const failed = await writeSettingsKey(g.file, (obj) => {
254
+ const r = {
255
+ file: g.file,
256
+ hadKey: Object.hasOwn(obj, ADVISOR_KEY),
257
+ at: new Date().toISOString(),
258
+ };
259
+ if (r.hadKey)
260
+ r.previous = obj[ADVISOR_KEY];
261
+ if (to === 'off') {
262
+ r.removed = true;
263
+ if (r.hadKey)
264
+ r.index = Object.keys(obj).indexOf(ADVISOR_KEY);
265
+ delete obj[ADVISOR_KEY];
266
+ }
267
+ else {
268
+ r.wrote = to;
269
+ obj[ADVISOR_KEY] = to;
270
+ }
271
+ const env = obj.env;
272
+ if (dropBetas && isObj(env) && truthy(env[BETAS_VAR])) {
273
+ r.betas = { previous: env[BETAS_VAR], index: Object.keys(env).indexOf(BETAS_VAR) };
274
+ obj.env = Object.fromEntries(Object.entries(env).filter(([k]) => k !== BETAS_VAR));
275
+ if (apiBetas && g.apiAccounts?.length)
276
+ r.apiBetas = apiBetas;
277
+ }
278
+ box.record = r;
279
+ return obj;
280
+ }, (obj) => {
281
+ if (obj.env !== undefined && !isObj(obj.env))
282
+ return `${ENV_NOT_OBJECT}.`;
283
+ const betas = dropBetas && isObj(obj.env) && truthy(obj.env[BETAS_VAR]);
284
+ return stateOf(obj[ADVISOR_KEY]).state === to && !betas
285
+ ? 'It was set that way meanwhile; nothing changed.'
286
+ : null;
287
+ });
288
+ if (!failed && box.record)
289
+ await writeKeyRecord(stateDir, RECORDS, g.file, box.record);
290
+ const betas = !failed && box.record?.betas !== undefined;
291
+ const done = (to === 'off' ? 'Turned off.' : `Set to ${to}.`) + (betas ? ` Removed env.${BETAS_VAR}.` : '');
292
+ return {
293
+ file: g.file,
294
+ accounts: g.accounts,
295
+ ok: !failed,
296
+ message: failed ?? done,
297
+ betas,
298
+ api: betas && box.record?.apiBetas !== undefined,
299
+ };
300
+ }
301
+ /**
302
+ * Sets `advisorModel` to `to` (`off` removes the key) in every group of the scope that does not hold it yet, and for a
303
+ * model removes a true `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`, remembering how to undo it. Where that file also
304
+ * serves API Accounts, config `claude.apiBetasOff` turns on first, so they never start without the variable. A model
305
+ * also turns config `advisor.unlock` on when it is off, once a file was written or none needed it.
306
+ */
307
+ export async function setAdvisor(accounts, ctx, to, opts) {
308
+ const scope = advisorScope(await advisorGroups(accounts, ctx), opts.account);
309
+ const plan = advisorPlan(scope, to, opts);
310
+ if (!plan.todo.length && !plan.unlock)
311
+ return advisorNothingToDo(to, scope);
312
+ let apiPrev;
313
+ if (plan.apiBetas) {
314
+ try {
315
+ const r = await editConfigClaude(opts.configFile, (c) => ({ ...c, apiBetasOff: true }));
316
+ if (r.changed)
317
+ apiPrev = { previous: typeof r.before?.apiBetasOff === 'boolean' ? r.before.apiBetasOff : null };
318
+ }
319
+ catch (err) {
320
+ return {
321
+ ok: false,
322
+ results: [],
323
+ unlocked: false,
324
+ message: `Nothing was changed: sideby could not turn on config claude.apiBetasOff, which keeps ${BETAS_VAR} for ${plan.apiAccounts.join(', ')}: ${err.message}`,
325
+ };
326
+ }
327
+ }
328
+ const written = [];
329
+ for (const g of plan.todo)
330
+ written.push(await writeGroup(ctx.stateDir, g, to, apiPrev));
331
+ const results = written.map(({ betas: _b, api: _a, ...r }) => r);
332
+ // No file the API Accounts use lost the variable after all: the config goes back as it was.
333
+ const apiOn = apiPrev !== undefined && written.some((r) => r.api);
334
+ if (apiPrev && !apiOn)
335
+ await restoreApiBetas(opts.configFile, apiPrev.previous).catch(() => false);
336
+ let ok = results.every((r) => r.ok);
337
+ let unlocked = false;
338
+ let unlockFailed = '';
339
+ if (plan.unlock && (!results.length || results.some((r) => r.ok))) {
340
+ try {
341
+ unlocked = (await editConfigAdvisor(opts.configFile, (c) => ({ ...c, unlock: true }))).changed;
342
+ }
343
+ catch (err) {
344
+ ok = false;
345
+ unlockFailed = err.message;
346
+ }
347
+ }
348
+ const api = written
349
+ .filter((r) => r.betas)
350
+ .flatMap((r) => scope.find((g) => g.file === r.file)?.apiAccounts ?? []);
351
+ return {
352
+ ok,
353
+ results,
354
+ unlocked,
355
+ ...(apiOn ? { apiBetas: true } : {}),
356
+ message: unlockFailed
357
+ ? `The settings were changed, but sideby could not turn on unlocking at launch: ${unlockFailed}. Then run \`sideby advisor unlock on\`.`
358
+ : !ok
359
+ ? 'Some files could not be changed; see each line.'
360
+ : doneMessage(to, written.some((r) => r.betas), api),
361
+ };
362
+ }
363
+ /** Groups sideby can put back: it wrote there and the key still holds what it wrote. */
364
+ export function advisorGroupsToUndo(groups) {
365
+ return groups.filter((g) => g.undo);
366
+ }
367
+ /**
368
+ * Puts back what each file had before the last change, each entry at its old place, only while `advisorModel` still
369
+ * holds what sideby wrote; a removed `env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` comes back only while it is still
370
+ * absent. Then config `claude.apiBetasOff` goes back to its earlier value, when that change turned it on, it still
371
+ * holds `true` and no file the API Accounts use still lacks the variable because of sideby. Leaves config
372
+ * `advisor.unlock` as it is.
373
+ */
374
+ export async function undoAdvisor(accounts, ctx, opts) {
375
+ const groups = await advisorGroups(accounts, ctx);
376
+ const todo = advisorGroupsToUndo(groups);
377
+ if (todo.length === 0)
378
+ return advisorNothingToDo('undo', []);
379
+ const results = [];
380
+ let apiPrev;
381
+ let apiBack = true;
382
+ for (const g of todo) {
383
+ const record = await readRecord(ctx.stateDir, g.file);
384
+ if (!record)
385
+ continue;
386
+ let back = false;
387
+ const failed = await writeSettingsKey(g.file, (obj) => {
388
+ let out = obj;
389
+ if (record.removed) {
390
+ if (record.hadKey)
391
+ out = insertAt(out, ADVISOR_KEY, record.previous, record.index);
392
+ }
393
+ else if (record.hadKey)
394
+ out[ADVISOR_KEY] = record.previous;
395
+ else
396
+ delete out[ADVISOR_KEY];
397
+ const b = record.betas;
398
+ if (b) {
399
+ if (out.env === undefined)
400
+ out.env = { [BETAS_VAR]: b.previous };
401
+ else if (isObj(out.env) && !Object.hasOwn(out.env, BETAS_VAR))
402
+ out.env = insertAt(out.env, BETAS_VAR, b.previous, b.index);
403
+ }
404
+ back = isObj(out.env) && truthy(out.env[BETAS_VAR]);
405
+ return out;
406
+ }, (obj) => holds(obj, record) ? null : 'The setting was changed after sideby set it, so it was left alone.');
407
+ if (!failed)
408
+ await rm(keyRecordPath(ctx.stateDir, RECORDS, g.file), { force: true });
409
+ if (record.apiBetas) {
410
+ apiPrev ??= record.apiBetas.previous;
411
+ if (failed || !back)
412
+ apiBack = false;
413
+ }
414
+ results.push({ file: g.file, accounts: g.accounts, ok: !failed, message: failed ?? 'Put back.' });
415
+ }
416
+ // A file sideby did not put back keeps its record: its API Accounts still need the variable from sideby.
417
+ for (const g of groups)
418
+ if (g.apiAccounts?.length && !todo.includes(g) && (await readRecord(ctx.stateDir, g.file))?.apiBetas)
419
+ apiBack = false;
420
+ let apiOff = false;
421
+ if (apiPrev !== undefined && apiBack)
422
+ apiOff = await restoreApiBetas(opts.configFile, apiPrev).catch(() => false);
423
+ const ok = results.length > 0 && results.every((r) => r.ok);
424
+ return {
425
+ ok,
426
+ results,
427
+ unlocked: false,
428
+ ...(apiOff ? { apiBetas: false } : {}),
429
+ message: [
430
+ ok
431
+ ? 'Undone. New sessions go back to the previous advisor setting.'
432
+ : 'Some files could not be put back; see each line.',
433
+ apiOff
434
+ ? `sideby no longer adds ${BETAS_VAR} for API accounts; the settings file sets it for them again.`
435
+ : apiPrev !== undefined
436
+ ? `API accounts still get ${BETAS_VAR} from sideby, because a file they use still lacks it. \`sideby config set claude.apiBetasOff false\` stops that.`
437
+ : '',
438
+ ok && opts.unlock
439
+ ? 'sideby still unlocks /advisor at launch; `sideby advisor unlock off` stops that.'
440
+ : '',
441
+ ]
442
+ .filter(Boolean)
443
+ .join(' '),
444
+ };
445
+ }
446
+ /**
447
+ * Turns config `advisor.unlock` on or off. Off removes the key (and the section once it is empty). `ok: false` when it
448
+ * already was, so the CLI exits 1.
449
+ */
450
+ export async function setAdvisorUnlock(configFile, on) {
451
+ const r = await editConfigAdvisor(configFile, (c) => {
452
+ if (on)
453
+ return { ...c, unlock: true };
454
+ const { unlock: _drop, ...rest } = c;
455
+ return Object.keys(rest).length ? rest : undefined;
456
+ });
457
+ if (!r.changed)
458
+ return {
459
+ ok: false,
460
+ unlock: on,
461
+ message: on
462
+ ? 'sideby already unlocks /advisor at launch (nothing changed).'
463
+ : 'sideby already leaves /advisor to Claude Code (nothing changed).',
464
+ };
465
+ return {
466
+ ok: true,
467
+ unlock: on,
468
+ message: on
469
+ ? 'Done. Claude sessions sideby starts now offer /advisor; restart sessions that are already running.'
470
+ : 'Done. sideby no longer unlocks /advisor; Claude Code shows it only where Anthropic has turned it on. Restart sessions that are already running.',
471
+ };
472
+ }
@@ -62,6 +62,22 @@ export interface BrowserOpenResult {
62
62
  * Chrome lists in `Local State`.
63
63
  */
64
64
  export declare function openInBrowser(rt: Runtime, account: Account, profile?: string): Promise<BrowserOpenResult>;
65
+ export interface VendorPageOpen {
66
+ ref: string;
67
+ url: string;
68
+ /** The Browser Profile it opened in; left out when the default browser opened it. */
69
+ profile?: {
70
+ dir: string;
71
+ name: string;
72
+ };
73
+ command: string[];
74
+ }
75
+ /**
76
+ * Opens the page where a Limit Reset of `account` is spent (`FamilyDef.limitReset.vendorPage`, ADR-0072): in the
77
+ * Browser Profile the user chose for the Account, or the only one found signed in to it, else in the default browser.
78
+ * sideby never reads which login that browser has. The url passed the loader's https check; no other is opened.
79
+ */
80
+ export declare function openVendorPage(rt: Runtime, account: Account): Promise<VendorPageOpen>;
65
81
  export interface BrowserChoice {
66
82
  ref: string;
67
83
  /** The browser user now chosen, or null when sideby finds it again by itself. */
@@ -346,6 +346,51 @@ export async function openInBrowser(rt, account, profile) {
346
346
  command: [cmd, ...args],
347
347
  };
348
348
  }
349
+ /**
350
+ * Opens the page where a Limit Reset of `account` is spent (`FamilyDef.limitReset.vendorPage`, ADR-0072): in the
351
+ * Browser Profile the user chose for the Account, or the only one found signed in to it, else in the default browser.
352
+ * sideby never reads which login that browser has. The url passed the loader's https check; no other is opened.
353
+ */
354
+ export async function openVendorPage(rt, account) {
355
+ const url = account.kind === 'api' ? undefined : rt.families.get(account.family)?.limitReset?.vendorPage;
356
+ if (!url)
357
+ throw new UserError(`${account.ref} has no page for limit resets; check the vendor's own usage page`, {
358
+ code: 'no-limit-reset',
359
+ });
360
+ const deps = depsFor(rt);
361
+ const run = async (cmd, args) => (await deps.exec(cmd, args)).code === 0;
362
+ // The Account's own Browser Profile, when one is known without asking; any problem falls back to the default browser.
363
+ // Nothing of a browser is read unless the user chose a Browser Profile for this Account or turned Browser Sign-ins on.
364
+ const chosen = rt.config.browser?.choices?.[account.ref];
365
+ const findIt = rt.config.browser?.signIns === true;
366
+ if ((deps.platform === 'darwin' || deps.wslMount) && (chosen || findIt)) {
367
+ const problems = [];
368
+ const launch = await chromeLauncher(deps, problems).catch(() => null);
369
+ const entries = launch
370
+ ? ((await profileEntries(launch.userData ?? chromeUserData(rt.paths.home), problems)) ?? [])
371
+ : [];
372
+ let pick = chosen ? entries.find((e) => e.dir === chosen) : undefined;
373
+ if (launch && !pick && findIt) {
374
+ const found = (await browserReport(rt, [account]).catch(() => undefined))?.profiles.filter((p) => p.signIns.includes(account.ref));
375
+ if (found?.length === 1)
376
+ pick = entries.find((e) => e.dir === found[0]?.dir);
377
+ }
378
+ if (launch && pick) {
379
+ const [cmd, ...args] = launch.command(`--profile-directory=${pick.dir}`, url);
380
+ if (await run(cmd, args))
381
+ return {
382
+ ref: account.ref,
383
+ url,
384
+ profile: { dir: pick.dir, name: pick.name },
385
+ command: [cmd, ...args],
386
+ };
387
+ }
388
+ }
389
+ const command = deps.platform === 'darwin' ? [OPEN, url] : ['xdg-open', url];
390
+ if (!(await run(command[0], command.slice(1))))
391
+ throw new UserError(`could not open a browser; open ${url} yourself`, { code: 'open-failed' });
392
+ return { ref: account.ref, url, command };
393
+ }
349
394
  /** The browser user `profile` names: its folder, else its name or Google account, which must be unique. */
350
395
  function findProfile(entries, profile) {
351
396
  const byDir = entries.find((e) => e.dir === profile);
@@ -87,6 +87,18 @@ export const CLI_COMMANDS = [
87
87
  },
88
88
  example: 'sideby model claude:work',
89
89
  },
90
+ {
91
+ id: 'advisor',
92
+ group: 'accounts',
93
+ usage: 'sideby advisor [fable|opus|sonnet|off|undo] [--account <account>] [--yes]',
94
+ help: "let Claude ask a stronger model for advice at key moments: sets Claude Code's advisor in every Claude settings file and unlocks /advisor in sessions sideby starts (shows the change first; unlock on|off toggles only the unlocking)",
95
+ summary: {
96
+ en: 'Let Claude ask a stronger model for advice at key moments',
97
+ zh: '让 Claude 在关键时刻请教更强的模型',
98
+ },
99
+ example: 'sideby advisor opus',
100
+ feature: 'setting.advisor',
101
+ },
90
102
  {
91
103
  id: 'edit',
92
104
  group: 'accounts',
@@ -331,6 +343,18 @@ export const CLI_COMMANDS = [
331
343
  help: 'undo it, restoring the original file',
332
344
  summary: { en: 'Undo the Claude quota setup', zh: '撤销 Claude 额度设置,恢复原文件' },
333
345
  },
346
+ {
347
+ id: 'quota.reset',
348
+ group: 'quota',
349
+ usage: 'sideby quota reset <account> [--yes] [--operation <id>] [--open]',
350
+ help: 'use a limit reset: shows the plan first, --yes uses one (cannot be undone); for Claude Code it names the page on claude.ai and --open opens it',
351
+ summary: {
352
+ en: 'Use a limit reset (shows the plan first; cannot be undone)',
353
+ zh: '使用一次重置(先给你看计划;用了不能撤销)',
354
+ },
355
+ example: 'sideby quota reset codex:main',
356
+ feature: 'action.limit-reset',
357
+ },
334
358
  {
335
359
  id: 'quota.check',
336
360
  group: 'quota',
@@ -828,7 +852,7 @@ export function cliHelp(list = CLI_COMMANDS) {
828
852
  return parts.join('\n');
829
853
  }
830
854
  const HELP_TAIL = `Options:
831
- --json machine-readable output (list, new, next, alias, doctor, quota, tune, model, remote-control, handoff,
855
+ --json machine-readable output (list, new, next, alias, doctor, quota, tune, model, advisor, remote-control, handoff,
832
856
  families, commands, plugins, app, desktop, sessions, history, send, messages, edit, browser, update, local, ask,
833
857
  terminal, key, try, autostart, menubar, config, network, unattended)
834
858
  -h, --help show this help; \`sideby <command> --help\` for new, alias, login, doctor, families, commands, desktop, edit, browser,
@@ -118,6 +118,12 @@ export declare const ConfigSchema: Type.TObject<{
118
118
  guard: Type.TOptional<Type.TBoolean>;
119
119
  allow: Type.TOptional<Type.TArray<Type.TString>>;
120
120
  }>>;
121
+ advisor: Type.TOptional<Type.TObject<{
122
+ unlock: Type.TOptional<Type.TBoolean>;
123
+ }>>;
124
+ claude: Type.TOptional<Type.TObject<{
125
+ apiBetasOff: Type.TOptional<Type.TBoolean>;
126
+ }>>;
121
127
  unattended: Type.TOptional<Type.TObject<{
122
128
  schedule: Type.TOptional<Type.TArray<Type.TObject<{
123
129
  name: Type.TOptional<Type.TString>;
@@ -187,6 +193,29 @@ export declare function editConfigNetwork(file: string, edit: (current: NetworkC
187
193
  before: NetworkConfig | undefined;
188
194
  after: NetworkConfig | undefined;
189
195
  }>;
196
+ export type AdvisorConfig = NonNullable<Config['advisor']>;
197
+ /**
198
+ * `sideby advisor` and the Panel's Advisor dialog (spec §3.41): changes the config `advisor` key with `edit` (see
199
+ * `editConfigKey` for how the file is written); `edit` returns undefined to remove the section. With `dryRun`, shows
200
+ * the change without writing.
201
+ */
202
+ export declare function editConfigAdvisor(file: string, edit: (current: AdvisorConfig) => AdvisorConfig | undefined, opts?: {
203
+ dryRun?: boolean;
204
+ }): Promise<{
205
+ changed: boolean;
206
+ before: AdvisorConfig | undefined;
207
+ after: AdvisorConfig | undefined;
208
+ }>;
209
+ export type ClaudeConfig = NonNullable<Config['claude']>;
210
+ /**
211
+ * The config `claude` key (spec §3.41): changed with `edit` (see `editConfigKey` for how the file is written); `edit`
212
+ * returns undefined to remove the section, or null to leave the file as it is.
213
+ */
214
+ export declare function editConfigClaude(file: string, edit: (current: ClaudeConfig) => ClaudeConfig | undefined | null): Promise<{
215
+ changed: boolean;
216
+ before: ClaudeConfig | undefined;
217
+ after: ClaudeConfig | undefined;
218
+ }>;
190
219
  export type UnattendedConfig = NonNullable<Config['unattended']>;
191
220
  /**
192
221
  * `sideby unattended on|schedule …` (spec §3.37): changes the config `unattended` key with `edit` (see `editConfigKey`