sideby 0.21.0 → 0.23.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 (97) hide show
  1. package/README.md +1 -0
  2. package/ai-tasks.json +14 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +7 -0
  5. package/dist/src/cli/commands.js +441 -31
  6. package/dist/src/cli/format.js +3 -2
  7. package/dist/src/cli/json-schemas.js +157 -47
  8. package/dist/src/cli/main.js +38 -7
  9. package/dist/src/core/accounts.d.ts +6 -1
  10. package/dist/src/core/accounts.js +16 -3
  11. package/dist/src/core/ask.d.ts +2 -1
  12. package/dist/src/core/ask.js +12 -4
  13. package/dist/src/core/claude-settings-file.d.ts +57 -0
  14. package/dist/src/core/claude-settings-file.js +104 -2
  15. package/dist/src/core/config.d.ts +34 -16
  16. package/dist/src/core/config.js +58 -5
  17. package/dist/src/core/create.js +4 -1
  18. package/dist/src/core/desktop-app.js +5 -1
  19. package/dist/src/core/handoff-overview.d.ts +4 -1
  20. package/dist/src/core/handoff-overview.js +3 -2
  21. package/dist/src/core/handoff-rules.d.ts +34 -0
  22. package/dist/src/core/handoff-rules.js +115 -0
  23. package/dist/src/core/handoff-select.js +45 -28
  24. package/dist/src/core/handoff-status.d.ts +37 -7
  25. package/dist/src/core/handoff-status.js +95 -19
  26. package/dist/src/core/handoff.d.ts +4 -1
  27. package/dist/src/core/handoff.js +8 -5
  28. package/dist/src/core/inbound.d.ts +11 -3
  29. package/dist/src/core/inbound.js +26 -74
  30. package/dist/src/core/launch.js +6 -4
  31. package/dist/src/core/quota-levels.d.ts +13 -2
  32. package/dist/src/core/quota-levels.js +21 -3
  33. package/dist/src/core/remote-control.d.ts +10 -12
  34. package/dist/src/core/remote-control.js +29 -86
  35. package/dist/src/core/themes.d.ts +107 -0
  36. package/dist/src/core/themes.js +463 -0
  37. package/dist/src/core/tuning-apply.js +12 -20
  38. package/dist/src/families/agy/index.d.ts +8 -0
  39. package/dist/src/families/agy/index.js +53 -0
  40. package/dist/src/families/agy/quota.d.ts +9 -0
  41. package/dist/src/families/agy/quota.js +110 -0
  42. package/dist/src/families/index.js +7 -0
  43. package/dist/src/families/logos.d.ts +10 -0
  44. package/dist/src/families/logos.js +12 -1
  45. package/dist/src/menubar/script.js +26 -3
  46. package/dist/src/menubar/snapshot.d.ts +33 -6
  47. package/dist/src/menubar/snapshot.js +138 -43
  48. package/dist/src/menubar/strings.d.ts +18 -2
  49. package/dist/src/menubar/strings.js +18 -2
  50. package/dist/src/panel/handler.d.ts +4 -1
  51. package/dist/src/panel/handler.js +206 -46
  52. package/dist/src/panel/i18n.d.ts +106 -7
  53. package/dist/src/panel/i18n.js +260 -62
  54. package/dist/src/panel/page-logic.d.ts +67 -20
  55. package/dist/src/panel/page-logic.js +74 -7
  56. package/dist/src/panel/page-script.js +522 -124
  57. package/dist/src/panel/page-styles.d.ts +2 -0
  58. package/dist/src/panel/page-styles.js +157 -34
  59. package/dist/src/panel/page.js +3 -3
  60. package/dist/src/panel/theme.d.ts +6 -1
  61. package/dist/src/panel/theme.js +4 -0
  62. package/dist/src/panel/themes.d.ts +14 -0
  63. package/dist/src/panel/themes.js +162 -0
  64. package/dist/src/plugins/check.js +27 -13
  65. package/dist/src/plugins/loader.d.ts +11 -0
  66. package/dist/src/plugins/loader.js +47 -1
  67. package/dist/src/runtime.d.ts +9 -2
  68. package/dist/src/runtime.js +12 -5
  69. package/dist/src/types.d.ts +35 -5
  70. package/package.json +2 -2
  71. package/schemas/config.json +45 -2
  72. package/schemas/families.json +13 -5
  73. package/schemas/handoff-disable.json +22 -0
  74. package/schemas/handoff-enable.json +22 -0
  75. package/schemas/handoff-rules.json +302 -0
  76. package/schemas/handoff-status.json +26 -0
  77. package/schemas/hide.json +157 -0
  78. package/schemas/list.json +15 -0
  79. package/schemas/menubar-snapshot.json +309 -2
  80. package/schemas/order.json +26 -1
  81. package/schemas/pin.json +17 -0
  82. package/schemas/theme-check.json +140 -0
  83. package/schemas/theme-export.json +86 -0
  84. package/schemas/theme-import.json +92 -0
  85. package/schemas/theme-preview.json +86 -0
  86. package/schemas/theme-remove.json +87 -0
  87. package/schemas/theme-use.json +88 -0
  88. package/schemas/theme.json +137 -0
  89. package/schemas/unhide.json +157 -0
  90. package/schemas/unpin.json +17 -0
  91. package/skills/sideby/SKILL.md +5 -2
  92. package/skills/sideby/references/accounts.md +1 -0
  93. package/skills/sideby/references/ai-tasks.md +1 -1
  94. package/skills/sideby/references/handoff.md +7 -3
  95. package/skills/sideby/references/panel.md +9 -0
  96. package/skills/sideby/references/quota.md +3 -1
  97. package/skills/sideby/references/themes.md +47 -0
