@parcha/agentrun-harness-claude 0.1.0-beta.57 → 0.1.0-beta.59
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 +55 -0
- package/dist/adapter.d.ts +7 -3
- package/dist/adapter.js +3 -3
- package/dist/env.d.ts +11 -1
- package/dist/env.js +18 -5
- package/dist/facts.d.ts +1 -0
- package/dist/facts.js +5 -0
- package/dist/harness.d.ts +9 -5
- package/dist/harness.js +36 -4
- package/dist/host/policy.d.ts +1 -3
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/login-refresh.d.ts +22 -0
- package/dist/login-refresh.js +45 -0
- package/dist/login.d.ts +40 -10
- package/dist/login.js +131 -33
- package/dist/store.d.ts +41 -5
- package/dist/store.js +85 -39
- package/dist/testing/fake-sdk.d.ts +11 -0
- package/dist/testing/fake-sdk.js +65 -0
- package/package.json +3 -3
package/dist/login.d.ts
CHANGED
|
@@ -17,11 +17,29 @@ export interface ClaudeAgentLogin {
|
|
|
17
17
|
/** With `secure`: the variable was set and empty, which on macOS names the Keychain item with no suffix, so it goes to
|
|
18
18
|
* the CLI empty there too. */
|
|
19
19
|
unsuffixed?: boolean;
|
|
20
|
-
/** The home of the person whose CLI keeps the login, read once by whoever makes the login (serve's
|
|
21
|
-
* server's `HOME` when
|
|
22
|
-
*
|
|
20
|
+
/** The home of the person whose CLI keeps the login, read once by whoever makes the login (serve's homeOf: the
|
|
21
|
+
* server's `HOME` when its user owns it, else that user's own home), so the status check, the sign-in and a run on
|
|
22
|
+
* macOS all run in that one home (personHome). With `home`, the same folder. */
|
|
23
23
|
userHome?: string;
|
|
24
|
+
/** Set where `userHome` is not the home a terminal with the server's env has (serve's homeOf: that env's `HOME` was
|
|
25
|
+
* another user's, so the server's user's own home was taken): the line a person runs (loginCommand) then carries
|
|
26
|
+
* `HOME`, so it signs in where the server reads, never in that terminal's own home. */
|
|
27
|
+
homeApart?: boolean;
|
|
24
28
|
}
|
|
29
|
+
/** A login handed to the CLI as its access token alone, by a host that holds the login itself. `token()` is asked at
|
|
30
|
+
* each start of the CLI and when Anthropic refuses the token the CLI holds: it answers the login's access token as
|
|
31
|
+
* the host reads it now, or throws in words that say what to do. The CLI gets it as CLAUDE_CODE_OAUTH_TOKEN, with no
|
|
32
|
+
* refresh token and no login directory. */
|
|
33
|
+
export interface ClaudeLoginToken {
|
|
34
|
+
token(): Promise<string>;
|
|
35
|
+
/** Told, before `token()` is asked again, that Anthropic refused `sent` (the CLI's 401): a host that renews the login
|
|
36
|
+
* renews it at that ask unless it already holds another token. */
|
|
37
|
+
refused?(sent: string): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** Whether `login` is handed as a token (ClaudeLoginToken), not as its directories. */
|
|
40
|
+
export declare const loginByToken: (login: ClaudeAgentLogin | ClaudeLoginToken) => login is ClaudeLoginToken;
|
|
41
|
+
/** The words a turn ends in when Anthropic refused the login's access token mid-turn and the host had no newer one. */
|
|
42
|
+
export declare const LOGIN_TOKEN_REFUSED = "Anthropic refused this machine's Claude login during the run, and no newer token was there: run the claude CLI once on this login to renew it, then start the run again.";
|
|
25
43
|
/** The variables that point a session's CLI at `login`: never its config dir (`CLAUDE_CONFIG_DIR`), which the Agent SDK
|
|
26
44
|
* copies a credentials file out of when it resumes a session, so the credentials dir (`CLAUDE_SECURESTORAGE_CONFIG_DIR`)
|
|
27
45
|
* is always set. On macOS the CLI names its Keychain item from that dir (`-<sha256 of it>` after the name) unless it is
|
|
@@ -54,7 +72,8 @@ export declare function signInEnv(login: ClaudeAgentLogin, platform?: NodeJS.Pla
|
|
|
54
72
|
* holding '=' as one more variable, so a CLI path holding one (/data/a=b/claude) goes to `sh -c` as its `$0`, single
|
|
55
73
|
* quoted, which every one of those shells reads alike too. What env skips: a `claude` alias or function of the
|
|
56
74
|
* person's shell. Elsewhere nothing is cleared, and the line is the variables in front of the CLI, as a shell reads
|
|
57
|
-
* them (sh, bash, zsh, fish 3.1 and later; not tcsh).
|
|
75
|
+
* them (sh, bash, zsh, fish 3.1 and later; not tcsh). A login whose home is not the terminal's (`homeApart`) carries
|
|
76
|
+
* `HOME` first (personHome), as the sign-in this host starts does. `platform`: as signInEnv's. */
|
|
58
77
|
export declare const loginCommand: (login: ClaudeAgentLogin, cli?: string, platform?: NodeJS.Platform) => string;
|
|
59
78
|
/** What the CLI says of its login: whether it is signed in, how, and the account's own words when it gives them. */
|
|
60
79
|
export interface ClaudeLoginStatus {
|
|
@@ -106,8 +125,17 @@ export declare function sweepClaudeStatusFolders(options?: {
|
|
|
106
125
|
* the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
|
|
107
126
|
* session's) it finds no keychain and reads signed out, whatever the variables. */
|
|
108
127
|
export declare const personHome: (login: ClaudeAgentLogin) => string;
|
|
109
|
-
/**
|
|
110
|
-
*
|
|
128
|
+
/** `USER` and `LOGNAME` for a CLI started on a login, built from nothing (the status check, the sign-in this host starts,
|
|
129
|
+
* a run): the user this process runs as, as the system has it (`os.userInfo()`, which reads the user database, never
|
|
130
|
+
* the server's own USER), the user whose home personHome is. On macOS the pinned CLI names its Keychain item's account
|
|
131
|
+
* by `$USER`, else by its runtime's `os.userInfo().username`; it is a Bun binary, whose userInfo reads `$USER` too and
|
|
132
|
+
* says "unknown" without it. So a CLI started with no USER saves and reads the login's tokens under the account
|
|
133
|
+
* "unknown", where the person's own `claude`, run in a terminal that has USER, never looks: it reads signed out while
|
|
134
|
+
* the badge reads signed in. A user the system cannot name (no entry in its user database) is the server's USER or
|
|
135
|
+
* LOGNAME, when it has one. */
|
|
136
|
+
export declare function loginUser(): Record<string, string>;
|
|
137
|
+
/** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH, the user (loginUser)
|
|
138
|
+
* and the login's variables beside it, in the person's home (personHome) on every place and platform.
|
|
111
139
|
* The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
|
|
112
140
|
* own, and adds a settings file, a backup and a lock beside it the first time, all in its config dir, so the check never
|
|
113
141
|
* runs it on the login's own file, whatever the caller says of the login: the config dir is a copy of the account file
|
|
@@ -119,9 +147,10 @@ export declare const personHome: (login: ClaudeAgentLogin) => string;
|
|
|
119
147
|
* Asks once. Throws when the CLI gives no answer that reads as one: ClaudeLoginTimedOut when it was still running at
|
|
120
148
|
* the limit (`timeoutMs`, LOGIN_STATUS_MS by default) and was ended there, else ClaudeLoginNoStatus. A CLI that never
|
|
121
149
|
* started throws the spawn's own error. At the limit the CLI is asked to go (SIGTERM) and killed STATUS_KILL_MS later;
|
|
122
|
-
* once it has exited or was killed, the check waits at most
|
|
123
|
-
* started may hold open. So a check settles within its limit
|
|
124
|
-
* whole number of ms from 1 to 2^31 - 1 throws a RangeError
|
|
150
|
+
* once it has exited or was killed, the check waits STATUS_DRAIN_MS more at most for its output, which a process it
|
|
151
|
+
* started may hold open, and then one more pass of the event loop's reads. So a check settles within its limit, 2 s and
|
|
152
|
+
* that pass, whatever the CLI does. A `timeoutMs` that is no whole number of ms from 1 to 2^31 - 1 throws a RangeError
|
|
153
|
+
* before anything starts. */
|
|
125
154
|
export declare function claudeLoginStatus(cli: string, login: ClaudeAgentLogin, options?: {
|
|
126
155
|
timeoutMs?: number;
|
|
127
156
|
path?: string;
|
|
@@ -150,7 +179,8 @@ export interface ClaudeSignIn {
|
|
|
150
179
|
stop(): void;
|
|
151
180
|
}
|
|
152
181
|
/** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
|
|
153
|
-
* (personHome)
|
|
182
|
+
* (personHome), as that person (loginUser: the account the Keychain item is saved under on macOS, the one their own
|
|
183
|
+
* terminal's `claude` reads), and on their desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
|
|
154
184
|
* Nothing of it is read here: its output goes nowhere. It is ended after `timeoutMs` (SIGN_IN_MS by default), which
|
|
155
185
|
* `ended` says apart from any other end.
|
|
156
186
|
* It dies with this process, as a session's CLI does: started under the kernel's parent watch (parentWatched; `watch`,
|
package/dist/login.js
CHANGED
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
// A person's own Claude Code login on this machine, which a claude-agent session may run on in place of a model key.
|
|
2
2
|
// Written for AgentRun.
|
|
3
3
|
//
|
|
4
|
-
// The pinned CLI keeps the login where it always does, in its own files, and calls Anthropic with it itself.
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
4
|
+
// The pinned CLI keeps the login where it always does, in its own files, and calls Anthropic with it itself. A session
|
|
5
|
+
// either tells the CLI where its login is (two directories, by environment), and the host asks the CLI whether it is
|
|
6
|
+
// signed in (`claude auth status`), reading nothing but that answer; or, where the host keeps the login out of the CLI's
|
|
7
|
+
// reach (a run under a user of its own), it is handed the login's access token alone (ClaudeLoginToken), by
|
|
8
|
+
// environment, asked of the host again at each start and when Anthropic refuses it. The CLI never gets a refresh token
|
|
9
|
+
// then, and never renews the login itself: the host does, if anyone (told which token was refused: `refused`).
|
|
10
|
+
// The status check runs the CLI on a private copy of the login's account file (`.claude.json`), which the CLI rewrites on
|
|
8
11
|
// start, so the file (the person's own, or AgentRun's) is only ever opened to read. The copy leaves out the fields that
|
|
9
12
|
// hold secrets (an API key, exported variables, MCP servers' tokens) and lasts the check.
|
|
10
13
|
// The check runs in the person's own home, as does a run on macOS, where the CLI's tokens are in the login keychain.
|
|
11
14
|
import { spawn } from "node:child_process";
|
|
12
|
-
import { accessSync, constants, mkdtempSync, rmSync } from "node:fs";
|
|
15
|
+
import { accessSync, closeSync, constants, mkdtempSync, openSync, readSync, rmSync, statSync } from "node:fs";
|
|
13
16
|
import { lstat, mkdir, open, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
14
|
-
import { homedir, tmpdir } from "node:os";
|
|
17
|
+
import { homedir, tmpdir, userInfo } from "node:os";
|
|
15
18
|
import { delimiter, join } from "node:path";
|
|
16
19
|
import { parentWatched } from "@parcha/agentrun-kernel/host";
|
|
20
|
+
/** Whether `login` is handed as a token (ClaudeLoginToken), not as its directories. */
|
|
21
|
+
export const loginByToken = (login) => typeof login.token === "function";
|
|
22
|
+
/** The words a turn ends in when Anthropic refused the login's access token mid-turn and the host had no newer one. */
|
|
23
|
+
export const LOGIN_TOKEN_REFUSED = "Anthropic refused this machine's Claude login during the run, and no newer token was there: run the claude CLI once on this login to renew it, then start the run again.";
|
|
17
24
|
/** `login.secure` as the CLI's variable on `platform` (undefined when it is not set apart): empty on macOS where the
|
|
18
25
|
* person's own was set and empty. */
|
|
19
26
|
const secureVar = (login, platform) => (login.secure === undefined ? undefined : login.unsuffixed && platform === "darwin" ? "" : login.secure);
|
|
@@ -59,11 +66,12 @@ const FOLDER_VARS = ["CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"];
|
|
|
59
66
|
* holding '=' as one more variable, so a CLI path holding one (/data/a=b/claude) goes to `sh -c` as its `$0`, single
|
|
60
67
|
* quoted, which every one of those shells reads alike too. What env skips: a `claude` alias or function of the
|
|
61
68
|
* person's shell. Elsewhere nothing is cleared, and the line is the variables in front of the CLI, as a shell reads
|
|
62
|
-
* them (sh, bash, zsh, fish 3.1 and later; not tcsh).
|
|
69
|
+
* them (sh, bash, zsh, fish 3.1 and later; not tcsh). A login whose home is not the terminal's (`homeApart`) carries
|
|
70
|
+
* `HOME` first (personHome), as the sign-in this host starts does. `platform`: as signInEnv's. */
|
|
63
71
|
export const loginCommand = (login, cli = "claude", platform = process.platform) => {
|
|
64
|
-
const env = signInEnv(login, platform);
|
|
72
|
+
const env = login.homeApart ? { HOME: personHome(login), ...signInEnv(login, platform) } : signInEnv(login, platform);
|
|
65
73
|
const cleared = FOLDER_VARS.filter((name) => !(name in env));
|
|
66
|
-
const vars = Object.entries(env).filter(([name]) => name !== "HOME").map(([name, value]) => `${name}=${shellWord(value)}`);
|
|
74
|
+
const vars = Object.entries(env).filter(([name]) => name !== "HOME" || login.homeApart).map(([name, value]) => `${name}=${shellWord(value)}`);
|
|
67
75
|
if (!cleared.length)
|
|
68
76
|
return [...vars, commandWord(cli), "auth", "login"].join(" ");
|
|
69
77
|
const run = cli.includes("=") ? ["sh", "-c", `'exec "$0" auth login'`, quoted(cli)] : [shellWord(cli), "auth", "login"];
|
|
@@ -288,8 +296,27 @@ async function accountCopy(from, to) {
|
|
|
288
296
|
* the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
|
|
289
297
|
* session's) it finds no keychain and reads signed out, whatever the variables. */
|
|
290
298
|
export const personHome = (login) => login.userHome ?? login.home ?? homedir();
|
|
291
|
-
/**
|
|
292
|
-
*
|
|
299
|
+
/** `USER` and `LOGNAME` for a CLI started on a login, built from nothing (the status check, the sign-in this host starts,
|
|
300
|
+
* a run): the user this process runs as, as the system has it (`os.userInfo()`, which reads the user database, never
|
|
301
|
+
* the server's own USER), the user whose home personHome is. On macOS the pinned CLI names its Keychain item's account
|
|
302
|
+
* by `$USER`, else by its runtime's `os.userInfo().username`; it is a Bun binary, whose userInfo reads `$USER` too and
|
|
303
|
+
* says "unknown" without it. So a CLI started with no USER saves and reads the login's tokens under the account
|
|
304
|
+
* "unknown", where the person's own `claude`, run in a terminal that has USER, never looks: it reads signed out while
|
|
305
|
+
* the badge reads signed in. A user the system cannot name (no entry in its user database) is the server's USER or
|
|
306
|
+
* LOGNAME, when it has one. */
|
|
307
|
+
export function loginUser() {
|
|
308
|
+
let name;
|
|
309
|
+
try {
|
|
310
|
+
name = userInfo().username || undefined;
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
name = undefined;
|
|
314
|
+
}
|
|
315
|
+
name ??= process.env.USER || process.env.LOGNAME || undefined;
|
|
316
|
+
return name === undefined ? {} : { USER: name, LOGNAME: name };
|
|
317
|
+
}
|
|
318
|
+
/** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH, the user (loginUser)
|
|
319
|
+
* and the login's variables beside it, in the person's home (personHome) on every place and platform.
|
|
293
320
|
* The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
|
|
294
321
|
* own, and adds a settings file, a backup and a lock beside it the first time, all in its config dir, so the check never
|
|
295
322
|
* runs it on the login's own file, whatever the caller says of the login: the config dir is a copy of the account file
|
|
@@ -301,9 +328,10 @@ export const personHome = (login) => login.userHome ?? login.home ?? homedir();
|
|
|
301
328
|
* Asks once. Throws when the CLI gives no answer that reads as one: ClaudeLoginTimedOut when it was still running at
|
|
302
329
|
* the limit (`timeoutMs`, LOGIN_STATUS_MS by default) and was ended there, else ClaudeLoginNoStatus. A CLI that never
|
|
303
330
|
* started throws the spawn's own error. At the limit the CLI is asked to go (SIGTERM) and killed STATUS_KILL_MS later;
|
|
304
|
-
* once it has exited or was killed, the check waits at most
|
|
305
|
-
* started may hold open. So a check settles within its limit
|
|
306
|
-
* whole number of ms from 1 to 2^31 - 1 throws a RangeError
|
|
331
|
+
* once it has exited or was killed, the check waits STATUS_DRAIN_MS more at most for its output, which a process it
|
|
332
|
+
* started may hold open, and then one more pass of the event loop's reads. So a check settles within its limit, 2 s and
|
|
333
|
+
* that pass, whatever the CLI does. A `timeoutMs` that is no whole number of ms from 1 to 2^31 - 1 throws a RangeError
|
|
334
|
+
* before anything starts. */
|
|
307
335
|
export async function claudeLoginStatus(cli, login, options = {}) {
|
|
308
336
|
const limitMs = options.timeoutMs ?? LOGIN_STATUS_MS;
|
|
309
337
|
// The limit is the check's timer and, with 2 s more, the end it writes for the sweep, which reads only a whole number
|
|
@@ -319,7 +347,7 @@ export async function claudeLoginStatus(cli, login, options = {}) {
|
|
|
319
347
|
const where = { HOME, ...loginEnv(login, options.platform), CLAUDE_CONFIG_DIR: await accountCopy(accountFile(login), join(scratch, "config")) };
|
|
320
348
|
const { stdout, timedOut } = await new Promise((resolve, reject) => {
|
|
321
349
|
const child = spawn(cli, ["auth", "status", "--json"], {
|
|
322
|
-
env: { PATH: options.path ?? process.env.PATH ?? "/usr/bin:/bin", ...where, DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" },
|
|
350
|
+
env: { PATH: options.path ?? process.env.PATH ?? "/usr/bin:/bin", ...loginUser(), ...where, DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" },
|
|
323
351
|
stdio: ["ignore", "pipe", "ignore"],
|
|
324
352
|
});
|
|
325
353
|
let out = "";
|
|
@@ -341,9 +369,11 @@ export async function claudeLoginStatus(cli, login, options = {}) {
|
|
|
341
369
|
child.stdout.destroy();
|
|
342
370
|
resolve({ stdout: out, timedOut });
|
|
343
371
|
});
|
|
344
|
-
// Once the CLI has exited or was killed, its pipe gets a short while to close, and is then left.
|
|
372
|
+
// Once the CLI has exited or was killed, its pipe gets a short while to close, and is then left. The timer gives up
|
|
373
|
+
// only after one more pass of the loop's reads (setImmediate runs after them): a loop held up past the drain, as on
|
|
374
|
+
// a busy server, runs its timers before its reads, and what the pipe already held would be dropped unread.
|
|
345
375
|
const drainSoon = () => {
|
|
346
|
-
drain ??= setTimeout(done, STATUS_DRAIN_MS);
|
|
376
|
+
drain ??= setTimeout(() => setImmediate(done), STATUS_DRAIN_MS);
|
|
347
377
|
};
|
|
348
378
|
// The limit is kept here, not by spawn's `timeout`, so the check knows it ended the CLI, and kills a CLI that
|
|
349
379
|
// outlasts the TERM.
|
|
@@ -383,28 +413,96 @@ const SIGN_IN_KILL_MS = 5_000;
|
|
|
383
413
|
/** Under the parent-watch shim, how long after passing the stop's TERM on the shim kills the CLI (parentWatched's
|
|
384
414
|
* `termGraceMs`). Shorter than SIGN_IN_KILL_MS, so the CLI is gone before the server's kill ends the shim. */
|
|
385
415
|
const SIGN_IN_TERM_GRACE_MS = 2_000;
|
|
416
|
+
/** Whether `file` is a regular file this process may execute. A Buffer is a path's own bytes, as the kernel takes them. */
|
|
417
|
+
function executable(file) {
|
|
418
|
+
try {
|
|
419
|
+
accessSync(file, constants.X_OK);
|
|
420
|
+
return statSync(file).isFile();
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
return false;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/** The first program named `name` on `path`, or undefined. */
|
|
427
|
+
function onPath(name, path) {
|
|
428
|
+
for (const dir of path.split(delimiter))
|
|
429
|
+
if (dir && executable(join(dir, name)))
|
|
430
|
+
return join(dir, name);
|
|
431
|
+
return undefined;
|
|
432
|
+
}
|
|
433
|
+
/** Whether a program named by the bytes `name` is on a folder of `path` (the sign-in's PATH, which env searches). */
|
|
434
|
+
const onPathBytes = (name, path) => path.split(delimiter).some((dir) => dir !== "" && executable(Buffer.concat([Buffer.from(join(dir, "/")), name])));
|
|
435
|
+
/** The first line of `file` (at most 256 bytes) as its bytes, or undefined when it can't be read. */
|
|
436
|
+
function firstLine(file) {
|
|
437
|
+
let fd;
|
|
438
|
+
try {
|
|
439
|
+
fd = openSync(file, "r");
|
|
440
|
+
const head = Buffer.alloc(256);
|
|
441
|
+
const read = head.subarray(0, readSync(fd, head, 0, head.length, 0));
|
|
442
|
+
const end = read.indexOf(0x0a);
|
|
443
|
+
return end < 0 ? read : read.subarray(0, end);
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
finally {
|
|
449
|
+
if (fd !== undefined)
|
|
450
|
+
closeSync(fd);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
/** The words of a `#!` line after the `#!` (the interpreter, then its argument), as bytes: the kernel reads the line as
|
|
454
|
+
* bytes and splits it at blanks, so a path under a folder whose name is not ASCII is that name's bytes, never a decode
|
|
455
|
+
* of them. Blanks are ASCII ones only: in UTF-8 the byte 0xA0 is part of a character (`à` is C3 A0), not a space. */
|
|
456
|
+
function shebangWords(line) {
|
|
457
|
+
if (!line || line[0] !== 0x23 || line[1] !== 0x21)
|
|
458
|
+
return [];
|
|
459
|
+
const words = [];
|
|
460
|
+
let start = -1;
|
|
461
|
+
for (let i = 2; i <= line.length; i++) {
|
|
462
|
+
const blank = i === line.length || [0x20, 0x09, 0x0d, 0x0b, 0x0c, 0x00].includes(line[i]);
|
|
463
|
+
if (blank && start >= 0) {
|
|
464
|
+
words.push(line.subarray(start, i));
|
|
465
|
+
start = -1;
|
|
466
|
+
}
|
|
467
|
+
else if (!blank && start < 0)
|
|
468
|
+
start = i;
|
|
469
|
+
}
|
|
470
|
+
return words;
|
|
471
|
+
}
|
|
472
|
+
const notStartable = (cli, why = "") => Object.assign(new Error(`spawn ${cli} ENOENT${why}`), { code: "ENOENT" });
|
|
386
473
|
/** Throws, in the spawn's words, when `cli` is no program this host can start: the parent watch starts a program of its
|
|
387
|
-
* own first (setpriv, or node with its shim), which would tell a
|
|
388
|
-
*
|
|
474
|
+
* own first (setpriv, or node with its shim), which would tell a failed start only as its own exit code (127), and the
|
|
475
|
+
* sign-in's output is read by no one. So a script whose first line names an interpreter that is not there (`#!/path`,
|
|
476
|
+
* or `#!/usr/bin/env <program>` with the program on no folder of `path`) throws too, naming it. A bare name is looked up
|
|
477
|
+
* on `path`. Not on Windows, whose names take an extension and which reads no `#!` line: the watch's exit says it there. */
|
|
389
478
|
function startable(cli, path) {
|
|
479
|
+
if (process.platform === "win32") {
|
|
480
|
+
if (/[\\/]/.test(cli))
|
|
481
|
+
accessSync(cli, constants.X_OK);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
let file = cli;
|
|
390
485
|
if (/[\\/]/.test(cli))
|
|
391
|
-
|
|
392
|
-
|
|
486
|
+
accessSync(cli, constants.X_OK);
|
|
487
|
+
else
|
|
488
|
+
file = onPath(cli, path) ?? "";
|
|
489
|
+
if (!file)
|
|
490
|
+
throw notStartable(cli);
|
|
491
|
+
// The interpreter and its argument are checked by their bytes (Buffer paths); the tests on their ASCII characters read
|
|
492
|
+
// them as Latin-1, which maps each byte to one character, so those tests see exactly the bytes. The words decode them.
|
|
493
|
+
const [interpreter, program] = shebangWords(firstLine(file));
|
|
494
|
+
if (!interpreter)
|
|
393
495
|
return;
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
}
|
|
400
|
-
catch {
|
|
401
|
-
// Not here.
|
|
402
|
-
}
|
|
496
|
+
if (!executable(interpreter))
|
|
497
|
+
throw notStartable(cli, `: the interpreter its first line names, ${interpreter.toString()}, is not there`);
|
|
498
|
+
// env runs the program it is given, looked up on the sign-in's PATH; an option or a variable is left to env.
|
|
499
|
+
if (/(^|\/)env$/.test(interpreter.toString("latin1")) && program && !/^-|=/.test(program.toString("latin1")) && !(program.includes(0x2f) ? executable(program) : onPathBytes(program, path))) {
|
|
500
|
+
throw notStartable(cli, `: the interpreter its first line names, ${program.toString()}, is on no folder of its PATH`);
|
|
403
501
|
}
|
|
404
|
-
throw Object.assign(new Error(`spawn ${cli} ENOENT`), { code: "ENOENT" });
|
|
405
502
|
}
|
|
406
503
|
/** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
|
|
407
|
-
* (personHome)
|
|
504
|
+
* (personHome), as that person (loginUser: the account the Keychain item is saved under on macOS, the one their own
|
|
505
|
+
* terminal's `claude` reads), and on their desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
|
|
408
506
|
* Nothing of it is read here: its output goes nowhere. It is ended after `timeoutMs` (SIGN_IN_MS by default), which
|
|
409
507
|
* `ended` says apart from any other end.
|
|
410
508
|
* It dies with this process, as a session's CLI does: started under the kernel's parent watch (parentWatched; `watch`,
|
|
@@ -426,7 +524,7 @@ export function startClaudeLogin(cli, login, options = {}) {
|
|
|
426
524
|
startable(cli, path);
|
|
427
525
|
const run = parentWatched({ command: cli, args: ["auth", "login", "--claudeai"] }, options.watch, { termGraceMs: SIGN_IN_TERM_GRACE_MS });
|
|
428
526
|
child = spawn(run.command, run.args, {
|
|
429
|
-
env: { PATH: path, HOME: personHome(login), ...display, ...signInEnv(login), DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1" },
|
|
527
|
+
env: { PATH: path, HOME: personHome(login), ...loginUser(), ...display, ...signInEnv(login), DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1" },
|
|
430
528
|
stdio: "ignore",
|
|
431
529
|
});
|
|
432
530
|
}
|
package/dist/store.d.ts
CHANGED
|
@@ -37,9 +37,16 @@ export declare const subStream: (subpath: string) => string;
|
|
|
37
37
|
export declare function toolUseIds(entry: TranscriptLine | undefined): string[];
|
|
38
38
|
/** The `tool_use_id`s a user entry answers (its `tool_result` blocks). */
|
|
39
39
|
export declare function toolResultIds(entry: TranscriptLine | undefined): string[];
|
|
40
|
+
/** The timers a barrier's wait runs on (the system's by default; a test passes a fake clock). */
|
|
41
|
+
export interface BarrierTimers {
|
|
42
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
43
|
+
clearTimeout(timer: unknown): void;
|
|
44
|
+
}
|
|
40
45
|
export interface JournalSessionStoreOptions {
|
|
41
46
|
/** The journal's records as of the drive's start, blobs resolved (`journal.read()`). */
|
|
42
47
|
records: JournalRecord[];
|
|
48
|
+
/** The timers `barrier` and `resultBarrier` wait on. Default the system's. */
|
|
49
|
+
timers?: BarrierTimers;
|
|
43
50
|
/**
|
|
44
51
|
* Hold appended entries this long before they go to the journal, so the
|
|
45
52
|
* SDK's frames (one `append` per line with eager flushing) ride in fewer
|
|
@@ -60,7 +67,11 @@ export interface JournalSessionStoreOptions {
|
|
|
60
67
|
* from machine to machine) is ignored.
|
|
61
68
|
* - `barrier(toolUseId)` resolves once the assistant entry that made that
|
|
62
69
|
* call is committed: before a `replay: 'never'` tool runs, the call that
|
|
63
|
-
* asked for it is in the log.
|
|
70
|
+
* asked for it is in the log. The SDK mirrors a message's lines only once
|
|
71
|
+
* the message ends, while the CLI runs each call as its block ends, so the
|
|
72
|
+
* wait's clock restarts on each stream event of the message that made the
|
|
73
|
+
* call, up to its `message_stop` (`heard`): it runs out `timeoutMs` after
|
|
74
|
+
* that message's last event.
|
|
64
75
|
*/
|
|
65
76
|
export declare class JournalSessionStore {
|
|
66
77
|
private readonly journal;
|
|
@@ -71,9 +82,15 @@ export declare class JournalSessionStore {
|
|
|
71
82
|
private readonly waiters;
|
|
72
83
|
private readonly results;
|
|
73
84
|
private readonly resultWaiters;
|
|
85
|
+
/** The message stream each call was made in (its `parent_tool_use_id`, `''` for the main thread), from the SDK's live
|
|
86
|
+
* blocks, until its message's `message_stop`. */
|
|
87
|
+
private readonly callScopes;
|
|
88
|
+
/** The clocks of the waits on each call, by its id: each one restarts its wait. */
|
|
89
|
+
private readonly clocks;
|
|
74
90
|
private held;
|
|
75
91
|
private timer;
|
|
76
92
|
private readonly coalesceMs;
|
|
93
|
+
private readonly timers;
|
|
77
94
|
/** Entries this drive appended (for tests and diagnostics). */
|
|
78
95
|
appended: number;
|
|
79
96
|
constructor(journal: NativeJournal, options: JournalSessionStoreOptions);
|
|
@@ -118,16 +135,35 @@ export declare class JournalSessionStore {
|
|
|
118
135
|
}): Promise<string[]>;
|
|
119
136
|
/**
|
|
120
137
|
* Resolve once the assistant entry that made `toolUseId` is committed. The
|
|
121
|
-
* SDK delivers
|
|
122
|
-
* runs
|
|
123
|
-
* first. Rejects after `timeoutMs` (the caller does
|
|
138
|
+
* SDK delivers a message's entries once the CLI has written the whole
|
|
139
|
+
* message, and the tool runs once the CLI wrote its block, so this usually
|
|
140
|
+
* waits for the mirror first. Rejects after `timeoutMs` (the caller does
|
|
141
|
+
* not run the tool), counted from the last stream event of the message that
|
|
142
|
+
* made the call (`heard`), or from now if none is heard.
|
|
124
143
|
*/
|
|
125
144
|
barrier(toolUseId: string, timeoutMs: number): Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* One message `query()` yielded. An `assistant` message names the calls its block made, in its stream (the main
|
|
147
|
+
* thread's, or a subagent's by its `parent_tool_use_id`); it and each `stream_event` of that stream restart the clock
|
|
148
|
+
* of every wait on a call made in it. A message's last event is its `message_stop`: it restarts those clocks one last
|
|
149
|
+
* time and unties the message's calls from the stream, whose next message reuses its `parent_tool_use_id`. So a call
|
|
150
|
+
* whose line never lands is refused `timeoutMs` after its message ended, whatever streams after it, and a stream that
|
|
151
|
+
* stalls, `timeoutMs` after its last event.
|
|
152
|
+
*/
|
|
153
|
+
heard(m: {
|
|
154
|
+
type: string;
|
|
155
|
+
parent_tool_use_id?: string | null;
|
|
156
|
+
message?: unknown;
|
|
157
|
+
event?: unknown;
|
|
158
|
+
}): void;
|
|
159
|
+
/** Wait for `note` to wake a waiter on `id` in `waiters`; reject with `error()` once the clock runs out (`heard` restarts it). */
|
|
160
|
+
private wait;
|
|
126
161
|
private note;
|
|
127
162
|
private user;
|
|
128
163
|
/**
|
|
129
164
|
* Resolve once the user entry that answers `toolUseId` (its `tool_result`) is committed: a call the CLI answered
|
|
130
|
-
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs
|
|
165
|
+
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs`, on the same
|
|
166
|
+
* clock as `barrier`: the answer is mirrored with the rest of its message, once that message ends.
|
|
131
167
|
*/
|
|
132
168
|
resultBarrier(toolUseId: string, timeoutMs: number): Promise<void>;
|
|
133
169
|
}
|
package/dist/store.js
CHANGED
|
@@ -21,6 +21,10 @@ export function toolResultIds(entry) {
|
|
|
21
21
|
return [];
|
|
22
22
|
return content.filter((c) => c?.type === 'tool_result' && typeof c.tool_use_id === 'string').map((c) => c.tool_use_id);
|
|
23
23
|
}
|
|
24
|
+
const SYSTEM_TIMERS = {
|
|
25
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
26
|
+
clearTimeout: (timer) => clearTimeout(timer),
|
|
27
|
+
};
|
|
24
28
|
/**
|
|
25
29
|
* A `SessionStore` (the SDK's `@alpha` mirror interface) whose storage is the
|
|
26
30
|
* drive's journal.
|
|
@@ -34,7 +38,11 @@ export function toolResultIds(entry) {
|
|
|
34
38
|
* from machine to machine) is ignored.
|
|
35
39
|
* - `barrier(toolUseId)` resolves once the assistant entry that made that
|
|
36
40
|
* call is committed: before a `replay: 'never'` tool runs, the call that
|
|
37
|
-
* asked for it is in the log.
|
|
41
|
+
* asked for it is in the log. The SDK mirrors a message's lines only once
|
|
42
|
+
* the message ends, while the CLI runs each call as its block ends, so the
|
|
43
|
+
* wait's clock restarts on each stream event of the message that made the
|
|
44
|
+
* call, up to its `message_stop` (`heard`): it runs out `timeoutMs` after
|
|
45
|
+
* that message's last event.
|
|
38
46
|
*/
|
|
39
47
|
export class JournalSessionStore {
|
|
40
48
|
journal;
|
|
@@ -45,14 +53,21 @@ export class JournalSessionStore {
|
|
|
45
53
|
waiters = new Map();
|
|
46
54
|
results = new Set();
|
|
47
55
|
resultWaiters = new Map();
|
|
56
|
+
/** The message stream each call was made in (its `parent_tool_use_id`, `''` for the main thread), from the SDK's live
|
|
57
|
+
* blocks, until its message's `message_stop`. */
|
|
58
|
+
callScopes = new Map();
|
|
59
|
+
/** The clocks of the waits on each call, by its id: each one restarts its wait. */
|
|
60
|
+
clocks = new Map();
|
|
48
61
|
held = [];
|
|
49
62
|
timer;
|
|
50
63
|
coalesceMs;
|
|
64
|
+
timers;
|
|
51
65
|
/** Entries this drive appended (for tests and diagnostics). */
|
|
52
66
|
appended = 0;
|
|
53
67
|
constructor(journal, options) {
|
|
54
68
|
this.journal = journal;
|
|
55
69
|
this.coalesceMs = options.coalesceMs ?? 0;
|
|
70
|
+
this.timers = options.timers ?? SYSTEM_TIMERS;
|
|
56
71
|
for (const r of options.records) {
|
|
57
72
|
if (r.stream !== CLAUDE_STREAM && !r.stream.startsWith(`${CLAUDE_STREAM}/`))
|
|
58
73
|
continue;
|
|
@@ -156,30 +171,75 @@ export class JournalSessionStore {
|
|
|
156
171
|
}
|
|
157
172
|
/**
|
|
158
173
|
* Resolve once the assistant entry that made `toolUseId` is committed. The
|
|
159
|
-
* SDK delivers
|
|
160
|
-
* runs
|
|
161
|
-
* first. Rejects after `timeoutMs` (the caller does
|
|
174
|
+
* SDK delivers a message's entries once the CLI has written the whole
|
|
175
|
+
* message, and the tool runs once the CLI wrote its block, so this usually
|
|
176
|
+
* waits for the mirror first. Rejects after `timeoutMs` (the caller does
|
|
177
|
+
* not run the tool), counted from the last stream event of the message that
|
|
178
|
+
* made the call (`heard`), or from now if none is heard.
|
|
162
179
|
*/
|
|
163
180
|
async barrier(toolUseId, timeoutMs) {
|
|
164
|
-
if (!this.calls.has(toolUseId))
|
|
165
|
-
await
|
|
166
|
-
const timer = setTimeout(() => {
|
|
167
|
-
const list = this.waiters.get(toolUseId)?.filter((w) => w !== done) ?? [];
|
|
168
|
-
if (list.length)
|
|
169
|
-
this.waiters.set(toolUseId, list);
|
|
170
|
-
else
|
|
171
|
-
this.waiters.delete(toolUseId);
|
|
172
|
-
reject(new Error(`the transcript entry for tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
173
|
-
}, timeoutMs);
|
|
174
|
-
const done = () => {
|
|
175
|
-
clearTimeout(timer);
|
|
176
|
-
resolve();
|
|
177
|
-
};
|
|
178
|
-
this.waiters.set(toolUseId, [...(this.waiters.get(toolUseId) ?? []), done]);
|
|
179
|
-
});
|
|
180
|
-
}
|
|
181
|
+
if (!this.calls.has(toolUseId))
|
|
182
|
+
await this.wait(toolUseId, timeoutMs, this.waiters, () => new Error(`the transcript entry for tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
181
183
|
await this.flush();
|
|
182
184
|
}
|
|
185
|
+
/**
|
|
186
|
+
* One message `query()` yielded. An `assistant` message names the calls its block made, in its stream (the main
|
|
187
|
+
* thread's, or a subagent's by its `parent_tool_use_id`); it and each `stream_event` of that stream restart the clock
|
|
188
|
+
* of every wait on a call made in it. A message's last event is its `message_stop`: it restarts those clocks one last
|
|
189
|
+
* time and unties the message's calls from the stream, whose next message reuses its `parent_tool_use_id`. So a call
|
|
190
|
+
* whose line never lands is refused `timeoutMs` after its message ended, whatever streams after it, and a stream that
|
|
191
|
+
* stalls, `timeoutMs` after its last event.
|
|
192
|
+
*/
|
|
193
|
+
heard(m) {
|
|
194
|
+
const scope = m.parent_tool_use_id ?? '';
|
|
195
|
+
if (m.type === 'assistant')
|
|
196
|
+
for (const id of toolUseIds(m))
|
|
197
|
+
this.callScopes.set(id, scope);
|
|
198
|
+
else if (m.type !== 'stream_event')
|
|
199
|
+
return;
|
|
200
|
+
for (const [id, restarts] of this.clocks)
|
|
201
|
+
if (this.callScopes.get(id) === scope)
|
|
202
|
+
for (const restart of [...restarts])
|
|
203
|
+
restart();
|
|
204
|
+
if (m.event?.type === 'message_stop')
|
|
205
|
+
for (const [id, of] of this.callScopes)
|
|
206
|
+
if (of === scope)
|
|
207
|
+
this.callScopes.delete(id);
|
|
208
|
+
}
|
|
209
|
+
/** Wait for `note` to wake a waiter on `id` in `waiters`; reject with `error()` once the clock runs out (`heard` restarts it). */
|
|
210
|
+
wait(id, timeoutMs, waiters, error) {
|
|
211
|
+
return new Promise((resolve, reject) => {
|
|
212
|
+
const clock = this.timers;
|
|
213
|
+
let timer;
|
|
214
|
+
const restart = () => {
|
|
215
|
+
clock.clearTimeout(timer);
|
|
216
|
+
timer = clock.setTimeout(expire, timeoutMs);
|
|
217
|
+
};
|
|
218
|
+
const stop = () => {
|
|
219
|
+
clock.clearTimeout(timer);
|
|
220
|
+
const restarts = this.clocks.get(id);
|
|
221
|
+
restarts?.delete(restart);
|
|
222
|
+
if (!restarts?.size)
|
|
223
|
+
this.clocks.delete(id);
|
|
224
|
+
};
|
|
225
|
+
const done = () => {
|
|
226
|
+
stop();
|
|
227
|
+
resolve();
|
|
228
|
+
};
|
|
229
|
+
const expire = () => {
|
|
230
|
+
stop();
|
|
231
|
+
const list = waiters.get(id)?.filter((w) => w !== done) ?? [];
|
|
232
|
+
if (list.length)
|
|
233
|
+
waiters.set(id, list);
|
|
234
|
+
else
|
|
235
|
+
waiters.delete(id);
|
|
236
|
+
reject(error());
|
|
237
|
+
};
|
|
238
|
+
waiters.set(id, [...(waiters.get(id) ?? []), done]);
|
|
239
|
+
this.clocks.set(id, (this.clocks.get(id) ?? new Set()).add(restart));
|
|
240
|
+
restart();
|
|
241
|
+
});
|
|
242
|
+
}
|
|
183
243
|
note(entry) {
|
|
184
244
|
if (entry.type === 'user' && entry.uuid)
|
|
185
245
|
this.user(entry.uuid);
|
|
@@ -207,26 +267,12 @@ export class JournalSessionStore {
|
|
|
207
267
|
}
|
|
208
268
|
/**
|
|
209
269
|
* Resolve once the user entry that answers `toolUseId` (its `tool_result`) is committed: a call the CLI answered
|
|
210
|
-
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs
|
|
270
|
+
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs`, on the same
|
|
271
|
+
* clock as `barrier`: the answer is mirrored with the rest of its message, once that message ends.
|
|
211
272
|
*/
|
|
212
273
|
async resultBarrier(toolUseId, timeoutMs) {
|
|
213
|
-
if (!this.results.has(toolUseId))
|
|
214
|
-
await
|
|
215
|
-
const timer = setTimeout(() => {
|
|
216
|
-
const list = this.resultWaiters.get(toolUseId)?.filter((w) => w !== done) ?? [];
|
|
217
|
-
if (list.length)
|
|
218
|
-
this.resultWaiters.set(toolUseId, list);
|
|
219
|
-
else
|
|
220
|
-
this.resultWaiters.delete(toolUseId);
|
|
221
|
-
reject(new Error(`the transcript entry answering tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
222
|
-
}, timeoutMs);
|
|
223
|
-
const done = () => {
|
|
224
|
-
clearTimeout(timer);
|
|
225
|
-
resolve();
|
|
226
|
-
};
|
|
227
|
-
this.resultWaiters.set(toolUseId, [...(this.resultWaiters.get(toolUseId) ?? []), done]);
|
|
228
|
-
});
|
|
229
|
-
}
|
|
274
|
+
if (!this.results.has(toolUseId))
|
|
275
|
+
await this.wait(toolUseId, timeoutMs, this.resultWaiters, () => new Error(`the transcript entry answering tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
230
276
|
await this.flush();
|
|
231
277
|
}
|
|
232
278
|
}
|
|
@@ -50,6 +50,17 @@ export interface FakeSdkOptions {
|
|
|
50
50
|
updatedInput?: Record<string, unknown>;
|
|
51
51
|
reason?: string;
|
|
52
52
|
}) => void;
|
|
53
|
+
/** The wait between a `batch` message's blocks. Default a real timer; a test on a fake clock passes its own. */
|
|
54
|
+
sleep?: (ms: number) => Promise<void>;
|
|
55
|
+
/** A `batch` call's handler returned: its block's place in the message (from 1), and what the tool server answered. */
|
|
56
|
+
onCallEnd?: (call: {
|
|
57
|
+
id: string;
|
|
58
|
+
index: number;
|
|
59
|
+
isError: boolean;
|
|
60
|
+
text: string;
|
|
61
|
+
}) => void;
|
|
62
|
+
/** A `batch` message's `message_stop` was taken: the consumer asked for what follows it, so it has heard the stop. */
|
|
63
|
+
onMessageEnd?: () => void;
|
|
53
64
|
}
|
|
54
65
|
export interface FakeSdk extends ClaudeAgentSdk {
|
|
55
66
|
queries: Record<string, any>[];
|