@kapybara/zerosub 1.5.1 → 1.18.3
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 +220 -26
- package/client/accounts-surface.tsx +344 -110
- package/client/add-account.tsx +335 -23
- package/client/api-account.tsx +250 -0
- package/client/azure-account.tsx +311 -0
- package/client/commands.ts +44 -8
- package/client/composer-item.tsx +203 -0
- package/client/fork-confirm.tsx +71 -0
- package/client/fork-settings.tsx +148 -0
- package/client/pace.tsx +196 -0
- package/client/pi-accounts.tsx +571 -0
- package/client/pills.ts +63 -25
- package/client/reset-confirm.tsx +12 -3
- package/client/settings-screen.tsx +48 -9
- package/client/store.ts +148 -19
- package/client/switch-row.tsx +28 -8
- package/client/ui.tsx +11 -0
- package/index.client.tsx +4 -1
- package/index.server.ts +53 -10
- package/package.json +5 -2
- package/server/account-identity.ts +11 -0
- package/server/adapter.ts +115 -8
- package/server/api-usage.ts +144 -0
- package/server/azure.ts +346 -0
- package/server/binaries.ts +41 -3
- package/server/claude.ts +276 -21
- package/server/codex-same-conversation.ts +71 -0
- package/server/codex.ts +35 -7
- package/server/continuations.ts +67 -17
- package/server/cursor.ts +222 -0
- package/server/families.ts +105 -8
- package/server/grok.ts +225 -0
- package/server/handoff.ts +211 -29
- package/server/homes.ts +1263 -35
- package/server/json-file.ts +39 -8
- package/server/launchers.ts +319 -0
- package/server/limits.ts +80 -3
- package/server/main-proxy.ts +238 -0
- package/server/modes.ts +20 -4
- package/server/paths.ts +81 -1
- package/server/pi.ts +528 -0
- package/server/placement.ts +133 -0
- package/server/process.ts +18 -1
- package/server/processes.ts +66 -0
- package/server/provider-env.ts +28 -0
- package/server/proxy.ts +282 -0
- package/server/reopen.ts +50 -8
- package/server/routing.ts +337 -30
- package/server/service.ts +4320 -805
- package/server/state.ts +303 -24
- package/server/usage.ts +2 -0
- package/shared/format.ts +170 -2
- package/shared/model.ts +339 -2
- package/shared/preferences.ts +22 -1
- package/shared/rpc.ts +130 -8
- package/shared/timeline.ts +11 -0
package/server/json-file.ts
CHANGED
|
@@ -1,30 +1,61 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
|
-
import { mkdir, readFile, rename, rm
|
|
2
|
+
import { mkdir, open, readFile, rename, rm } from "node:fs/promises";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
/** The file's text, or `undefined` when there is no file. */
|
|
6
|
+
export async function readText(path: string): Promise<string | undefined> {
|
|
7
7
|
try {
|
|
8
|
-
|
|
8
|
+
return await readFile(path, "utf8");
|
|
9
9
|
} catch (error) {
|
|
10
10
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
11
11
|
throw error;
|
|
12
12
|
}
|
|
13
|
-
return JSON.parse(raw) as unknown;
|
|
14
13
|
}
|
|
15
14
|
|
|
16
|
-
/**
|
|
17
|
-
export async function
|
|
15
|
+
/** The file's JSON, or `undefined` when there is no file. */
|
|
16
|
+
export async function readJson(path: string): Promise<unknown | undefined> {
|
|
17
|
+
const raw = await readText(path);
|
|
18
|
+
if (raw === undefined) return undefined;
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(raw) as unknown;
|
|
21
|
+
} catch {
|
|
22
|
+
// The parser's message quotes the text around the mistake, and settings files hold keys and tokens.
|
|
23
|
+
throw new Error(`${path} isn't valid JSON`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Writes through a sibling temp file and rename, so readers never see a partial file. When
|
|
29
|
+
* `durable`, the data is on disk before the rename and the rename after it, so a crash leaves the
|
|
30
|
+
* old file or the new one, never an empty one. (On macOS each of those syncs is a full flush that
|
|
31
|
+
* takes milliseconds, so files that are only a spare copy skip them.)
|
|
32
|
+
*/
|
|
33
|
+
export async function writeJsonAtomic(path: string, value: unknown, { mode = 0o600, durable = true } = {}): Promise<void> {
|
|
18
34
|
const directory = dirname(path);
|
|
19
35
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
20
36
|
const temporary = join(directory, `.${randomBytes(6).toString("hex")}.tmp`);
|
|
21
37
|
try {
|
|
22
|
-
await
|
|
38
|
+
const file = await open(temporary, "wx", mode);
|
|
39
|
+
try {
|
|
40
|
+
await file.writeFile(`${JSON.stringify(value, null, 2)}\n`);
|
|
41
|
+
if (durable) await file.sync();
|
|
42
|
+
} finally {
|
|
43
|
+
await file.close();
|
|
44
|
+
}
|
|
23
45
|
await rename(temporary, path);
|
|
24
46
|
} catch (error) {
|
|
25
47
|
await rm(temporary, { force: true });
|
|
26
48
|
throw error;
|
|
27
49
|
}
|
|
50
|
+
if (durable) await syncDirectory(directory);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Makes a rename in `directory` durable. Where a directory can't be opened or synced, it's skipped. */
|
|
54
|
+
async function syncDirectory(directory: string): Promise<void> {
|
|
55
|
+
const handle = await open(directory, "r").catch(() => null);
|
|
56
|
+
if (!handle) return;
|
|
57
|
+
await handle.sync().catch(() => undefined);
|
|
58
|
+
await handle.close();
|
|
28
59
|
}
|
|
29
60
|
|
|
30
61
|
/** Runs async sections one at a time, in call order. */
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { isOwnHome, launcherDir, paseoHome, piLauncherDir } from "./paths";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A script per added Claude account that starts the Claude CLI on it, for use outside Paseo: put
|
|
8
|
+
* `~/.claude-config` on `PATH` once, then run `claude-work.sh`. Accounts added later get theirs
|
|
9
|
+
* without touching the shell profile again. `ZEROSUB_LAUNCHER_DIR` puts them somewhere else.
|
|
10
|
+
*
|
|
11
|
+
* Each script sets exactly what ZeroSub sets for an agent on that account, then hands over to
|
|
12
|
+
* `claude`, so the caller's shell is untouched. The account's proxy (and an API account's key,
|
|
13
|
+
* base URL and blanked credential variables) needs nothing here: it lives in the home's
|
|
14
|
+
* `settings.json` `env`, which Claude Code applies over whatever the shell exports.
|
|
15
|
+
*
|
|
16
|
+
* Each added Pi account gets one too, `pi-<account>.sh` in `~/.pi-config` (`ZEROSUB_PI_DIR`): it
|
|
17
|
+
* sets the account's agent directory, takes the proxy ZeroSub gives its agents from the account's
|
|
18
|
+
* `zerosub.env` (kept up to date there, see `PiAdapter.prepareHome`) and runs `pi`. Each kind only
|
|
19
|
+
* ever touches its own scripts, so both can share a directory.
|
|
20
|
+
*/
|
|
21
|
+
export { launcherDir, piLauncherDir };
|
|
22
|
+
|
|
23
|
+
/** Which CLI a script starts. */
|
|
24
|
+
export type LauncherKind = "claude" | "pi";
|
|
25
|
+
|
|
26
|
+
interface KindSpec {
|
|
27
|
+
/** Script names start with `<prefix>-`. */
|
|
28
|
+
prefix: string;
|
|
29
|
+
/** Third line: says which account the script is for. */
|
|
30
|
+
describe(label: string): string;
|
|
31
|
+
describePattern: RegExp;
|
|
32
|
+
/** The variable whose value is the account's home. */
|
|
33
|
+
homeVariable: string;
|
|
34
|
+
/** The lines after the third. */
|
|
35
|
+
body(home: string): string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** File in a Pi account's home holding the proxy variables its agents get, which its script reads. */
|
|
39
|
+
export const PI_LAUNCH_ENV = "zerosub.env";
|
|
40
|
+
|
|
41
|
+
const KINDS: Record<LauncherKind, KindSpec> = {
|
|
42
|
+
claude: {
|
|
43
|
+
prefix: "claude",
|
|
44
|
+
describe: (label) => `# Starts the Claude CLI on "${label}", an account added in Paseo.`,
|
|
45
|
+
describePattern: /^# Starts the Claude CLI on "(.*)", an account added in Paseo\.$/,
|
|
46
|
+
homeVariable: "CLAUDE_CONFIG_DIR",
|
|
47
|
+
body: (home) => [
|
|
48
|
+
`unset ${OVERRIDING_AUTH.join(" ")}`,
|
|
49
|
+
`export CLAUDE_CONFIG_DIR=${quote(home)}`,
|
|
50
|
+
`export CLAUDE_SECURESTORAGE_CONFIG_DIR=${quote(home)}`,
|
|
51
|
+
'exec claude "$@"',
|
|
52
|
+
],
|
|
53
|
+
},
|
|
54
|
+
pi: {
|
|
55
|
+
prefix: "pi",
|
|
56
|
+
describe: (label) => `# Starts Pi on "${label}", an account added in Paseo.`,
|
|
57
|
+
describePattern: /^# Starts Pi on "(.*)", an account added in Paseo\.$/,
|
|
58
|
+
homeVariable: "PI_CODING_AGENT_DIR",
|
|
59
|
+
body: (home) => [
|
|
60
|
+
`export PI_CODING_AGENT_DIR=${quote(home)}`,
|
|
61
|
+
"# The proxy this account's agents use in Paseo, kept up to date by ZeroSub; it wins over the shell's.",
|
|
62
|
+
`[ -f "$PI_CODING_AGENT_DIR/${PI_LAUNCH_ENV}" ] && . "$PI_CODING_AGENT_DIR/${PI_LAUNCH_ENV}"`,
|
|
63
|
+
'exec pi "$@"',
|
|
64
|
+
],
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** Which kind of ZeroSub script `content` is, by its third line; null when it's neither. */
|
|
69
|
+
function kindOf(content: string): LauncherKind | null {
|
|
70
|
+
const line = content.split("\n")[2] ?? "";
|
|
71
|
+
for (const kind of Object.keys(KINDS) as LauncherKind[]) if (KINDS[kind].describePattern.test(line)) return kind;
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface LauncherAccount {
|
|
76
|
+
id: string;
|
|
77
|
+
label: string;
|
|
78
|
+
home: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Variables that would make the CLI use something other than the account's own login. */
|
|
82
|
+
const OVERRIDING_AUTH = ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"];
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Second line of every script ZeroSub writes. It names the Paseo home of the daemon that wrote it,
|
|
86
|
+
* since daemons with different `PASEO_HOME`s can share the directory: each only ever rewrites,
|
|
87
|
+
* removes or releases scripts carrying its own. Of those, only the ones that start a home of
|
|
88
|
+
* ZeroSub's own are ever removed; the rest are released (see `RELEASED`).
|
|
89
|
+
*/
|
|
90
|
+
function marker(): string {
|
|
91
|
+
return `# Generated by ZeroSub (Paseo home ${paseoHomeTag()}). Don't edit: it's rewritten whenever accounts change.`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const MARKER_PATTERN = /^# Generated by ZeroSub \(Paseo home ([0-9a-f]{8})\)\. /;
|
|
95
|
+
|
|
96
|
+
/** Short tag for this daemon's Paseo home in the marker: the first 8 hex digits of its path's SHA-256. */
|
|
97
|
+
export function paseoHomeTag(): string {
|
|
98
|
+
return createHash("sha256").update(paseoHome()).digest("hex").slice(0, 8);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Takes the marker's place in a script ZeroSub stops managing but mustn't delete: one that starts
|
|
103
|
+
* a home outside `homesDir()`, which stays the user's account after ZeroSub forgets it, one whose
|
|
104
|
+
* home is still there after its account went missing, or a copy under another name.
|
|
105
|
+
*/
|
|
106
|
+
const RELEASED = "# No longer managed by ZeroSub (its account was removed or renamed there). ZeroSub won't delete it.";
|
|
107
|
+
|
|
108
|
+
export function slug(label: string): string {
|
|
109
|
+
return label
|
|
110
|
+
.normalize("NFKD")
|
|
111
|
+
.replace(/[̀-ͯ]/g, "")
|
|
112
|
+
.toLowerCase()
|
|
113
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
114
|
+
.replace(/^-+|-+$/g, "")
|
|
115
|
+
.slice(0, 32)
|
|
116
|
+
.replace(/-+$/, "");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The name part of a `kind` script or home for `label`: `claude-work`, `pi-work` (a label already starting `pi-` keeps it once). */
|
|
120
|
+
export function kindName(kind: LauncherKind, label: string): string {
|
|
121
|
+
const { prefix } = KINDS[kind];
|
|
122
|
+
const base = slug(label);
|
|
123
|
+
return base.startsWith(`${prefix}-`) ? base : `${prefix}-${base}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The first six hex digits of an account's ID, which tell names apart. */
|
|
127
|
+
export function idSuffix(id: string): string {
|
|
128
|
+
return id.replace(/^[a-z]+-/, "").slice(0, 6);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* `claude-<label>.sh` (`pi-<label>.sh` for `kind` "pi"), made unique: a label that's empty or taken falls back to the account's ID.
|
|
133
|
+
* `kept` lists scripts ZeroSub must not overwrite, by file name, with the home each starts (null
|
|
134
|
+
* when no account may take it over); an account only gets one of those names if the script starts
|
|
135
|
+
* that account's own home.
|
|
136
|
+
*/
|
|
137
|
+
export function launcherNames(
|
|
138
|
+
accounts: readonly LauncherAccount[],
|
|
139
|
+
kept: ReadonlyMap<string, string | null> = new Map(),
|
|
140
|
+
kind: LauncherKind = "claude",
|
|
141
|
+
): Map<string, string> {
|
|
142
|
+
const { prefix } = KINDS[kind];
|
|
143
|
+
const names = new Map<string, string>();
|
|
144
|
+
const taken = new Set<string>();
|
|
145
|
+
for (const account of accounts) {
|
|
146
|
+
const free = (name: string) => {
|
|
147
|
+
if (taken.has(name)) return false;
|
|
148
|
+
const home = kept.get(`${name}.sh`);
|
|
149
|
+
return home === undefined || (home !== null && resolve(home) === resolve(account.home));
|
|
150
|
+
};
|
|
151
|
+
const suffix = idSuffix(account.id);
|
|
152
|
+
const base = slug(account.label) ? kindName(kind, account.label) : `${prefix}-${suffix}`;
|
|
153
|
+
let name = base;
|
|
154
|
+
if (!free(name)) name = `${name}-${suffix}`;
|
|
155
|
+
for (let n = 2; !free(name); n++) name = `${base}-${suffix}-${n}`;
|
|
156
|
+
taken.add(name);
|
|
157
|
+
names.set(account.id, `${name}.sh`);
|
|
158
|
+
}
|
|
159
|
+
return names;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function quote(value: string): string {
|
|
163
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function renderLauncher(account: LauncherAccount, kind: LauncherKind = "claude"): string {
|
|
167
|
+
const spec = KINDS[kind];
|
|
168
|
+
return ["#!/bin/sh", marker(), spec.describe(account.label.replace(/[\r\n]+/g, " ")), ...spec.body(account.home), ""].join("\n");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Who wrote a script: this or another daemon's tag, or null if not ZeroSub. */
|
|
172
|
+
function writer(content: string): string | null {
|
|
173
|
+
return MARKER_PATTERN.exec(content.split("\n")[1] ?? "")?.[1] ?? null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function released(content: string): boolean {
|
|
177
|
+
return content.split("\n")[1] === RELEASED;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The account a script says it's for, read back from the line `renderLauncher` writes. */
|
|
181
|
+
function scriptLabel(content: string, kind: LauncherKind): string | null {
|
|
182
|
+
return KINDS[kind].describePattern.exec(content.split("\n")[2] ?? "")?.[1] ?? null;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Whether a script is where `launcherNames` puts the account it's for (account IDs are hex). A copy under a name of the user's is the user's. */
|
|
186
|
+
function namedFor(name: string, content: string, kind: LauncherKind): boolean {
|
|
187
|
+
const label = scriptLabel(content, kind);
|
|
188
|
+
if (label === null) return false;
|
|
189
|
+
const id = "[0-9a-f]{6}";
|
|
190
|
+
const { prefix } = KINDS[kind];
|
|
191
|
+
const base = slug(label) ? kindName(kind, label) : `${prefix}-${id}`;
|
|
192
|
+
return new RegExp(`^(?:${base}|${prefix}-${id})(?:-${id}(?:-[0-9]+)?)?\\.sh$`).test(name);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Whether a released script is still exactly as ZeroSub released it, so its account may have it back. */
|
|
196
|
+
function asReleased(content: string, home: string, kind: LauncherKind): boolean {
|
|
197
|
+
const label = scriptLabel(content, kind);
|
|
198
|
+
if (label === null) return false;
|
|
199
|
+
const lines = renderLauncher({ id: "", label, home }, kind).split("\n");
|
|
200
|
+
lines[1] = RELEASED;
|
|
201
|
+
return lines.join("\n") === content;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The home a script starts the CLI on, read back from the line `renderLauncher` writes. */
|
|
205
|
+
function scriptHome(content: string, kind: LauncherKind): string | null {
|
|
206
|
+
const prefix = `export ${KINDS[kind].homeVariable}=`;
|
|
207
|
+
const value = content.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length);
|
|
208
|
+
if (!value || !/^'(?:[^']|'\\'')*'$/.test(value)) return null;
|
|
209
|
+
return value.slice(1, -1).replace(/'\\''/g, "'");
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* What's at `path`: undefined if nothing, null for anything ZeroSub never replaces (a symlink, a
|
|
214
|
+
* directory, a file it can't read), otherwise the file's content.
|
|
215
|
+
*/
|
|
216
|
+
async function readEntry(path: string): Promise<string | null | undefined> {
|
|
217
|
+
const entry = await lstat(path).catch(() => undefined);
|
|
218
|
+
if (!entry) return undefined;
|
|
219
|
+
if (!entry.isFile()) return null;
|
|
220
|
+
return readFile(path, "utf8").catch(() => null);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The entries in `directory` that could be scripts, as `readEntry` sees them. */
|
|
224
|
+
async function readScripts(directory: string): Promise<Map<string, string | null>> {
|
|
225
|
+
const scripts = new Map<string, string | null>();
|
|
226
|
+
for (const entry of await readdir(directory).catch(() => [] as string[])) {
|
|
227
|
+
// Dot files include another write's temporary file, about to be renamed into place.
|
|
228
|
+
if (entry.startsWith(".") || !entry.endsWith(".sh")) continue;
|
|
229
|
+
const content = await readEntry(join(directory, entry));
|
|
230
|
+
if (content !== undefined) scripts.set(entry, content);
|
|
231
|
+
}
|
|
232
|
+
return scripts;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Puts `content` in place atomically, provided the file is still what was read (`expected`, or
|
|
237
|
+
* undefined if there was none): a file someone put there meanwhile is never replaced.
|
|
238
|
+
*/
|
|
239
|
+
async function writeScript(directory: string, name: string, content: string, expected: string | undefined): Promise<void> {
|
|
240
|
+
const path = join(directory, name);
|
|
241
|
+
const temporary = join(directory, `.${name}.${randomBytes(4).toString("hex")}.tmp`);
|
|
242
|
+
try {
|
|
243
|
+
await writeFile(temporary, content, { mode: 0o755 });
|
|
244
|
+
if ((await readEntry(path)) === expected) await rename(temporary, path);
|
|
245
|
+
} finally {
|
|
246
|
+
await rm(temporary, { force: true });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Writes each account's script (only when it changed) and tidies up this daemon's scripts for
|
|
252
|
+
* accounts that are gone or renamed: one that starts a home ZeroSub owns (see `isOwnHome`) is
|
|
253
|
+
* removed when that home's account was renamed, or the home is `leaving` (listed for cleanup) or
|
|
254
|
+
* gone; any other is released, its marker line replaced, so it keeps working and is the user's
|
|
255
|
+
* from then on. That includes the script of a home of ZeroSub's own that only the registry lost
|
|
256
|
+
* track of, and a copy the user made of a script under another name. A released script goes back
|
|
257
|
+
* to its account if that home is added again, unless the user changed it; until then released
|
|
258
|
+
* and hand-written scripts, other daemons' scripts and anything that isn't a plain file (a
|
|
259
|
+
* symlink, say) are never overwritten by an account's, and anything else in the directory is left
|
|
260
|
+
* alone. A script of this daemon's for a home that `moved` (old home to new) to an account's is
|
|
261
|
+
* that account's, rewritten under its name. Returns each account's script name.
|
|
262
|
+
*/
|
|
263
|
+
export async function writeLaunchers(
|
|
264
|
+
accounts: readonly LauncherAccount[],
|
|
265
|
+
directory = launcherDir(),
|
|
266
|
+
leaving: Iterable<string> = [],
|
|
267
|
+
moved: ReadonlyMap<string, string> = new Map(),
|
|
268
|
+
kind: LauncherKind = "claude",
|
|
269
|
+
): Promise<Map<string, string>> {
|
|
270
|
+
const scripts = await readScripts(directory);
|
|
271
|
+
// The other kind's scripts are that kind's to manage: neither this kind's nor names it may take.
|
|
272
|
+
for (const [name, content] of scripts) {
|
|
273
|
+
const of = content === null ? null : kindOf(content);
|
|
274
|
+
if (of !== null && of !== kind && writer(content!) !== null) scripts.delete(name);
|
|
275
|
+
}
|
|
276
|
+
const tag = paseoHomeTag();
|
|
277
|
+
const homes = new Set(accounts.map((account) => resolve(account.home)));
|
|
278
|
+
const going = new Set([...leaving].map((home) => resolve(home)));
|
|
279
|
+
const goes = async (home: string) =>
|
|
280
|
+
homes.has(resolve(home)) ||
|
|
281
|
+
going.has(resolve(home)) ||
|
|
282
|
+
(await lstat(home).then(
|
|
283
|
+
() => false,
|
|
284
|
+
(error: NodeJS.ErrnoException) => error.code === "ENOENT",
|
|
285
|
+
));
|
|
286
|
+
/** This daemon's scripts: the only ones it rewrites, removes or releases. */
|
|
287
|
+
const mine = new Map<string, string>();
|
|
288
|
+
const kept = new Map<string, string | null>();
|
|
289
|
+
for (const [name, content] of scripts) {
|
|
290
|
+
const started = content === null ? null : scriptHome(content, kind);
|
|
291
|
+
const movedTo = started === null ? undefined : moved.get(resolve(started));
|
|
292
|
+
const home = movedTo !== undefined && homes.has(resolve(movedTo)) ? movedTo : started;
|
|
293
|
+
if (content !== null && writer(content) === tag) {
|
|
294
|
+
mine.set(name, content);
|
|
295
|
+
if (home === null || !namedFor(name, content, kind) || !(await isOwnHome(home)) || !(await goes(home))) kept.set(name, home);
|
|
296
|
+
} else {
|
|
297
|
+
// Only a released script goes back to an account: the one whose home it starts, if unchanged.
|
|
298
|
+
kept.set(name, content !== null && home !== null && released(content) && asReleased(content, home, kind) ? home : null);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const names = launcherNames(accounts, kept, kind);
|
|
302
|
+
const wanted = new Map(accounts.map((account) => [names.get(account.id)!, renderLauncher(account, kind)]));
|
|
303
|
+
if (wanted.size > 0) await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
304
|
+
for (const [name, content] of wanted) {
|
|
305
|
+
const current = scripts.get(name);
|
|
306
|
+
if (current !== null && current !== content) await writeScript(directory, name, content, current);
|
|
307
|
+
}
|
|
308
|
+
for (const [name, content] of mine) {
|
|
309
|
+
if (wanted.has(name)) continue;
|
|
310
|
+
if (kept.has(name)) {
|
|
311
|
+
const lines = content.split("\n");
|
|
312
|
+
lines[1] = RELEASED;
|
|
313
|
+
await writeScript(directory, name, lines.join("\n"), content);
|
|
314
|
+
} else if ((await readEntry(join(directory, name))) === content) {
|
|
315
|
+
await rm(join(directory, name), { force: true });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return names;
|
|
319
|
+
}
|
package/server/limits.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AgentTimelineItem, LimitHit, LimitKind, TurnEvent } from "./adapter";
|
|
2
|
+
import { isTurnPrompt } from "./handoff";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Claude Code's exact wording for hard limits (2.1.x templates: `You've hit your ${limit}${suffix}`),
|
|
@@ -45,6 +46,13 @@ const CLAUDE_SIGNED_OUT =
|
|
|
45
46
|
const CODEX_SIGNED_OUT =
|
|
46
47
|
/refresh token was already used|please log out and sign in again|access token could not be refreshed|refresh_token_reused|refresh_token_expired/i;
|
|
47
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Anthropic refusing the key a Pi account sends (`401 {"type":"error","error":{"type":"authentication_error",
|
|
51
|
+
* "message":"invalid x-api-key"}}`). Other providers' refusals word it otherwise, so a model of
|
|
52
|
+
* another provider failing on the account doesn't mark its Anthropic key as refused.
|
|
53
|
+
*/
|
|
54
|
+
const PI_SIGNED_OUT = /"type"\s*:\s*"authentication_error"|invalid x-api-key/i;
|
|
55
|
+
|
|
48
56
|
const SYSTEM_ERROR = /^\[System Error\]\s*/;
|
|
49
57
|
const MAX_NOTICE = 400;
|
|
50
58
|
|
|
@@ -64,7 +72,7 @@ export function turnRows(entries: ReadonlyArray<{ item: AgentTimelineItem; turnI
|
|
|
64
72
|
const entry = entries[index];
|
|
65
73
|
if (!entry) continue;
|
|
66
74
|
if (entry.turnId === turnId) rows.push(entry.item);
|
|
67
|
-
else if (rows.length > 0 && entry.turnId && entry.item
|
|
75
|
+
else if (rows.length > 0 && entry.turnId && isTurnPrompt(entry.item)) break;
|
|
68
76
|
}
|
|
69
77
|
return rows.reverse();
|
|
70
78
|
}
|
|
@@ -84,7 +92,7 @@ function notices(event: TurnEvent, includeFinalReplies: boolean): string[] {
|
|
|
84
92
|
for (let index = timeline.length - 1; index >= 0; index -= 1) {
|
|
85
93
|
const item = timeline[index];
|
|
86
94
|
if (!item) continue;
|
|
87
|
-
if (item
|
|
95
|
+
if (isTurnPrompt(item)) break;
|
|
88
96
|
if (item.type === "error") found.push(item.message);
|
|
89
97
|
else if (item.type === "notification" && item.level !== "info") found.push(item.message);
|
|
90
98
|
else if (item.type === "assistant_message") {
|
|
@@ -100,11 +108,17 @@ function firstLine(text: string): string {
|
|
|
100
108
|
return (text.split("\n")[0] ?? text).trim();
|
|
101
109
|
}
|
|
102
110
|
|
|
111
|
+
/** The model a Claude limit notice names ("hit your Fable limit", "reached your Fable 5.2 limit"), lowercase. */
|
|
112
|
+
const CLAUDE_SCOPE = new RegExp(`^You${APOSTROPHE}ve (?:hit|reached) your (Opus|Sonnet|Fable|Haiku)\\b`, "i");
|
|
113
|
+
|
|
103
114
|
export function detectClaudeLimit(event: TurnEvent, now: Date = new Date()): LimitHit | null {
|
|
104
115
|
for (const text of notices(event, true)) {
|
|
105
116
|
const line = firstLine(text);
|
|
106
117
|
const match = CLAUDE_LIMITS.find(({ pattern }) => pattern.test(line));
|
|
107
|
-
if (match)
|
|
118
|
+
if (match) {
|
|
119
|
+
const scope = match.kind === "window" ? (line.match(CLAUDE_SCOPE)?.[1]?.toLowerCase() ?? null) : null;
|
|
120
|
+
return { message: line, kind: match.kind, resetsAt: parseClaudeReset(line, now), scope };
|
|
121
|
+
}
|
|
108
122
|
}
|
|
109
123
|
return null;
|
|
110
124
|
}
|
|
@@ -123,11 +137,74 @@ export function detectClaudeSignOut(event: TurnEvent): string | null {
|
|
|
123
137
|
return null;
|
|
124
138
|
}
|
|
125
139
|
|
|
140
|
+
/** A Pi turn that failed because Anthropic refused the account's key. */
|
|
141
|
+
export function detectPiSignOut(event: TurnEvent): string | null {
|
|
142
|
+
for (const text of notices(event, false)) if (PI_SIGNED_OUT.test(text)) return firstLine(text);
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
|
|
126
146
|
export function detectCodexSignOut(event: TurnEvent): string | null {
|
|
127
147
|
for (const text of notices(event, false)) if (CODEX_SIGNED_OUT.test(text)) return firstLine(text);
|
|
128
148
|
return null;
|
|
129
149
|
}
|
|
130
150
|
|
|
151
|
+
// --------------------------------------------------------------------------- Azure OpenAI (API key)
|
|
152
|
+
|
|
153
|
+
/** How long an Azure account is set aside after a rate limit (HTTP 429) without a "retry after". */
|
|
154
|
+
export const AZURE_RATE_LIMIT_MS = 60_000;
|
|
155
|
+
/** How long after an exhausted quota or spend limit (`insufficient_quota`), which doesn't lift in seconds. */
|
|
156
|
+
export const AZURE_QUOTA_MS = 30 * 60_000;
|
|
157
|
+
const AZURE_RATE_LIMIT_MAX_MS = 10 * 60_000;
|
|
158
|
+
|
|
159
|
+
/** Codex's words for an exhausted API quota (`CodexErr::QuotaExceeded`) and the raw error code. */
|
|
160
|
+
const AZURE_QUOTA = /insufficient_quota|quota exceeded|exceeded your current quota/i;
|
|
161
|
+
/** A rate limit, as Codex reports a 429 after its retries ("exceeded retry limit, last status: 429 …") or Azure words it. */
|
|
162
|
+
const AZURE_RATE_LIMIT = /\b429\b|too many requests|rate[ _-]?limit(?:ed|_exceeded)?\b|exceeded (?:the )?(?:token )?rate limit/i;
|
|
163
|
+
/** Azure refusing the key (or the endpoint refusing it): 401/403, or Azure's own wording. */
|
|
164
|
+
const AZURE_REFUSED =
|
|
165
|
+
/\b401\b|\b403\b|unauthorized|forbidden|invalid subscription key|access denied due to invalid|invalid api key|incorrect api key/i;
|
|
166
|
+
|
|
167
|
+
/** "Please retry after 20 seconds" / "retry-after: 20", as Azure's 429 bodies say it. */
|
|
168
|
+
function azureRetryAfterMs(text: string): number | null {
|
|
169
|
+
const match = text.match(/retry[ -]after:?\s*(\d{1,5})\s*(?:s\b|sec|second)?/i);
|
|
170
|
+
if (!match?.[1]) return null;
|
|
171
|
+
return Math.min(AZURE_RATE_LIMIT_MAX_MS, Math.max(10_000, Number(match[1]) * 1_000));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* A turn on an Azure OpenAI account that failed on the API's quota or rate limit. Azure has no 5-hour
|
|
176
|
+
* or weekly windows, so either one is a short cooldown (`window` for a rate limit, `budget` for an
|
|
177
|
+
* exhausted quota), after which the account counts as available again: failover moves on, or stops,
|
|
178
|
+
* without coming straight back to it.
|
|
179
|
+
*
|
|
180
|
+
* Only a failed turn is read: these patterns are broad (a status code), and a completed turn's
|
|
181
|
+
* warnings can carry another service's, like an MCP server's "HTTP 429" while it starts.
|
|
182
|
+
*/
|
|
183
|
+
export function detectAzureLimit(event: TurnEvent, now: Date = new Date()): LimitHit | null {
|
|
184
|
+
if (event.outcome.kind !== "failed") return null;
|
|
185
|
+
for (const text of notices(event, false)) {
|
|
186
|
+
if (AZURE_QUOTA.test(text)) {
|
|
187
|
+
return { kind: "budget", message: firstLine(text), resetsAt: new Date(now.getTime() + AZURE_QUOTA_MS).toISOString() };
|
|
188
|
+
}
|
|
189
|
+
if (AZURE_RATE_LIMIT.test(text)) {
|
|
190
|
+
const wait = azureRetryAfterMs(text) ?? AZURE_RATE_LIMIT_MS;
|
|
191
|
+
return { kind: "window", message: firstLine(text), resetsAt: new Date(now.getTime() + wait).toISOString() };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A failed turn on an Azure OpenAI account that looks like its key (or endpoint) was refused. Only a
|
|
199
|
+
* hint, as for `detectAzureLimit`: a 401 or 403 in the turn can still be another service's, so the
|
|
200
|
+
* service asks Azure about the key before taking the account for signed out (see `confirmSignedOut`).
|
|
201
|
+
*/
|
|
202
|
+
export function detectAzureSignOut(event: TurnEvent): string | null {
|
|
203
|
+
if (event.outcome.kind !== "failed") return null;
|
|
204
|
+
for (const text of notices(event, false)) if (AZURE_REFUSED.test(text) && !AZURE_RATE_LIMIT.test(text)) return firstLine(text);
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
|
|
131
208
|
// --------------------------------------------------------------------------- reset times
|
|
132
209
|
|
|
133
210
|
const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|