sideby 0.20.0 → 0.22.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.
- package/README.md +1 -0
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.js +115 -10
- package/dist/src/cli/format.js +3 -2
- package/dist/src/cli/json-schemas.js +81 -46
- package/dist/src/cli/main.js +6 -3
- package/dist/src/core/accounts.d.ts +6 -1
- package/dist/src/core/accounts.js +16 -3
- package/dist/src/core/ask.d.ts +2 -1
- package/dist/src/core/ask.js +6 -3
- package/dist/src/core/claude-settings-file.d.ts +57 -0
- package/dist/src/core/claude-settings-file.js +104 -2
- package/dist/src/core/config.d.ts +29 -15
- package/dist/src/core/config.js +40 -2
- package/dist/src/core/create.js +4 -1
- package/dist/src/core/desktop-app.js +5 -1
- package/dist/src/core/handoff-overview.d.ts +4 -1
- package/dist/src/core/handoff-overview.js +3 -2
- package/dist/src/core/handoff-rules.d.ts +34 -0
- package/dist/src/core/handoff-rules.js +115 -0
- package/dist/src/core/handoff-select.js +45 -28
- package/dist/src/core/handoff-status.d.ts +37 -7
- package/dist/src/core/handoff-status.js +95 -19
- package/dist/src/core/handoff.d.ts +4 -1
- package/dist/src/core/handoff.js +8 -5
- package/dist/src/core/inbound.d.ts +11 -3
- package/dist/src/core/inbound.js +26 -74
- package/dist/src/core/launch.js +6 -4
- package/dist/src/core/quota-levels.d.ts +6 -0
- package/dist/src/core/quota-levels.js +8 -0
- package/dist/src/core/remote-control.d.ts +10 -12
- package/dist/src/core/remote-control.js +29 -86
- package/dist/src/core/tuning-apply.js +12 -20
- package/dist/src/families/agy/index.d.ts +8 -0
- package/dist/src/families/agy/index.js +53 -0
- package/dist/src/families/agy/quota.d.ts +9 -0
- package/dist/src/families/agy/quota.js +110 -0
- package/dist/src/families/index.js +7 -0
- package/dist/src/families/logos.d.ts +10 -0
- package/dist/src/families/logos.js +12 -1
- package/dist/src/menubar/script.js +26 -3
- package/dist/src/menubar/snapshot.d.ts +23 -6
- package/dist/src/menubar/snapshot.js +126 -39
- package/dist/src/menubar/strings.d.ts +12 -2
- package/dist/src/menubar/strings.js +12 -2
- package/dist/src/panel/handler.d.ts +2 -1
- package/dist/src/panel/handler.js +81 -45
- package/dist/src/panel/i18n.d.ts +58 -7
- package/dist/src/panel/i18n.js +158 -56
- package/dist/src/panel/page-logic.d.ts +52 -19
- package/dist/src/panel/page-logic.js +47 -7
- package/dist/src/panel/page-script.js +333 -115
- package/dist/src/panel/page-styles.js +112 -21
- package/dist/src/panel/page.js +3 -3
- package/dist/src/plugins/check.js +27 -13
- package/dist/src/plugins/loader.d.ts +11 -0
- package/dist/src/plugins/loader.js +47 -1
- package/dist/src/runtime.d.ts +5 -2
- package/dist/src/runtime.js +12 -5
- package/dist/src/types.d.ts +35 -5
- package/package.json +2 -2
- package/schemas/config.json +16 -1
- package/schemas/families.json +8 -5
- package/schemas/handoff-disable.json +22 -0
- package/schemas/handoff-enable.json +22 -0
- package/schemas/handoff-rules.json +302 -0
- package/schemas/handoff-status.json +26 -0
- package/schemas/list.json +5 -0
- package/schemas/menubar-snapshot.json +309 -2
- package/skills/sideby/SKILL.md +3 -2
- package/skills/sideby/references/accounts.md +1 -0
- package/skills/sideby/references/handoff.md +7 -3
- package/skills/sideby/references/quota.md +2 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// One Claude Account's `settings.json`, as the writers of a single key use it (tune apply, ADR-0012; Remote Control,
|
|
2
2
|
// ADR-0017; Cross-session inbound, ADR-0040): where it really lives, a safe read, rendering it back with the file's
|
|
3
|
-
// own indentation, the write of one key and its undo record.
|
|
4
|
-
import { mkdir, readFile, stat } from 'node:fs/promises';
|
|
3
|
+
// own indentation, the write of one key and its undo record, and `settingsKey`, the write-and-undo of one key.
|
|
4
|
+
import { mkdir, readFile, rm, stat } from 'node:fs/promises';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import { lstatOrNull, realpathOrNull, sha256, writeFileAtomic, writeIfUnchanged } from './fs-safe.js';
|
|
7
7
|
const MAX_BYTES = 5_000_000;
|
|
@@ -100,3 +100,105 @@ export async function readKeyRecord(stateDir, dir, file) {
|
|
|
100
100
|
return null;
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* One top-level key of Claude's settings files that sideby writes for the user and can undo (Remote Control,
|
|
105
|
+
* ADR-0017; Cross-session inbound, ADR-0040). Each write goes through `writeSettingsKey` and leaves an undo record in
|
|
106
|
+
* `<state>/<records>/`; undo puts the old value back (or removes the key) only while it still holds what sideby
|
|
107
|
+
* wrote. `legacyWrote` reads a record from before `wrote` was kept as one that wrote that value.
|
|
108
|
+
*/
|
|
109
|
+
export function settingsKey(key, records, opts = {}) {
|
|
110
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
111
|
+
const readRecord = async (stateDir, file) => {
|
|
112
|
+
const r = await readKeyRecord(stateDir, records, file);
|
|
113
|
+
if (!r)
|
|
114
|
+
return null;
|
|
115
|
+
const wrote = 'wrote' in r ? r.wrote : opts.legacyWrote;
|
|
116
|
+
if (wrote === undefined)
|
|
117
|
+
return null;
|
|
118
|
+
// Records from before `hadKey` kept null for a key that was not there.
|
|
119
|
+
const hadKey = typeof r.hadKey === 'boolean' ? r.hadKey : r.previous !== null && r.previous !== undefined;
|
|
120
|
+
return { file, hadKey, ...(hadKey ? { previous: r.previous } : {}), wrote, at: String(r.at ?? '') };
|
|
121
|
+
};
|
|
122
|
+
return {
|
|
123
|
+
key,
|
|
124
|
+
/** Whether sideby wrote `obj`'s key in `file` and it still holds that, so undo can put it back. */
|
|
125
|
+
async undoable(stateDir, file, obj) {
|
|
126
|
+
const record = await readRecord(stateDir, file);
|
|
127
|
+
return record !== null && same(obj[key], record.wrote);
|
|
128
|
+
},
|
|
129
|
+
/**
|
|
130
|
+
* Sets the key to `to` in each group, remembering the old value. `expect` gets the value in the file right before
|
|
131
|
+
* the write and refuses with a message when the change no longer fits it.
|
|
132
|
+
*/
|
|
133
|
+
async set(stateDir, groups, to, expect, done) {
|
|
134
|
+
const results = [];
|
|
135
|
+
for (const g of groups) {
|
|
136
|
+
let before = { hadKey: false };
|
|
137
|
+
const failed = await writeSettingsKey(g.file, (obj) => {
|
|
138
|
+
before = key in obj ? { hadKey: true, previous: obj[key] } : { hadKey: false };
|
|
139
|
+
obj[key] = to;
|
|
140
|
+
return obj;
|
|
141
|
+
}, (obj) => expect(obj[key]));
|
|
142
|
+
if (!failed) {
|
|
143
|
+
const record = { file: g.file, ...before, wrote: to, at: new Date().toISOString() };
|
|
144
|
+
await writeKeyRecord(stateDir, records, g.file, record);
|
|
145
|
+
}
|
|
146
|
+
results.push({ file: g.file, accounts: g.accounts, ok: !failed, message: failed ?? done });
|
|
147
|
+
}
|
|
148
|
+
return results;
|
|
149
|
+
},
|
|
150
|
+
/** Puts back what each group had before `set`, only while the key still holds what sideby wrote. */
|
|
151
|
+
async undo(stateDir, groups) {
|
|
152
|
+
const results = [];
|
|
153
|
+
for (const g of groups) {
|
|
154
|
+
const record = await readRecord(stateDir, g.file);
|
|
155
|
+
if (!record)
|
|
156
|
+
continue;
|
|
157
|
+
const failed = await writeSettingsKey(g.file, (obj) => {
|
|
158
|
+
if (record.hadKey)
|
|
159
|
+
obj[key] = record.previous;
|
|
160
|
+
else
|
|
161
|
+
delete obj[key];
|
|
162
|
+
return obj;
|
|
163
|
+
}, (obj) => same(obj[key], record.wrote)
|
|
164
|
+
? null
|
|
165
|
+
: 'The setting was changed after sideby set it, so it was left alone.');
|
|
166
|
+
if (!failed)
|
|
167
|
+
await rm(keyRecordPath(stateDir, records, g.file), { force: true });
|
|
168
|
+
results.push({ file: g.file, accounts: g.accounts, ok: !failed, message: failed ?? 'Put back.' });
|
|
169
|
+
}
|
|
170
|
+
return results;
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
const NO_SETTINGS = 'this account has no settings.json; run `sideby doctor --fix` so it shares the main one, then try again';
|
|
175
|
+
/**
|
|
176
|
+
* Every Claude Account's settings file, grouped as `settingsFileGroups` does, with the parsed object, or the problem
|
|
177
|
+
* and a reason that says what to do (the Panel words it from `why`).
|
|
178
|
+
*/
|
|
179
|
+
export async function readSettingsGroups(accounts) {
|
|
180
|
+
const out = [];
|
|
181
|
+
for (const { file, accounts: refs, where } of await settingsFileGroups(accounts)) {
|
|
182
|
+
if (where.broken)
|
|
183
|
+
out.push({
|
|
184
|
+
file,
|
|
185
|
+
accounts: refs,
|
|
186
|
+
why: 'broken-link',
|
|
187
|
+
reason: 'settings.json is a link to a file that does not exist; run `sideby doctor` to see how to fix it',
|
|
188
|
+
});
|
|
189
|
+
else if (!where.exists)
|
|
190
|
+
out.push({ file, accounts: refs, why: 'no-settings', reason: NO_SETTINGS });
|
|
191
|
+
else {
|
|
192
|
+
const read = await readObject(where.file);
|
|
193
|
+
out.push('error' in read
|
|
194
|
+
? {
|
|
195
|
+
file,
|
|
196
|
+
accounts: refs,
|
|
197
|
+
why: 'unsafe',
|
|
198
|
+
reason: `settings.json cannot be changed safely: ${read.error}. Fix or move the file, then try again`,
|
|
199
|
+
}
|
|
200
|
+
: { file, accounts: refs, obj: read.obj });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
@@ -16,20 +16,28 @@ export declare const aliasAccount: (value: AliasValue) => string;
|
|
|
16
16
|
export declare const aliasArgs: (value: AliasValue | undefined) => string[];
|
|
17
17
|
/** `aliases` as alias → Account ref, for lookups that ignore the arguments. */
|
|
18
18
|
export declare function aliasRefs(aliases: Readonly<Record<string, AliasValue>> | undefined): Record<string, string>;
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
19
|
+
/**
|
|
20
|
+
* The `handoff` settings with every default filled in (`handoffSettings`). One schema for the type, the `--json`
|
|
21
|
+
* outputs that carry it and the Panel page.
|
|
22
|
+
*/
|
|
23
|
+
export declare const HandoffSettingsSchema: Type.TObject<{
|
|
24
|
+
auto: Type.TBoolean;
|
|
25
|
+
sameFamily: Type.TBoolean;
|
|
26
|
+
otherFamilies: Type.TBoolean;
|
|
27
|
+
familyOrder: Type.TArray<Type.TString>;
|
|
28
|
+
api: Type.TBoolean;
|
|
29
|
+
prepareAt: Type.TNumber;
|
|
30
|
+
threshold: Type.TNumber;
|
|
31
|
+
adaptive: Type.TBoolean;
|
|
32
|
+
waitIfResetWithinMinutes: Type.TNumber;
|
|
33
|
+
countdownSeconds: Type.TNumber;
|
|
34
|
+
crossOrganization: Type.TArray<Type.TString>;
|
|
35
|
+
families: Type.TRecord<"^.*$", Type.TObject<{
|
|
36
|
+
policy: Type.TUnion<[Type.TLiteral<"pressure">, Type.TLiteral<"order">]>;
|
|
37
|
+
order: Type.TArray<Type.TString>;
|
|
38
|
+
}>>;
|
|
39
|
+
}>;
|
|
40
|
+
export type HandoffSettings = Static<typeof HandoffSettingsSchema>;
|
|
33
41
|
export declare const ConfigSchema: Type.TObject<{
|
|
34
42
|
$schema: Type.TOptional<Type.TString>;
|
|
35
43
|
panel: Type.TOptional<Type.TObject<{
|
|
@@ -69,6 +77,9 @@ export declare const ConfigSchema: Type.TObject<{
|
|
|
69
77
|
handoff: Type.TOptional<Type.TObject<{
|
|
70
78
|
auto: Type.TOptional<Type.TBoolean>;
|
|
71
79
|
sameFamily: Type.TOptional<Type.TBoolean>;
|
|
80
|
+
otherFamilies: Type.TOptional<Type.TBoolean>;
|
|
81
|
+
familyOrder: Type.TOptional<Type.TArray<Type.TString>>;
|
|
82
|
+
api: Type.TOptional<Type.TBoolean>;
|
|
72
83
|
prepareAt: Type.TOptional<Type.TInteger>;
|
|
73
84
|
threshold: Type.TOptional<Type.TInteger>;
|
|
74
85
|
adaptive: Type.TOptional<Type.TBoolean>;
|
|
@@ -286,11 +297,14 @@ export interface ConfigChange {
|
|
|
286
297
|
/**
|
|
287
298
|
* `sideby config set|unset` (spec §3.29): sets `key` to `value`, or removes it when `value` is undefined (and parents
|
|
288
299
|
* left empty with it). The whole result must match the schema; `accounts.<ref>.args` takes only what `argsProblem`
|
|
289
|
-
* accepts (the model and effort arguments, as `sideby model`), and without `argsProblem` it is refused
|
|
300
|
+
* accepts (the model and effort arguments, as `sideby model`), and without `argsProblem` it is refused; a
|
|
301
|
+
* `handoff` change passes `checkHandoff`, the same check the Panel and `sideby handoff` use. Written as
|
|
290
302
|
* every other config change (see `editConfigKey`); `dryRun` shows the change without writing.
|
|
291
303
|
*/
|
|
292
304
|
export declare function editConfigPath(file: string, key: string, value: unknown, opts?: {
|
|
293
305
|
dryRun?: boolean;
|
|
294
306
|
argsProblem?: (ref: string, args: string[]) => string | null;
|
|
307
|
+
/** Throws when a changed `handoff` setting names a Family or Account that does not exist. */
|
|
308
|
+
checkHandoff?: (before: HandoffConfig | undefined, after: HandoffConfig | undefined) => void;
|
|
295
309
|
}): Promise<ConfigChange>;
|
|
296
310
|
export {};
|
package/dist/src/core/config.js
CHANGED
|
@@ -49,11 +49,20 @@ const Percent = (description) => Type.Optional(Type.Integer({ minimum: 1, maximu
|
|
|
49
49
|
/** Auto Handoff (spec §3.17, ADR-0010). Every key is optional; `handoffSettings` fills the defaults. */
|
|
50
50
|
const HandoffSchema = Type.Object({
|
|
51
51
|
auto: Type.Optional(Type.Boolean({
|
|
52
|
-
description: 'Hand a running session to the next account when its Quota runs low: only to other families
|
|
52
|
+
description: 'Hand a running session to the next account when its Quota runs low: within the family only with `sameFamily`, to other families only with `otherFamilies`, to API accounts only with `api`. Off by default.',
|
|
53
53
|
})),
|
|
54
54
|
sameFamily: Type.Optional(Type.Boolean({
|
|
55
55
|
description: 'Also hand off to an account of the same family (cc001 → cc002). The kind vendors are most likely to act on. Off by default.',
|
|
56
56
|
})),
|
|
57
|
+
otherFamilies: Type.Optional(Type.Boolean({
|
|
58
|
+
description: 'When no account of the family can take over, let accounts of other families take over, family by family in `familyOrder`. Off by default.',
|
|
59
|
+
})),
|
|
60
|
+
familyOrder: Type.Optional(Type.Array(Type.String(), {
|
|
61
|
+
description: 'Families to try with `otherFamilies`, first to last (for example ["codex", "grok"]); families left out come after, in the usual order.',
|
|
62
|
+
})),
|
|
63
|
+
api: Type.Optional(Type.Boolean({
|
|
64
|
+
description: 'Let API accounts take over as the last resort, when no subscription account can. They are billed per use and sideby does not cap spending. Off by default (ADR-0046).',
|
|
65
|
+
})),
|
|
57
66
|
prepareAt: Percent('Quota Pressure at which the session starts keeping a Handoff Brief (default 80).'),
|
|
58
67
|
threshold: Percent('Quota Pressure at which the Handoff begins (default 95). With `adaptive`, a window uses it until the run has measured a turn of it.'),
|
|
59
68
|
adaptive: Type.Optional(Type.Boolean({
|
|
@@ -79,6 +88,29 @@ const HandoffSchema = Type.Object({
|
|
|
79
88
|
description: 'Handoff Order per family the session starts in: `pressure` (default) or an `order` list.',
|
|
80
89
|
})),
|
|
81
90
|
}, { additionalProperties: false });
|
|
91
|
+
/**
|
|
92
|
+
* The `handoff` settings with every default filled in (`handoffSettings`). One schema for the type, the `--json`
|
|
93
|
+
* outputs that carry it and the Panel page.
|
|
94
|
+
*/
|
|
95
|
+
export const HandoffSettingsSchema = Type.Object({
|
|
96
|
+
auto: Type.Boolean(),
|
|
97
|
+
sameFamily: Type.Boolean(),
|
|
98
|
+
otherFamilies: Type.Boolean({
|
|
99
|
+
description: 'Other AIs may take over when this one has no account that can (ADR-0046).',
|
|
100
|
+
}),
|
|
101
|
+
familyOrder: Type.Array(Type.String(), { description: 'The order other AIs are tried in.' }),
|
|
102
|
+
api: Type.Boolean({ description: 'API accounts may take over, last; billed per use (ADR-0046).' }),
|
|
103
|
+
prepareAt: Type.Number(),
|
|
104
|
+
threshold: Type.Number(),
|
|
105
|
+
adaptive: Type.Boolean(),
|
|
106
|
+
waitIfResetWithinMinutes: Type.Number(),
|
|
107
|
+
countdownSeconds: Type.Number(),
|
|
108
|
+
crossOrganization: Type.Array(Type.String()),
|
|
109
|
+
families: Type.Record(Type.String(), Type.Object({
|
|
110
|
+
policy: Type.Union([Type.Literal('pressure'), Type.Literal('order')]),
|
|
111
|
+
order: Type.Array(Type.String()),
|
|
112
|
+
})),
|
|
113
|
+
});
|
|
82
114
|
export const ConfigSchema = Type.Object({
|
|
83
115
|
$schema: Type.Optional(Type.String()),
|
|
84
116
|
panel: Type.Optional(Type.Object({
|
|
@@ -205,6 +237,9 @@ export function handoffSettings(config) {
|
|
|
205
237
|
return {
|
|
206
238
|
auto: h.auto ?? false,
|
|
207
239
|
sameFamily: h.sameFamily ?? false,
|
|
240
|
+
otherFamilies: h.otherFamilies ?? false,
|
|
241
|
+
familyOrder: [...(h.familyOrder ?? [])],
|
|
242
|
+
api: h.api ?? false,
|
|
208
243
|
prepareAt: h.prepareAt ?? 80,
|
|
209
244
|
threshold: h.threshold ?? 95,
|
|
210
245
|
adaptive: h.adaptive ?? true,
|
|
@@ -670,7 +705,8 @@ const isEmptyObject = (v) => typeof v === 'object' && v !== null && !Array.isArr
|
|
|
670
705
|
/**
|
|
671
706
|
* `sideby config set|unset` (spec §3.29): sets `key` to `value`, or removes it when `value` is undefined (and parents
|
|
672
707
|
* left empty with it). The whole result must match the schema; `accounts.<ref>.args` takes only what `argsProblem`
|
|
673
|
-
* accepts (the model and effort arguments, as `sideby model`), and without `argsProblem` it is refused
|
|
708
|
+
* accepts (the model and effort arguments, as `sideby model`), and without `argsProblem` it is refused; a
|
|
709
|
+
* `handoff` change passes `checkHandoff`, the same check the Panel and `sideby handoff` use. Written as
|
|
674
710
|
* every other config change (see `editConfigKey`); `dryRun` shows the change without writing.
|
|
675
711
|
*/
|
|
676
712
|
export async function editConfigPath(file, key, value, opts = {}) {
|
|
@@ -683,6 +719,8 @@ export async function editConfigPath(file, key, value, opts = {}) {
|
|
|
683
719
|
const result = path.length === 1 ? next : isEmptyObject(next) ? undefined : next;
|
|
684
720
|
if (top === 'accounts')
|
|
685
721
|
checkAccountArgs(current, result, opts.argsProblem);
|
|
722
|
+
if (top === 'handoff')
|
|
723
|
+
opts.checkHandoff?.(current, result);
|
|
686
724
|
return result;
|
|
687
725
|
}, opts);
|
|
688
726
|
const inner = path.slice(1);
|
package/dist/src/core/create.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { mkdir, readFile, symlink } from 'node:fs/promises';
|
|
2
2
|
import { dirname, join, relative, sep } from 'node:path';
|
|
3
3
|
import { HookError } from '../plugins/bus.js';
|
|
4
|
-
import { ACCOUNT_NAME, accountAt, accountDirOf, mainDirOf } from './accounts.js';
|
|
4
|
+
import { ACCOUNT_NAME, accountAt, accountDirOf, mainDirOf, mainOnlyMessage } from './accounts.js';
|
|
5
5
|
import { UserError } from './errors.js';
|
|
6
6
|
import { assertInside, lstatOrNull, parseJsonSafely, replaceWithCopy, statOrNull, writeFileAtomic, } from './fs-safe.js';
|
|
7
7
|
import { installHint } from './launch.js';
|
|
@@ -30,6 +30,9 @@ function actionFor(item, api) {
|
|
|
30
30
|
}
|
|
31
31
|
export async function createAccount(opts) {
|
|
32
32
|
const { family, name, api, home } = opts;
|
|
33
|
+
// A Main-only Family (ADR-0047) has no second Account to create, API Accounts included: refused before any write.
|
|
34
|
+
if (family.mainOnly)
|
|
35
|
+
throw new CreateError(mainOnlyMessage(family), { code: 'family-main-only' });
|
|
33
36
|
if (!ACCOUNT_NAME.test(name) || name === 'main')
|
|
34
37
|
throw new CreateError(`"${name}" is not a valid account name: use 1–32 lowercase letters, digits or "-", not "main"`);
|
|
35
38
|
const mainDir = mainDirOf(family, home);
|
|
@@ -178,7 +178,11 @@ export async function activate(deps, pid) {
|
|
|
178
178
|
}
|
|
179
179
|
/** The environment `open` runs with: the caller's, without anything that would pick another Account (spec §3.5). */
|
|
180
180
|
function openEnv(base, family, def) {
|
|
181
|
-
return cleanEnv(base, [
|
|
181
|
+
return cleanEnv(base, [
|
|
182
|
+
...family.hijackVars,
|
|
183
|
+
...(family.selectVar ? [family.selectVar] : []),
|
|
184
|
+
...def.clearVars,
|
|
185
|
+
]);
|
|
182
186
|
}
|
|
183
187
|
/** The caller's environment without `clear`, `SIDEBY_*` and the variables of the agent session it may run in. */
|
|
184
188
|
export function cleanEnv(base, clear) {
|
|
@@ -23,4 +23,7 @@ export interface HandoffOverview {
|
|
|
23
23
|
}
|
|
24
24
|
/** The latest hand-overs, newest first: a hop that ended with a trigger and was followed by another hop. */
|
|
25
25
|
export declare function readRecentHandoffs(stateDir: string, limit?: number): Promise<RecentHandoff[]>;
|
|
26
|
-
|
|
26
|
+
/** `always`: also while Auto Handoff is off, to show what turning it on would do (the Handoff Rules). */
|
|
27
|
+
export declare function handoffOverview(rt: Runtime, opts?: {
|
|
28
|
+
always?: boolean;
|
|
29
|
+
}): Promise<HandoffOverview>;
|
|
@@ -35,10 +35,11 @@ export async function readRecentHandoffs(stateDir, limit = RECENT) {
|
|
|
35
35
|
}
|
|
36
36
|
return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
|
|
37
37
|
}
|
|
38
|
-
|
|
38
|
+
/** `always`: also while Auto Handoff is off, to show what turning it on would do (the Handoff Rules). */
|
|
39
|
+
export async function handoffOverview(rt, opts = {}) {
|
|
39
40
|
const settings = rt.handoffSettings();
|
|
40
41
|
const recent = await readRecentHandoffs(rt.paths.stateDir);
|
|
41
|
-
if (!settings.auto)
|
|
42
|
+
if (!settings.auto && !opts.always)
|
|
42
43
|
return { settings, takeover: [], recent };
|
|
43
44
|
const starters = new Set([...rt.families.values()]
|
|
44
45
|
.filter((f) => f.handoff?.starts.length && HOOK_FAMILIES.includes(f.id))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Runtime } from '../runtime.ts';
|
|
2
|
+
import type { HandoffSettings } from './config.ts';
|
|
3
|
+
import { type HandoffOverview } from './handoff-overview.ts';
|
|
4
|
+
export type HandoffRuleId = 'when' | 'windows' | 'takeover' | 'wait' | 'sameFamily' | 'otherFamilies' | 'api' | 'organization' | 'order' | 'countdown';
|
|
5
|
+
export interface HandoffRule {
|
|
6
|
+
id: HandoffRuleId;
|
|
7
|
+
/** What the sentence needs; the Panel words it from these. */
|
|
8
|
+
params: Record<string, string | number | boolean | string[]>;
|
|
9
|
+
/** The `handoff` config keys that change it; empty when it is fixed. */
|
|
10
|
+
settings: string[];
|
|
11
|
+
/** The rule in plain English, for the CLI and `--json` readers. */
|
|
12
|
+
text: string;
|
|
13
|
+
}
|
|
14
|
+
export interface HandoffRulesView {
|
|
15
|
+
auto: boolean;
|
|
16
|
+
rules: HandoffRule[];
|
|
17
|
+
/**
|
|
18
|
+
* Set while Auto Handoff is on, the user has API Accounts and has not yet said whether they may take over: up to
|
|
19
|
+
* ADR-0046 they did, now they do not until the user allows it again.
|
|
20
|
+
*/
|
|
21
|
+
apiUndecided: boolean;
|
|
22
|
+
/** Where each account's work would go if a Handoff started now (spec §3.17, Q12). */
|
|
23
|
+
takeover: HandoffOverview['takeover'];
|
|
24
|
+
}
|
|
25
|
+
/** The rules for `settings`; `titles` names each Family, `families` is every Family in load order. */
|
|
26
|
+
export declare function handoffRules(s: HandoffSettings, ctx: {
|
|
27
|
+
titles: Readonly<Record<string, string>>;
|
|
28
|
+
families: readonly string[];
|
|
29
|
+
apiAccounts: number;
|
|
30
|
+
}): HandoffRule[];
|
|
31
|
+
/** The Handoff Rules as they apply on this machine, with where each account's work would go now. */
|
|
32
|
+
export declare function handoffRulesView(rt: Runtime, overview?: HandoffOverview): Promise<HandoffRulesView>;
|
|
33
|
+
/** Whether to ask a user who had Auto Handoff on before ADR-0046 if API Accounts may still take over. */
|
|
34
|
+
export declare function apiUndecided(rt: Runtime, apiAccounts: number): boolean;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Handoff Rules (spec §3.17 "接力规则", ADR-0046): every rule that decides when a Handoff happens and which Account
|
|
2
|
+
// takes over, as it applies now, each with the settings that change it. The CLI prints the English sentences; the
|
|
3
|
+
// Panel draws its own words from the same ids and params, so both always say the same thing.
|
|
4
|
+
import { LEVEL_MAX } from '../handoff/levels.js';
|
|
5
|
+
import { handoffOverview } from './handoff-overview.js';
|
|
6
|
+
import { takeoverLimit } from './quota-levels.js';
|
|
7
|
+
const list = (xs) => xs.join(' → ');
|
|
8
|
+
/** The rules for `settings`; `titles` names each Family, `families` is every Family in load order. */
|
|
9
|
+
export function handoffRules(s, ctx) {
|
|
10
|
+
const title = (f) => ctx.titles[f] ?? f;
|
|
11
|
+
const limit = takeoverLimit(s.threshold);
|
|
12
|
+
const familyOrder = [
|
|
13
|
+
...new Set([...s.familyOrder.filter((f) => ctx.families.includes(f)), ...ctx.families]),
|
|
14
|
+
];
|
|
15
|
+
const rules = [
|
|
16
|
+
{
|
|
17
|
+
id: 'when',
|
|
18
|
+
params: { prepareAt: s.prepareAt, threshold: s.threshold, adaptive: s.adaptive, max: LEVEL_MAX },
|
|
19
|
+
settings: ['prepareAt', 'threshold', 'adaptive'],
|
|
20
|
+
text: s.adaptive
|
|
21
|
+
? `From ${s.prepareAt}% the session writes a handoff note. It hands over at ${s.threshold}% until sideby has measured how fast this session uses quota; then between ${s.prepareAt}% and ${LEVEL_MAX}%, earlier when recent turns used a lot.`
|
|
22
|
+
: `From ${s.prepareAt}% the session writes a handoff note. It hands over at ${s.threshold}%.`,
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
id: 'windows',
|
|
26
|
+
params: {},
|
|
27
|
+
settings: [],
|
|
28
|
+
text: 'Every quota window counts (5 hours, weekly, a billing period); the fullest one decides. No host has a daily quota.',
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
id: 'takeover',
|
|
32
|
+
params: { limit },
|
|
33
|
+
settings: ['threshold'],
|
|
34
|
+
text: `An account more than ${limit}% used does not take over, so the next one starts with room to work (${s.threshold}% − 10).`,
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
id: 'wait',
|
|
38
|
+
params: { minutes: s.waitIfResetWithinMinutes },
|
|
39
|
+
settings: ['waitIfResetWithinMinutes'],
|
|
40
|
+
text: s.waitIfResetWithinMinutes > 0
|
|
41
|
+
? `If the full window resets within ${s.waitIfResetWithinMinutes} minutes and the session goes on by itself at the reset (Claude Code), it waits instead of switching. Codex and Grok switch right away.`
|
|
42
|
+
: 'It never waits for a reset; it switches right away.',
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
id: 'sameFamily',
|
|
46
|
+
params: { on: s.sameFamily },
|
|
47
|
+
settings: ['sameFamily'],
|
|
48
|
+
text: s.sameFamily
|
|
49
|
+
? 'Other accounts of the same AI may take over first, most quota left first. Vendors may act on moving work between subscriptions.'
|
|
50
|
+
: 'Other accounts of the same AI do not take over.',
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
id: 'otherFamilies',
|
|
54
|
+
params: { on: s.otherFamilies, order: familyOrder },
|
|
55
|
+
settings: ['otherFamilies', 'familyOrder'],
|
|
56
|
+
text: s.otherFamilies
|
|
57
|
+
? `When the same AI has no account that can take over, other AIs may, in this order: ${list(familyOrder.map(title))}; inside each, most quota left first.`
|
|
58
|
+
: 'Other AIs do not take over.',
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: 'api',
|
|
62
|
+
params: { on: s.api, accounts: ctx.apiAccounts },
|
|
63
|
+
settings: ['api'],
|
|
64
|
+
text: s.api
|
|
65
|
+
? 'API accounts may take over last, when no subscription account can. They are billed per use and sideby does not cap spending: set a limit in the provider’s console.'
|
|
66
|
+
: 'API accounts do not take over (they are billed per use).',
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
id: 'organization',
|
|
70
|
+
params: { allowed: s.crossOrganization },
|
|
71
|
+
settings: ['crossOrganization'],
|
|
72
|
+
text: s.crossOrganization.length
|
|
73
|
+
? `An account signed in to another organization does not take over, except ${s.crossOrganization.join(', ')}.`
|
|
74
|
+
: 'An account signed in to another organization does not take over.',
|
|
75
|
+
},
|
|
76
|
+
];
|
|
77
|
+
for (const [family, f] of Object.entries(s.families))
|
|
78
|
+
if (f.policy === 'order' && f.order.length)
|
|
79
|
+
rules.push({
|
|
80
|
+
id: 'order',
|
|
81
|
+
params: { family, order: f.order },
|
|
82
|
+
settings: ['families'],
|
|
83
|
+
text: `From ${title(family)}, accounts are tried in your order: ${list(f.order)}.`,
|
|
84
|
+
});
|
|
85
|
+
rules.push({
|
|
86
|
+
id: 'countdown',
|
|
87
|
+
params: { seconds: s.countdownSeconds },
|
|
88
|
+
settings: ['countdownSeconds'],
|
|
89
|
+
text: s.countdownSeconds > 0
|
|
90
|
+
? `Before the next account starts, a ${s.countdownSeconds}-second countdown runs; Enter cancels it.`
|
|
91
|
+
: 'The next account starts without a countdown.',
|
|
92
|
+
});
|
|
93
|
+
return rules;
|
|
94
|
+
}
|
|
95
|
+
/** The Handoff Rules as they apply on this machine, with where each account's work would go now. */
|
|
96
|
+
export async function handoffRulesView(rt, overview) {
|
|
97
|
+
const s = rt.handoffSettings();
|
|
98
|
+
const apiAccounts = (await rt.accounts()).filter((a) => a.kind === 'api').length;
|
|
99
|
+
const families = [...rt.families.values()];
|
|
100
|
+
overview ??= await handoffOverview(rt, { always: true });
|
|
101
|
+
return {
|
|
102
|
+
auto: s.auto,
|
|
103
|
+
rules: handoffRules(s, {
|
|
104
|
+
titles: Object.fromEntries(families.map((f) => [f.id, f.title])),
|
|
105
|
+
families: families.filter((f) => f.handoff).map((f) => f.id),
|
|
106
|
+
apiAccounts,
|
|
107
|
+
}),
|
|
108
|
+
apiUndecided: apiUndecided(rt, apiAccounts),
|
|
109
|
+
takeover: overview.takeover,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Whether to ask a user who had Auto Handoff on before ADR-0046 if API Accounts may still take over. */
|
|
113
|
+
export function apiUndecided(rt, apiAccounts) {
|
|
114
|
+
return rt.handoffSettings().auto && rt.config.handoff?.api === undefined && apiAccounts > 0;
|
|
115
|
+
}
|
|
@@ -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
|
|
38
|
-
*
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
|
|
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
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
//
|
|
91
|
-
(s.sameFamily || c.family !== origin.family
|
|
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:
|
|
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
|
};
|