sideby 0.35.8 → 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 (71) 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/after-install.js +11 -4
  11. package/dist/src/core/ask.d.ts +6 -1
  12. package/dist/src/core/ask.js +16 -5
  13. package/dist/src/core/browser-profiles.d.ts +16 -0
  14. package/dist/src/core/browser-profiles.js +45 -0
  15. package/dist/src/core/cli-commands.js +25 -1
  16. package/dist/src/core/config.d.ts +29 -0
  17. package/dist/src/core/config.js +25 -0
  18. package/dist/src/core/handoff-select.d.ts +13 -2
  19. package/dist/src/core/handoff-select.js +6 -2
  20. package/dist/src/core/launch.d.ts +4 -0
  21. package/dist/src/core/launch.js +7 -0
  22. package/dist/src/core/limit-reset.d.ts +198 -0
  23. package/dist/src/core/limit-reset.js +299 -0
  24. package/dist/src/core/local-build.d.ts +4 -3
  25. package/dist/src/core/local-build.js +6 -4
  26. package/dist/src/core/quota-fetch.d.ts +57 -2
  27. package/dist/src/core/quota-fetch.js +291 -13
  28. package/dist/src/core/quota-levels.d.ts +70 -0
  29. package/dist/src/core/quota-levels.js +80 -0
  30. package/dist/src/core/quota-store.d.ts +15 -1
  31. package/dist/src/core/quota-store.js +26 -1
  32. package/dist/src/core/same-login.d.ts +8 -0
  33. package/dist/src/core/same-login.js +39 -2
  34. package/dist/src/core/search-catalog.js +38 -0
  35. package/dist/src/families/claude/index.js +2 -0
  36. package/dist/src/families/codex/index.js +3 -1
  37. package/dist/src/families/codex/quota.d.ts +23 -1
  38. package/dist/src/families/codex/quota.js +122 -21
  39. package/dist/src/families/grok/quota-log.d.ts +1 -0
  40. package/dist/src/menubar/script.js +70 -18
  41. package/dist/src/menubar/snapshot.d.ts +33 -1
  42. package/dist/src/menubar/snapshot.js +79 -11
  43. package/dist/src/menubar/strings.d.ts +16 -0
  44. package/dist/src/menubar/strings.js +16 -0
  45. package/dist/src/panel/handler.d.ts +21 -0
  46. package/dist/src/panel/handler.js +111 -9
  47. package/dist/src/panel/i18n.d.ts +87 -0
  48. package/dist/src/panel/i18n.js +174 -0
  49. package/dist/src/panel/page-logic.d.ts +17 -0
  50. package/dist/src/panel/page-logic.js +23 -0
  51. package/dist/src/panel/page-script.js +440 -19
  52. package/dist/src/panel/page-styles.js +38 -2
  53. package/dist/src/plugins/loader.d.ts +2 -0
  54. package/dist/src/plugins/loader.js +27 -0
  55. package/dist/src/runtime.d.ts +63 -1
  56. package/dist/src/runtime.js +529 -9
  57. package/dist/src/types.d.ts +67 -0
  58. package/package.json +1 -1
  59. package/schemas/advisor.json +332 -0
  60. package/schemas/config.json +22 -0
  61. package/schemas/error.json +4 -0
  62. package/schemas/menubar-reset.json +93 -0
  63. package/schemas/menubar-snapshot.json +70 -2
  64. package/schemas/quota-reset.json +369 -0
  65. package/schemas/quota.json +30 -0
  66. package/schemas/update.json +4 -0
  67. package/skills/sideby/SKILL.md +6 -2
  68. package/skills/sideby/references/ai-tasks.md +1 -1
  69. package/skills/sideby/references/panel.md +14 -0
  70. package/skills/sideby/references/quota.md +27 -0
  71. 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
