@parcha/agentrun-harness-claude 0.1.0-beta.56 → 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.
@@ -0,0 +1,45 @@
1
+ // How the pinned CLI renews a person's login, for a host that holds the login itself and renews it in the CLI's place
2
+ // (serve's runner, whose runs under a user of their own get the access token alone: login.ts ClaudeLoginToken).
3
+ // Written for AgentRun.
4
+ //
5
+ // Read from the pinned CLI's bundled code (2.1.286, from Agent SDK 0.3.286: versions.ts), with no run of it. Each value
6
+ // below is cited by the code it is in; test/pins.test.mjs reads the installed CLI and turns red when a repin moves any
7
+ // of them (the token URL, the client id, the request's body or header, the answer's fields, the write back, the lock).
8
+ //
9
+ // - The request: the CLI's refresh (`grant_type:"refresh_token"`) posts
10
+ // `{grant_type:"refresh_token",refresh_token:<the login's>,client_id:<the login's clientId>??CLIENT_ID,scope:<scopes>.join(" ")}`
11
+ // as JSON to `cn().TOKEN_URL`, with `{headers:{"Content-Type":"application/json"},timeout:30000}`. Its scopes are the
12
+ // login's own (`scopes:X.scopes`, what it sends when the login names its client, and its fallback), or the list below.
13
+ // - The answer: `{access_token, refresh_token = the one sent, expires_in}` (seconds), and `refresh_token_expires_in`
14
+ // and `scope` when given. Any status but 200 is a failure; `invalid_grant` marks the refresh token dead.
15
+ // - The write back: `{...file, claudeAiOauth: {accessToken, refreshToken, expiresAt: now + expires_in * 1000,
16
+ // refreshTokenExpiresAt: the answer's ?? the file's, scopes, subscriptionType, rateLimitTier, clientId}}`, only while
17
+ // the file still holds the refresh token it sent (or a cleared one), through its atomic writer at mode 0600
18
+ // (`await <write>(<path>,<json>,384),await <chmod>(<path>,384)`, 384 = 0o600).
19
+ // - The lock: before it reads the login to renew it, it takes a lock with proper-lockfile's options
20
+ // `{lockfilePath:<credentials dir>/.oauth_refresh.lock,realpath:!1,stale:60000,update:5000}` (a directory made with
21
+ // mkdir, its mtime touched every 5 s while held, taken over once 60 s old), then the older path
22
+ // `<realpath of the credentials dir>.lock` with the same options; it reads the login again under them, and takes a
23
+ // token another holder renewed meanwhile instead of renewing.
24
+ /** The pinned CLI's renewal of a login: where it posts, as which client, with which scopes when the login names none,
25
+ * and the lock it holds while it renews. */
26
+ export const LOGIN_REFRESH = Object.freeze({
27
+ /** `TOKEN_URL:"https://platform.claude.com/v1/oauth/token"` in the CLI's production OAuth config (the one object that
28
+ * also holds its `CLIENT_ID`). */
29
+ tokenUrl: "https://platform.claude.com/v1/oauth/token",
30
+ /** `CLIENT_ID:"9d1c250a-e61b-44d9-88ed-5944d1962f5e"` in the same object: the CLI's public OAuth client, which it sends
31
+ * when the login names no `clientId` of its own (`client_id:s??cn().CLIENT_ID`). */
32
+ clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
33
+ /** The scopes it asks for when the login holds none: its list
34
+ * `[user:profile, user:inference, "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"]`, and
35
+ * `user:plugins` (its production config's `PLUGINS_SCOPE_REGISTERED:!0`). */
36
+ scopes: Object.freeze(["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload", "user:plugins"]),
37
+ /** The lock's directory in the credentials directory: `lockfilePath:<join>(e,".oauth_refresh.lock")`. */
38
+ lockName: ".oauth_refresh.lock",
39
+ /** The older lock's suffix, on the credentials directory's real path: `` `${await <realpath>(e)}.lock` ``. */
40
+ legacyLockSuffix: ".lock",
41
+ /** A lock older than this is a dead holder's, taken over: `stale:60000`. */
42
+ lockStaleMs: 60_000,
43
+ /** How often a holder touches its lock: `update:5000`. */
44
+ lockUpdateMs: 5_000,
45
+ });
package/dist/login.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ModelPort } from "@parcha/agentrun-kernel";
2
+ import { type ParentWatch } from "@parcha/agentrun-kernel/host";
2
3
  /** Where the pinned CLI keeps a login: its credentials file's directory (`CLAUDE_SECURESTORAGE_CONFIG_DIR`) and its
3
4
  * Anthropic profiles (`ANTHROPIC_CONFIG_DIR`). The CLI reads and writes both; nothing else does. */