@@ -1,5 +1,5 @@
1
1
  import { planHandoff } from './handoff.js';
2
- import { windowReset } from './quota-levels.js';
2
+ import { takeoverLimit, windowReset } from './quota-levels.js';
3
3
  const domain = (email) => email.slice(email.lastIndexOf('@') + 1).toLowerCase();
4
4
  /** Organizations when both have one, else email domains when both have one, else the same. */
5
5
  export function sameOrganization(a, b) {
@@ -34,22 +34,17 @@ function waitUntil(origin, s, now, ahead) {
34
34
  return new Date(last).toISOString();
35
35
  }
36
36
  /**
37
- * One candidate's §3.13 state; API accounts are pickable here, as the last resort. An Account already at the user's
38
- * threshold counts as full even below §3.13's 85%, or it would hand over again on its first tool call.
37
+ * One candidate's §3.13 state; API accounts are pickable here, as the last resort. An Account at or above the
38
+ * Takeover Limit counts as full, so the next Account starts with room to work (spec §3.17 "接力规则").
39
39
  */
40
40
  function stateOf(c, s, now) {
41
- const e = planHandoff(c.family, [c], now, { includeApi: true }).accounts[0];
42
- if (e.state !== 'ready' || e.pressure === null || e.pressure < s.threshold || c.quota.status !== 'ok')
43
- return e;
44
- const resets = c.quota.windows
45
- .filter((w) => w.usedPercent >= s.threshold && !windowReset(w.resetsAt, now))
46
- .map((w) => Date.parse(w.resetsAt))
47
- .filter(Number.isFinite);
48
- return {
49
- ...e,
50
- state: 'full',
51
- ...(resets.length ? { resetsAt: new Date(Math.max(...resets)).toISOString() } : {}),
52
- };
41
+ return planHandoff(c.family, [c], now, { includeApi: true, fullAt: takeoverLimit(s.threshold) })
42
+ .accounts[0];
43
+ }
44
+ /** Families in the order `otherFamilies` tries them: `familyOrder` first, then the rest as the candidates come. */
45
+ function familiesInOrder(s, candidates) {
46
+ const seen = [...new Set(candidates.map((c) => c.family))];
47
+ return [...new Set([...s.familyOrder.filter((f) => seen.includes(f)), ...seen])];
53
48
  }
54
49
  export function selectNext(input) {
55
50
  const { origin, settings: s, now } = input;
@@ -67,15 +62,22 @@ export function selectNext(input) {
67
62
  const allowed = new Set(s.crossOrganization.map(refOf));
68
63
  const used = new Set([origin.ref, ...input.used]);
69
64
  const family = s.families[origin.family];
65
+ const fullAt = takeoverLimit(s.threshold);
66
+ const rank = (fam) => planHandoff(fam, input.candidates.filter((c) => c.family === fam), now, { includeApi: true, fullAt }).accounts.map((e) => byRef.get(e.ref));
70
67
  let list;
71
68
  if (family?.policy === 'order') {
72
69
  list = family.order.map(refOf).flatMap((r) => (byRef.has(r) ? [byRef.get(r)] : []));
73
70
  }
74
71
  else {
75
- // The Family by §3.13's ranking, then other Families' API accounts.
76
- const own = input.candidates.filter((c) => c.family === origin.family);
77
- const ranked = planHandoff(origin.family, own, now, { includeApi: true }).accounts.map((e) => byRef.get(e.ref));
78
- list = [...ranked, ...input.candidates.filter((c) => c.family !== origin.family && c.kind === 'api')];
72
+ // The Family by §3.13's ranking; with `otherFamilies`, every other Family's subscriptions the same way, Family by
73
+ // Family; API accounts last, the origin's Family first (spec §3.17 "接力规则").
74
+ const families = familiesInOrder(s, input.candidates).filter((f) => f !== origin.family);
75
+ const ranked = [origin.family, ...families].map((f) => ({ f, list: rank(f) }));
76
+ list = [
77
+ ...ranked[0].list.filter((c) => c.kind !== 'api'),
78
+ ...(s.otherFamilies ? ranked.slice(1).flatMap((r) => r.list.filter((c) => c.kind !== 'api')) : []),
79
+ ...ranked.flatMap((r) => r.list.filter((c) => c.kind === 'api')),
80
+ ];
79
81
  }
80
82
  // The same login shares the origin's Quota, so taking over there gains nothing (spec §3.21).
81
83
  const sameLogin = new Set(origin.sameLogin ?? []);
@@ -83,12 +85,12 @@ export function selectNext(input) {
83
85
  .filter((c) => sameLogin.has(c.ref))
84
86
  .map((c) => ({ ref: c.ref, reason: `same login as ${origin.ref}, so it shares the same quota` }));
85
87
  const withSkipped = skipped.length ? { skipped } : {};
86
- const eligible = list.filter((c) => !sameLogin.has(c.ref) &&
87
- !used.has(c.ref) &&
88
- c.installed &&
89
- c.receive &&
90
- // An API account pays per request, so it gets past no vendor's limit: sameFamily does not apply to it.
91
- (s.sameFamily || c.family !== origin.family || c.kind === 'api') &&
88
+ // Could take over if the settings allowed it: another login, its Host installed and able to receive.
89
+ const couldTake = (c) => !sameLogin.has(c.ref) && !used.has(c.ref) && c.installed && c.receive;
90
+ const eligible = list.filter((c) => couldTake(c) &&
91
+ // An API account pays per request, so it gets past no vendor's limit: sameFamily does not apply to it, but it
92
+ // takes over only when the user allowed paying for it (`api`, ADR-0046).
93
+ (c.kind === 'api' ? s.api : s.sameFamily || c.family !== origin.family) &&
92
94
  (allowed.has(c.ref) || sameOrganization(origin.identity, c.identity)));
93
95
  const states = eligible.map((c) => ({ c, e: stateOf(c, s, now) }));
94
96
  const first = states.find(({ e }) => e.state === 'ready' || e.state === 'unknown') ??
@@ -98,11 +100,26 @@ export function selectNext(input) {
98
100
  const full = states
99
101
  .filter(({ e }) => e.state === 'full' && e.resetsAt)
100
102
  .sort((a, b) => Date.parse(a.e.resetsAt) - Date.parse(b.e.resetsAt))[0];
103
+ // Say what the user could allow, so "none" is never a dead end; only settings that would bring in an account
104
+ // that can really take over.
105
+ const notAllowed = [
106
+ !s.sameFamily &&
107
+ list.some((c) => c.family === origin.family && c.kind !== 'api' && c.ref !== origin.ref && couldTake(c))
108
+ ? 'accounts of the same AI (`handoff.sameFamily`)'
109
+ : null,
110
+ !s.otherFamilies &&
111
+ family?.policy !== 'order' &&
112
+ input.candidates.some((c) => c.family !== origin.family && c.kind !== 'api' && couldTake(c))
113
+ ? 'other AIs (`handoff.otherFamilies`)'
114
+ : null,
115
+ !s.api && list.some((c) => c.kind === 'api' && couldTake(c)) ? 'API accounts (`handoff.api`)' : null,
116
+ ].filter(Boolean);
117
+ const why = eligible.length
118
+ ? 'every account that may take over is full or signed out'
119
+ : 'no account may take over';
101
120
  return {
102
121
  kind: 'none',
103
- reason: eligible.length
104
- ? 'every account that may take over is full or signed out'
105
- : 'no account may take over',
122
+ reason: notAllowed.length ? `${why}; not allowed now: ${notAllowed.join(', ')}` : why,
106
123
  ...(full ? { earliestReset: { ref: full.c.ref, at: full.e.resetsAt } } : {}),
107
124
  ...withSkipped,
108
125
  };
@@ -1,5 +1,6 @@
1
1
  import type { Runtime } from '../runtime.ts';
2
- import { type HandoffSettings } from './config.ts';
2
+ import type { Account } from '../types.ts';
3
+ import { type HandoffConfig, type HandoffSettings } from './config.ts';
3
4
  export interface HandoffFamilyStatus {
4
5
  family: string;
5
6
  /** What the Family can start; empty when it can only take over. */
@@ -31,21 +32,48 @@ export interface HandoffStatus {
31
32
  }
32
33
  export declare function handoffStatus(rt: Runtime): Promise<HandoffStatus>;
33
34
  /** One `handoff` change; fields left out keep their value. The Panel and the CLI send the same shape. */
35
+ /** A `handoff` change; for a single setting, null removes the key so the default applies again. */
34
36
  export interface HandoffChange {
35
- auto?: boolean;
36
- sameFamily?: boolean;
37
- prepareAt?: number;
38
- threshold?: number;
39
- waitIfResetWithinMinutes?: number;
40
- countdownSeconds?: number;
37
+ auto?: boolean | null;
38
+ sameFamily?: boolean | null;
39
+ otherFamilies?: boolean | null;
40
+ /** Families `otherFamilies` tries, first to last. */
41
+ familyOrder?: string[];
42
+ /** Null leaves the question open again (ADR-0046). */
43
+ api?: boolean | null;
44
+ adaptive?: boolean | null;
45
+ /** Accounts that may take over across organizations; an empty list removes the key. */
46
+ crossOrganization?: string[];
47
+ prepareAt?: number | null;
48
+ threshold?: number | null;
49
+ waitIfResetWithinMinutes?: number | null;
50
+ countdownSeconds?: number | null;
41
51
  /** Handoff Orders by Family; an empty list sends that Family back to ranking by quota. */
42
52
  orders?: {
43
53
  family: string;
44
54
  order: string[];
45
55
  }[];
46
56
  }
57
+ /**
58
+ * The change that puts back what `change` replaced, read from the config as it was: a key that was not there comes
59
+ * back as null (or an empty list), so undoing removes it instead of writing its default.
60
+ */
61
+ export declare function handoffUndo(before: HandoffConfig | undefined, change: HandoffChange): HandoffChange;
47
62
  /** A line diff of two small texts: unchanged lines start with two spaces, removed with `- `, added with `+ `. */
48
63
  export declare function lineDiff(before: string, after: string): string;
64
+ /** What `checkHandoffRefs` resolves names against: the Families, the Accounts and the short commands. */
65
+ export interface HandoffRefs {
66
+ families: readonly string[];
67
+ accounts: readonly Account[];
68
+ aliases: Readonly<Record<string, string>>;
69
+ }
70
+ export declare function handoffRefs(rt: Runtime): Promise<HandoffRefs>;
71
+ /**
72
+ * Refuses a `handoff` setting that names a Family or an Account that does not exist: a Family's Handoff Order,
73
+ * `familyOrder` and `crossOrganization`, each checked only when it changed from `before`, so an old name that has
74
+ * since gone away does not block an unrelated change. The Panel, `sideby handoff` and `sideby config set` all use it.
75
+ */
76
+ export declare function checkHandoffRefs(refs: HandoffRefs, before: HandoffConfig | undefined, after: HandoffConfig | undefined): void;
49
77
  /**
50
78
  * Shows, or with `apply` writes, the `handoff` change (spec §3.17). Every other setting stays. Names in `order`
51
79
  * must resolve to an Account.
@@ -58,6 +86,8 @@ export declare function configureHandoff(rt: Runtime, change: HandoffChange, opt
58
86
  file: string;
59
87
  diff: string;
60
88
  settings: HandoffSettings;
89
+ /** The change that puts the old settings back. */
90
+ undo: HandoffChange;
61
91
  }>;
62
92
  /**
63
93
  * After a session ends with Auto Handoff off: one line pointing at it when the Account's quota passed the threshold
@@ -2,7 +2,8 @@
2
2
  // and the one config change that turns it on or off. Status only reads; enable and disable write the `handoff` key.
3
3
  import { join } from 'node:path';
4
4
  import { HOOK_FAMILIES } from '../handoff/hook.js';
5
- import { editConfigHandoff, handoffSettings } from './config.js';
5
+ import { resolveRef } from './accounts.js';
6
+ import { aliasRefs, editConfigHandoff, handoffSettings, } from './config.js';
6
7
  import { UserError } from './errors.js';
7
8
  import { ensureChainDir, readJsonFile, writeJsonFile } from './handoff-chain.js';
8
9
  import { hookEntryWorks } from './handoff-run.js';
@@ -99,6 +100,37 @@ export async function handoffStatus(rt) {
99
100
  nextSteps: steps,
100
101
  };
101
102
  }
103
+ const SINGLE_KEYS = [
104
+ 'auto',
105
+ 'sameFamily',
106
+ 'otherFamilies',
107
+ 'api',
108
+ 'adaptive',
109
+ 'prepareAt',
110
+ 'threshold',
111
+ 'waitIfResetWithinMinutes',
112
+ 'countdownSeconds',
113
+ ];
114
+ /**
115
+ * The change that puts back what `change` replaced, read from the config as it was: a key that was not there comes
116
+ * back as null (or an empty list), so undoing removes it instead of writing its default.
117
+ */
118
+ export function handoffUndo(before, change) {
119
+ const b = before ?? {};
120
+ const undo = {};
121
+ for (const k of SINGLE_KEYS)
122
+ if (change[k] !== undefined)
123
+ undo[k] = b[k] === undefined ? null : b[k];
124
+ for (const k of ['familyOrder', 'crossOrganization'])
125
+ if (change[k] !== undefined)
126
+ undo[k] = [...(b[k] ?? [])];
127
+ if (change.orders?.length)
128
+ undo.orders = change.orders.map(({ family }) => {
129
+ const cur = b.families?.[family];
130
+ return { family, order: cur?.policy === 'order' ? [...(cur.order ?? [])] : [] };
131
+ });
132
+ return undo;
133
+ }
102
134
  /** A line diff of two small texts: unchanged lines start with two spaces, removed with `- `, added with `+ `. */
103
135
  export function lineDiff(before, after) {
104
136
  const a = before.split('\n');
@@ -129,33 +161,75 @@ export function lineDiff(before, after) {
129
161
  }
130
162
  return out.join('\n');
131
163
  }
164
+ export async function handoffRefs(rt) {
165
+ return {
166
+ families: [...rt.families.keys()],
167
+ accounts: await rt.accounts(),
168
+ aliases: aliasRefs(rt.config.aliases),
169
+ };
170
+ }
171
+ const unknownFamily = (families, family) => new UserError(`unknown family "${family}"; available: ${[...families].join(', ')}`);
172
+ /**
173
+ * Refuses a `handoff` setting that names a Family or an Account that does not exist: a Family's Handoff Order,
174
+ * `familyOrder` and `crossOrganization`, each checked only when it changed from `before`, so an old name that has
175
+ * since gone away does not block an unrelated change. The Panel, `sideby handoff` and `sideby config set` all use it.
176
+ */
177
+ export function checkHandoffRefs(refs, before, after) {
178
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
179
+ const missing = [];
180
+ const check = (names) => {
181
+ for (const name of names)
182
+ try {
183
+ resolveRef(name, refs.accounts, refs.aliases);
184
+ }
185
+ catch {
186
+ if (!missing.includes(name))
187
+ missing.push(name);
188
+ }
189
+ };
190
+ for (const [family, entry] of Object.entries(after?.families ?? {})) {
191
+ if (same(entry, before?.families?.[family]))
192
+ continue;
193
+ if (!refs.families.includes(family))
194
+ throw unknownFamily(refs.families, family);
195
+ check(entry.order ?? []);
196
+ }
197
+ if (!same(after?.familyOrder, before?.familyOrder))
198
+ for (const f of after?.familyOrder ?? [])
199
+ if (!refs.families.includes(f))
200
+ throw unknownFamily(refs.families, f);
201
+ if (!same(after?.crossOrganization, before?.crossOrganization))
202
+ check(after?.crossOrganization ?? []);
203
+ if (!missing.length)
204
+ return;
205
+ const known = [...refs.accounts.map((a) => a.ref), ...Object.keys(refs.aliases)];
206
+ throw new UserError(`${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} not an account or short command; use one of: ${known.join(', ')}`, { code: 'unknown-account' });
207
+ }
132
208
  const pretty = (v) => JSON.stringify(v ?? {}, null, 2);
133
209
  /**
134
210
  * Shows, or with `apply` writes, the `handoff` change (spec §3.17). Every other setting stays. Names in `order`
135
211
  * must resolve to an Account.
136
212
  */
137
213
  export async function configureHandoff(rt, change, opts) {
138
- const known = [...(await rt.accounts()).map((a) => a.ref), ...Object.keys(rt.config.aliases ?? {})];
139
- for (const { family, order } of change.orders ?? []) {
214
+ for (const { family } of change.orders ?? [])
140
215
  if (!rt.families.has(family))
141
- throw new UserError(`unknown family "${family}"; available: ${[...rt.families.keys()].join(', ')}`);
142
- const missing = [];
143
- for (const name of order)
144
- await rt.resolve(name).catch(() => missing.push(name));
145
- if (missing.length)
146
- throw new UserError(`${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} not an account or short command; use one of: ${known.join(', ')}`, { code: 'unknown-account' });
147
- }
216
+ throw unknownFamily(rt.families.keys(), family);
217
+ const refs = await handoffRefs(rt);
148
218
  const edit = (current) => {
149
219
  const next = { ...current };
150
- for (const k of [
151
- 'auto',
152
- 'sameFamily',
153
- 'prepareAt',
154
- 'threshold',
155
- 'waitIfResetWithinMinutes',
156
- 'countdownSeconds',
157
- ])
158
- if (change[k] !== undefined)
220
+ for (const k of ['familyOrder', 'crossOrganization']) {
221
+ const v = change[k];
222
+ if (v === undefined)
223
+ continue;
224
+ if (v.length)
225
+ next[k] = [...v];
226
+ else
227
+ delete next[k];
228
+ }
229
+ for (const k of SINGLE_KEYS)
230
+ if (change[k] === null)
231
+ delete next[k];
232
+ else if (change[k] !== undefined)
159
233
  next[k] = change[k];
160
234
  if (change.orders?.length) {
161
235
  const families = { ...(current.families ?? {}) };
@@ -166,6 +240,7 @@ export async function configureHandoff(rt, change, opts) {
166
240
  delete families[family];
167
241
  next.families = families;
168
242
  }
243
+ checkHandoffRefs(refs, current, next);
169
244
  return next;
170
245
  };
171
246
  const file = rt.paths.configFile;
@@ -178,6 +253,7 @@ export async function configureHandoff(rt, change, opts) {
178
253
  ? `--- ${join('sideby', 'config.json')} (handoff)\n${lineDiff(pretty(r.before), pretty(r.after))}\n`
179
254
  : '',
180
255
  settings: handoffSettings({ handoff: r.after }),
256
+ undo: handoffUndo(r.before, change),
181
257
  };
182
258
  }
183
259
  const HINT_EVERY_MS = 24 * 60 * 60 * 1000;
@@ -47,7 +47,10 @@ export interface HandoffPlan {
47
47
  at: string;
48
48
  };
49
49
  }
50
- export declare function planHandoff(family: string, candidates: readonly HandoffCandidate[], now: Date, opts?: {
50
+ export declare function planHandoff(family: string, candidates: readonly HandoffCandidate[], now: Date,
51
+ /** `fullAt`: the Takeover Limit, at or above which an Account is full (default 85, the limit at threshold 95). */
52
+ opts?: {
51
53
  includeApi?: boolean;
52
54
  from?: string;
55
+ fullAt?: number;
53
56
  }): HandoffPlan;
@@ -2,7 +2,7 @@ import { QUOTA_FAIL_PERCENT, quotaPressure, windowReset } from './quota-levels.j
2
2
  const ORDER = { ready: 0, unknown: 1, api: 2, full: 3, 'logged-out': 4 };
3
3
  /** A full Account without a readable reset time sorts after every one that has one. */
4
4
  const resetTime = (e) => (e.resetsAt ? Date.parse(e.resetsAt) : Number.POSITIVE_INFINITY);
5
- function entry(c, now) {
5
+ function entry(c, now, fullAt) {
6
6
  const pressure = quotaPressure(c.quota, now);
7
7
  const base = {
8
8
  ref: c.ref,
@@ -17,19 +17,22 @@ function entry(c, now) {
17
17
  return { ...base, state: 'logged-out' };
18
18
  if (pressure === null)
19
19
  return { ...base, state: 'unknown' };
20
- if (pressure < QUOTA_FAIL_PERCENT)
20
+ if (pressure < fullAt)
21
21
  return { ...base, state: 'ready' };
22
22
  // Usable again only when every full window has reset: the latest of their reset times.
23
23
  let last;
24
24
  if (c.quota.status === 'ok')
25
25
  for (const w of c.quota.windows) {
26
26
  const t = Date.parse(w.resetsAt);
27
- if (w.usedPercent >= QUOTA_FAIL_PERCENT && !windowReset(w.resetsAt, now) && Number.isFinite(t))
27
+ if (w.usedPercent >= fullAt && !windowReset(w.resetsAt, now) && Number.isFinite(t))
28
28
  last = Math.max(last ?? t, t);
29
29
  }
30
30
  return { ...base, state: 'full', ...(last === undefined ? {} : { resetsAt: new Date(last).toISOString() }) };
31
31
  }
32
- export function planHandoff(family, candidates, now, opts = {}) {
32
+ export function planHandoff(family, candidates, now,
33
+ /** `fullAt`: the Takeover Limit, at or above which an Account is full (default 85, the limit at threshold 95). */
34
+ opts = {}) {
35
+ const fullAt = opts.fullAt ?? QUOTA_FAIL_PERCENT;
33
36
  const current = opts.from ? candidates.find((c) => c.ref === opts.from) : undefined;
34
37
  const byRef = new Map(candidates.map((c) => [c.ref, c]));
35
38
  const tie = (a, b) => {
@@ -39,7 +42,7 @@ export function planHandoff(family, candidates, now, opts = {}) {
39
42
  };
40
43
  const accounts = candidates
41
44
  .map((c) => {
42
- const e = entry(c, now);
45
+ const e = entry(c, now, fullAt);
43
46
  return current?.sameLogin?.includes(c.ref) ? { ...e, sameLoginAs: current.ref } : e;
44
47
  })
45
48
  .sort((a, b) =>
@@ -1,4 +1,5 @@
1
1
  import type { Account, CheckResult, ReadContext } from '../types.ts';
2
+ import { type SettingsProblem } from './claude-settings-file.ts';
2
3
  export declare const INBOUND_KEY = "crossSessionInbound";
3
4
  /**
4
5
  * `accept`, `hold`, `refuse`: the key holds that value; `default`: no key, so Claude Code's default decides (a session
@@ -12,7 +13,9 @@ export interface InboundGroup {
12
13
  /** Refs of the Accounts whose `settings.json` is `file`, in discovery order. */
13
14
  accounts: string[];
14
15
  state: InboundState;
15
- /** For `blocked`, `missing` and `refuse`: why, and what to do. */
16
+ /** For `blocked`, `missing`, `refuse` and `other`: why, as a code the Panel words in its language. */
17
+ why?: SettingsProblem | 'refuse' | 'other';
18
+ /** For `blocked`, `missing`, `refuse` and `other`: why, and what to do. */
16
19
  reason?: string;
17
20
  /** sideby set it here and can put the earlier value back. */
18
21
  undo: boolean;
@@ -37,8 +40,13 @@ export declare function inboundOf(account: Account, ctx: ReadContext): Promise<I
37
40
  * its Accounts starts in bypass permission mode (doctor's `messages.inbound-held`). Reads what doctor reads.
38
41
  */
39
42
  export declare function waitingFiles(groups: readonly InboundGroup[], accounts: readonly Account[], starts: (a: Account) => readonly (readonly string[])[]): Promise<Set<string>>;
40
- /** The groups `accept` would change: not set, or `hold`. A `refuse` or a value sideby does not know is left alone. */
41
- export declare function groupsToAccept(groups: readonly InboundGroup[]): InboundGroup[];
43
+ /**
44
+ * The groups `accept` would change: not set, or `hold`. A `refuse` or a value sideby does not know is left alone.
45
+ * Self-contained, so the Panel page runs this same function (page-script.ts).
46
+ */
47
+ export declare function groupsToAccept<G extends {
48
+ state: string;
49
+ }>(groups: readonly G[]): G[];
42
50
  /** The groups `accept` leaves alone and why: refused, unknown, blocked or without a settings file. */
43
51
  export declare function inboundLeftAlone(groups: readonly InboundGroup[]): InboundGroup[];
44
52
  /** Groups sideby can put back: it wrote there and the key still holds what it wrote. */
@@ -4,12 +4,10 @@
4
4
  // minutes), `refuse` drops it. Writes follow Remote Control's rules (spec §3.22): a preview first, `writeIfUnchanged`,
5
5
  // every other key kept, a shared file written once at its real target, never a settings.json created, and undo only
6
6
  // while the key still holds what sideby wrote. A `refuse` the user chose is never changed.
7
- import { rm } from 'node:fs/promises';
8
7
  import { argsBypass } from '../families/claude/messaging.js';
9
- import { isObj, keyRecordPath, locate, readKeyRecord, readObject, settingsFileGroups, writeKeyRecord, writeSettingsKey, } from './claude-settings-file.js';
8
+ import { isObj, locate, readObject, readSettingsGroups, settingsKey, } from './claude-settings-file.js';
10
9
  export const INBOUND_KEY = 'crossSessionInbound';
11
- const RECORDS = 'cross-session-inbound';
12
- const NO_SETTINGS = 'this account has no settings.json; run `sideby doctor --fix` so it shares the main one, then try again';
10
+ const inbound = settingsKey(INBOUND_KEY, 'cross-session-inbound');
13
11
  const REFUSE = 'you set it to refuse, so sideby leaves it alone; Messages to these sessions need pasting. To get them, set "crossSessionInbound": "accept" in this file yourself';
14
12
  const OTHER = 'it holds a value sideby does not know, so sideby leaves it alone; set "crossSessionInbound" to "accept" in this file yourself, or remove the key and run `sideby messages inbound accept` again';
15
13
  export function inboundStateOf(v) {
@@ -17,41 +15,24 @@ export function inboundStateOf(v) {
17
15
  return 'default';
18
16
  return v === 'accept' || v === 'hold' || v === 'refuse' ? v : 'other';
19
17
  }
20
- async function readRecord(ctx, file) {
21
- const r = await readKeyRecord(ctx.stateDir, RECORDS, file);
22
- return r && typeof r.wrote === 'string' && typeof r.hadKey === 'boolean'
23
- ? r
24
- : null;
25
- }
26
18
  /** Every Claude Account's setting, grouped by the file it lives in. Reads only the one key; writes nothing. */
27
19
  export async function inboundGroups(accounts, ctx) {
28
20
  const out = [];
29
- for (const { file, accounts: refs, where } of await settingsFileGroups(accounts)) {
30
- const group = { file, accounts: refs, state: 'missing', undo: false };
31
- out.push(group);
32
- if (where.broken) {
33
- group.state = 'blocked';
34
- group.reason =
35
- 'settings.json is a link to a file that does not exist; run `sideby doctor` to see how to fix it';
36
- }
37
- else if (!where.exists)
38
- group.reason = NO_SETTINGS;
39
- else {
40
- const read = await readObject(where.file);
41
- if ('error' in read) {
42
- group.state = 'blocked';
43
- group.reason = `settings.json cannot be changed safely: ${read.error}. Fix or move the file, then try again`;
44
- }
45
- else {
46
- group.state = inboundStateOf(read.obj[INBOUND_KEY]);
47
- if (group.state === 'refuse')
48
- group.reason = REFUSE;
49
- if (group.state === 'other')
50
- group.reason = OTHER;
51
- const record = await readRecord(ctx, where.file);
52
- group.undo = record !== null && read.obj[INBOUND_KEY] === record.wrote;
53
- }
21
+ for (const g of await readSettingsGroups(accounts)) {
22
+ if ('why' in g) {
23
+ const state = g.why === 'no-settings' ? 'missing' : 'blocked';
24
+ out.push({ file: g.file, accounts: g.accounts, state, why: g.why, reason: g.reason, undo: false });
25
+ continue;
54
26
  }
27
+ const state = inboundStateOf(g.obj[INBOUND_KEY]);
28
+ const why = state === 'refuse' || state === 'other' ? state : undefined;
29
+ out.push({
30
+ file: g.file,
31
+ accounts: g.accounts,
32
+ state,
33
+ ...(why ? { why, reason: why === 'refuse' ? REFUSE : OTHER } : {}),
34
+ undo: await inbound.undoable(ctx.stateDir, g.file, g.obj),
35
+ });
55
36
  }
56
37
  return out;
57
38
  }
@@ -79,7 +60,10 @@ export async function waitingFiles(groups, accounts, starts) {
79
60
  }
80
61
  return out;
81
62
  }
82
- /** The groups `accept` would change: not set, or `hold`. A `refuse` or a value sideby does not know is left alone. */
63
+ /**
64
+ * The groups `accept` would change: not set, or `hold`. A `refuse` or a value sideby does not know is left alone.
65
+ * Self-contained, so the Panel page runs this same function (page-script.ts).
66
+ */
83
67
  export function groupsToAccept(groups) {
84
68
  return groups.filter((g) => g.state === 'default' || g.state === 'hold');
85
69
  }
@@ -116,26 +100,11 @@ export async function acceptInbound(accounts, ctx) {
116
100
  const todo = groupsToAccept(groups);
117
101
  if (todo.length === 0)
118
102
  return inboundNothingToDo('accept', groups);
119
- const results = [];
120
- for (const g of todo) {
121
- let before = { hadKey: false };
122
- const failed = await writeSettingsKey(g.file, (obj) => {
123
- before = INBOUND_KEY in obj ? { hadKey: true, previous: obj[INBOUND_KEY] } : { hadKey: false };
124
- obj[INBOUND_KEY] = 'accept';
125
- return obj;
126
- }, (obj) => obj[INBOUND_KEY] === undefined || obj[INBOUND_KEY] === 'hold'
127
- ? null
128
- : obj[INBOUND_KEY] === 'accept'
129
- ? 'It was set to accept meanwhile; nothing changed.'
130
- : 'It was changed meanwhile, so sideby left it alone.');
131
- if (failed) {
132
- results.push({ file: g.file, accounts: g.accounts, ok: false, message: failed });
133
- continue;
134
- }
135
- const record = { file: g.file, ...before, wrote: 'accept', at: new Date().toISOString() };
136
- await writeKeyRecord(ctx.stateDir, RECORDS, g.file, record);
137
- results.push({ file: g.file, accounts: g.accounts, ok: true, message: 'Set to accept.' });
138
- }
103
+ const results = await inbound.set(ctx.stateDir, todo, 'accept', (v) => v === undefined || v === 'hold'
104
+ ? null
105
+ : v === 'accept'
106
+ ? 'It was set to accept meanwhile; nothing changed.'
107
+ : 'It was changed meanwhile, so sideby left it alone.', 'Set to accept.');
139
108
  const ok = results.every((r) => r.ok);
140
109
  const left = leftAloneLines(groups);
141
110
  return {
@@ -153,24 +122,7 @@ export async function undoInbound(accounts, ctx) {
153
122
  const todo = inboundGroupsToUndo(groups);
154
123
  if (todo.length === 0)
155
124
  return inboundNothingToDo('undo', groups);
156
- const results = [];
157
- for (const g of todo) {
158
- const record = await readRecord(ctx, g.file);
159
- if (!record)
160
- continue;
161
- const failed = await writeSettingsKey(g.file, (obj) => {
162
- if (!record.hadKey)
163
- delete obj[INBOUND_KEY];
164
- else
165
- obj[INBOUND_KEY] = record.previous;
166
- return obj;
167
- }, (obj) => obj[INBOUND_KEY] === record.wrote
168
- ? null
169
- : 'The setting was changed after sideby set it, so it was left alone.');
170
- if (!failed)
171
- await rm(keyRecordPath(ctx.stateDir, RECORDS, g.file), { force: true });
172
- results.push({ file: g.file, accounts: g.accounts, ok: !failed, message: failed ?? 'Put back.' });
173
- }
125
+ const results = await inbound.undo(ctx.stateDir, todo);
174
126
  const ok = results.length > 0 && results.every((r) => r.ok);
175
127
  return {
176
128
  ok,
@@ -72,9 +72,11 @@ export function accountEnv(family, account, baseEnv) {
72
72
  const env = { ...baseEnv };
73
73
  for (const v of family.hijackVars)
74
74
  delete env[v];
75
- delete env[family.selectVar];
76
- if (!account.isMain)
77
- env[family.selectVar] = account.dir;
75
+ if (family.selectVar) {
76
+ delete env[family.selectVar];
77
+ if (!account.isMain)
78
+ env[family.selectVar] = account.dir;
79
+ }
78
80
  return env;
79
81
  }
80
82
  /**
@@ -111,7 +113,7 @@ export async function prepareLaunch(opts) {
111
113
  if (account.secretFile)
112
114
  Object.assign(env, await readSecretFile(account.secretFile, opts.baseEnv));
113
115
  // The Secret File may not move the Account: its directory always wins.
114
- if (!account.isMain)
116
+ if (!account.isMain && family.selectVar)
115
117
  env[family.selectVar] = account.dir;
116
118
  // Which Account this is, for a status line, prompt or hook to show (spec §3.5); set for every Launch, so a value
117
119
  // inherited from another sideby Launch never leaks through.
@@ -5,14 +5,25 @@ import type { QuotaResult, QuotaWindow } from '../types.ts';
5
5
  */
6
6
  export declare const QUOTA_FAIL_PERCENT = 85;
7
7
  export declare const QUOTA_WARN_PERCENT = 60;
8
+ /**
9
+ * Takeover Limit (spec §3.17 "接力规则"): an Account more used than this does not take over a Handoff, so the next
10
+ * Account starts with room to work. It sits this many points below the Handoff Threshold and moves with it.
11
+ */
12
+ export declare const TAKEOVER_GAP = 10;
13
+ export declare function takeoverLimit(threshold: number): number;
8
14
  /** Days of Usage every Family reports. */
9
15
  export declare const USAGE_DAYS = 7;
10
16
  export type QuotaLevel = 'ok' | 'warn' | 'fail';
11
- /** Shared by the Panel and menu bar. Self-contained so the Panel can inline it without other module state. */
17
+ /**
18
+ * Shared by the Panel and menu bar. Self-contained so the Panel can inline it without other module state.
19
+ * A reading over an hour old is still current when `lastUseAt`, the newest use of its login on this computer, came at
20
+ * most 10 minutes after it (a session's last records land after its last status line): nothing here has used the
21
+ * Quota since (spec §3.31). Use on the web or another computer cannot be seen; the hover text says so.
22
+ */
12
23
  export declare function quotaIsStale(quota: {
13
24
  observedAt: string;
14
25
  fetchError?: string;
15
- }, now: number): boolean;
26
+ }, now: number, lastUseAt?: string | null): boolean;
16
27
  export declare function quotaLevel(usedPercent: number): QuotaLevel;
17
28
  /** True once a window's reset time has passed; an unreadable time never counts as reset. */
18
29
  export declare function windowReset(resetsAt: string, now: Date): boolean;