+ }
@@ -1,4 +1,4 @@
1
- import { SKILL_UPDATE } from './skill-check.js';
1
+ import { SKILL_INSTALL, SKILL_UPDATE } from './skill-check.js';
2
2
  /**
3
3
  * The skill step the new code runs by name. `--skill` updates only the installed skill: it never installs the CLI,
4
4
  * even when the registry has moved on since the user confirmed.
@@ -12,9 +12,16 @@ export async function runSkillUpdate(m, plan, env, onOutput) {
12
12
  const r = await m
13
13
  .exec(file, args, { env, ...(onOutput ? { onOutput } : {}) })
14
14
  .catch((e) => ({ code: 1, output: e instanceof Error ? e.message : String(e) }));
15
- return r.code === 0
16
- ? { ok: true, message: 'updated the sideby skill' }
17
- : { ok: false, message: `\`${plan.command}\` failed (exit ${r.code}); run it yourself to see why` };
15
+ if (r.code !== 0)
16
+ return { ok: false, message: `\`${plan.command}\` failed (exit ${r.code}); run it yourself to see why` };
17
+ // The skills tool exits 0 when its install record does not list the skill: it changed nothing, and the skill is
18
+ // as old as before.
19
+ if (/No installed skills found/i.test(r.output))
20
+ return {
21
+ ok: false,
22
+ message: `the skills tool does not list the sideby skill as one it installed, so it updated nothing; run \`${SKILL_INSTALL}\` to install the current one`,
23
+ };
24
+ return { ok: true, message: 'updated the sideby skill' };
18
25
  }
19
26
  async function autostartByName(m, home, env) {
20
27
  // Never created here: only a login item `sideby autostart on` wrote is refreshed (ADR-0029).
@@ -62,7 +62,12 @@ export declare function taskStateDir(dir: string): Promise<string>;
62
62
  * `<promptArg>=<prompt>` instead, since its Host refuses a positional prompt.
63
63
  */
64
64
  export declare function taskHostArgs(rt: Runtime, task: TaskFile): Promise<string[]>;
65
- /** `env` with the HOME and XDG folders the task was written under, so the Runtime sees what the Panel saw. */
65
+ /**
66
+ * `env` with the HOME and XDG folders the task was written under, so the Runtime sees what the Panel saw. A folder at
67
+ * its default place under that HOME gets no variable (paths.ts reads an unset one as the default): the whole session
68
+ * inherits this, and other tools change where they keep their files once an XDG variable is set. Only a value the
69
+ * terminal already has for that same folder stays.
70
+ */
66
71
  export declare function taskEnv(task: TaskFile, env: Env): Env;
67
72
  export declare function readTask(id: string, paths?: Pick<Paths, 'stateDir'>): Promise<TaskFile>;
68
73
  export declare function terminals(rt: Runtime): Promise<{
@@ -2,7 +2,7 @@ import { randomBytes } from 'node:crypto';
2
2
  import { constants } from 'node:fs';
3
3
  import { lstat, mkdtemp, open, readdir, realpath, rm, stat, unlink } from 'node:fs/promises';
4
4
  import { userInfo } from 'node:os';
5
- import { dirname, isAbsolute, join, sep } from 'node:path';
5
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
6
6
  import { MODEL_NAME, takeFlag } from '../families/shared/model-args.js';
7
7
  import { AI_TASK_KINDS, stripSecrets, taskPrompt } from '../panel/page-logic.js';
8
8
  import { checkAttachmentFiles, copyAttachments, MAX_ATTACHMENTS, privateDir, removeOldAttachments, stagedAttachments, takeStaged, } from './attachments.js';
@@ -155,15 +155,26 @@ export async function taskHostArgs(rt, task) {
155
155
  const prompt = task.prompt ?? '';
156
156
  return [...images, family?.promptArg ? `${family.promptArg}=${prompt}` : prompt];
157
157
  }
158
- /** `env` with the HOME and XDG folders the task was written under, so the Runtime sees what the Panel saw. */
158
+ /**
159
+ * `env` with the HOME and XDG folders the task was written under, so the Runtime sees what the Panel saw. A folder at
160
+ * its default place under that HOME gets no variable (paths.ts reads an unset one as the default): the whole session
161
+ * inherits this, and other tools change where they keep their files once an XDG variable is set. Only a value the
162
+ * terminal already has for that same folder stays.
163
+ */
159
164
  export function taskEnv(task, env) {
160
165
  if (!task.home || !task.configDir || !task.stateDir)
161
166
  return env;
167
+ const { XDG_CONFIG_HOME: config, XDG_STATE_HOME: state, ...rest } = env;
168
+ const configBase = dirname(task.configDir);
169
+ const stateBase = dirname(task.stateDir);
170
+ // The same folder however the terminal spells it (`…/state/`, `…/./state`), not the same string.
171
+ const sameDir = (a, b) => isAbsolute(a) && resolve(a) === resolve(b);
172
+ const named = (dir, byDefault, had) => !sameDir(byDefault, dir) || (had !== undefined && sameDir(had, dir));
162
173
  return {
163
- ...env,
174
+ ...rest,
164
175
  HOME: task.home,
165
- XDG_CONFIG_HOME: dirname(task.configDir),
166
- XDG_STATE_HOME: dirname(task.stateDir),
176
+ ...(named(configBase, join(task.home, '.config'), config) ? { XDG_CONFIG_HOME: configBase } : {}),
177
+ ...(named(stateBase, join(task.home, '.local', 'state'), state) ? { XDG_STATE_HOME: stateBase } : {}),
167
178
  };
168
179
  }
169
180
  export async function readTask(id, paths = resolvePaths()) {
@@ -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);