4
5
  export interface ClaudeAgentLogin {
@@ -10,37 +11,65 @@ export interface ClaudeAgentLogin {
10
11
  * home. Their own CLI, run with no folder variable, keeps the account in `<home>/.claude.json` and, on macOS, its
11
12
  * tokens in the Keychain item with no suffix; the variables below reach that same login (signInEnv, loginEnv). */
12
13
  home?: string;
13
- /** Set for this machine's own login, which the person's own CLI uses too (the default folder or their
14
- * `CLAUDE_CONFIG_DIR`): a status check never runs the CLI on its account file, only on a copy (claudeLoginStatus). */
15
- shared?: boolean;
14
+ /** Set only for a person's own login whose CLI keeps its credentials apart from `dir`, because the server's env sets
15
+ * `CLAUDE_SECURESTORAGE_CONFIG_DIR`: the folder it names, absolute (set and empty, `<home>/.claude`, the CLI's rule). */
16
+ secure?: string;
17
+ /** With `secure`: the variable was set and empty, which on macOS names the Keychain item with no suffix, so it goes to
18
+ * the CLI empty there too. */
19
+ unsuffixed?: boolean;
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
+ userHome?: string;
16
24
  }
25
+ /** A login handed to the CLI as its access token alone, by a host that holds the login itself. `token()` is asked at
26
+ * each start of the CLI and when Anthropic refuses the token the CLI holds: it answers the login's access token as
27
+ * 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
28
+ * refresh token and no login directory. */
29
+ export interface ClaudeLoginToken {
30
+ token(): Promise<string>;
31
+ /** Told, before `token()` is asked again, that Anthropic refused `sent` (the CLI's 401): a host that renews the login
32
+ * renews it at that ask unless it already holds another token. */
33
+ refused?(sent: string): Promise<void>;
34
+ }
35
+ /** Whether `login` is handed as a token (ClaudeLoginToken), not as its directories. */
36
+ export declare const loginByToken: (login: ClaudeAgentLogin | ClaudeLoginToken) => login is ClaudeLoginToken;
37
+ /** The words a turn ends in when Anthropic refused the login's access token mid-turn and the host had no newer one. */
38
+ 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.";
17
39
  /** The variables that point a session's CLI at `login`: never its config dir (`CLAUDE_CONFIG_DIR`), which the Agent SDK
18
40
  * copies a credentials file out of when it resumes a session, so the credentials dir (`CLAUDE_SECURESTORAGE_CONFIG_DIR`)
19
41
  * is always set. On macOS the CLI names its Keychain item from that dir (`-<sha256 of it>` after the name) unless it is
20
42
  * set and empty; unset, it would hash the session's own config dir. So a login on the CLI's default folder (`home`) gets
21
43
  * an empty one on macOS (the item with no suffix, the person's own CLI's), and its folder elsewhere, where the CLI keeps
22
- * `.credentials.json` in that dir. A status check on a login the person's own CLI uses has a config dir of its own too
23
- * (a copy of the account file), so it takes this rule (claudeLoginStatus). `platform`: the one the CLI runs on, this
24
- * host's. */
44
+ * `.credentials.json` in that dir. A login whose credentials dir is set apart (`secure`) gets that one, as the person's
45
+ * own CLI with it does. A status check has a config dir of its own too (a copy of the account file), so it takes this
46
+ * rule (claudeLoginStatus). `platform`: the one the CLI runs on, this host's. */
25
47
  export declare function loginEnv(login: ClaudeAgentLogin, platform?: NodeJS.Platform): Record<string, string>;
26
48
  /** The variables of the CLI's own sign-in at `login`. The line a person runs (loginCommand) and the sign-in this host
27
- * starts (startClaudeLogin) both take these, and so does the status check (claudeLoginStatus) on AgentRun's own login,
28
- * both in the person's home (personHome), so they cannot drift apart. Neither is a session, whose config dir stays its own (loginEnv). On a login the person's
29
- * own CLI uses too (`home`, `shared`) the status check runs on a copy of the account file instead.
49
+ * starts (startClaudeLogin) both take these, the sign-in in the person's home (personHome), so they cannot drift apart.
50
+ * Neither is a session, whose config dir stays its own (loginEnv), and neither is the status check, which runs on a copy
51
+ * of the account file with a run's variables (claudeLoginStatus).
30
52
  * - On the CLI's default folder (`home`): the person's own CLI as it runs, with no config or credentials dir, in their
31
53
  * home (`HOME`; a terminal of theirs has it already, so the shown line leaves it out, and clears the two folder
32
54
  * variables a terminal may export). It writes the account in `<home>/.claude.json` and the tokens where that person's
33
55
  * CLI keeps them, on every platform.
34
56
  * - Anywhere else: the login's folder as both the config dir and the credentials dir. `auth login` writes the account it
35
- * signed in to its config dir's `.claude.json`, where the status check reads it (from a copy, on a folder the person's
36
- * own CLI uses). For a folder the person's own
57
+ * signed in to its config dir's `.claude.json`, where the status check reads it (from a copy). For a folder the person's own
37
58
  * CLI uses through `CLAUDE_CONFIG_DIR`, the credentials dir set to that folder is where that CLI keeps its tokens too
38
- * (Linux: the same file; macOS: the same item, hashed from the same folder). */
39
- export declare function signInEnv(login: ClaudeAgentLogin): Record<string, string>;
59
+ * (Linux: the same file; macOS: the same item, hashed from the same folder).
60
+ * - A credentials dir set apart (`secure`, from the server's `CLAUDE_SECURESTORAGE_CONFIG_DIR`) is the credentials dir
61
+ * in either case, as for the person's own CLI with that variable (secureVar: empty on macOS when theirs is empty).
62
+ * `platform`: the one the CLI runs on, this host's. */
63
+ export declare function signInEnv(login: ClaudeAgentLogin, platform?: NodeJS.Platform): Record<string, string>;
40
64
  /** The line a person runs to sign the CLI in at `login` (the CLI opens a browser itself), with signInEnv's variables
41
65
  * but HOME, which is their terminal's own. A folder variable signInEnv leaves unset (the CLI's default folder) is
42
- * cleared with `env -u` (GNU's and macOS's env both have it), since a terminal that exports it would sign in there. */
43
- export declare const loginCommand: (login: ClaudeAgentLogin, cli?: string) => string;
66
+ * cleared by `env -u`, since a terminal that exports it would sign in there: env is a program, so sh, bash, zsh, fish
67
+ * and tcsh all run that line alike (fish has no `( ... )` subshell, tcsh no `NAME=value cmd`). env reads any word
68
+ * holding '=' as one more variable, so a CLI path holding one (/data/a=b/claude) goes to `sh -c` as its `$0`, single
69
+ * quoted, which every one of those shells reads alike too. What env skips: a `claude` alias or function of the
70
+ * person's shell. Elsewhere nothing is cleared, and the line is the variables in front of the CLI, as a shell reads
71
+ * them (sh, bash, zsh, fish 3.1 and later; not tcsh). `platform`: as signInEnv's. */
72
+ export declare const loginCommand: (login: ClaudeAgentLogin, cli?: string, platform?: NodeJS.Platform) => string;
44
73
  /** What the CLI says of its login: whether it is signed in, how, and the account's own words when it gives them. */
45
74
  export interface ClaudeLoginStatus {
46
75
  signedIn: boolean;
@@ -55,29 +84,63 @@ export interface ClaudeLoginStatus {
55
84
  export declare function parseLoginStatus(stdout: string): ClaudeLoginStatus | undefined;
56
85
  /** The longest a status check may take. */
57
86
  export declare const LOGIN_STATUS_MS = 15000;
58
- /** The home of the person whose CLI keeps `login`: the login's own (`home`, the CLI's default folder), else `given`, else
59
- * the server's (`os.homedir()`). On macOS the CLI reads its tokens from the login keychain, which is under that home:
60
- * in any other home (an empty one, a session's) it finds no keychain and reads signed out, whatever the variables. */
61
- export declare const personHome: (login: ClaudeAgentLogin, given?: string) => string;
87
+ /** A status check the CLI outlasted: ended at its limit (`limitMs`) with no answer, which says nothing of the login (a
88
+ * loaded host can take that long), apart from a CLI that answered, in time, what reads as no status. `code` is
89
+ * `timed_out`, so a caller that loads the harness lazily can tell it without the class. */
90
+ export declare class ClaudeLoginTimedOut extends Error {
91
+ readonly limitMs: number;
92
+ readonly code = "timed_out";
93
+ constructor(limitMs: number);
94
+ }
95
+ /** A status check the CLI answered in time with nothing that reads as a status: no answer either, apart from a CLI that
96
+ * never started (the spawn's own error, `ENOENT` and the like). `code` is `no_status`, for a caller that loads the
97
+ * harness lazily. */
98
+ export declare class ClaudeLoginNoStatus extends Error {
99
+ readonly code = "no_status";
100
+ constructor();
101
+ }
102
+ /** Removes what status checks cut off mid-way left: a server killed outright (SIGKILL) runs no `finally`, so its check's
103
+ * folder (claudeLoginStatus's `scratch`), with the copy of the account file in it, stays in the temporary folder. Takes
104
+ * each folder there named as a check's (the prefix and mkdtemp's six characters, nothing longer) that is this user's
105
+ * (`uid`, `process.getuid()` by default) and whose check has ended: more than STATUS_SWEEP_MARGIN_MS (15 s) before
106
+ * `now` by the end the check wrote in it (STATUS_ENDS_FILE), whatever limit its caller gave it, so a check another
107
+ * server on this host is running is never taken. A folder with no such end (its check was killed before writing it,
108
+ * or what the file holds is no time, or one before the file was written: checkEnds) is taken once it was last changed
109
+ * more than twice a check's limit (LOGIN_STATUS_MS) before `now`. Exactly at its margin, a folder stays by either
110
+ * rule. Another user's folder, a link or a file is never taken. `dir`: the temporary folder (`os.tmpdir()` by
111
+ * default). Nothing on Windows, which has no uid to tell whose a folder is. Never throws: a folder that can't be read or
112
+ * removed stays. Resolves to the folders it removed. The server runs it as it starts. */
113
+ export declare function sweepClaudeStatusFolders(options?: {
114
+ dir?: string;
115
+ uid?: number;
116
+ now?: number;
117
+ }): Promise<string[]>;
118
+ /** The home of the person whose CLI keeps `login`, the one every use of the login reads: the login's `userHome`, else
119
+ * its `home` (the CLI's default folder), else the server's (`os.homedir()`), for a login made with neither. On macOS
120
+ * the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
121
+ * session's) it finds no keychain and reads signed out, whatever the variables. */
122
+ export declare const personHome: (login: ClaudeAgentLogin) => string;
62
123
  /** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH and the login's
63
- * variables beside it, in the person's home (personHome; `home` given, else the server's) on every place and platform.
124
+ * variables beside it, in the person's home (personHome) on every place and platform.
64
125
  * The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
65
126
  * 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
66
- * runs it on a file the person's own CLI keeps:
67
- * - AgentRun's own login: the sign-in's variables (signInEnv), so it reads the account `auth login` left in the login's
68
- * folder, which is AgentRun's alone.
69
- * - A login the person's own CLI uses too (the default folder, `home`; their `CLAUDE_CONFIG_DIR`, `shared`): the config
70
- * dir is a copy of their account file in a folder of its own (`scratch`, one per check, removed after it answers or
71
- * throws), less its secrets (accountCopy), and the credentials dir is a run's (loginEnv): on macOS it names the
72
- * Keychain item ahead of the config dir (empty: the item with no suffix, the default folder's; else hashed from the
73
- * folder), so the copy never renames it.
127
+ * 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
128
+ * (accountFile: the default folder's in the home, else the login folder's) in a folder of its own (`scratch`, one per
129
+ * check, removed after it answers or throws), less its secrets (accountCopy), and the credentials dir is a run's
130
+ * (loginEnv): on macOS it names the Keychain item ahead of the config dir (empty: the item with no suffix, the default
131
+ * folder's; else hashed from the login's folder, as the sign-in there named it), so the copy never renames it.
74
132
  * A status check is no session: nothing resumes in its config dir. `platform`: the one the CLI runs on, this host's.
75
- * Throws when the CLI gives no answer that reads as one. */
133
+ * Asks once. Throws when the CLI gives no answer that reads as one: ClaudeLoginTimedOut when it was still running at
134
+ * the limit (`timeoutMs`, LOGIN_STATUS_MS by default) and was ended there, else ClaudeLoginNoStatus. A CLI that never
135
+ * started throws the spawn's own error. At the limit the CLI is asked to go (SIGTERM) and killed STATUS_KILL_MS later;
136
+ * once it has exited or was killed, the check waits STATUS_DRAIN_MS more at most for its output, which a process it
137
+ * 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
138
+ * that pass, whatever the CLI does. A `timeoutMs` that is no whole number of ms from 1 to 2^31 - 1 throws a RangeError
139
+ * before anything starts. */
76
140
  export declare function claudeLoginStatus(cli: string, login: ClaudeAgentLogin, options?: {
77
141
  timeoutMs?: number;
78
142
  path?: string;
79
143
  platform?: NodeJS.Platform;
80
- home?: string;
81
144
  }): Promise<ClaudeLoginStatus>;
82
145
  /** How long the CLI's own sign-in waits for its browser before it is ended. */
83
146
  export declare const SIGN_IN_MS: number;
@@ -102,14 +165,18 @@ export interface ClaudeSignIn {
102
165
  stop(): void;
103
166
  }
104
167
  /** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
105
- * (`home`) and desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
168
+ * (personHome) and desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
106
169
  * Nothing of it is read here: its output goes nowhere. It is ended after `timeoutMs` (SIGN_IN_MS by default), which
107
- * `ended` says apart from any other end. */
170
+ * `ended` says apart from any other end.
171
+ * It dies with this process, as a session's CLI does: started under the kernel's parent watch (parentWatched; `watch`,
172
+ * by default what this machine supports), so a server that is SIGKILLed, and runs no stop or limit timer, leaves no CLI
173
+ * waiting on the browser's port. It is not detached: it stays in this process's group, so a terminal's Ctrl-C ends it
174
+ * with the server as before, and nothing here kills a group, which would take a browser the CLI started with it. */
108
175
  export declare function startClaudeLogin(cli: string, login: ClaudeAgentLogin, options?: {
109
176
  timeoutMs?: number;
110
177
  path?: string;
111
- home?: string;
112
178
  display?: Readonly<Record<string, string | undefined>>;
179
+ watch?: ParentWatch;
113
180
  }): ClaudeSignIn;
114
181
  /** How a session on a login books its requests: no proxy sees them, so each response the CLI streams is booked from its
115
182
  * own events, billed to the plan, at no price here. No proxy can hold a request back either, so a request is admitted