@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.58
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/CHANGELOG.md +52 -0
- package/README.md +64 -33
- package/dist/api-only.d.ts +2 -4
- package/dist/api-only.js +2 -4
- package/dist/box-paths.d.ts +4 -3
- package/dist/box-paths.js +7 -4
- package/dist/claude-login-token.d.ts +117 -0
- package/dist/claude-login-token.js +737 -0
- package/dist/claude-login.d.ts +52 -12
- package/dist/claude-login.js +164 -39
- package/dist/cli.js +7 -41
- package/dist/computer-attach.d.ts +35 -17
- package/dist/computer-attach.js +301 -49
- package/dist/computers.d.ts +10 -10
- package/dist/computers.js +5 -5
- package/dist/console/assets/{backend-DVhHzJX2.js → backend-CSAWUqtZ.js} +1 -1
- package/dist/console/assets/index-DPh29cyz.js +747 -0
- package/dist/console/index.html +1 -1
- package/dist/dial-relay.d.ts +25 -4
- package/dist/dial-relay.js +129 -1
- package/dist/env-switch.d.ts +1 -3
- package/dist/env-switch.js +1 -3
- package/dist/fal-price.d.ts +1 -3
- package/dist/fal-price.js +77 -26
- package/dist/learn/ledger.d.ts +170 -0
- package/dist/learn/ledger.js +218 -0
- package/dist/learn/promote.d.ts +3 -3
- package/dist/learn/promote.js +1 -1
- package/dist/learning-cost.d.ts +22 -20
- package/dist/learning-cost.js +15 -21
- package/dist/live-reach.d.ts +2 -0
- package/dist/live-reach.js +2 -0
- package/dist/mcp-api-only-origins.d.ts +8 -3
- package/dist/mcp-api-only-origins.js +17 -17
- package/dist/micro.d.ts +2 -0
- package/dist/micro.js +2 -0
- package/dist/model.d.ts +5 -4
- package/dist/model.js +7 -6
- package/dist/monid.d.ts +14 -1
- package/dist/monid.js +103 -26
- package/dist/openapi.js +34 -12
- package/dist/place-offers.d.ts +4 -0
- package/dist/place-offers.js +7 -4
- package/dist/provider.d.ts +2 -2
- package/dist/provider.js +9 -5
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-view.d.ts +1 -2
- package/dist/run-view.js +2 -1
- package/dist/runner/adapter-loop.js +3 -16
- package/dist/runner/adapter-run-spec.d.ts +20 -13
- package/dist/runner/adapter-run-spec.js +57 -48
- package/dist/runner/beside.d.ts +9 -2
- package/dist/runner/beside.js +24 -7
- package/dist/runner/claim-secrets.d.ts +17 -15
- package/dist/runner/claim-secrets.js +32 -34
- package/dist/runner/cli-run-spec.js +21 -9
- package/dist/runner/held.d.ts +16 -4
- package/dist/runner/main.d.ts +11 -6
- package/dist/runner/main.js +12 -7
- package/dist/runner/mcp-claim.js +3 -2
- package/dist/runner/mcp-run.d.ts +3 -6
- package/dist/runner/mcp-run.js +3 -4
- package/dist/runner/presence.d.ts +11 -1
- package/dist/runner/presence.js +7 -0
- package/dist/runner/reflect-hook.js +1 -1
- package/dist/runner/run-child-host.d.ts +19 -8
- package/dist/runner/run-child-host.js +80 -34
- package/dist/runner/runner.d.ts +3 -0
- package/dist/runner/runner.js +1 -1
- package/dist/runner/save-slots.js +2 -1
- package/dist/runner/subagent.d.ts +11 -0
- package/dist/runner/subagent.js +17 -3
- package/dist/runner/workflow-first.d.ts +27 -14
- package/dist/runner/workflow-first.js +29 -22
- package/dist/runner/workflow-spec.js +1 -1
- package/dist/server.d.ts +18 -7
- package/dist/server.js +150 -64
- package/dist/slots.d.ts +9 -0
- package/dist/slots.js +45 -0
- package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
- package/dist/store/schema.d.ts +17 -0
- package/dist/store/schema.js +47 -1
- package/dist/store/sqlite/run-patch.d.ts +11 -1
- package/dist/store/sqlite/run-patch.js +29 -1
- package/dist/store/sqlite/store.js +72 -9
- package/dist/store/store.d.ts +14 -0
- package/dist/store-reads/learning.d.ts +81 -124
- package/dist/store-reads/learning.js +207 -286
- package/dist/template-eval.d.ts +19 -0
- package/dist/template-eval.js +92 -43
- package/dist/template-import.d.ts +0 -10
- package/dist/template-import.js +5 -10
- package/dist/timeline/web-calls.d.ts +12 -14
- package/dist/timeline/web-calls.js +14 -30
- package/dist/web-save.d.ts +4 -9
- package/dist/web-save.js +4 -43
- package/dist/workspace/attached-computers.d.ts +32 -9
- package/dist/workspace/attached-computers.js +77 -13
- package/dist/workspace/computer-deps.d.ts +6 -1
- package/dist/workspace/computer-deps.js +1 -1
- package/dist/workspace/computer-for-claim.js +6 -3
- package/dist/workspace/paired-route.d.ts +91 -0
- package/dist/workspace/paired-route.js +153 -0
- package/dist/wrapped.d.ts +8 -2
- package/dist/wrapped.js +21 -6
- package/package.json +12 -12
- package/templates/README.md +3 -3
- package/dist/console/assets/index-okP-y8PK.js +0 -747
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
// Claude Code's login on this machine, as a runner hands it to a run that is a user of its own (run-child-host.ts
|
|
2
|
+
// staysInRunner): the runner, the server's user, reads the login's access token from AgentRun's own login folder, and
|
|
3
|
+
// the run's process is handed that token alone (held.ts claudeLogin), never the folder or its refresh token.
|
|
4
|
+
//
|
|
5
|
+
// The runner reads the login's file again at every ask, so a renewal written there by anyone is taken at once, and it
|
|
6
|
+
// renews the login itself, with the pinned CLI's own request (renewLogin; the Claude adapter's login-refresh.ts says what
|
|
7
|
+
// that request is and where in the CLI it was read): at an ask that finds less than LOGIN_MARGIN_MS left, and at the ask
|
|
8
|
+
// after Anthropic refused the token it handed (`refused`, the CLI's 401). One ask posts once at most: one renewal is in
|
|
9
|
+
// flight per refresh token in this process, and across processes the renewer holds the CLI's own refresh lock on the
|
|
10
|
+
// folder and reads the file again once it holds it, so a token another holder (the CLI, another runner) renewed is
|
|
11
|
+
// taken and nothing is posted. It holds that lock as the CLI's lock library does, by the directory it made and the mtime
|
|
12
|
+
// it set (to the microsecond; on a filesystem that keeps whole seconds alone, any mtime in that second, as the CLI's
|
|
13
|
+
// library reads its own there), and a lock another holder took over is never touched, removed or posted under once a
|
|
14
|
+
// check reads it. Runners make or take over a lock one at a time, under a takeover mark beside it, so between runners
|
|
15
|
+
// one holder at a time holds it, unless a runner stalls past the 60 s stale time inside a takeover or its release. The
|
|
16
|
+
// CLI never sees the mark: between a runner and the CLI the lock is as safe as the CLI's own (proper-lockfile), and the
|
|
17
|
+
// CLI's second lock, beside the folder, keeps a takeover's late removal (or, on such a filesystem, a lock made in the
|
|
18
|
+
// runner's second) from letting both post where that lock can be made. The answer is written back only to the file it
|
|
19
|
+
// came from, atomically (a temp file at mode 0600 in the same folder before any byte is in it, synced, then renamed over
|
|
20
|
+
// it), every other field kept as it was. A
|
|
21
|
+
// pair whose write fails is held in this process's memory until it is saved: every ask hands its token and tries the
|
|
22
|
+
// write again, under the same refresh lock with the file read again under it, so it never lands over a newer pair, and
|
|
23
|
+
// one whose token nears its own end still unsaved is refused in LOGIN_NOT_SAVED's words. A refresh
|
|
24
|
+
// token Anthropic took (a 200 that rotated it) or refused for good (`invalid_grant`) is never posted again by this
|
|
25
|
+
// process. A renewal that fails is refused after one more read of the file (another holder may have renewed meanwhile),
|
|
26
|
+
// in LOGIN_REFUSED_NOT_RENEWED's words when Anthropic refused the token, else LOGIN_RUNNING_OUT's, and nothing retries
|
|
27
|
+
// it. No token is in a log field, an error or an event: a failure is told by its status and
|
|
28
|
+
// its OAuth error code alone, never a response body or a thrown error's words. Each value read or answered joins this
|
|
29
|
+
// process's redaction (secrets.ts holdSecret), and each token handed joins every watcher's.
|
|
30
|
+
//
|
|
31
|
+
// A runner whose runs on the login stay in its own process (`process` isolation, or none) has its CLI read and renew the
|
|
32
|
+
// same folder. Each runner says on the data folder which it is (sayLoginRunner), and a run under a user of its own is
|
|
33
|
+
// refused while such a runner is there (loginRunnerInProcess).
|
|
34
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
35
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
36
|
+
import { lstat, mkdir, open, readFile, realpath, rename, rm, stat, utimes } from "node:fs/promises";
|
|
37
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
38
|
+
import { dirname, join } from "node:path";
|
|
39
|
+
import { loginRefresh } from "@parcha/agentrun-harness-claude/facts";
|
|
40
|
+
import { LOGIN_SIGNED_OUT, loginAt } from "./claude-login.js";
|
|
41
|
+
import { PRESENCE_STALE_MS } from "./runner/presence.js";
|
|
42
|
+
import { holdSecret } from "./secrets.js";
|
|
43
|
+
/** The pinned CLI's credentials file in its credentials directory (CLAUDE_SECURESTORAGE_CONFIG_DIR). */
|
|
44
|
+
export const LOGIN_FILE = ".credentials.json";
|
|
45
|
+
/** The least a token handed to a run has left: the pinned CLI's own margin before it calls a token expired (its
|
|
46
|
+
* `n+300000>=e`), and when the runner renews it. */
|
|
47
|
+
export const LOGIN_MARGIN_MS = 5 * 60_000;
|
|
48
|
+
/** The longest one renewal request may take: the runner gives it up then (chatgpt-plan.ts's own). */
|
|
49
|
+
export const REFRESH_CALL_MS = 15_000;
|
|
50
|
+
/** How long an ask waits while another holder (the CLI, another runner) holds the login's refresh lock: the CLI's own
|
|
51
|
+
* request timeout (30 s) and its write back. Then it refuses, having posted nothing. */
|
|
52
|
+
export const LOCK_WAIT_MS = 35_000;
|
|
53
|
+
/** How often a waiting ask reads the file and tries the lock again. */
|
|
54
|
+
const LOCK_POLL_MS = 200;
|
|
55
|
+
/** The words a run gets when the login's token has less than the margin left and the runner could not renew it. */
|
|
56
|
+
export const LOGIN_RUNNING_OUT = "Claude Code's login on this machine runs out in less than 5 minutes, and the runner could not renew it: open Claude Code on this login once to renew it, or sign in again under Settings → Model keys, then start the run again.";
|
|
57
|
+
/** The words a run gets when Anthropic refused the login's token (the run's CLI's 401), whatever time it had left, and
|
|
58
|
+
* the runner could not renew it. */
|
|
59
|
+
export const LOGIN_REFUSED_NOT_RENEWED = "Claude refused this login and it could not be renewed; open Claude Code once to sign in again.";
|
|
60
|
+
/** The words a run gets when the runner renewed the login but could not write the renewal to the login's file, and the
|
|
61
|
+
* renewed token it holds in memory has less than the margin left: Anthropic took the file's refresh token, so only that
|
|
62
|
+
* held pair can be renewed, and the runner renews only from the file. */
|
|
63
|
+
export const LOGIN_NOT_SAVED = "Claude Code's login on this machine was renewed, but the runner could not save the renewal to the login's file, and the renewed token runs out in less than 5 minutes: make room on the disk (or fix the login folder's permissions) and start the run again; if the runner restarted meanwhile, sign in again under Settings → Model keys.";
|
|
64
|
+
/** A renewal that holds a pair it could not save, whose token nears its end (LOGIN_NOT_SAVED). */
|
|
65
|
+
class LoginNotSaved extends Error {
|
|
66
|
+
constructor() {
|
|
67
|
+
super(LOGIN_NOT_SAVED);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** The words a run gets when the login is kept in a form this runner does not read (not the pinned CLI's plaintext file). */
|
|
71
|
+
export const LOGIN_SEALED = "Claude Code's login on this machine is kept in a form this runner cannot hand to a run of its own user: set AGENTRUN_RUN_USER=same, or give the run a model_key.";
|
|
72
|
+
const strings = (values) => values.filter((value) => typeof value === "string");
|
|
73
|
+
/** The access token in a credentials file's text, in the pinned CLI's shape (`claudeAiOauth.{accessToken, expiresAt}`),
|
|
74
|
+
* every value in it held for redaction. No `claudeAiOauth`, or one the CLI cleared (an empty token), is signed out;
|
|
75
|
+
* anything else is a form this runner does not read. */
|
|
76
|
+
function readLogin(text) {
|
|
77
|
+
let parsed;
|
|
78
|
+
try {
|
|
79
|
+
parsed = JSON.parse(text);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return { refused: LOGIN_SEALED };
|
|
83
|
+
}
|
|
84
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
85
|
+
return { refused: LOGIN_SEALED };
|
|
86
|
+
const oauth = parsed.claudeAiOauth;
|
|
87
|
+
if (oauth === undefined || oauth === null)
|
|
88
|
+
return { refused: LOGIN_SIGNED_OUT };
|
|
89
|
+
if (typeof oauth !== "object" || Array.isArray(oauth))
|
|
90
|
+
return { refused: LOGIN_SEALED };
|
|
91
|
+
const { accessToken, refreshToken, expiresAt } = oauth;
|
|
92
|
+
holdSecret(...strings([accessToken, refreshToken]));
|
|
93
|
+
if (accessToken === "")
|
|
94
|
+
return { refused: LOGIN_SIGNED_OUT };
|
|
95
|
+
if (typeof accessToken !== "string" || typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
|
|
96
|
+
return { refused: LOGIN_SEALED };
|
|
97
|
+
return { access: accessToken, expiresAt };
|
|
98
|
+
}
|
|
99
|
+
/** The runner's reader of one login's access token, and its renewer. */
|
|
100
|
+
export class LoginTokens {
|
|
101
|
+
#file;
|
|
102
|
+
#login;
|
|
103
|
+
#now;
|
|
104
|
+
#renew;
|
|
105
|
+
#watchers = new Set();
|
|
106
|
+
/** An access token Anthropic refused (refused): the next ask renews rather than hand it again. */
|
|
107
|
+
#refusedAccess;
|
|
108
|
+
constructor(options) {
|
|
109
|
+
this.#login = options.login;
|
|
110
|
+
this.#file = join(options.login.dir, LOGIN_FILE);
|
|
111
|
+
this.#now = options.now ?? Date.now;
|
|
112
|
+
this.#renew = options.renew ?? renewLogin({ ...(options.fetch ? { fetch: options.fetch } : {}), now: this.#now, ...(options.log ? { log: options.log } : {}) });
|
|
113
|
+
}
|
|
114
|
+
/** Tells `listener` each token as it is handed, for a redactor. */
|
|
115
|
+
watch(listener) {
|
|
116
|
+
this.#watchers.add(listener);
|
|
117
|
+
}
|
|
118
|
+
/** The login's access token, read from its file now, with at least LOGIN_MARGIN_MS left: renewed first (once) when
|
|
119
|
+
* it has less, or when Anthropic refused it (refused). Else it throws in words (signed out, a form not read here, or
|
|
120
|
+
* near its end and not renewed), never with a value of the file in them. */
|
|
121
|
+
async token() {
|
|
122
|
+
let read = await this.#read();
|
|
123
|
+
// A pair a renewal could not save yet (heldPairs) is the renewal's to hand, and to save, at every ask.
|
|
124
|
+
if (!("refused" in read) && (read.access === this.#refusedAccess || read.expiresAt - this.#now() < LOGIN_MARGIN_MS || heldPairs.has(this.#file))) {
|
|
125
|
+
const seen = read.access;
|
|
126
|
+
let renewed;
|
|
127
|
+
let notSaved = false;
|
|
128
|
+
try {
|
|
129
|
+
renewed = await this.#renew(this.#login, seen, this.#refusedAccess);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
// Refused below in LOGIN_NOT_SAVED's, LOGIN_REFUSED_NOT_RENEWED's or LOGIN_RUNNING_OUT's words: a renewal's
|
|
133
|
+
// own never reach a run.
|
|
134
|
+
notSaved = error instanceof LoginNotSaved;
|
|
135
|
+
}
|
|
136
|
+
// The one read after it: the renewal's write, or another holder's that renewed meanwhile (a failed post included).
|
|
137
|
+
read = await this.#read();
|
|
138
|
+
if (!("refused" in read) && read.access === seen) {
|
|
139
|
+
if (notSaved)
|
|
140
|
+
throw new Error(LOGIN_NOT_SAVED);
|
|
141
|
+
// A held pair, still unsaved, whose token Anthropic refused: its refresh token is not the file's, and the runner
|
|
142
|
+
// renews only from the file, so it is refused in those words rather than the file's old token handed.
|
|
143
|
+
if (!renewed && this.#refusedAccess !== undefined && heldPairs.get(this.#file)?.renewed.access === this.#refusedAccess)
|
|
144
|
+
throw new Error(LOGIN_REFUSED_NOT_RENEWED);
|
|
145
|
+
if (renewed)
|
|
146
|
+
read = renewed;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if ("refused" in read)
|
|
150
|
+
throw new Error(read.refused);
|
|
151
|
+
// A token Anthropic refused is said so, whatever time it had left: "runs out in less than 5 minutes" would not be true.
|
|
152
|
+
if (read.access === this.#refusedAccess)
|
|
153
|
+
throw new Error(LOGIN_REFUSED_NOT_RENEWED);
|
|
154
|
+
if (read.expiresAt - this.#now() < LOGIN_MARGIN_MS)
|
|
155
|
+
throw new Error(LOGIN_RUNNING_OUT);
|
|
156
|
+
for (const listener of this.#watchers)
|
|
157
|
+
listener([read.access]);
|
|
158
|
+
return read.access;
|
|
159
|
+
}
|
|
160
|
+
/** Anthropic refused `sent` (the run's CLI's 401): the next ask renews it, unless the file holds another token by
|
|
161
|
+
* then (another holder renewed it, and that one is handed). */
|
|
162
|
+
async refused(sent) {
|
|
163
|
+
const read = await this.#read();
|
|
164
|
+
// The token of a pair held unsaved is the one handed while the file still holds the old one.
|
|
165
|
+
if (!("refused" in read) && (read.access === sent || heldPairs.get(this.#file)?.renewed.access === sent))
|
|
166
|
+
this.#refusedAccess = sent;
|
|
167
|
+
}
|
|
168
|
+
async #read() {
|
|
169
|
+
let text;
|
|
170
|
+
try {
|
|
171
|
+
text = await readFile(this.#file, "utf8");
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
// No file: signed out. One the runner may not open is not the pinned CLI's file as the runner knows it.
|
|
175
|
+
return { refused: error?.code === "ENOENT" ? LOGIN_SIGNED_OUT : LOGIN_SEALED };
|
|
176
|
+
}
|
|
177
|
+
return readLogin(text);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/** Refresh tokens this process never posts again: one Anthropic refused for good (`invalid_grant`), and one it took (a
|
|
181
|
+
* 200 that answered another refresh token: the one posted is spent). */
|
|
182
|
+
const dead = new Set();
|
|
183
|
+
/** The renewals in flight in this process, by the refresh token they spend: two asks on one login share one. */
|
|
184
|
+
const flights = new Map();
|
|
185
|
+
/** The pairs this process renewed and could not save yet, by the file they belong in: every ask on that login hands the
|
|
186
|
+
* held token and tries the write again (saveHeld), until it lands, another holder writes the file, or the process ends. */
|
|
187
|
+
const heldPairs = new Map();
|
|
188
|
+
/** `held` written into `file` as the pinned CLI writes a renewal back (login-refresh.ts): only while the file still holds
|
|
189
|
+
* the refresh token it spent (or one the CLI cleared), the fields it gives over the file's, the rest kept as they are.
|
|
190
|
+
* "saved" once written, "held" while the write fails (kept in heldPairs), and "dropped" when the file holds another
|
|
191
|
+
* holder's pair (or no longer holds a login the runner reads): the file wins, as the CLI's own check lets it. */
|
|
192
|
+
async function saveHeld(file, held, options, owned) {
|
|
193
|
+
const say = options.log ?? (() => undefined);
|
|
194
|
+
const forget = () => {
|
|
195
|
+
if (heldPairs.get(file) === held)
|
|
196
|
+
heldPairs.delete(file);
|
|
197
|
+
};
|
|
198
|
+
const current = await credentialsNow(file);
|
|
199
|
+
if (!current || (current.oauth.refreshToken !== held.posted && current.oauth.refreshToken !== "")) {
|
|
200
|
+
forget();
|
|
201
|
+
say({ claude_login: "renewed", saved: "no", reason: "newer" });
|
|
202
|
+
return "dropped";
|
|
203
|
+
}
|
|
204
|
+
// `owned`: the refresh lock this save holds, asked after the read and before the write. One lost since (taken over)
|
|
205
|
+
// means another holder may write now: the pair stays held, and a later ask tries again.
|
|
206
|
+
if (owned && !(await owned())) {
|
|
207
|
+
heldPairs.set(file, held);
|
|
208
|
+
say({ claude_login: "renewed", saved: "no", reason: "lock_lost" });
|
|
209
|
+
return "held";
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
await replaceFile(file, JSON.stringify({ ...current.json, claudeAiOauth: { ...current.oauth, ...held.fields } }));
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
heldPairs.set(file, held);
|
|
216
|
+
say({ claude_login: "renewed", saved: "no", reason: "held" });
|
|
217
|
+
return "held";
|
|
218
|
+
}
|
|
219
|
+
forget();
|
|
220
|
+
say({ claude_login: "renewed", saved: "yes" });
|
|
221
|
+
return "saved";
|
|
222
|
+
}
|
|
223
|
+
/** A held pair's save as renewLogin makes it at an ask: under the CLI's refresh locks on the login's folder, as a
|
|
224
|
+
* renewal is, so it takes its turn with every renewal of that file (the CLI's, another runner's, this process's own),
|
|
225
|
+
* and saveHeld's read and check are made while it holds them. A save that read the file before a renewal wrote a newer
|
|
226
|
+
* pair, and writes after, would put the held pair back over it, its refresh token spent. While another holder has the
|
|
227
|
+
* locks it waits, as a renewal does, then the pair stays held for a later ask; so it does when the locks cannot be
|
|
228
|
+
* made at all (a full disk refuses a mkdir too). */
|
|
229
|
+
async function saveHeldUnderLock(dir, file, held, options) {
|
|
230
|
+
const say = options.log ?? (() => undefined);
|
|
231
|
+
const fs = options.lockFs ?? LOCK_FS;
|
|
232
|
+
const updateMs = options.lockUpdateMs ?? loginRefresh.lockUpdateMs;
|
|
233
|
+
const giveUp = Date.now() + (options.lockWaitMs ?? LOCK_WAIT_MS);
|
|
234
|
+
for (;;) {
|
|
235
|
+
let locks;
|
|
236
|
+
try {
|
|
237
|
+
locks = await takeRefreshLocks(dir, fs, updateMs);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
say({ claude_login: "renewed", saved: "no", reason: "held" });
|
|
241
|
+
return "held";
|
|
242
|
+
}
|
|
243
|
+
if (locks) {
|
|
244
|
+
try {
|
|
245
|
+
return await saveHeld(file, held, options, locks.owned);
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
await locks.release().catch(() => undefined);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// Another holder renews now: its write lands first, and the check under the locks then drops the held pair.
|
|
252
|
+
if (Date.now() > giveUp) {
|
|
253
|
+
say({ claude_login: "renewed", saved: "no", reason: "locked" });
|
|
254
|
+
return "held";
|
|
255
|
+
}
|
|
256
|
+
await sleep(LOCK_POLL_MS);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/** The login's credentials file as it is now, in the pinned CLI's shape: its parsed object and its `claudeAiOauth`,
|
|
260
|
+
* every token in it held for redaction; none when it is not there or not that shape. */
|
|
261
|
+
async function credentialsNow(file) {
|
|
262
|
+
let json;
|
|
263
|
+
try {
|
|
264
|
+
json = JSON.parse(await readFile(file, "utf8"));
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
if (json === null || typeof json !== "object" || Array.isArray(json))
|
|
270
|
+
return undefined;
|
|
271
|
+
const oauth = json.claudeAiOauth;
|
|
272
|
+
if (oauth === null || typeof oauth !== "object" || Array.isArray(oauth))
|
|
273
|
+
return undefined;
|
|
274
|
+
const fields = oauth;
|
|
275
|
+
holdSecret(...strings([fields.accessToken, fields.refreshToken]));
|
|
276
|
+
return { json: json, oauth: fields };
|
|
277
|
+
}
|
|
278
|
+
/** The pinned CLI's renewal of a login (the adapter's login-refresh.ts), as the runner does it in the CLI's place. */
|
|
279
|
+
export function renewLogin(options = {}) {
|
|
280
|
+
const now = options.now ?? Date.now;
|
|
281
|
+
return async (login, seen, refusedAccess) => {
|
|
282
|
+
const file = join(login.dir, LOGIN_FILE);
|
|
283
|
+
// A pair renewed here and not saved yet: its token is handed and its write tried again (under the refresh locks, read
|
|
284
|
+
// again there: saveHeldUnderLock), and nothing is posted, for the file's refresh token is spent. Once saved, a token
|
|
285
|
+
// near its own end, or one Anthropic refused (refusedAccess), is renewed from the file as any other.
|
|
286
|
+
const held = heldPairs.get(file);
|
|
287
|
+
if (held) {
|
|
288
|
+
const kept = await saveHeldUnderLock(login.dir, file, held, options);
|
|
289
|
+
if (kept === "dropped")
|
|
290
|
+
return undefined;
|
|
291
|
+
const refusedHeld = held.renewed.access === refusedAccess;
|
|
292
|
+
if (!refusedHeld && held.renewed.expiresAt - now() >= LOGIN_MARGIN_MS)
|
|
293
|
+
return held.renewed;
|
|
294
|
+
if (kept === "held") {
|
|
295
|
+
// Unsaved, nothing can renew it here: refused (LoginTokens.token says which words), never handed again.
|
|
296
|
+
if (refusedHeld)
|
|
297
|
+
throw new Error("Anthropic refused the held token, and its pair is not saved");
|
|
298
|
+
throw new LoginNotSaved();
|
|
299
|
+
}
|
|
300
|
+
seen = held.renewed.access;
|
|
301
|
+
}
|
|
302
|
+
const read = await credentialsNow(file);
|
|
303
|
+
// Another holder renewed it since it was read, or it changed: the caller reads it again.
|
|
304
|
+
if (read?.oauth.accessToken !== seen)
|
|
305
|
+
return undefined;
|
|
306
|
+
const refresh = read.oauth.refreshToken;
|
|
307
|
+
if (typeof refresh !== "string" || refresh === "")
|
|
308
|
+
throw new Error("the login holds no refresh token");
|
|
309
|
+
if (dead.has(refresh))
|
|
310
|
+
throw new Error("the login's refresh token is spent or was refused for good");
|
|
311
|
+
let flight = flights.get(refresh);
|
|
312
|
+
if (!flight) {
|
|
313
|
+
flight = renewUnderLock(login.dir, file, seen, refresh, options).finally(() => flights.delete(refresh));
|
|
314
|
+
flights.set(refresh, flight);
|
|
315
|
+
}
|
|
316
|
+
return flight;
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
const LOCK_FS = { mkdir: (path) => mkdir(path), stat: (path) => stat(path), utimes: (path, atime, mtime) => utimes(path, atime, mtime), rm: (path, options) => rm(path, options) };
|
|
320
|
+
/** Whether two reads are of one directory with one mtime, exactly: what a takeover removes is only the lock it read. */
|
|
321
|
+
const sameLock = (read, kept) => read.dev === kept.dev && read.ino === kept.ino && read.mtimeMs === kept.mtimeMs;
|
|
322
|
+
/** Whether `read` is this holder's own lock: the directory it made (`kept`, once known) with the mtime it set (`set`)
|
|
323
|
+
* as the filesystem keeps it: within 10 µs (libuv keeps whole microseconds, and the round trip through a double is
|
|
324
|
+
* under one more), or, on a filesystem that keeps whole seconds alone, any mtime in the second `set` falls in. That
|
|
325
|
+
* second is the CLI's lock library's own rule there; between runners the takeover mark keeps a second holder out. */
|
|
326
|
+
const ownRead = (read, kept, set) => (kept === undefined || (read.dev === kept.dev && read.ino === kept.ino)) &&
|
|
327
|
+
(Math.abs(read.mtimeMs - set) < 0.01 || (read.mtimeMs % 1000 === 0 && read.mtimeMs === Math.floor(set / 1000) * 1000));
|
|
328
|
+
/** Beside each lock, the runners' takeover mark: a directory `<lock>.takeover`, never inside the lock, made, taken over
|
|
329
|
+
* when dead and released as a lock of its own (makeLock, ownRead). It is held for a few file operations, so a mark
|
|
330
|
+
* older than lockStaleMs is a crashed (or 60 s stalled) runner's. */
|
|
331
|
+
const TAKEOVER_MARK = ".takeover";
|
|
332
|
+
/** Lock `path` made, or a dead one (older than lockStaleMs) taken over, its mtime set and read back: this holder's own
|
|
333
|
+
* directory and mtime, or none while another holds it. A dead lock is removed only while a read right before the
|
|
334
|
+
* removal shows the same directory, still stale. One this holder made and could not touch or read back is removed
|
|
335
|
+
* only while it can still be its own: never once a touch finds it gone (what is at the path then may be another
|
|
336
|
+
* holder's), and after a failed read only while a second read shows the mtime this holder set. The takeover mark is
|
|
337
|
+
* taken with it, and a lock only under the mark. */
|
|
338
|
+
async function makeLock(path, fs) {
|
|
339
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
340
|
+
try {
|
|
341
|
+
await fs.mkdir(path);
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
if (error?.code !== "EEXIST")
|
|
345
|
+
throw error;
|
|
346
|
+
const seen = await fs.stat(path).catch(() => undefined);
|
|
347
|
+
// Released since: try again.
|
|
348
|
+
if (!seen)
|
|
349
|
+
continue;
|
|
350
|
+
if (Date.now() - seen.mtimeMs <= loginRefresh.lockStaleMs)
|
|
351
|
+
return undefined;
|
|
352
|
+
const again = await fs.stat(path).catch(() => undefined);
|
|
353
|
+
if (!again || !sameLock(again, seen) || Date.now() - again.mtimeMs <= loginRefresh.lockStaleMs)
|
|
354
|
+
continue;
|
|
355
|
+
await fs.rm(path, { recursive: true, force: true });
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const set = Date.now();
|
|
359
|
+
try {
|
|
360
|
+
await fs.utimes(path, new Date(set), new Date(set));
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
if (error?.code !== "ENOENT")
|
|
364
|
+
await fs.rm(path, { recursive: true, force: true }).catch(() => undefined);
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
let made;
|
|
368
|
+
try {
|
|
369
|
+
made = await fs.stat(path);
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
if (error?.code !== "ENOENT") {
|
|
373
|
+
const again = await fs.stat(path).catch(() => undefined);
|
|
374
|
+
if (again && ownRead(again, undefined, set))
|
|
375
|
+
await fs.rm(path, { recursive: true, force: true }).catch(() => undefined);
|
|
376
|
+
}
|
|
377
|
+
return undefined;
|
|
378
|
+
}
|
|
379
|
+
// Another's (an mtime this holder did not set): not this holder's to touch or remove.
|
|
380
|
+
return ownRead(made, undefined, set) ? { dev: made.dev, ino: made.ino, set } : undefined;
|
|
381
|
+
}
|
|
382
|
+
return undefined;
|
|
383
|
+
}
|
|
384
|
+
/** A lock in proper-lockfile's form, as the pinned CLI takes it (login-refresh.ts): a directory made with mkdir, its
|
|
385
|
+
* mtime touched every `updateMs` while it is held, taken over once older than lockStaleMs. Nothing is ever put inside
|
|
386
|
+
* it: proper-lockfile removes a lock with rmdir. It is this holder's while a read shows the directory it made with the
|
|
387
|
+
* mtime it last set (ownRead); any other read (another directory, another mtime, the lock gone) marks it lost for
|
|
388
|
+
* good, the CLI's "compromised", and it is never touched or removed again. None while another holds it.
|
|
389
|
+
* Runners make, take over and read back a lock only under the takeover mark beside it, one runner at a time, so
|
|
390
|
+
* between runners one holder at a time holds it. Left open, as in every lease lock: a runner stalled past the stale
|
|
391
|
+
* time inside a takeover (its mark taken over as dead, its removal then lands in another's lock), or between its
|
|
392
|
+
* release's check and its removal. The pinned CLI never sees the mark: against the CLI the lock keeps proper-lockfile's
|
|
393
|
+
* rules, a takeover's late removal included (the second lock, beside the folder, keeps the two from both posting where
|
|
394
|
+
* it can be made). */
|
|
395
|
+
async function lockDirectory(path, fs, updateMs) {
|
|
396
|
+
const markPath = `${path}${TAKEOVER_MARK}`;
|
|
397
|
+
const mark = await makeLock(markPath, fs);
|
|
398
|
+
// Another runner makes, takes over or reads back this lock now: as good as held.
|
|
399
|
+
if (!mark)
|
|
400
|
+
return undefined;
|
|
401
|
+
let made;
|
|
402
|
+
try {
|
|
403
|
+
made = await makeLock(path, fs);
|
|
404
|
+
}
|
|
405
|
+
finally {
|
|
406
|
+
// Only the mark made here: one another runner made after taking this one over as dead (this runner stalled past the
|
|
407
|
+
// stale time) is that runner's.
|
|
408
|
+
const still = await fs.stat(markPath).catch(() => undefined);
|
|
409
|
+
if (still && ownRead(still, mark, mark.set))
|
|
410
|
+
await fs.rm(markPath, { recursive: true, force: true }).catch(() => undefined);
|
|
411
|
+
}
|
|
412
|
+
if (!made)
|
|
413
|
+
return undefined;
|
|
414
|
+
let mine = made;
|
|
415
|
+
let lost = false;
|
|
416
|
+
let timer;
|
|
417
|
+
/** Every read of the lock (owned), the heartbeat's read and touch, and the release run one at a time, in order: a
|
|
418
|
+
* read never meets a touch half done (the mtime on disk new, `mine` still the old one, or the other way round), so
|
|
419
|
+
* this holder never takes its own live lock for another's. */
|
|
420
|
+
let turn = Promise.resolve();
|
|
421
|
+
const inTurn = (step) => {
|
|
422
|
+
const run = turn.then(step, step);
|
|
423
|
+
turn = run.catch(() => undefined);
|
|
424
|
+
return run;
|
|
425
|
+
};
|
|
426
|
+
/** A heartbeat waiting or running: the next tick adds none. */
|
|
427
|
+
let beating = false;
|
|
428
|
+
const check = async () => {
|
|
429
|
+
if (lost)
|
|
430
|
+
return false;
|
|
431
|
+
try {
|
|
432
|
+
if (ownRead(await fs.stat(path), mine, mine.set))
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
// Unread but not gone (a transient failure): not touched or removed at this read, and read again at the next, as
|
|
437
|
+
// proper-lockfile does.
|
|
438
|
+
if (error?.code !== "ENOENT")
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
// Gone, or another's: lost.
|
|
442
|
+
lost = true;
|
|
443
|
+
clearInterval(timer);
|
|
444
|
+
return false;
|
|
445
|
+
};
|
|
446
|
+
const owned = () => inTurn(check);
|
|
447
|
+
timer = setInterval(() => {
|
|
448
|
+
if (lost || beating)
|
|
449
|
+
return;
|
|
450
|
+
beating = true;
|
|
451
|
+
void inTurn(async () => {
|
|
452
|
+
if (!(await check()))
|
|
453
|
+
return;
|
|
454
|
+
const at = Date.now();
|
|
455
|
+
try {
|
|
456
|
+
await fs.utimes(path, new Date(at), new Date(at));
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
// Gone since it was read: lost. Another failure is tried again at the next beat, as proper-lockfile does.
|
|
460
|
+
if (error?.code === "ENOENT") {
|
|
461
|
+
lost = true;
|
|
462
|
+
clearInterval(timer);
|
|
463
|
+
}
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
// The mtime it set, kept in the same turn: the next read must show exactly that (ownRead), on the same directory.
|
|
467
|
+
mine = { dev: mine.dev, ino: mine.ino, set: at };
|
|
468
|
+
}).finally(() => {
|
|
469
|
+
beating = false;
|
|
470
|
+
});
|
|
471
|
+
}, updateMs);
|
|
472
|
+
timer.unref();
|
|
473
|
+
return {
|
|
474
|
+
owned,
|
|
475
|
+
release: async () => {
|
|
476
|
+
clearInterval(timer);
|
|
477
|
+
await inTurn(async () => {
|
|
478
|
+
if (await check())
|
|
479
|
+
await fs.rm(path, { recursive: true, force: true });
|
|
480
|
+
lost = true;
|
|
481
|
+
});
|
|
482
|
+
},
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
/** The CLI's two refresh locks on credentials directory `dir`, in its order (the lock in the folder, then the older one
|
|
486
|
+
* beside the folder's real path; that one taken where it can be, as the CLI does): whether both are still this
|
|
487
|
+
* holder's, and their release; or none while another holder has either. */
|
|
488
|
+
async function takeRefreshLocks(dir, fs, updateMs) {
|
|
489
|
+
const current = await lockDirectory(join(dir, loginRefresh.lockName), fs, updateMs);
|
|
490
|
+
if (!current)
|
|
491
|
+
return undefined;
|
|
492
|
+
// null: the older lock could not be made, and the CLI goes on without it then (only another holder of it stops it).
|
|
493
|
+
let legacy;
|
|
494
|
+
try {
|
|
495
|
+
legacy = await lockDirectory(`${await realpath(dir).catch(() => dir)}${loginRefresh.legacyLockSuffix}`, fs, updateMs);
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
legacy = null;
|
|
499
|
+
}
|
|
500
|
+
if (legacy === undefined) {
|
|
501
|
+
await current.release();
|
|
502
|
+
return undefined;
|
|
503
|
+
}
|
|
504
|
+
const older = legacy;
|
|
505
|
+
return {
|
|
506
|
+
// Both asked each time: each one's own lost mark is set by its own read.
|
|
507
|
+
owned: async () => ((await current.owned()) ? older === null || (await older.owned()) : false),
|
|
508
|
+
release: async () => {
|
|
509
|
+
await older?.release().catch(() => undefined);
|
|
510
|
+
await current.release();
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
/** One renewal of the login in file `file` whose access token was `seen` and refresh token `refresh`: under the CLI's
|
|
515
|
+
* refresh locks, the file read again, one post, and the answer written back. A lock lost before the post (taken over
|
|
516
|
+
* while this holder was paused) is never posted under: the holder waits for the new one's write as for any other's,
|
|
517
|
+
* the pinned CLI's own check before its post (`tengu_oauth_token_refresh_lock_compromised_pre_post`). One lost after
|
|
518
|
+
* the post keeps the answer: the refresh token posted is spent, so the pair is written back by the same check the CLI
|
|
519
|
+
* makes (the file still holds the refresh token posted, or a cleared one), without the lock, as the CLI writes it then
|
|
520
|
+
* (`tengu_oauth_refresh_compromised_cas_saved`), and held in memory if that write fails (saveHeld). */
|
|
521
|
+
async function renewUnderLock(dir, file, seen, refresh, options) {
|
|
522
|
+
const say = options.log ?? (() => undefined);
|
|
523
|
+
const fs = options.lockFs ?? LOCK_FS;
|
|
524
|
+
const updateMs = options.lockUpdateMs ?? loginRefresh.lockUpdateMs;
|
|
525
|
+
const giveUp = Date.now() + (options.lockWaitMs ?? LOCK_WAIT_MS);
|
|
526
|
+
for (;;) {
|
|
527
|
+
const locks = await takeRefreshLocks(dir, fs, updateMs);
|
|
528
|
+
if (locks) {
|
|
529
|
+
try {
|
|
530
|
+
// Read again under the lock: a holder that renewed before it was taken has written its pair, which is taken.
|
|
531
|
+
const held = await credentialsNow(file);
|
|
532
|
+
if (!held || held.oauth.accessToken !== seen || held.oauth.refreshToken !== refresh)
|
|
533
|
+
return undefined;
|
|
534
|
+
if (await locks.owned()) {
|
|
535
|
+
const answer = await postRefresh(held.oauth, refresh, options);
|
|
536
|
+
if (!(await locks.owned()))
|
|
537
|
+
say({ claude_login: "lock_lost", at: "after_post" });
|
|
538
|
+
return await writeBack(file, refresh, answer, options);
|
|
539
|
+
}
|
|
540
|
+
say({ claude_login: "lock_lost", at: "before_post" });
|
|
541
|
+
}
|
|
542
|
+
finally {
|
|
543
|
+
await locks.release().catch(() => undefined);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
// Another holder renews it now: its write is taken when it lands, never a second post of the same refresh token.
|
|
547
|
+
if ((await credentialsNow(file))?.oauth.accessToken !== seen)
|
|
548
|
+
return undefined;
|
|
549
|
+
if (Date.now() > giveUp) {
|
|
550
|
+
say({ claude_login: "renew_failed", reason: "locked" });
|
|
551
|
+
throw new Error("another holder kept the login's refresh lock");
|
|
552
|
+
}
|
|
553
|
+
await sleep(LOCK_POLL_MS);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
/** The pinned CLI's refresh request for the login whose fields are `oauth` (login-refresh.ts), posted once. Every token
|
|
557
|
+
* in its answer is held for redaction before anything else reads it. A failure throws words with no value of the
|
|
558
|
+
* request or the answer in them, and is told to the log by its status and OAuth error code alone. */
|
|
559
|
+
async function postRefresh(oauth, refresh, options) {
|
|
560
|
+
const say = options.log ?? (() => undefined);
|
|
561
|
+
const scopes = Array.isArray(oauth.scopes) && oauth.scopes.length > 0 && oauth.scopes.every((scope) => typeof scope === "string") ? oauth.scopes : loginRefresh.scopes;
|
|
562
|
+
const body = {
|
|
563
|
+
grant_type: "refresh_token",
|
|
564
|
+
refresh_token: refresh,
|
|
565
|
+
client_id: typeof oauth.clientId === "string" && oauth.clientId !== "" ? oauth.clientId : loginRefresh.clientId,
|
|
566
|
+
scope: scopes.join(" "),
|
|
567
|
+
};
|
|
568
|
+
let response;
|
|
569
|
+
try {
|
|
570
|
+
// Never followed: a 307 or 308 would post the same body, refresh token included, to the Location's host. A redirect
|
|
571
|
+
// rejects as fetch's network error, a failed post like any other: nothing saved, the refresh token not taken as refused.
|
|
572
|
+
response = await (options.fetch ?? globalThis.fetch)(loginRefresh.tokenUrl, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), redirect: "error", signal: AbortSignal.timeout(options.callMs ?? REFRESH_CALL_MS) });
|
|
573
|
+
}
|
|
574
|
+
catch (error) {
|
|
575
|
+
say({ claude_login: "renew_failed", reason: error?.name === "TimeoutError" ? "timeout" : "network" });
|
|
576
|
+
throw new Error("the login's renewal request got no answer");
|
|
577
|
+
}
|
|
578
|
+
let parsed;
|
|
579
|
+
try {
|
|
580
|
+
parsed = await response.json();
|
|
581
|
+
}
|
|
582
|
+
catch {
|
|
583
|
+
parsed = undefined;
|
|
584
|
+
}
|
|
585
|
+
const answer = (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {});
|
|
586
|
+
holdSecret(...strings([answer.access_token, answer.refresh_token]));
|
|
587
|
+
if (response.status !== 200) {
|
|
588
|
+
const code = typeof answer.error === "string" && /^[a-z_]{1,40}$/.test(answer.error) ? answer.error : undefined;
|
|
589
|
+
// The CLI's own: a refresh token refused as invalid_grant is dead, and never sent again.
|
|
590
|
+
if (code === "invalid_grant")
|
|
591
|
+
dead.add(refresh);
|
|
592
|
+
say({ claude_login: "renew_refused", status: String(response.status), ...(code ? { error: code } : {}) });
|
|
593
|
+
throw new Error(`the login's renewal was answered ${response.status}${code ? ` (${code})` : ""}`);
|
|
594
|
+
}
|
|
595
|
+
const { access_token: access, refresh_token: next, expires_in: expiresIn, refresh_token_expires_in: refreshExpiresIn, scope } = answer;
|
|
596
|
+
if (typeof access !== "string" || access === "" || typeof expiresIn !== "number" || !(expiresIn > 0)) {
|
|
597
|
+
say({ claude_login: "renew_failed", reason: "answer" });
|
|
598
|
+
throw new Error("the login's renewal answer held no token");
|
|
599
|
+
}
|
|
600
|
+
// Anthropic took the refresh token and answered another: the one posted is spent, and never posted again, whatever
|
|
601
|
+
// becomes of the answer's write. One answered with no new refresh token is the CLI's `refresh_token:K=e`: still the
|
|
602
|
+
// login's, kept.
|
|
603
|
+
if (typeof next === "string" && next !== "" && next !== refresh)
|
|
604
|
+
dead.add(refresh);
|
|
605
|
+
return {
|
|
606
|
+
access,
|
|
607
|
+
refresh: typeof next === "string" && next !== "" ? next : undefined,
|
|
608
|
+
expiresIn,
|
|
609
|
+
refreshExpiresIn: typeof refreshExpiresIn === "number" && Number.isFinite(refreshExpiresIn) ? refreshExpiresIn : undefined,
|
|
610
|
+
scope: typeof scope === "string" ? scope : undefined,
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
/** The renewal's answer written into `file`, the one it came from (saveHeld): the token it got, whether the write landed
|
|
614
|
+
* or not. One that did not land is held in this process's memory (heldPairs) and written at a later ask; one the file
|
|
615
|
+
* holds another holder's pair in place of is dropped, its token handed to this ask alone. */
|
|
616
|
+
async function writeBack(file, posted, answer, options) {
|
|
617
|
+
const now = (options.now ?? Date.now)();
|
|
618
|
+
const renewed = { access: answer.access, expiresAt: now + answer.expiresIn * 1000 };
|
|
619
|
+
const fields = {
|
|
620
|
+
accessToken: answer.access,
|
|
621
|
+
refreshToken: answer.refresh ?? posted,
|
|
622
|
+
expiresAt: renewed.expiresAt,
|
|
623
|
+
...(answer.refreshExpiresIn === undefined ? {} : { refreshTokenExpiresAt: now + answer.refreshExpiresIn * 1000 }),
|
|
624
|
+
...(answer.scope === undefined ? {} : { scopes: answer.scope.split(" ").filter(Boolean) }),
|
|
625
|
+
};
|
|
626
|
+
await saveHeld(file, { posted, fields, renewed }, options);
|
|
627
|
+
return renewed;
|
|
628
|
+
}
|
|
629
|
+
/** `file` replaced by `text` atomically: a new file beside it, at mode 0600 before any byte is written to it, synced,
|
|
630
|
+
* then renamed over it, and its folder synced. A `file` that is no plain file (a link, say) is never written. */
|
|
631
|
+
async function replaceFile(file, text) {
|
|
632
|
+
if (!(await lstat(file)).isFile())
|
|
633
|
+
throw new Error("the login's file is not a plain file");
|
|
634
|
+
const dir = dirname(file);
|
|
635
|
+
const temp = join(dir, `${LOGIN_FILE}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
636
|
+
// O_CREAT | O_EXCL: a new file of this process's alone, never one that was there.
|
|
637
|
+
const handle = await open(temp, "wx", 0o600);
|
|
638
|
+
try {
|
|
639
|
+
// Exactly 0600 (a umask only narrows the mode open was given), before a byte of a token is in it.
|
|
640
|
+
await handle.chmod(0o600);
|
|
641
|
+
await handle.writeFile(text, "utf8");
|
|
642
|
+
await handle.sync();
|
|
643
|
+
}
|
|
644
|
+
catch (error) {
|
|
645
|
+
await handle.close().catch(() => undefined);
|
|
646
|
+
await rm(temp, { force: true });
|
|
647
|
+
throw error;
|
|
648
|
+
}
|
|
649
|
+
await handle.close();
|
|
650
|
+
try {
|
|
651
|
+
await rename(temp, file);
|
|
652
|
+
}
|
|
653
|
+
catch (error) {
|
|
654
|
+
await rm(temp, { force: true });
|
|
655
|
+
throw error;
|
|
656
|
+
}
|
|
657
|
+
const folder = await open(dir, "r");
|
|
658
|
+
try {
|
|
659
|
+
await folder.sync();
|
|
660
|
+
}
|
|
661
|
+
catch {
|
|
662
|
+
// A folder some filesystems cannot sync still holds the rename.
|
|
663
|
+
}
|
|
664
|
+
finally {
|
|
665
|
+
await folder.close();
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/** Whether `login` is AgentRun's own login folder in `data` (claude-login.ts loginAt "agentrun"), the one login a run
|
|
669
|
+
* under a user of its own is handed a token of; this machine's own Claude Code login is not. */
|
|
670
|
+
export const agentRunLogin = (login, data) => login.dir === loginAt("agentrun", data).dir;
|
|
671
|
+
/** One reader per login folder in this process, so every claim on it holds the same watchers' tokens and the same
|
|
672
|
+
* refused token; each renews with the pinned CLI's own request (renewLogin). */
|
|
673
|
+
const readers = new Map();
|
|
674
|
+
export function loginTokensFor(login) {
|
|
675
|
+
let reader = readers.get(login.dir);
|
|
676
|
+
if (!reader)
|
|
677
|
+
readers.set(login.dir, (reader = new LoginTokens({ login })));
|
|
678
|
+
return reader;
|
|
679
|
+
}
|
|
680
|
+
/** The words a run's claim is refused in by its runner (held.ts claudeLogin) when the claim goes on a login the runner
|
|
681
|
+
* hands no reader of to a run's own process: one not on AgentRun's own login folder. */
|
|
682
|
+
export const LOGIN_NOT_HANDED = "This run's runner handed it no Claude Code login: it runs each run as a user of its own and hands such a run only AgentRun's own login folder's token. Switch to that folder under Settings → Model keys, set AGENTRUN_RUN_USER=same, or give the run a model_key.";
|
|
683
|
+
/** A run's own process's login (held.ts claudeLogin's reader): each token it reads held by `hold` (the run's redactors)
|
|
684
|
+
* and this process's own (secrets.ts holdSecret) before the run's CLI is handed it, and a token Anthropic refused told
|
|
685
|
+
* to the runner, which renews it at the next ask. */
|
|
686
|
+
export function heldTokenLogin(reader, hold) {
|
|
687
|
+
return {
|
|
688
|
+
token: async () => {
|
|
689
|
+
const token = await reader.token();
|
|
690
|
+
holdSecret(token);
|
|
691
|
+
hold([token]);
|
|
692
|
+
return token;
|
|
693
|
+
},
|
|
694
|
+
refused: async (sent) => {
|
|
695
|
+
await reader.refused?.(sent);
|
|
696
|
+
},
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
/** Where the runners on a data folder say whether their runs on the login stay in their own process: one file per
|
|
700
|
+
* runner, named by the sha256 of its whole name, so two names never share a file and no name is a folder (`.`,
|
|
701
|
+
* `..`). The file holds the name itself, which loginRunnerInProcess reads. */
|
|
702
|
+
export const loginRunnersDir = (data) => join(data, "claude-login-runners");
|
|
703
|
+
const runnerFile = (data, runner) => join(loginRunnersDir(data), createHash("sha256").update(runner, "utf8").digest("hex"));
|
|
704
|
+
/** Runner `runner` says, at its start, how its runs on the login run: `process` (in its own process, its CLI on the
|
|
705
|
+
* login folder), or `uid` (each a user of its own, on a token), which takes back what an earlier start of that name said. */
|
|
706
|
+
export function sayLoginRunner(data, runner, isolation) {
|
|
707
|
+
const file = runnerFile(data, runner);
|
|
708
|
+
if (isolation === "uid")
|
|
709
|
+
return void rmSync(file, { force: true });
|
|
710
|
+
mkdirSync(loginRunnersDir(data), { recursive: true, mode: 0o700 });
|
|
711
|
+
writeFileSync(file, `${runner}\n`, { mode: 0o600 });
|
|
712
|
+
}
|
|
713
|
+
/** The name of a runner on data folder `data` whose runs on the login stay in its own process, and whose word in the
|
|
714
|
+
* store is fresh (presence.ts); none when there is no such runner. */
|
|
715
|
+
export async function loginRunnerInProcess(data, runners) {
|
|
716
|
+
const dir = loginRunnersDir(data);
|
|
717
|
+
let files;
|
|
718
|
+
try {
|
|
719
|
+
files = readdirSync(dir);
|
|
720
|
+
}
|
|
721
|
+
catch {
|
|
722
|
+
return undefined;
|
|
723
|
+
}
|
|
724
|
+
const said = new Set(files.flatMap((file) => {
|
|
725
|
+
try {
|
|
726
|
+
const name = readFileSync(join(dir, file), "utf8").trim();
|
|
727
|
+
return name ? [name] : [];
|
|
728
|
+
}
|
|
729
|
+
catch {
|
|
730
|
+
// Taken back since the list was read.
|
|
731
|
+
return [];
|
|
732
|
+
}
|
|
733
|
+
}));
|
|
734
|
+
if (said.size === 0)
|
|
735
|
+
return undefined;
|
|
736
|
+
return (await runners.live(PRESENCE_STALE_MS)).find((row) => said.has(row.runner))?.runner;
|
|
737
|
+
}
|