sideby 0.35.9 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +12 -0
- package/dist/src/cli/commands.js +480 -6
- package/dist/src/cli/format.d.ts +12 -1
- package/dist/src/cli/format.js +23 -3
- package/dist/src/cli/json-schemas.js +166 -1
- package/dist/src/cli/main.js +18 -4
- package/dist/src/core/advisor.d.ts +176 -0
- package/dist/src/core/advisor.js +472 -0
- package/dist/src/core/browser-profiles.d.ts +16 -0
- package/dist/src/core/browser-profiles.js +45 -0
- package/dist/src/core/cli-commands.js +25 -1
- package/dist/src/core/config.d.ts +29 -0
- package/dist/src/core/config.js +25 -0
- package/dist/src/core/handoff-select.d.ts +13 -2
- package/dist/src/core/handoff-select.js +6 -2
- package/dist/src/core/launch.d.ts +4 -0
- package/dist/src/core/launch.js +7 -0
- package/dist/src/core/limit-reset.d.ts +198 -0
- package/dist/src/core/limit-reset.js +299 -0
- package/dist/src/core/quota-fetch.d.ts +57 -2
- package/dist/src/core/quota-fetch.js +291 -13
- package/dist/src/core/quota-levels.d.ts +70 -0
- package/dist/src/core/quota-levels.js +80 -0
- package/dist/src/core/quota-store.d.ts +15 -1
- package/dist/src/core/quota-store.js +26 -1
- package/dist/src/core/same-login.d.ts +8 -0
- package/dist/src/core/same-login.js +39 -2
- package/dist/src/core/search-catalog.js +38 -0
- package/dist/src/families/claude/index.js +2 -0
- package/dist/src/families/codex/index.js +3 -1
- package/dist/src/families/codex/quota.d.ts +23 -1
- package/dist/src/families/codex/quota.js +122 -21
- package/dist/src/families/grok/quota-log.d.ts +1 -0
- package/dist/src/menubar/script.js +70 -18
- package/dist/src/menubar/snapshot.d.ts +33 -1
- package/dist/src/menubar/snapshot.js +79 -11
- package/dist/src/menubar/strings.d.ts +16 -0
- package/dist/src/menubar/strings.js +16 -0
- package/dist/src/panel/handler.d.ts +21 -0
- package/dist/src/panel/handler.js +111 -9
- package/dist/src/panel/i18n.d.ts +87 -0
- package/dist/src/panel/i18n.js +174 -0
- package/dist/src/panel/page-logic.d.ts +17 -0
- package/dist/src/panel/page-logic.js +23 -0
- package/dist/src/panel/page-script.js +440 -19
- package/dist/src/panel/page-styles.js +38 -2
- package/dist/src/plugins/loader.d.ts +2 -0
- package/dist/src/plugins/loader.js +27 -0
- package/dist/src/runtime.d.ts +63 -1
- package/dist/src/runtime.js +529 -9
- package/dist/src/types.d.ts +67 -0
- package/package.json +1 -1
- package/schemas/advisor.json +332 -0
- package/schemas/config.json +22 -0
- package/schemas/error.json +4 -0
- package/schemas/menubar-reset.json +93 -0
- package/schemas/menubar-snapshot.json +70 -2
- package/schemas/quota-reset.json +369 -0
- package/schemas/quota.json +30 -0
- package/schemas/update.json +4 -0
- package/skills/sideby/SKILL.md +6 -2
- package/skills/sideby/references/ai-tasks.md +1 -1
- package/skills/sideby/references/panel.md +14 -0
- package/skills/sideby/references/quota.md +27 -0
- package/skills/sideby/references/update.md +1 -1
package/dist/src/core/config.js
CHANGED
|
@@ -241,6 +241,16 @@ export const ConfigSchema = Type.Object({
|
|
|
241
241
|
description: 'Countries (ISO 3166-1 alpha-2, such as `US` or `JP`) a Host may send requests from. Network Guard cannot be turned on while it is empty.',
|
|
242
242
|
})),
|
|
243
243
|
}, { additionalProperties: false, description: 'Network Guard (spec §3.35, ADR-0053).' })),
|
|
244
|
+
advisor: Type.Optional(Type.Object({
|
|
245
|
+
unlock: Type.Optional(Type.Boolean({
|
|
246
|
+
description: "Unlock Claude Code's advisor (`/advisor`) in the sessions sideby starts for Claude subscription accounts, by setting `CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL=1` at launch (never when `CLAUDE_CODE_DISABLE_ADVISOR_TOOL` is set). Off by default; choosing a model with `sideby advisor <model>` turns it on.",
|
|
247
|
+
})),
|
|
248
|
+
}, { additionalProperties: false, description: 'Advisor (spec §3.41, ADR-0074).' })),
|
|
249
|
+
claude: Type.Optional(Type.Object({
|
|
250
|
+
apiBetasOff: Type.Optional(Type.Boolean({
|
|
251
|
+
description: "Give Claude API accounts `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` when sideby starts them, for gateways that reject Claude Code's `anthropic-beta` headers. The account's own proxy.env and a value already in the environment win. Off by default; `sideby advisor <model>` turns it on when it removes that variable from a settings file API accounts share.",
|
|
252
|
+
})),
|
|
253
|
+
}, { additionalProperties: false, description: 'Claude Code launches (spec §3.41, ADR-0074).' })),
|
|
244
254
|
unattended: Type.Optional(Type.Object({
|
|
245
255
|
schedule: Type.Optional(Type.Array(UnattendedSlotSchema, {
|
|
246
256
|
description: "Slots that turn Unattended Mode on and off by themselves, in this computer's time zone. Empty by default.",
|
|
@@ -467,6 +477,21 @@ export function editConfigUpdate(file, edit, opts = {}) {
|
|
|
467
477
|
export function editConfigNetwork(file, edit, opts = {}) {
|
|
468
478
|
return editConfigKey(file, 'network', 'change the setting', (current) => edit(current ?? {}), opts);
|
|
469
479
|
}
|
|
480
|
+
/**
|
|
481
|
+
* `sideby advisor` and the Panel's Advisor dialog (spec §3.41): changes the config `advisor` key with `edit` (see
|
|
482
|
+
* `editConfigKey` for how the file is written); `edit` returns undefined to remove the section. With `dryRun`, shows
|
|
483
|
+
* the change without writing.
|
|
484
|
+
*/
|
|
485
|
+
export function editConfigAdvisor(file, edit, opts = {}) {
|
|
486
|
+
return editConfigKey(file, 'advisor', 'change the setting', (current) => edit(current ?? {}), opts);
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* The config `claude` key (spec §3.41): changed with `edit` (see `editConfigKey` for how the file is written); `edit`
|
|
490
|
+
* returns undefined to remove the section, or null to leave the file as it is.
|
|
491
|
+
*/
|
|
492
|
+
export function editConfigClaude(file, edit) {
|
|
493
|
+
return editConfigKey(file, 'claude', 'change the setting', (current) => edit(current ?? {}));
|
|
494
|
+
}
|
|
470
495
|
/**
|
|
471
496
|
* `sideby unattended on|schedule …` (spec §3.37): changes the config `unattended` key with `edit` (see `editConfigKey`
|
|
472
497
|
* for how the file is written); `edit` gets `undefined` while the section is missing and returns null to leave it.
|
|
@@ -50,17 +50,28 @@ export type UsedAccount = string | {
|
|
|
50
50
|
window?: {
|
|
51
51
|
resetsAt: string;
|
|
52
52
|
};
|
|
53
|
+
/** When the hop began, as `chain.json` keeps it. */
|
|
54
|
+
startedAt?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Set by the Runtime: a Limit Reset the user confirmed was spent for this Account after the hop began, and the
|
|
57
|
+
* Quota read that followed it is kept (ADR-0072, amending ADR-0060).
|
|
58
|
+
*/
|
|
59
|
+
resetUsed?: boolean;
|
|
53
60
|
};
|
|
54
61
|
/** What an automatic handoff does with the Accounts this chain already used (spec §3.17 "选号" 3, ADR-0060). */
|
|
55
62
|
export interface UsedRule {
|
|
56
63
|
/** Left out: the origin, a bare ref, and an Account whose latest hop handed over for a window that has not reset. */
|
|
57
64
|
out: Set<string>;
|
|
58
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* Back only when its own Quota data shows it ready: its latest hop recorded no window (a manual handoff, an older
|
|
67
|
+
* chain), or it handed over for a window that has not reset by itself but a Limit Reset was spent for it since.
|
|
68
|
+
*/
|
|
59
69
|
ifReady: Set<string>;
|
|
60
70
|
}
|
|
61
71
|
/**
|
|
62
72
|
* Sorts the Accounts this chain used by their latest hop: one that handed over for a Quota window that has reset by
|
|
63
|
-
* `now` may take over again like any other, one with no recorded window
|
|
73
|
+
* `now` may take over again like any other, one with no recorded window, or one a Limit Reset was spent for since
|
|
74
|
+
* (`resetUsed`), only when it is `ready`, the rest stay out.
|
|
64
75
|
* A bare ref stays out, and so does the origin.
|
|
65
76
|
*/
|
|
66
77
|
export declare function stillUsed(origin: string, used: readonly UsedAccount[], now: Date): UsedRule;
|
|
@@ -2,7 +2,8 @@ import { planHandoff } from './handoff.js';
|
|
|
2
2
|
import { takeoverLimits, windowReset } from './quota-levels.js';
|
|
3
3
|
/**
|
|
4
4
|
* Sorts the Accounts this chain used by their latest hop: one that handed over for a Quota window that has reset by
|
|
5
|
-
* `now` may take over again like any other, one with no recorded window
|
|
5
|
+
* `now` may take over again like any other, one with no recorded window, or one a Limit Reset was spent for since
|
|
6
|
+
* (`resetUsed`), only when it is `ready`, the rest stay out.
|
|
6
7
|
* A bare ref stays out, and so does the origin.
|
|
7
8
|
*/
|
|
8
9
|
export function stillUsed(origin, used, now) {
|
|
@@ -12,8 +13,11 @@ export function stillUsed(origin, used, now) {
|
|
|
12
13
|
latest.set(u, 'out');
|
|
13
14
|
else if (u.window === undefined)
|
|
14
15
|
latest.set(u.ref, 'ifReady');
|
|
16
|
+
else if (windowReset(u.window.resetsAt, now))
|
|
17
|
+
latest.set(u.ref, 'back');
|
|
18
|
+
// A confirmed Limit Reset may have emptied the window early: its Quota, read after the spend, decides.
|
|
15
19
|
else
|
|
16
|
-
latest.set(u.ref,
|
|
20
|
+
latest.set(u.ref, u.resetUsed ? 'ifReady' : 'out');
|
|
17
21
|
}
|
|
18
22
|
latest.set(origin, 'out');
|
|
19
23
|
const refs = (k) => new Set([...latest].flatMap(([ref, v]) => (v === k ? [ref] : [])));
|
|
@@ -79,6 +79,10 @@ export declare function prepareLaunch(opts: LaunchCommandOptions & {
|
|
|
79
79
|
bus: HookBus;
|
|
80
80
|
/** What the Host may show as the Account (`SIDEBY_LABEL`): the short command, else the ref. */
|
|
81
81
|
label?: string;
|
|
82
|
+
/** Config `advisor.unlock` (spec §3.41, ADR-0074): unlock Claude Code's advisor in a Claude subscription session. */
|
|
83
|
+
advisorUnlock?: boolean;
|
|
84
|
+
/** Config `claude.apiBetasOff` (spec §3.41, ADR-0074): a Claude API Account gets `BETAS_VAR=1`. */
|
|
85
|
+
apiBetasOff?: boolean;
|
|
82
86
|
}): Promise<PreparedLaunch>;
|
|
83
87
|
/**
|
|
84
88
|
* Runs the Host with the terminal attached and returns sideby's exit code (spec §3.5):
|
package/dist/src/core/launch.js
CHANGED
|
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';
|
|
|
2
2
|
import { access, constants } from 'node:fs/promises';
|
|
3
3
|
import { constants as osConstants } from 'node:os';
|
|
4
4
|
import { delimiter, join } from 'node:path';
|
|
5
|
+
import { apiBetasEnv, unlockAdvisorEnv } from './advisor.js';
|
|
5
6
|
import { lstatOrNull, realpathOrNull } from './fs-safe.js';
|
|
6
7
|
import { readSecretFile } from './secret-file.js';
|
|
7
8
|
/**
|
|
@@ -110,6 +111,9 @@ function aiTaskArgs(family, args) {
|
|
|
110
111
|
export async function prepareLaunch(opts) {
|
|
111
112
|
const { account, family } = opts;
|
|
112
113
|
const env = accountEnv(family, account, opts.baseEnv);
|
|
114
|
+
// Before the Secret File, so the Account's own proxy.env still decides; a value already in the environment stays.
|
|
115
|
+
if (opts.apiBetasOff)
|
|
116
|
+
apiBetasEnv(env, family.id, account);
|
|
113
117
|
if (account.secretFile)
|
|
114
118
|
Object.assign(env, await readSecretFile(account.secretFile, opts.baseEnv));
|
|
115
119
|
// The Secret File may not move the Account: its directory always wins.
|
|
@@ -119,6 +123,9 @@ export async function prepareLaunch(opts) {
|
|
|
119
123
|
// inherited from another sideby Launch never leaks through.
|
|
120
124
|
env.SIDEBY_ACCOUNT = account.ref;
|
|
121
125
|
env.SIDEBY_LABEL = opts.label || account.ref;
|
|
126
|
+
// Before the Plugins' `launch.before`, so a Plugin sees it and may take it out again.
|
|
127
|
+
if (opts.advisorUnlock && opts.command === 'run')
|
|
128
|
+
unlockAdvisorEnv(env, family.id, account);
|
|
122
129
|
const { args, notice } = launchCommand(opts);
|
|
123
130
|
await opts.bus.run('launch.before', family.id, {
|
|
124
131
|
account,
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import type { LimitResetOutcome, LimitResets, QuotaResult } from '../types.ts';
|
|
2
|
+
import { UserError } from './errors.ts';
|
|
3
|
+
import { type ReleaseLock } from './lock.ts';
|
|
4
|
+
/**
|
|
5
|
+
* `planned`: shown, not confirmed. `pending`: a request was (or is about to be) sent and no final outcome came back.
|
|
6
|
+
* An outcome: the Host answered. `not-sent`: the request never left this computer, so nothing was spent. `stopped`:
|
|
7
|
+
* written by an older sideby only, for an operation it gave up on; it is read as ended and never written now, because
|
|
8
|
+
* an operation whose outcome is unknown stays `pending` until the Host answers its own key.
|
|
9
|
+
*/
|
|
10
|
+
export type LimitResetState = 'planned' | 'pending' | LimitResetOutcome | 'not-sent' | 'stopped';
|
|
11
|
+
/**
|
|
12
|
+
* A salted digest of a login's comparison key (`loginComparisonKey`, core/same-login.ts): `sha256(salt + key)` with a
|
|
13
|
+
* salt of its own. It can only tell that the login of one operation is unchanged; it is never the Login Key or the
|
|
14
|
+
* Identity, and two records of one login do not share it.
|
|
15
|
+
*/
|
|
16
|
+
export interface LoginDigest {
|
|
17
|
+
salt: string;
|
|
18
|
+
digest: string;
|
|
19
|
+
}
|
|
20
|
+
/** What the record of one operation holds. Never a Login Key, an Identity, a credit id or a credential. */
|
|
21
|
+
export interface LimitResetRecord {
|
|
22
|
+
version: 1;
|
|
23
|
+
operationId: string;
|
|
24
|
+
/**
|
|
25
|
+
* The refs of every Account of the Same Login when the operation was made, sorted. While it is unresolved, the
|
|
26
|
+
* Accounts that resumed it are added; with its outcome, they are the Accounts of the login then.
|
|
27
|
+
*/
|
|
28
|
+
accounts: string[];
|
|
29
|
+
/**
|
|
30
|
+
* The login the operation was made for, as a digest to compare only. A record without one (written by an older
|
|
31
|
+
* sideby) cannot be shown to belong to any login, so it is never sent.
|
|
32
|
+
*/
|
|
33
|
+
login?: LoginDigest;
|
|
34
|
+
/** Sent with every attempt of this operation, and with no other. */
|
|
35
|
+
idempotencyKey: string;
|
|
36
|
+
state: LimitResetState;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
/** When each request was about to be sent (ISO), written before sending. */
|
|
39
|
+
attempts: string[];
|
|
40
|
+
/** When the operation reached a state that is not `planned` or `pending`. */
|
|
41
|
+
finishedAt?: string;
|
|
42
|
+
/** When the Quota read that followed a spend was kept. */
|
|
43
|
+
quotaReadAt?: string;
|
|
44
|
+
}
|
|
45
|
+
/** What a user is shown before confirming one spend (ADR-0072). It promises nothing about which windows refill. */
|
|
46
|
+
export interface LimitResetPlan {
|
|
47
|
+
/** The Account the user named. */
|
|
48
|
+
account: string;
|
|
49
|
+
/** The Account whose Host sends the request: the first signed-in Account of the Same Login. */
|
|
50
|
+
via: string;
|
|
51
|
+
/** The other Accounts of its Same Login; a spend applies to all of them. */
|
|
52
|
+
sameLogin: string[];
|
|
53
|
+
/** Pass it back to confirm this plan; left out when the plan cannot be confirmed (`canUse` false). */
|
|
54
|
+
operationId?: string;
|
|
55
|
+
/**
|
|
56
|
+
* An earlier attempt for this login got no final answer. Confirming asks the Host again with the same request, so
|
|
57
|
+
* it spends nothing more when that attempt already went through.
|
|
58
|
+
*/
|
|
59
|
+
unresolved?: true;
|
|
60
|
+
/** The Quota as it was read for this plan: each window's used percent and own reset time. */
|
|
61
|
+
quota: QuotaResult;
|
|
62
|
+
/** The Limit Resets the login holds now; left out when the Host did not tell. */
|
|
63
|
+
limitResets?: LimitResets;
|
|
64
|
+
/** The count expected after one spend; left out when the count is unknown or zero. */
|
|
65
|
+
expectedAfter?: number;
|
|
66
|
+
/** False when the plan cannot be confirmed; `blocked` then says why and what to do. */
|
|
67
|
+
canUse: boolean;
|
|
68
|
+
blocked?: string;
|
|
69
|
+
/** In plain words: what confirming does, and that it cannot be undone. */
|
|
70
|
+
message: string;
|
|
71
|
+
}
|
|
72
|
+
/** What one confirmed spend ended as. */
|
|
73
|
+
export interface LimitResetResult {
|
|
74
|
+
account: string;
|
|
75
|
+
via: string;
|
|
76
|
+
sameLogin: string[];
|
|
77
|
+
operationId: string;
|
|
78
|
+
outcome: LimitResetOutcome;
|
|
79
|
+
/** This confirmation finished an earlier attempt instead of making a new request of its own. */
|
|
80
|
+
resumed?: true;
|
|
81
|
+
/** The outcome was already known for this operation; no request to use one was sent now. */
|
|
82
|
+
replayed?: true;
|
|
83
|
+
/**
|
|
84
|
+
* The Quota for the Account the user named. After a spend, only numbers whose read began after it; left out when
|
|
85
|
+
* that read failed.
|
|
86
|
+
*/
|
|
87
|
+
quota?: QuotaResult;
|
|
88
|
+
/** The reset was used but the Quota could not be read afterwards: the numbers on show are still the old ones. */
|
|
89
|
+
quotaPending?: true;
|
|
90
|
+
message: string;
|
|
91
|
+
}
|
|
92
|
+
/** A refused or unfinished spend. `operationId` names the operation to retry, when there is one. */
|
|
93
|
+
export declare class LimitResetError extends UserError {
|
|
94
|
+
readonly operationId?: string;
|
|
95
|
+
constructor(message: string, opts: {
|
|
96
|
+
code: string;
|
|
97
|
+
operationId?: string;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/** States a Host's answer ends an operation in. */
|
|
101
|
+
export declare const LIMIT_RESET_OUTCOMES: readonly LimitResetOutcome[];
|
|
102
|
+
/** A finished or never-confirmed record is removed this long after it was finished or made. */
|
|
103
|
+
export declare const RECORD_KEEP_MS: number;
|
|
104
|
+
export declare const limitResetDir: (stateDir: string) => string;
|
|
105
|
+
/** Whether `id` has the shape of an operation id, so it is safe as a file name. */
|
|
106
|
+
export declare const isOperationId: (id: unknown) => id is string;
|
|
107
|
+
export declare function newOperationId(): string;
|
|
108
|
+
/** Whether a Host answered this operation: a spend happened (`reset`, `already-done`) or the Host said why not. */
|
|
109
|
+
export declare const isOutcome: (s: LimitResetState) => s is LimitResetOutcome;
|
|
110
|
+
/** Whether the operation spent a Limit Reset. */
|
|
111
|
+
export declare const spent: (s: LimitResetState) => boolean;
|
|
112
|
+
/** A new digest for the login whose comparison key is `key`, with a salt no other record has. */
|
|
113
|
+
export declare function newLoginDigest(key: string): LoginDigest;
|
|
114
|
+
/**
|
|
115
|
+
* Whether `key`, the comparison key of the login that would send the request now, is the one `record` was made for.
|
|
116
|
+
* False when either is unknown: a record without a digest, or a login that cannot be read now (signed out, an
|
|
117
|
+
* unreadable sign-in). False always means "do not send".
|
|
118
|
+
*/
|
|
119
|
+
export declare function loginUnchanged(record: LimitResetRecord, key: string | undefined): boolean;
|
|
120
|
+
/** Where the record of `operationId` is kept. */
|
|
121
|
+
export declare const limitResetFile: (stateDir: string, operationId: string) => string;
|
|
122
|
+
/**
|
|
123
|
+
* Why nothing may be sent while `paths` (operation files, or the folder itself) cannot be read, and what to do.
|
|
124
|
+
* Names the paths, never their contents.
|
|
125
|
+
*/
|
|
126
|
+
export declare function unreadableRecordsMessage(stateDir: string, paths: readonly string[]): string;
|
|
127
|
+
/**
|
|
128
|
+
* The record of `operationId`, or null when there is none. Throws a `LimitResetError` (`records-unreadable`) when
|
|
129
|
+
* its file is there but cannot be read or is not a record sideby wrote.
|
|
130
|
+
*/
|
|
131
|
+
export declare function readLimitResetRecord(stateDir: string, operationId: string): Promise<LimitResetRecord | null>;
|
|
132
|
+
/** Keeps `record` (folder 700, file 600, written through a temp file and a rename). */
|
|
133
|
+
export declare function writeLimitResetRecord(stateDir: string, record: LimitResetRecord): Promise<void>;
|
|
134
|
+
/**
|
|
135
|
+
* A new operation for the Accounts of one login, not yet confirmed. `loginKey` is that login's comparison key; only
|
|
136
|
+
* its salted digest is kept.
|
|
137
|
+
*/
|
|
138
|
+
export declare function newLimitResetRecord(accounts: readonly string[], now: Date, loginKey: string): LimitResetRecord;
|
|
139
|
+
/** What the folder of operations holds: the records that can be read, and what is there but cannot be. */
|
|
140
|
+
export interface LimitResetScan {
|
|
141
|
+
/** Every record that can be read, oldest first. */
|
|
142
|
+
records: LimitResetRecord[];
|
|
143
|
+
/**
|
|
144
|
+
* Paths that are there but cannot be read: an operation file (no permission, damaged, not a record sideby wrote),
|
|
145
|
+
* or the folder itself when it cannot be listed. Any of them may hide an unresolved spend, so while this is not
|
|
146
|
+
* empty no new operation is made and nothing is sent.
|
|
147
|
+
*/
|
|
148
|
+
unreadable: string[];
|
|
149
|
+
}
|
|
150
|
+
/** Reads every operation file. A folder that is not there yet holds nothing; any other failure is `unreadable`. */
|
|
151
|
+
export declare function scanLimitResetRecords(stateDir: string): Promise<LimitResetScan>;
|
|
152
|
+
/**
|
|
153
|
+
* Every record that can be read, oldest first. For readers that spend nothing (pruning, Auto Handoff's look at
|
|
154
|
+
* confirmed spends); a spend goes through `scanLimitResetRecords`, which also tells what could not be read.
|
|
155
|
+
*/
|
|
156
|
+
export declare function listLimitResetRecords(stateDir: string): Promise<LimitResetRecord[]>;
|
|
157
|
+
/** Whether a plan was made too long ago to confirm: its numbers are a day old, and pruning may remove it. */
|
|
158
|
+
export declare const planExpired: (record: LimitResetRecord, now: Date) => boolean;
|
|
159
|
+
/**
|
|
160
|
+
* Removes records nobody needs any more: a finished one 24 hours after it finished, a plan nobody confirmed 24 hours
|
|
161
|
+
* after it was made. An unresolved one (`pending`) is never removed: only its own key may ask the Host again. Nor is
|
|
162
|
+
* a file that cannot be read: it may be one.
|
|
163
|
+
*
|
|
164
|
+
* A record is removed only under the spend lock of its Accounts, the one a confirmation holds from before it writes
|
|
165
|
+
* `pending` until it has its answer, and only after it was read again there: a plan confirmed since this looked is
|
|
166
|
+
* unresolved now, and its key must stay. A lock that is held is not waited for; the next pruning looks again.
|
|
167
|
+
* `seam` is for tests: it runs after a record was read as removable and before its lock is taken.
|
|
168
|
+
*/
|
|
169
|
+
export declare function pruneLimitResetRecords(stateDir: string, now: Date, seam?: {
|
|
170
|
+
afterRead?: (record: LimitResetRecord) => Promise<void>;
|
|
171
|
+
}): Promise<void>;
|
|
172
|
+
/**
|
|
173
|
+
* The unresolved operation of a login, the oldest first; undefined when there is none. `loginKey` is the comparison
|
|
174
|
+
* key of the login that asks now: an operation made for that login comes first, whichever Accounts it names, so an
|
|
175
|
+
* Account that signed in as the login since finds it too. Then one that names one of `accounts`: it may be another
|
|
176
|
+
* login's by now, which `loginUnchanged` tells, but no new operation is made beside it.
|
|
177
|
+
*/
|
|
178
|
+
export declare function unresolvedFor(records: readonly LimitResetRecord[], accounts: readonly string[], loginKey?: string): LimitResetRecord | undefined;
|
|
179
|
+
/**
|
|
180
|
+
* Whether a record's Accounts are exactly `accounts`: the group the operation was made for has not changed. Equal
|
|
181
|
+
* refs do not show that the login behind them is the same; `loginUnchanged` does.
|
|
182
|
+
*/
|
|
183
|
+
export declare function sameAccounts(record: LimitResetRecord, accounts: readonly string[]): boolean;
|
|
184
|
+
/**
|
|
185
|
+
* Spends that went through and whose following Quota read is kept (ADR-0072, amending ADR-0060): the Accounts they
|
|
186
|
+
* were for and when that read landed. Auto Handoff may take such an Account back before its window's old reset time.
|
|
187
|
+
*/
|
|
188
|
+
export declare function confirmedSpends(stateDir: string): Promise<{
|
|
189
|
+
accounts: string[];
|
|
190
|
+
quotaReadAt: string;
|
|
191
|
+
}[]>;
|
|
192
|
+
/**
|
|
193
|
+
* The spend lock of one login, across processes: one lock file per Account of the Same Login, taken in sorted order
|
|
194
|
+
* so two takers never wait on each other. Null when another sideby keeps it for longer than `waitMs`.
|
|
195
|
+
*/
|
|
196
|
+
export declare function takeLimitResetLock(stateDir: string, accounts: readonly string[], waitMs: number): Promise<ReleaseLock | null>;
|
|
197
|
+
/** What each outcome means for the user, in plain words. */
|
|
198
|
+
export declare function outcomeMessage(outcome: LimitResetOutcome, ref: string): string;
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// Spending a Limit Reset (spec §3.40, ADR-0072): the record of each attempt and the lock that makes the Panel, the CLI
|
|
2
|
+
// and the menu take turns. Each confirmation is one operation with one idempotency key, kept in
|
|
3
|
+
// `<state>/quota/limit-reset/<operation>.json` before the request is sent, so a retry, also from another process,
|
|
4
|
+
// reuses the key until the Host gives a final outcome. The Runtime owns the flow; a Family only sends the request.
|
|
5
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
6
|
+
import { chmod, mkdir, readdir, readFile, rm } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { UserError } from './errors.js';
|
|
9
|
+
import { writeFileAtomic } from './fs-safe.js';
|
|
10
|
+
import { takeFileLock } from './lock.js';
|
|
11
|
+
/** A refused or unfinished spend. `operationId` names the operation to retry, when there is one. */
|
|
12
|
+
export class LimitResetError extends UserError {
|
|
13
|
+
operationId;
|
|
14
|
+
constructor(message, opts) {
|
|
15
|
+
super(message, { code: opts.code });
|
|
16
|
+
if (opts.operationId)
|
|
17
|
+
this.operationId = opts.operationId;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** States a Host's answer ends an operation in. */
|
|
21
|
+
export const LIMIT_RESET_OUTCOMES = [
|
|
22
|
+
'reset',
|
|
23
|
+
'nothing-to-reset',
|
|
24
|
+
'none-left',
|
|
25
|
+
'already-done',
|
|
26
|
+
];
|
|
27
|
+
const STATES = [
|
|
28
|
+
'planned',
|
|
29
|
+
'pending',
|
|
30
|
+
...LIMIT_RESET_OUTCOMES,
|
|
31
|
+
'not-sent',
|
|
32
|
+
'stopped',
|
|
33
|
+
];
|
|
34
|
+
/** A finished or never-confirmed record is removed this long after it was finished or made. */
|
|
35
|
+
export const RECORD_KEEP_MS = 24 * 3600_000;
|
|
36
|
+
const ID_RE = /^lr-[a-z0-9]{6,12}-[a-f0-9]{8}$/;
|
|
37
|
+
const HEX_RE = /^[a-f0-9]{32,64}$/;
|
|
38
|
+
const REF_RE = /^[a-z][a-z0-9-]{0,31}:[a-z0-9][a-z0-9-]{0,31}$/;
|
|
39
|
+
export const limitResetDir = (stateDir) => join(stateDir, 'quota', 'limit-reset');
|
|
40
|
+
/** Whether `id` has the shape of an operation id, so it is safe as a file name. */
|
|
41
|
+
export const isOperationId = (id) => typeof id === 'string' && ID_RE.test(id);
|
|
42
|
+
export function newOperationId() {
|
|
43
|
+
return `lr-${Date.now().toString(36)}-${randomBytes(4).toString('hex')}`;
|
|
44
|
+
}
|
|
45
|
+
/** Whether a Host answered this operation: a spend happened (`reset`, `already-done`) or the Host said why not. */
|
|
46
|
+
export const isOutcome = (s) => LIMIT_RESET_OUTCOMES.includes(s);
|
|
47
|
+
/** Whether the operation spent a Limit Reset. */
|
|
48
|
+
export const spent = (s) => s === 'reset' || s === 'already-done';
|
|
49
|
+
async function ensureDir(stateDir) {
|
|
50
|
+
const dir = limitResetDir(stateDir);
|
|
51
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
52
|
+
// mkdir's mode is reduced by the umask and leaves an existing folder as it is.
|
|
53
|
+
await chmod(dir, 0o700);
|
|
54
|
+
return dir;
|
|
55
|
+
}
|
|
56
|
+
const isTime = (v) => typeof v === 'string' && Number.isFinite(Date.parse(v));
|
|
57
|
+
const saltedDigest = (salt, key) => createHash('sha256')
|
|
58
|
+
.update(salt + key)
|
|
59
|
+
.digest('hex');
|
|
60
|
+
/** A new digest for the login whose comparison key is `key`, with a salt no other record has. */
|
|
61
|
+
export function newLoginDigest(key) {
|
|
62
|
+
const salt = randomBytes(16).toString('hex');
|
|
63
|
+
return { salt, digest: saltedDigest(salt, key) };
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Whether `key`, the comparison key of the login that would send the request now, is the one `record` was made for.
|
|
67
|
+
* False when either is unknown: a record without a digest, or a login that cannot be read now (signed out, an
|
|
68
|
+
* unreadable sign-in). False always means "do not send".
|
|
69
|
+
*/
|
|
70
|
+
export function loginUnchanged(record, key) {
|
|
71
|
+
return Boolean(key && record.login && saltedDigest(record.login.salt, key) === record.login.digest);
|
|
72
|
+
}
|
|
73
|
+
function parseRecord(text) {
|
|
74
|
+
let v;
|
|
75
|
+
try {
|
|
76
|
+
v = JSON.parse(text);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
if (typeof v !== 'object' || v === null || v.version !== 1)
|
|
82
|
+
return null;
|
|
83
|
+
if (!isOperationId(v.operationId) || typeof v.idempotencyKey !== 'string' || !v.idempotencyKey)
|
|
84
|
+
return null;
|
|
85
|
+
if (!Array.isArray(v.accounts) || !v.accounts.length || !v.accounts.every((r) => REF_RE.test(String(r))))
|
|
86
|
+
return null;
|
|
87
|
+
if (!STATES.includes(v.state) || !isTime(v.createdAt))
|
|
88
|
+
return null;
|
|
89
|
+
const m = v.login;
|
|
90
|
+
const login = typeof m === 'object' && m !== null && HEX_RE.test(String(m.salt)) && HEX_RE.test(String(m.digest))
|
|
91
|
+
? { salt: String(m.salt), digest: String(m.digest) }
|
|
92
|
+
: undefined;
|
|
93
|
+
return {
|
|
94
|
+
version: 1,
|
|
95
|
+
operationId: v.operationId,
|
|
96
|
+
accounts: [...v.accounts].sort(),
|
|
97
|
+
...(login ? { login } : {}),
|
|
98
|
+
idempotencyKey: v.idempotencyKey,
|
|
99
|
+
state: v.state,
|
|
100
|
+
createdAt: v.createdAt,
|
|
101
|
+
attempts: Array.isArray(v.attempts) ? v.attempts.filter(isTime) : [],
|
|
102
|
+
...(isTime(v.finishedAt) ? { finishedAt: v.finishedAt } : {}),
|
|
103
|
+
...(isTime(v.quotaReadAt) ? { quotaReadAt: v.quotaReadAt } : {}),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** Where the record of `operationId` is kept. */
|
|
107
|
+
export const limitResetFile = (stateDir, operationId) => join(limitResetDir(stateDir), `${operationId}.json`);
|
|
108
|
+
const errorCode = (err) => err?.code;
|
|
109
|
+
/**
|
|
110
|
+
* The file of `operationId`: its record, `missing` when there is no such file, or `unreadable` when the file is
|
|
111
|
+
* there but cannot be read or is not a record sideby wrote. The two are never mixed up: a file that cannot be read
|
|
112
|
+
* may be an unresolved spend.
|
|
113
|
+
*/
|
|
114
|
+
async function loadRecord(stateDir, operationId) {
|
|
115
|
+
let text;
|
|
116
|
+
try {
|
|
117
|
+
text = await readFile(limitResetFile(stateDir, operationId), 'utf8');
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
return errorCode(err) === 'ENOENT' ? 'missing' : 'unreadable';
|
|
121
|
+
}
|
|
122
|
+
const r = parseRecord(text);
|
|
123
|
+
return r && r.operationId === operationId ? r : 'unreadable';
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Why nothing may be sent while `paths` (operation files, or the folder itself) cannot be read, and what to do.
|
|
127
|
+
* Names the paths, never their contents.
|
|
128
|
+
*/
|
|
129
|
+
export function unreadableRecordsMessage(stateDir, paths) {
|
|
130
|
+
const [first, ...more] = paths;
|
|
131
|
+
const why = 'so it cannot tell whether an earlier attempt is still unresolved and will not use a limit reset';
|
|
132
|
+
if (first === limitResetDir(stateDir))
|
|
133
|
+
return `sideby cannot read the folder ${first}, where it keeps its limit reset operations, ${why}. Make it readable again (\`chmod 700 ${first}\`), then try again`;
|
|
134
|
+
return `sideby cannot read ${first}${more.length ? ` (and ${more.length} more beside it)` : ''}, the record of an earlier limit reset operation, ${why}. Make it readable again (\`chmod 600 ${first}\`); if the file is damaged, check the count on the vendor's own usage page first, then move the file away`;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The record of `operationId`, or null when there is none. Throws a `LimitResetError` (`records-unreadable`) when
|
|
138
|
+
* its file is there but cannot be read or is not a record sideby wrote.
|
|
139
|
+
*/
|
|
140
|
+
export async function readLimitResetRecord(stateDir, operationId) {
|
|
141
|
+
if (!isOperationId(operationId))
|
|
142
|
+
return null;
|
|
143
|
+
const r = await loadRecord(stateDir, operationId);
|
|
144
|
+
if (r === 'unreadable')
|
|
145
|
+
throw new LimitResetError(`${unreadableRecordsMessage(stateDir, [limitResetFile(stateDir, operationId)])}. Nothing was sent`, { code: 'records-unreadable' });
|
|
146
|
+
return r === 'missing' ? null : r;
|
|
147
|
+
}
|
|
148
|
+
/** Keeps `record` (folder 700, file 600, written through a temp file and a rename). */
|
|
149
|
+
export async function writeLimitResetRecord(stateDir, record) {
|
|
150
|
+
const dir = await ensureDir(stateDir);
|
|
151
|
+
await writeFileAtomic(join(dir, `${record.operationId}.json`), `${JSON.stringify(record, null, 2)}\n`, 0o600);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* A new operation for the Accounts of one login, not yet confirmed. `loginKey` is that login's comparison key; only
|
|
155
|
+
* its salted digest is kept.
|
|
156
|
+
*/
|
|
157
|
+
export function newLimitResetRecord(accounts, now, loginKey) {
|
|
158
|
+
return {
|
|
159
|
+
version: 1,
|
|
160
|
+
operationId: newOperationId(),
|
|
161
|
+
accounts: [...accounts].sort(),
|
|
162
|
+
login: newLoginDigest(loginKey),
|
|
163
|
+
idempotencyKey: randomUUID(),
|
|
164
|
+
state: 'planned',
|
|
165
|
+
createdAt: now.toISOString(),
|
|
166
|
+
attempts: [],
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/** Reads every operation file. A folder that is not there yet holds nothing; any other failure is `unreadable`. */
|
|
170
|
+
export async function scanLimitResetRecords(stateDir) {
|
|
171
|
+
const dir = limitResetDir(stateDir);
|
|
172
|
+
let names;
|
|
173
|
+
try {
|
|
174
|
+
names = await readdir(dir);
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
return { records: [], unreadable: errorCode(err) === 'ENOENT' ? [] : [dir] };
|
|
178
|
+
}
|
|
179
|
+
const records = [];
|
|
180
|
+
const unreadable = [];
|
|
181
|
+
for (const n of names.sort()) {
|
|
182
|
+
if (!n.endsWith('.json') || !isOperationId(n.slice(0, -5)))
|
|
183
|
+
continue;
|
|
184
|
+
const r = await loadRecord(stateDir, n.slice(0, -5));
|
|
185
|
+
if (r === 'unreadable')
|
|
186
|
+
unreadable.push(join(dir, n));
|
|
187
|
+
else if (r !== 'missing')
|
|
188
|
+
records.push(r);
|
|
189
|
+
}
|
|
190
|
+
records.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
|
|
191
|
+
return { records, unreadable };
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Every record that can be read, oldest first. For readers that spend nothing (pruning, Auto Handoff's look at
|
|
195
|
+
* confirmed spends); a spend goes through `scanLimitResetRecords`, which also tells what could not be read.
|
|
196
|
+
*/
|
|
197
|
+
export async function listLimitResetRecords(stateDir) {
|
|
198
|
+
return (await scanLimitResetRecords(stateDir)).records;
|
|
199
|
+
}
|
|
200
|
+
/** Whether a plan was made too long ago to confirm: its numbers are a day old, and pruning may remove it. */
|
|
201
|
+
export const planExpired = (record, now) => now.getTime() - Date.parse(record.createdAt) >= RECORD_KEEP_MS;
|
|
202
|
+
/** Whether nobody needs `r` any more. Never an unresolved one. */
|
|
203
|
+
const removable = (r, now) => r.state === 'planned'
|
|
204
|
+
? planExpired(r, now)
|
|
205
|
+
: r.state !== 'pending' && now.getTime() - Date.parse(r.finishedAt ?? r.createdAt) >= RECORD_KEEP_MS;
|
|
206
|
+
/**
|
|
207
|
+
* Removes records nobody needs any more: a finished one 24 hours after it finished, a plan nobody confirmed 24 hours
|
|
208
|
+
* after it was made. An unresolved one (`pending`) is never removed: only its own key may ask the Host again. Nor is
|
|
209
|
+
* a file that cannot be read: it may be one.
|
|
210
|
+
*
|
|
211
|
+
* A record is removed only under the spend lock of its Accounts, the one a confirmation holds from before it writes
|
|
212
|
+
* `pending` until it has its answer, and only after it was read again there: a plan confirmed since this looked is
|
|
213
|
+
* unresolved now, and its key must stay. A lock that is held is not waited for; the next pruning looks again.
|
|
214
|
+
* `seam` is for tests: it runs after a record was read as removable and before its lock is taken.
|
|
215
|
+
*/
|
|
216
|
+
export async function pruneLimitResetRecords(stateDir, now, seam) {
|
|
217
|
+
for (const seen of await listLimitResetRecords(stateDir)) {
|
|
218
|
+
if (!removable(seen, now))
|
|
219
|
+
continue;
|
|
220
|
+
await seam?.afterRead?.(seen);
|
|
221
|
+
const release = await takeLimitResetLock(stateDir, seen.accounts, 0);
|
|
222
|
+
if (!release)
|
|
223
|
+
continue;
|
|
224
|
+
try {
|
|
225
|
+
const r = await loadRecord(stateDir, seen.operationId);
|
|
226
|
+
if (typeof r === 'object' && removable(r, now) && sameAccounts(r, seen.accounts))
|
|
227
|
+
await rm(limitResetFile(stateDir, r.operationId), { force: true }).catch(() => { });
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
await release();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* The unresolved operation of a login, the oldest first; undefined when there is none. `loginKey` is the comparison
|
|
236
|
+
* key of the login that asks now: an operation made for that login comes first, whichever Accounts it names, so an
|
|
237
|
+
* Account that signed in as the login since finds it too. Then one that names one of `accounts`: it may be another
|
|
238
|
+
* login's by now, which `loginUnchanged` tells, but no new operation is made beside it.
|
|
239
|
+
*/
|
|
240
|
+
export function unresolvedFor(records, accounts, loginKey) {
|
|
241
|
+
const open = records.filter((r) => r.state === 'pending');
|
|
242
|
+
return (open.find((r) => loginUnchanged(r, loginKey)) ??
|
|
243
|
+
open.find((r) => r.accounts.some((a) => accounts.includes(a))));
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Whether a record's Accounts are exactly `accounts`: the group the operation was made for has not changed. Equal
|
|
247
|
+
* refs do not show that the login behind them is the same; `loginUnchanged` does.
|
|
248
|
+
*/
|
|
249
|
+
export function sameAccounts(record, accounts) {
|
|
250
|
+
const now = [...accounts].sort();
|
|
251
|
+
return record.accounts.length === now.length && record.accounts.every((r, i) => r === now[i]);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Spends that went through and whose following Quota read is kept (ADR-0072, amending ADR-0060): the Accounts they
|
|
255
|
+
* were for and when that read landed. Auto Handoff may take such an Account back before its window's old reset time.
|
|
256
|
+
*/
|
|
257
|
+
export async function confirmedSpends(stateDir) {
|
|
258
|
+
return (await listLimitResetRecords(stateDir)).flatMap((r) => spent(r.state) && r.quotaReadAt ? [{ accounts: r.accounts, quotaReadAt: r.quotaReadAt }] : []);
|
|
259
|
+
}
|
|
260
|
+
const LOCK = { staleMs: 30_000, beatMs: 5_000, maxMs: 180_000 };
|
|
261
|
+
/**
|
|
262
|
+
* The spend lock of one login, across processes: one lock file per Account of the Same Login, taken in sorted order
|
|
263
|
+
* so two takers never wait on each other. Null when another sideby keeps it for longer than `waitMs`.
|
|
264
|
+
*/
|
|
265
|
+
export async function takeLimitResetLock(stateDir, accounts, waitMs) {
|
|
266
|
+
const dir = join(await ensureDir(stateDir), 'locks');
|
|
267
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
268
|
+
const held = [];
|
|
269
|
+
const release = async () => {
|
|
270
|
+
for (const r of held.reverse())
|
|
271
|
+
await r();
|
|
272
|
+
};
|
|
273
|
+
const deadline = Date.now() + waitMs;
|
|
274
|
+
for (const ref of [...new Set(accounts)].sort()) {
|
|
275
|
+
const lock = await takeFileLock(join(dir, `${ref.replace(':', '.')}.lock`), {
|
|
276
|
+
...LOCK,
|
|
277
|
+
wait: { timeoutMs: Math.max(0, deadline - Date.now()), pollMs: 100 },
|
|
278
|
+
}).catch(() => null);
|
|
279
|
+
if (!lock) {
|
|
280
|
+
await release();
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
held.push(lock);
|
|
284
|
+
}
|
|
285
|
+
return release;
|
|
286
|
+
}
|
|
287
|
+
/** What each outcome means for the user, in plain words. */
|
|
288
|
+
export function outcomeMessage(outcome, ref) {
|
|
289
|
+
switch (outcome) {
|
|
290
|
+
case 'reset':
|
|
291
|
+
return `A limit reset was used for ${ref}.`;
|
|
292
|
+
case 'already-done':
|
|
293
|
+
return `This limit reset was already used for ${ref}; nothing more was spent.`;
|
|
294
|
+
case 'nothing-to-reset':
|
|
295
|
+
return `Nothing was spent: no limit of ${ref} can be reset right now.`;
|
|
296
|
+
case 'none-left':
|
|
297
|
+
return `Nothing was spent: ${ref} holds no limit reset.`;
|
|
298
|
+
}
|
|
299
|
+
}
|