@parcha/agentrun-harness-claude 0.1.0-beta.56 → 0.1.0-beta.57
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 +32 -0
- package/dist/adapter.d.ts +8 -3
- package/dist/adapter.js +7 -3
- package/dist/harness.d.ts +3 -2
- package/dist/harness.js +14 -5
- package/dist/host/machine.d.ts +2 -0
- package/dist/host/machine.js +1 -0
- package/dist/host/policy.d.ts +6 -0
- package/dist/host/policy.js +29 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/login.d.ts +85 -33
- package/dist/login.js +289 -70
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,38 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.57 (2026-11-24)
|
|
6
|
+
|
|
7
|
+
**Breaking:**
|
|
8
|
+
|
|
9
|
+
- The harness's Claude login (`ClaudeAgentLogin`) no longer has the `shared` flag 0.1.0-beta.56 gave it. Every status check now runs the CLI on a copy of the account file, as a check on a login marked `shared` did, so the flag has nothing left to choose. A host that set it drops it. TypeScript flags `shared` in a login written as an object literal as an unknown property; from JavaScript it is ignored. <!-- changes/claude-login-no-shared.md -->
|
|
10
|
+
- `startClaudeLogin` no longer takes a `home` option. A host that calls it with `{ home }` sets that home on the login as `userHome` instead (`startClaudeLogin(cli, { ...login, userHome: home })`); the status check and a run on macOS read the same field, so one home serves all three. TypeScript flags a `home` option as an unknown property; from JavaScript it is ignored, and the sign-in runs in the login's own `home`, else the OS's home. <!-- changes/claude-login-start-home.md -->
|
|
11
|
+
- `claudeLoginStatus` no longer takes a `home` option. A host that calls it with `{ home }` sets that home on the login as `userHome` instead (`claudeLoginStatus(cli, { ...login, userHome: home })`); the sign-in and a run on macOS read the same field, so one home serves all three. TypeScript flags a `home` option as an unknown property; from JavaScript it is ignored, and the check runs in the login's own `home`, else the OS's home. <!-- changes/claude-login-status-home.md -->
|
|
12
|
+
|
|
13
|
+
**Changes:**
|
|
14
|
+
|
|
15
|
+
- `web_search`'s default, `auto`, is now agentrun's own search on every harness: Parallel where the server holds a Parallel key, else keyless Firecrawl with keyless Exa behind it. Before, `auto` on codex was Codex's own live search, and on pi with a direct `anthropic/*` or `openai/*` model it was one request to that provider's hosted search. Both now go through agentrun's `web_search` instead. This changes what a codex or pi search costs and returns: Parallel's fee per search on the server's key, or keyless Firecrawl at no charge, in place of the provider's per-search fee, and those providers' results in place of Codex's or the model provider's. <!-- changes/web-search-auto-ours.md -->
|
|
16
|
+
`native` stays a provider you can pick, for an agent (`definition.tool_settings`) or the server (`PUT /settings/tools`). Picked, it still turns on Claude's WebSearch, Codex's live search or pi's hosted search, and it is unavailable where it was before (behind a gateway, on OpenRouter, under a spend cap). To keep the old behaviour on codex or pi, pick `native`. claude-agent's `auto` is unchanged.
|
|
17
|
+
The openapi document's `web_search` provider list is unchanged (`native` stays in it). Only `auto`'s description and capabilities' `resolves` and `why` change: on codex and pi, `resolves` reads `parallel` or `firecrawl-keyless` where it read `native`. A run that started before the upgrade keeps the plane it launched with, `native` included, for its life.
|
|
18
|
+
A claude-agent session now also names the claude CLI's WebFetch in its `disallowedTools` (`CLAUDE_AGENT_ALSO_OFF`), as it names WebSearch. WebFetch was already off three ways: the session's tools list is empty, the PreToolUse hook denies it, and the CLI's sandbox network is deny-all. Naming it keeps the host's `web_fetch` the session's only fetch even if one of those changes.
|
|
19
|
+
- A claude-agent run on a clock the host set (the adapter's `now`; in serve, a template eval case's `now:`) is now told that clock's day by the Claude CLI too. The CLI dates the session from the machine's clock in its own lines ("Today's date is 2026-11-24.", and "Today's date is now ..." on a later day), and has no setting for it. On a case clock set to another day, the model was told both days and went by the CLI's, so every date a grader checked against the case clock failed. The session's model proxy now rewrites those two lines to the clock's day in the run's zone (`zone`), in the CLI's own `system` message only, where the CLI puts them. The person's prompt, the model's replies, tool results and the app's system prompt are never rewritten, so a date someone wrote, quoted or read reaches the model as it was. A run with no `now`, which is every production run, is unchanged. <!-- changes/claude-agent-case-clock-date.md -->
|
|
20
|
+
A session on a person's Claude login has no model proxy, so there the CLI's lines keep the machine's date. Run clocked cases on the provider route (an API key or gateway).
|
|
21
|
+
- Settings → Model keys' login on this machine: fixes to the claude CLI's sign-in and to its status check. <!-- changes/claude-sign-in-followups.md -->
|
|
22
|
+
- The line shown for "this machine's" login on the CLI's default folder starts a CLI whose path holds `=` (a data folder such as `/data/a=b`): it still clears the CLI's folder variables with 0.1.0-beta.56's `env -u CLAUDE_CONFIG_DIR -u CLAUDE_SECURESTORAGE_CONFIG_DIR ...`, and such a path goes to `sh -c 'exec "$0" auth login'` as its `$0`. Before, env read that path as one more variable, and the CLI never started. The line runs alike pasted into sh, bash, zsh, fish or tcsh; env skips a `claude` alias or function of the person's shell.
|
|
23
|
+
- `PUT /v2/settings/claude-login` that moves the login to the other `place` ends a sign-in the server started that still waits, and answers once its CLI is gone; before, that CLI kept waiting to sign in at the old place. A `PUT` at the same place leaves it waiting. A move or a turn-off that lands while a sign-in is starting now waits for that start and then ends it, or comes first, and the sign-in starts on what it saved; before, the sign-in could start after it with the old setting, at the old place or for a login that was off.
|
|
24
|
+
- "This machine's" login honours `CLAUDE_SECURESTORAGE_CONFIG_DIR` in the server's environment, as the person's own claude CLI with that variable does: the status check, the sign-in, the shown line and a run keep the tokens in that folder (on macOS the Keychain item named from it). Set and empty, it means `~/.claude` and, on macOS, the Keychain item with no suffix, which the CLI gets as an empty value there. A relative value is not taken. The view says it as `machine.credentials`, and the console names it under the folder. Before, the server ignored it and read the tokens from the config folder, so a person whose CLI sets it read signed out. The harness's login takes `secure` and `unsuffixed` for it, and `claudeSignInEnv` and `claudeLoginCommand` take the platform, as `claudeLoginEnv` does. A run with the CLI's own sandbox on denies its commands reading that folder too, as it does the login's own folders; on macOS an empty value names a Keychain item, and adds nothing.
|
|
25
|
+
- The sign-in's CLI dies with the server that started it: `startClaudeLogin` starts it under the kernel's parent watch (`parentWatched`: the parent-death signal through `setpriv` on Linux, else the watching shim), as a session's CLI is. Before, a server killed outright (SIGKILL, the OOM killer) left `auth login` running with no limit, holding the browser's callback port. A CLI path that is no program still reads as never started, in the spawn's words. `startClaudeLogin` takes `watch` to choose the watch. A sign-in stopped or ended at its limit under the shim ends only once its CLI is gone, though the CLI ignores SIGTERM: the shim kills it 2 s after passing the TERM on, before the server's own kill 5 s after it, which reaches the shim alone.
|
|
26
|
+
- The login's setting names the machine it was turned on for by an id the server makes once in its data folder (`machine-id`, 0600) and reads back on every later start, in place of the hostname. Before, a laptop's hostname changed with its network, so a login turned on at home read "turned on for another machine" elsewhere, and its runs asked for a key. Two data folders are two machines.
|
|
27
|
+
- Settings → Model keys: Turn on says why it is grey while "Only I run agents on this server" is not ticked, beside it and as its description for a screen reader.
|
|
28
|
+
- The Playground's "No model yet" bar is gone for an agent on Claude Agent (`claude-agent`) while the login is on and reads signed in, since Claude Agent runs on it. Before, it offered ChatGPT or a key as if no model were there. An agent on another harness keeps the bar. The bar reads the revision picked in the Playground, which the run will use, and the agent's current one when none is picked; a picked revision whose definition the console does not hold keeps it. The bar stays for a run in a sandbox box, by the revision's own place or the server's default one, since only a run on the runner uses the login. It stays too for a revision that names a model the login does not serve: only Anthropic's own models (or none) run on it, and an OpenRouter model, Anthropic's included, still needs `OPENROUTER_API_KEY`. The console reads the login once, again on leaving Settings (where a sign-in finishes) and after a run starts, never on each move between pages, since each read runs `claude auth status` on the server.
|
|
29
|
+
- The status check copies the account file only when it is a regular file of at most 32 MiB, read without holding up the server: it opens the file without waiting (`O_NONBLOCK`) and checks what it opened before reading. Before, a FIFO in its place stopped the whole server until something wrote to it, and a device such as `/dev/zero` or a huge file was read whole into memory. A FIFO, a device, a folder or a bigger file is copied as nothing, as a file that doesn't parse is. A link is still followed, since dotfile managers often link `~/.claude.json`.
|
|
30
|
+
- Every status check runs the CLI on a copy of the account file in a folder of its own, AgentRun's own login folder included, never on the file itself, so a check never has the CLI rewrite the login's `.claude.json`. In 0.1.0-beta.56 the check on AgentRun's own folder, and on any harness login not marked `shared`, read the login's folder as its config dir, as that release's entry says; none does now. The harness login's `shared` flag is gone (see its breaking entry).
|
|
31
|
+
- A server sweeps the status checks' folders (`agentrun-claude-status-*` in the temporary folder) as it starts, when the Claude login is allowed on it: the ones this user owns whose check has ended: each check writes in its folder when it ends at the latest (its limit, whatever the caller gave, and 2 s), and the sweep takes the folder more than 15 s after that; a folder with no such end, or one that lies before its file was written (empty, a partial write, a negative), is taken once changed more than twice the status check's limit ago. `claudeLoginStatus` throws a `RangeError` for a `timeoutMs` that is no whole number of ms from 1 to 2^31 - 1, before it starts the CLI. A check that was killed mid-way (SIGKILL runs no clean-up) left its folder, with a copy of the account file in it, until the machine cleared its temporary folder. The harness exports `sweepClaudeStatusFolders`.
|
|
32
|
+
- The status check ends at its limit whatever the CLI does: it asks the CLI to go (SIGTERM), kills it (SIGKILL) 1 s later, and waits at most 1 s more for the CLI's output, then reads as timed out. Before, it sent one SIGTERM and waited for the output's pipe to close, so a CLI that ignored the TERM, or a process it started that held its output open, kept the check, and the run's claim behind it, waiting for ever.
|
|
33
|
+
- The person's home is read once, where the server makes the login (the server's `HOME` when it is an absolute path, else the OS's home), and the status check, the sign-in and a run on macOS all take it from the login's new `userHome`. Before, the sign-in took the server's `HOME` while the status check and a run took the OS's home, so a server started with another `HOME` signed in at one home and checked another. `claudeLoginStatus` and `startClaudeLogin` no longer take the `home` option 0.1.0-beta.56 gave them (see their breaking entries).
|
|
34
|
+
- A Claude-plan run no longer fails because the login's status check was slow. On a loaded machine the claude CLI could take longer than the check's 15 s, and the run was refused as "could not say whether its login is signed in" though the login was fine. Now a check that gives no answer (the CLI outlasts it, or answers nothing that reads as a status) is asked once more; if that one gives no answer either, the run goes on when the same login read signed in within the last 10 minutes on this server (at a run's check or in Settings), and is refused as before otherwise, in words that say why (a check that timed out says so, and after how long). Any other failure of the check, such as no CLI at its path, refuses the run at once in its own words, as before. A signed-out answer still refuses the run at once, and is never asked again. The harness's `claudeLoginStatus` throws `ClaudeLoginTimedOut` (`code: "timed_out"`) when the CLI outlasts its limit, and `ClaudeLoginNoStatus` (`code: "no_status"`) when it answers in time with no status.
|
|
35
|
+
- On macOS, a run on the login runs in the person's home, so the claude CLI writes its cache and logs under their `~/Library/Caches/claude-cli-nodejs`, where they stay after the run. Removing that folder is safe.
|
|
36
|
+
|
|
5
37
|
## 0.1.0-beta.56 (2026-11-24)
|
|
6
38
|
|
|
7
39
|
- Settings → Model keys' "Open the CLI's sign-in here" signs the claude CLI in at the login's own folder, so the login reads signed in afterwards. The sign-in ran with a temporary config dir, where `auth login` wrote the account it signed in (`.claude.json`); that folder was removed when the sign-in ended, and the login's folder stayed without it, so AgentRun kept saying "not signed in" while running the shown command by hand worked. The sign-in, the shown command and the status check now take their variables from one function (`claudeSignInEnv`), and the status check reads the login's folder as its config dir. <!-- changes/claude-sign-in-folder.md -->
|
package/dist/adapter.d.ts
CHANGED
|
@@ -6,7 +6,8 @@ import { type ConfineChild } from "./host/machine.js";
|
|
|
6
6
|
import type { ClaudeAgentLogin } from "./login.js";
|
|
7
7
|
import type { ToolServerModules } from "./host/tool-server.js";
|
|
8
8
|
export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
|
|
9
|
-
/** The pinned CLI's tools
|
|
9
|
+
/** The pinned CLI's tools off by name in every session (WebSearch unless `webSearch`): those the copied harness leaves
|
|
10
|
+
* undecided, and WebFetch, which fetches from the CLI's own process where the host's web_fetch is the session's. */
|
|
10
11
|
export declare const CLAUDE_AGENT_ALSO_OFF: readonly string[];
|
|
11
12
|
/** The local plugin the session's skills are served from: the model sees each as `agentrun:<name>`, and may load it by
|
|
12
13
|
* that name or, unless the CLI has a command or skill of that name (`CLAUDE_AGENT_CLI_SKILL_NAMES`), by its bare one. */
|
|
@@ -97,9 +98,13 @@ export interface ClaudeAgentAdapterOptions {
|
|
|
97
98
|
/** How hard the model thinks when a node names no level (its `thinking`, else its `effort`). Default medium; it is
|
|
98
99
|
* never off. */
|
|
99
100
|
thinking?: ClaudeAgentThinking;
|
|
100
|
-
/**
|
|
101
|
+
/** The fetch the model proxy forwards with: the host's route for a model it translates onto this wire (a test's
|
|
102
|
+
* recorder, too); absent, the network. Forwarding it is the harness contract (HARNESS.md, the facts' `wire`). */
|
|
101
103
|
fetch?: typeof fetch;
|
|
102
|
-
/**
|
|
104
|
+
/** The run's clock, when the host sets one (serve: a template eval case's `now`): a user turn's day is read from it
|
|
105
|
+
* (harness.ts dateLine), and the CLI's own date lines, which it reads from the machine's clock, are made to say its
|
|
106
|
+
* day in `zone` at the session's model proxy (policy.ts `day`). A session on a login has no proxy: there the CLI's
|
|
107
|
+
* lines keep the machine's date. Default the system's clock, and the CLI's lines pass as written. */
|
|
103
108
|
now?: () => Date;
|
|
104
109
|
/** The IANA zone a user turn's day is read in (harness.ts dateLine), the one the host's environment line names. Default UTC. */
|
|
105
110
|
zone?: string;
|
package/dist/adapter.js
CHANGED
|
@@ -16,7 +16,7 @@ import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } f
|
|
|
16
16
|
import { toolSchemaProblems } from "@parcha/agentrun-kernel";
|
|
17
17
|
import { bridgeTool, NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
|
|
18
18
|
import { checkedOnce, checkedOnceAsync, hostHeaderProblems, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
19
|
-
import { anthropicPolicy, withWebSearches } from "./host/policy.js";
|
|
19
|
+
import { anthropicPolicy, isoDay, withWebSearches } from "./host/policy.js";
|
|
20
20
|
import { findClaudeExecutable, platformSuffix } from "./binary.js";
|
|
21
21
|
import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
22
22
|
import { claudeCodeHarness, claudeToolSearch, lostPrompts } from "./harness.js";
|
|
@@ -25,8 +25,9 @@ import { localMachine } from "./host/machine.js";
|
|
|
25
25
|
import { serialWriter } from "./serial.js";
|
|
26
26
|
import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
|
|
27
27
|
export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
|
|
28
|
-
/** The pinned CLI's tools
|
|
29
|
-
|
|
28
|
+
/** The pinned CLI's tools off by name in every session (WebSearch unless `webSearch`): those the copied harness leaves
|
|
29
|
+
* undecided, and WebFetch, which fetches from the CLI's own process where the host's web_fetch is the session's. */
|
|
30
|
+
export const CLAUDE_AGENT_ALSO_OFF = Object.freeze(["Skill", "WebSearch", "WebFetch"]);
|
|
30
31
|
/** The local plugin the session's skills are served from: the model sees each as `agentrun:<name>`, and may load it by
|
|
31
32
|
* that name or, unless the CLI has a command or skill of that name (`CLAUDE_AGENT_CLI_SKILL_NAMES`), by its bare one. */
|
|
32
33
|
export const CLAUDE_AGENT_SKILLS_PLUGIN = "agentrun";
|
|
@@ -335,6 +336,9 @@ export function claudeAgentAdapter(options) {
|
|
|
335
336
|
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
336
337
|
...(provider.auth ? { auth: provider.auth } : {}),
|
|
337
338
|
...(provider.headers ? { headers: provider.headers } : {}),
|
|
339
|
+
// On a clock the host set (`now`), the CLI's own date lines, read from the machine's clock, say that clock's day in
|
|
340
|
+
// the run's zone. A session on a login has no proxy, and keeps the machine's date.
|
|
341
|
+
...(options.now ? { day: () => isoDay(options.now(), options.zone) } : {}),
|
|
338
342
|
...(options.log ? { log: options.log } : {}),
|
|
339
343
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
340
344
|
} } : {}),
|
package/dist/harness.d.ts
CHANGED
|
@@ -308,8 +308,9 @@ export declare const CLAUDE_TOOL_SEARCH = "ToolSearch";
|
|
|
308
308
|
export declare const claudeBuiltinReplay: (name: string) => ReplayPolicy;
|
|
309
309
|
/** The `builtins` option, resolved: the `tools` option for `query()` (undefined: the preset, all of them). */
|
|
310
310
|
export declare function builtinTools(builtins: ClaudeBuiltins | undefined): string[] | undefined;
|
|
311
|
-
/** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16).
|
|
312
|
-
|
|
311
|
+
/** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16).
|
|
312
|
+
* `platform`: the one the CLI runs on, as loginEnv takes it. */
|
|
313
|
+
export declare function claudeSandboxSettings(machine: Pick<SessionMachine, 'root' | 'dirs'>, network: ClaudeSandboxNetwork, login?: ClaudeAgentLogin, platform?: NodeJS.Platform): NonNullable<QueryOptions['sandbox']>;
|
|
313
314
|
/** Loopback, as names and literals a command could hand the sandbox's proxy for the model port. */
|
|
314
315
|
export declare const LOOPBACK_NAMES: string[];
|
|
315
316
|
export declare function claudeCodeHarness(options?: ClaudeCodeHarnessOptions): Harness;
|
package/dist/harness.js
CHANGED
|
@@ -10,7 +10,7 @@ import { defersCatalog } from '@parcha/agentrun-kernel';
|
|
|
10
10
|
import { Restart, Unavailable } from './host/kernel.js';
|
|
11
11
|
import { askGate, BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, toolKey, waitForSubmissions, } from './host/process.js';
|
|
12
12
|
import { durableEnv, nativeModelId } from './env.js';
|
|
13
|
-
import { loginBooking } from './login.js';
|
|
13
|
+
import { loginBooking, loginEnv } from './login.js';
|
|
14
14
|
import { uuidFrom } from './ids.js';
|
|
15
15
|
import { MessageQueue } from './inbox.js';
|
|
16
16
|
import { sandboxSpawn } from './spawn.js';
|
|
@@ -144,16 +144,25 @@ export function builtinTools(builtins) {
|
|
|
144
144
|
return undefined;
|
|
145
145
|
throw new TypeError("agentrun-harness-claude: builtins takes true, a list of tool names, or { type: 'preset', preset: 'claude_code' }");
|
|
146
146
|
}
|
|
147
|
-
/** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16).
|
|
148
|
-
|
|
147
|
+
/** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16).
|
|
148
|
+
* `platform`: the one the CLI runs on, as loginEnv takes it. */
|
|
149
|
+
export function claudeSandboxSettings(machine, network, login, platform = process.platform) {
|
|
149
150
|
const { dirs } = machine;
|
|
150
151
|
const open = [dirs.tmp, dirs.home, dirs.cache];
|
|
152
|
+
const denyRead = [dirname(dirs.config), ...(login ? [login.dir, login.profiles] : [])];
|
|
153
|
+
// The folder the CLI reads the login's credentials from (loginEnv's own value), when the server's env sets it apart.
|
|
154
|
+
// Empty on macOS it names a Keychain item, no folder.
|
|
155
|
+
const secure = login ? loginEnv(login, platform).CLAUDE_SECURESTORAGE_CONFIG_DIR : '';
|
|
156
|
+
if (secure && !denyRead.includes(secure))
|
|
157
|
+
denyRead.push(secure);
|
|
151
158
|
return {
|
|
152
159
|
enabled: true,
|
|
153
160
|
failIfUnavailable: true,
|
|
154
161
|
allowUnsandboxedCommands: false,
|
|
155
|
-
// A person's login
|
|
156
|
-
|
|
162
|
+
// A run on a person's login comes through claudeAgentAdapter, which passes builtins: false (the CLI has no Bash),
|
|
163
|
+
// and AgentRun's own tools never run on the server host. Where commands do run, denyRead keeps them from the login's
|
|
164
|
+
// files on Linux. On macOS the token is a Keychain item, which denyRead does not cover.
|
|
165
|
+
filesystem: { allowWrite: [machine.root, ...open], denyRead, allowRead: open },
|
|
157
166
|
credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
|
|
158
167
|
network: {
|
|
159
168
|
...(network === 'allow-all' ? { allowedDomains: ['*'] } : network === 'deny-all' ? { allowedDomains: [], strictAllowlist: true } : { allowedDomains: [...network.allow], strictAllowlist: true }),
|
package/dist/host/machine.d.ts
CHANGED
|
@@ -37,6 +37,8 @@ export interface LocalMachineOptions {
|
|
|
37
37
|
webSearchAllowance?: number;
|
|
38
38
|
/** The CLI's own tool search is on: its beta, its tools and its tool references pass (anthropicPolicy). */
|
|
39
39
|
toolSearch?: boolean;
|
|
40
|
+
/** The day of the run's clock, when the host set it: the CLI's date lines say it (anthropicPolicy `day`). */
|
|
41
|
+
day?: () => string;
|
|
40
42
|
/** The tokens' price; each web search a response reports is added to it (`withWebSearches`). */
|
|
41
43
|
price?: ModelProxyOptions["price"];
|
|
42
44
|
maxOutputTokens?: number;
|
package/dist/host/machine.js
CHANGED
|
@@ -139,6 +139,7 @@ export function localMachine(options) {
|
|
|
139
139
|
...(po.webSearch ? { webSearch: true, ...(po.webSearchAllowance !== undefined ? { webSearchAllowance: po.webSearchAllowance } : {}) } : {}),
|
|
140
140
|
...(po.auth ? { auth: po.auth } : {}),
|
|
141
141
|
...(po.toolSearch ? { toolSearch: true } : {}),
|
|
142
|
+
...(po.day ? { day: po.day } : {}),
|
|
142
143
|
onThinkingDisabled: ({ model: main }) => po.log?.("claude-agent: thinking.disabled", { model: main }),
|
|
143
144
|
}),
|
|
144
145
|
hooks: po.hooks,
|
package/dist/host/policy.d.ts
CHANGED
|
@@ -52,7 +52,13 @@ export interface AnthropicPolicyOptions {
|
|
|
52
52
|
onThinkingDisabled?: (request: {
|
|
53
53
|
model: string;
|
|
54
54
|
}) => void;
|
|
55
|
+
/** The day of the run's clock (YYYY-MM-DD, `isoDay`), when the host set that clock (a template eval case's `now`):
|
|
56
|
+
* the CLI's own date lines, which it reads from the machine's clock, say this day instead (`CLI_DATE`). Absent, they
|
|
57
|
+
* pass as the CLI wrote them. */
|
|
58
|
+
day?: () => string;
|
|
55
59
|
}
|
|
60
|
+
/** `now`'s day in `zone` (default UTC) as YYYY-MM-DD, the form the CLI's date line takes. */
|
|
61
|
+
export declare function isoDay(now: Date, zone?: string): string;
|
|
56
62
|
/** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
|
|
57
63
|
export declare function thinks(body: Record<string, unknown>): boolean;
|
|
58
64
|
/** The tokens a request keeps for its answer when its output is limited, and the least thinking budget the provider
|
package/dist/host/policy.js
CHANGED
|
@@ -67,6 +67,10 @@ export const CLAUDE_WEB_SEARCH_TOOL = "web_search_20250305";
|
|
|
67
67
|
const WEB_SEARCH_KEYS = new Set(["type", "name", "max_uses", "allowed_domains", "blocked_domains"]);
|
|
68
68
|
/** The most searches one request may ask the provider for: the pinned CLI's `max_uses`. */
|
|
69
69
|
const WEB_SEARCH_MAX_USES = 8;
|
|
70
|
+
/** `now`'s day in `zone` (default UTC) as YYYY-MM-DD, the form the CLI's date line takes. */
|
|
71
|
+
export function isoDay(now, zone = "UTC") {
|
|
72
|
+
return new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
|
|
73
|
+
}
|
|
70
74
|
/** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
|
|
71
75
|
export function thinks(body) {
|
|
72
76
|
const thinking = body.thinking;
|
|
@@ -115,6 +119,26 @@ function blocks(content, where, inResult = false, references) {
|
|
|
115
119
|
blocks(block.content, "a tool result's content", true, references);
|
|
116
120
|
}
|
|
117
121
|
}
|
|
122
|
+
/** The pinned CLI's date lines, read from the machine's clock in its own local time: "Today's date is 2026-11-24.", and on
|
|
123
|
+
* a later day "Today's date is now 2026-11-25. ...". The CLI has no setting for its date (test/case-clock.test.mjs fails
|
|
124
|
+
* if a CLI bump words these differently, or moves them). */
|
|
125
|
+
const CLI_DATE = /\bToday's date is (now )?\d{4}-\d{2}-\d{2}\./g;
|
|
126
|
+
/** `text` with each of the CLI's date lines saying `day`. */
|
|
127
|
+
const onDay = (text, day) => text.replace(CLI_DATE, (_line, now) => `Today's date is ${now ?? ""}${day}.`);
|
|
128
|
+
/** A message with the CLI's date lines saying `day`, when it is one of the CLI's own: a `system` message among the
|
|
129
|
+
* messages, where the pinned CLI puts its environment note and the date at its end. Every other message (the person's
|
|
130
|
+
* words, the app's tool results, the model's replies) and the system prompt (the app's instructions) are never changed, so
|
|
131
|
+
* a date someone wrote, quoted or read reaches the model as it was. */
|
|
132
|
+
function messageOnDay(message, day) {
|
|
133
|
+
if (!isPlain(message) || message.role !== "system")
|
|
134
|
+
return message;
|
|
135
|
+
const content = message.content;
|
|
136
|
+
if (typeof content === "string")
|
|
137
|
+
return { ...message, content: onDay(content, day) };
|
|
138
|
+
if (!Array.isArray(content))
|
|
139
|
+
return message;
|
|
140
|
+
return { ...message, content: content.map((block) => (isPlain(block) && block.type === "text" && typeof block.text === "string" ? { ...block, text: onDay(block.text, day) } : block)) };
|
|
141
|
+
}
|
|
118
142
|
/** A message with the CLI's note of its own image file left out of each tool result that holds the image itself: the
|
|
119
143
|
* note names a path in the session's directory, which differs between a session and its resumption, and says nothing
|
|
120
144
|
* the image doesn't. */
|
|
@@ -288,7 +312,11 @@ export function applyAnthropic(body, route, options, context = {}) {
|
|
|
288
312
|
const small = options.smallModel ?? options.model;
|
|
289
313
|
if (body.model !== options.model && body.model !== small)
|
|
290
314
|
refuse(403, "the model is not this session's");
|
|
291
|
-
|
|
315
|
+
// On a set clock, the CLI's date lines say its day, in its own system messages only (messageOnDay). The host's own side
|
|
316
|
+
// requests carry none of the CLI's lines, and are left as they are.
|
|
317
|
+
const day = context.host === undefined ? options.day?.() : undefined;
|
|
318
|
+
const messages = body.messages.map(withoutImageNotes);
|
|
319
|
+
const out = { ...body, messages: day === undefined ? messages : messages.map((m) => messageOnDay(m, day)), ...(tools === undefined ? {} : { tools }) };
|
|
292
320
|
if (count)
|
|
293
321
|
return out;
|
|
294
322
|
// A main-model request that would not think is said, never passed silently (it is still forwarded: the CLI decides
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claude
|
|
|
7
7
|
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
|
|
8
8
|
export type { AnthropicPolicyOptions, AnthropicUsage } from "./host/policy.js";
|
|
9
9
|
export type { ChildCommand, ConfineChild } from "./host/machine.js";
|
|
10
|
-
export { claudeLoginStatus, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
10
|
+
export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
11
11
|
export type { ClaudeAgentLogin, ClaudeLoginStatus } from "./login.js";
|
|
12
12
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
|
|
13
13
|
export type { ServedTool } from "./host/tool-server.js";
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,6 @@ export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch,
|
|
|
4
4
|
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_AGENT_BASE_INPUT_TOKENS, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
|
|
5
5
|
export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
|
|
6
6
|
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
|
|
7
|
-
export { claudeLoginStatus, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
7
|
+
export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
8
8
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
|
|
9
9
|
export { SIGN_IN_MS as CLAUDE_SIGN_IN_MS, signInEnv as claudeSignInEnv } from "./login.js";
|
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,51 @@ 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
|
|
14
|
-
* `
|
|
15
|
-
|
|
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 loginAt: the
|
|
21
|
+
* server's `HOME` when absolute, else `os.homedir()`, as the person's own CLI reads it), so the status check, the
|
|
22
|
+
* sign-in and a run on macOS all run in that one home (personHome). With `home`, the same folder. */
|
|
23
|
+
userHome?: string;
|
|
16
24
|
}
|
|
17
25
|
/** The variables that point a session's CLI at `login`: never its config dir (`CLAUDE_CONFIG_DIR`), which the Agent SDK
|
|
18
26
|
* copies a credentials file out of when it resumes a session, so the credentials dir (`CLAUDE_SECURESTORAGE_CONFIG_DIR`)
|
|
19
27
|
* is always set. On macOS the CLI names its Keychain item from that dir (`-<sha256 of it>` after the name) unless it is
|
|
20
28
|
* 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
29
|
* 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
|
|
23
|
-
* (a copy of the account file), so it takes this
|
|
24
|
-
* host's. */
|
|
30
|
+
* `.credentials.json` in that dir. A login whose credentials dir is set apart (`secure`) gets that one, as the person's
|
|
31
|
+
* 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
|
|
32
|
+
* rule (claudeLoginStatus). `platform`: the one the CLI runs on, this host's. */
|
|
25
33
|
export declare function loginEnv(login: ClaudeAgentLogin, platform?: NodeJS.Platform): Record<string, string>;
|
|
26
34
|
/** 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,
|
|
28
|
-
*
|
|
29
|
-
*
|
|
35
|
+
* starts (startClaudeLogin) both take these, the sign-in in the person's home (personHome), so they cannot drift apart.
|
|
36
|
+
* Neither is a session, whose config dir stays its own (loginEnv), and neither is the status check, which runs on a copy
|
|
37
|
+
* of the account file with a run's variables (claudeLoginStatus).
|
|
30
38
|
* - On the CLI's default folder (`home`): the person's own CLI as it runs, with no config or credentials dir, in their
|
|
31
39
|
* home (`HOME`; a terminal of theirs has it already, so the shown line leaves it out, and clears the two folder
|
|
32
40
|
* variables a terminal may export). It writes the account in `<home>/.claude.json` and the tokens where that person's
|
|
33
41
|
* CLI keeps them, on every platform.
|
|
34
42
|
* - 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
|
|
36
|
-
* own CLI uses). For a folder the person's own
|
|
43
|
+
* 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
44
|
* 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
|
-
|
|
45
|
+
* (Linux: the same file; macOS: the same item, hashed from the same folder).
|
|
46
|
+
* - A credentials dir set apart (`secure`, from the server's `CLAUDE_SECURESTORAGE_CONFIG_DIR`) is the credentials dir
|
|
47
|
+
* in either case, as for the person's own CLI with that variable (secureVar: empty on macOS when theirs is empty).
|
|
48
|
+
* `platform`: the one the CLI runs on, this host's. */
|
|
49
|
+
export declare function signInEnv(login: ClaudeAgentLogin, platform?: NodeJS.Platform): Record<string, string>;
|
|
40
50
|
/** The line a person runs to sign the CLI in at `login` (the CLI opens a browser itself), with signInEnv's variables
|
|
41
51
|
* but HOME, which is their terminal's own. A folder variable signInEnv leaves unset (the CLI's default folder) is
|
|
42
|
-
* cleared
|
|
43
|
-
|
|
52
|
+
* cleared by `env -u`, since a terminal that exports it would sign in there: env is a program, so sh, bash, zsh, fish
|
|
53
|
+
* and tcsh all run that line alike (fish has no `( ... )` subshell, tcsh no `NAME=value cmd`). env reads any word
|
|
54
|
+
* holding '=' as one more variable, so a CLI path holding one (/data/a=b/claude) goes to `sh -c` as its `$0`, single
|
|
55
|
+
* quoted, which every one of those shells reads alike too. What env skips: a `claude` alias or function of the
|
|
56
|
+
* 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). `platform`: as signInEnv's. */
|
|
58
|
+
export declare const loginCommand: (login: ClaudeAgentLogin, cli?: string, platform?: NodeJS.Platform) => string;
|
|
44
59
|
/** What the CLI says of its login: whether it is signed in, how, and the account's own words when it gives them. */
|
|
45
60
|
export interface ClaudeLoginStatus {
|
|
46
61
|
signedIn: boolean;
|
|
@@ -55,29 +70,62 @@ export interface ClaudeLoginStatus {
|
|
|
55
70
|
export declare function parseLoginStatus(stdout: string): ClaudeLoginStatus | undefined;
|
|
56
71
|
/** The longest a status check may take. */
|
|
57
72
|
export declare const LOGIN_STATUS_MS = 15000;
|
|
58
|
-
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
export declare
|
|
73
|
+
/** A status check the CLI outlasted: ended at its limit (`limitMs`) with no answer, which says nothing of the login (a
|
|
74
|
+
* loaded host can take that long), apart from a CLI that answered, in time, what reads as no status. `code` is
|
|
75
|
+
* `timed_out`, so a caller that loads the harness lazily can tell it without the class. */
|
|
76
|
+
export declare class ClaudeLoginTimedOut extends Error {
|
|
77
|
+
readonly limitMs: number;
|
|
78
|
+
readonly code = "timed_out";
|
|
79
|
+
constructor(limitMs: number);
|
|
80
|
+
}
|
|
81
|
+
/** A status check the CLI answered in time with nothing that reads as a status: no answer either, apart from a CLI that
|
|
82
|
+
* never started (the spawn's own error, `ENOENT` and the like). `code` is `no_status`, for a caller that loads the
|
|
83
|
+
* harness lazily. */
|
|
84
|
+
export declare class ClaudeLoginNoStatus extends Error {
|
|
85
|
+
readonly code = "no_status";
|
|
86
|
+
constructor();
|
|
87
|
+
}
|
|
88
|
+
/** Removes what status checks cut off mid-way left: a server killed outright (SIGKILL) runs no `finally`, so its check's
|
|
89
|
+
* folder (claudeLoginStatus's `scratch`), with the copy of the account file in it, stays in the temporary folder. Takes
|
|
90
|
+
* each folder there named as a check's (the prefix and mkdtemp's six characters, nothing longer) that is this user's
|
|
91
|
+
* (`uid`, `process.getuid()` by default) and whose check has ended: more than STATUS_SWEEP_MARGIN_MS (15 s) before
|
|
92
|
+
* `now` by the end the check wrote in it (STATUS_ENDS_FILE), whatever limit its caller gave it, so a check another
|
|
93
|
+
* server on this host is running is never taken. A folder with no such end (its check was killed before writing it,
|
|
94
|
+
* or what the file holds is no time, or one before the file was written: checkEnds) is taken once it was last changed
|
|
95
|
+
* more than twice a check's limit (LOGIN_STATUS_MS) before `now`. Exactly at its margin, a folder stays by either
|
|
96
|
+
* rule. Another user's folder, a link or a file is never taken. `dir`: the temporary folder (`os.tmpdir()` by
|
|
97
|
+
* default). Nothing on Windows, which has no uid to tell whose a folder is. Never throws: a folder that can't be read or
|
|
98
|
+
* removed stays. Resolves to the folders it removed. The server runs it as it starts. */
|
|
99
|
+
export declare function sweepClaudeStatusFolders(options?: {
|
|
100
|
+
dir?: string;
|
|
101
|
+
uid?: number;
|
|
102
|
+
now?: number;
|
|
103
|
+
}): Promise<string[]>;
|
|
104
|
+
/** The home of the person whose CLI keeps `login`, the one every use of the login reads: the login's `userHome`, else
|
|
105
|
+
* its `home` (the CLI's default folder), else the server's (`os.homedir()`), for a login made with neither. On macOS
|
|
106
|
+
* the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
|
|
107
|
+
* session's) it finds no keychain and reads signed out, whatever the variables. */
|
|
108
|
+
export declare const personHome: (login: ClaudeAgentLogin) => string;
|
|
62
109
|
/** 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
|
|
110
|
+
* variables beside it, in the person's home (personHome) on every place and platform.
|
|
64
111
|
* The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
|
|
65
112
|
* 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
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
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.
|
|
113
|
+
* 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
|
|
114
|
+
* (accountFile: the default folder's in the home, else the login folder's) in a folder of its own (`scratch`, one per
|
|
115
|
+
* check, removed after it answers or throws), less its secrets (accountCopy), and the credentials dir is a run's
|
|
116
|
+
* (loginEnv): on macOS it names the Keychain item ahead of the config dir (empty: the item with no suffix, the default
|
|
117
|
+
* folder's; else hashed from the login's folder, as the sign-in there named it), so the copy never renames it.
|
|
74
118
|
* 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
|
|
119
|
+
* Asks once. Throws when the CLI gives no answer that reads as one: ClaudeLoginTimedOut when it was still running at
|
|
120
|
+
* the limit (`timeoutMs`, LOGIN_STATUS_MS by default) and was ended there, else ClaudeLoginNoStatus. A CLI that never
|
|
121
|
+
* 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 STATUS_DRAIN_MS more for its output, which a process it
|
|
123
|
+
* started may hold open. So a check settles within its limit and 2 s, whatever the CLI does. A `timeoutMs` that is no
|
|
124
|
+
* whole number of ms from 1 to 2^31 - 1 throws a RangeError before anything starts. */
|
|
76
125
|
export declare function claudeLoginStatus(cli: string, login: ClaudeAgentLogin, options?: {
|
|
77
126
|
timeoutMs?: number;
|
|
78
127
|
path?: string;
|
|
79
128
|
platform?: NodeJS.Platform;
|
|
80
|
-
home?: string;
|
|
81
129
|
}): Promise<ClaudeLoginStatus>;
|
|
82
130
|
/** How long the CLI's own sign-in waits for its browser before it is ended. */
|
|
83
131
|
export declare const SIGN_IN_MS: number;
|
|
@@ -102,14 +150,18 @@ export interface ClaudeSignIn {
|
|
|
102
150
|
stop(): void;
|
|
103
151
|
}
|
|
104
152
|
/** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
|
|
105
|
-
* (
|
|
153
|
+
* (personHome) and desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
|
|
106
154
|
* 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.
|
|
155
|
+
* `ended` says apart from any other end.
|
|
156
|
+
* It dies with this process, as a session's CLI does: started under the kernel's parent watch (parentWatched; `watch`,
|
|
157
|
+
* by default what this machine supports), so a server that is SIGKILLed, and runs no stop or limit timer, leaves no CLI
|
|
158
|
+
* 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
|
|
159
|
+
* with the server as before, and nothing here kills a group, which would take a browser the CLI started with it. */
|
|
108
160
|
export declare function startClaudeLogin(cli: string, login: ClaudeAgentLogin, options?: {
|
|
109
161
|
timeoutMs?: number;
|
|
110
162
|
path?: string;
|
|
111
|
-
home?: string;
|
|
112
163
|
display?: Readonly<Record<string, string | undefined>>;
|
|
164
|
+
watch?: ParentWatch;
|
|
113
165
|
}): ClaudeSignIn;
|
|
114
166
|
/** How a session on a login books its requests: no proxy sees them, so each response the CLI streams is booked from its
|
|
115
167
|
* own events, billed to the plan, at no price here. No proxy can hold a request back either, so a request is admitted
|
package/dist/login.js
CHANGED
|
@@ -4,58 +4,76 @@
|
|
|
4
4
|
// The pinned CLI keeps the login where it always does, in its own files, and calls Anthropic with it itself. AgentRun
|
|
5
5
|
// never reads, copies, stores or relays its tokens: a session only tells the CLI where its login is (two directories, by
|
|
6
6
|
// environment), and the host asks the CLI whether it is signed in (`claude auth status`), reading nothing but that answer.
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
7
|
+
// That check runs the CLI on a private copy of the login's account file (`.claude.json`), which the CLI rewrites on
|
|
8
|
+
// 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
|
+
// hold secrets (an API key, exported variables, MCP servers' tokens) and lasts the check.
|
|
10
10
|
// 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
11
|
import { spawn } from "node:child_process";
|
|
12
|
-
import {
|
|
12
|
+
import { accessSync, constants, mkdtempSync, rmSync } from "node:fs";
|
|
13
|
+
import { lstat, mkdir, open, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
13
14
|
import { homedir, tmpdir } from "node:os";
|
|
14
|
-
import { join } from "node:path";
|
|
15
|
+
import { delimiter, join } from "node:path";
|
|
16
|
+
import { parentWatched } from "@parcha/agentrun-kernel/host";
|
|
17
|
+
/** `login.secure` as the CLI's variable on `platform` (undefined when it is not set apart): empty on macOS where the
|
|
18
|
+
* person's own was set and empty. */
|
|
19
|
+
const secureVar = (login, platform) => (login.secure === undefined ? undefined : login.unsuffixed && platform === "darwin" ? "" : login.secure);
|
|
15
20
|
/** The variables that point a session's CLI at `login`: never its config dir (`CLAUDE_CONFIG_DIR`), which the Agent SDK
|
|
16
21
|
* copies a credentials file out of when it resumes a session, so the credentials dir (`CLAUDE_SECURESTORAGE_CONFIG_DIR`)
|
|
17
22
|
* is always set. On macOS the CLI names its Keychain item from that dir (`-<sha256 of it>` after the name) unless it is
|
|
18
23
|
* set and empty; unset, it would hash the session's own config dir. So a login on the CLI's default folder (`home`) gets
|
|
19
24
|
* an empty one on macOS (the item with no suffix, the person's own CLI's), and its folder elsewhere, where the CLI keeps
|
|
20
|
-
* `.credentials.json` in that dir. A
|
|
21
|
-
* (a copy of the account file), so it takes this
|
|
22
|
-
* host's. */
|
|
25
|
+
* `.credentials.json` in that dir. A login whose credentials dir is set apart (`secure`) gets that one, as the person's
|
|
26
|
+
* 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
|
|
27
|
+
* rule (claudeLoginStatus). `platform`: the one the CLI runs on, this host's. */
|
|
23
28
|
export function loginEnv(login, platform = process.platform) {
|
|
24
|
-
|
|
29
|
+
const secure = secureVar(login, platform) ?? (login.home !== undefined && platform === "darwin" ? "" : login.dir);
|
|
30
|
+
return { CLAUDE_SECURESTORAGE_CONFIG_DIR: secure, ANTHROPIC_CONFIG_DIR: login.profiles };
|
|
25
31
|
}
|
|
26
32
|
/** 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,
|
|
28
|
-
*
|
|
29
|
-
*
|
|
33
|
+
* starts (startClaudeLogin) both take these, the sign-in in the person's home (personHome), so they cannot drift apart.
|
|
34
|
+
* Neither is a session, whose config dir stays its own (loginEnv), and neither is the status check, which runs on a copy
|
|
35
|
+
* of the account file with a run's variables (claudeLoginStatus).
|
|
30
36
|
* - On the CLI's default folder (`home`): the person's own CLI as it runs, with no config or credentials dir, in their
|
|
31
37
|
* home (`HOME`; a terminal of theirs has it already, so the shown line leaves it out, and clears the two folder
|
|
32
38
|
* variables a terminal may export). It writes the account in `<home>/.claude.json` and the tokens where that person's
|
|
33
39
|
* CLI keeps them, on every platform.
|
|
34
40
|
* - 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
|
|
36
|
-
* own CLI uses). For a folder the person's own
|
|
41
|
+
* 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
42
|
* 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
|
-
|
|
43
|
+
* (Linux: the same file; macOS: the same item, hashed from the same folder).
|
|
44
|
+
* - A credentials dir set apart (`secure`, from the server's `CLAUDE_SECURESTORAGE_CONFIG_DIR`) is the credentials dir
|
|
45
|
+
* in either case, as for the person's own CLI with that variable (secureVar: empty on macOS when theirs is empty).
|
|
46
|
+
* `platform`: the one the CLI runs on, this host's. */
|
|
47
|
+
export function signInEnv(login, platform = process.platform) {
|
|
48
|
+
const secure = secureVar(login, platform);
|
|
40
49
|
if (login.home !== undefined)
|
|
41
|
-
return { HOME: login.home, ANTHROPIC_CONFIG_DIR: login.profiles };
|
|
42
|
-
return { CLAUDE_CONFIG_DIR: login.dir, CLAUDE_SECURESTORAGE_CONFIG_DIR: login.dir, ANTHROPIC_CONFIG_DIR: login.profiles };
|
|
50
|
+
return { HOME: login.home, ...(secure !== undefined ? { CLAUDE_SECURESTORAGE_CONFIG_DIR: secure } : {}), ANTHROPIC_CONFIG_DIR: login.profiles };
|
|
51
|
+
return { CLAUDE_CONFIG_DIR: login.dir, CLAUDE_SECURESTORAGE_CONFIG_DIR: secure ?? login.dir, ANTHROPIC_CONFIG_DIR: login.profiles };
|
|
43
52
|
}
|
|
44
53
|
/** The CLI's folder variables: where it keeps its config (the account) and its credentials. */
|
|
45
54
|
const FOLDER_VARS = ["CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"];
|
|
46
55
|
/** The line a person runs to sign the CLI in at `login` (the CLI opens a browser itself), with signInEnv's variables
|
|
47
56
|
* but HOME, which is their terminal's own. A folder variable signInEnv leaves unset (the CLI's default folder) is
|
|
48
|
-
* cleared
|
|
49
|
-
|
|
50
|
-
|
|
57
|
+
* cleared by `env -u`, since a terminal that exports it would sign in there: env is a program, so sh, bash, zsh, fish
|
|
58
|
+
* and tcsh all run that line alike (fish has no `( ... )` subshell, tcsh no `NAME=value cmd`). env reads any word
|
|
59
|
+
* holding '=' as one more variable, so a CLI path holding one (/data/a=b/claude) goes to `sh -c` as its `$0`, single
|
|
60
|
+
* quoted, which every one of those shells reads alike too. What env skips: a `claude` alias or function of the
|
|
61
|
+
* 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). `platform`: as signInEnv's. */
|
|
63
|
+
export const loginCommand = (login, cli = "claude", platform = process.platform) => {
|
|
64
|
+
const env = signInEnv(login, platform);
|
|
51
65
|
const cleared = FOLDER_VARS.filter((name) => !(name in env));
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
...
|
|
55
|
-
|
|
56
|
-
].join(" ");
|
|
66
|
+
const vars = Object.entries(env).filter(([name]) => name !== "HOME").map(([name, value]) => `${name}=${shellWord(value)}`);
|
|
67
|
+
if (!cleared.length)
|
|
68
|
+
return [...vars, commandWord(cli), "auth", "login"].join(" ");
|
|
69
|
+
const run = cli.includes("=") ? ["sh", "-c", `'exec "$0" auth login'`, quoted(cli)] : [shellWord(cli), "auth", "login"];
|
|
70
|
+
return ["env", ...cleared.flatMap((name) => ["-u", name]), ...vars, ...run].join(" ");
|
|
57
71
|
};
|
|
58
|
-
const
|
|
72
|
+
const quoted = (word) => `'${word.replace(/'/g, `'\\''`)}'`;
|
|
73
|
+
const shellWord = (word) => (/^[A-Za-z0-9_./:@%+=-]+$/.test(word) ? word : quoted(word));
|
|
74
|
+
/** The CLI as the line's command word: quoted when it holds '=', so a relative `a=b/claude` is never read as a variable;
|
|
75
|
+
* a bare `claude` stays bare, so the shell's alias or function of that name is the one it runs. */
|
|
76
|
+
const commandWord = (word) => (word.includes("=") ? quoted(word) : shellWord(word));
|
|
59
77
|
const text = (value) => (typeof value === "string" && value.trim() ? value.trim().slice(0, 200) : undefined);
|
|
60
78
|
/** `claude auth status --json`'s answer, read for the fields above alone; undefined when it is no such answer. */
|
|
61
79
|
export function parseLoginStatus(stdout) {
|
|
@@ -79,9 +97,106 @@ export function parseLoginStatus(stdout) {
|
|
|
79
97
|
}
|
|
80
98
|
/** The longest a status check may take. */
|
|
81
99
|
export const LOGIN_STATUS_MS = 15_000;
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
|
|
100
|
+
/** After a status check's limit asks its CLI to go (SIGTERM), how long before the CLI is killed (SIGKILL). */
|
|
101
|
+
const STATUS_KILL_MS = 1_000;
|
|
102
|
+
/** Once a status check's CLI has exited, or was killed, how long the check still waits for its output's pipe to close
|
|
103
|
+
* before it leaves it: a process the CLI started can hold that pipe open with no end. */
|
|
104
|
+
const STATUS_DRAIN_MS = 1_000;
|
|
105
|
+
/** The longest delay setTimeout keeps (2^31 - 1 ms): past it, the timer fires at once. */
|
|
106
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
107
|
+
/** A status check the CLI outlasted: ended at its limit (`limitMs`) with no answer, which says nothing of the login (a
|
|
108
|
+
* loaded host can take that long), apart from a CLI that answered, in time, what reads as no status. `code` is
|
|
109
|
+
* `timed_out`, so a caller that loads the harness lazily can tell it without the class. */
|
|
110
|
+
export class ClaudeLoginTimedOut extends Error {
|
|
111
|
+
limitMs;
|
|
112
|
+
code = "timed_out";
|
|
113
|
+
constructor(limitMs) {
|
|
114
|
+
super(`the claude CLI gave no login status: the check timed out after ${Number((limitMs / 1000).toFixed(1))} s`);
|
|
115
|
+
this.limitMs = limitMs;
|
|
116
|
+
this.name = "ClaudeLoginTimedOut";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** A status check the CLI answered in time with nothing that reads as a status: no answer either, apart from a CLI that
|
|
120
|
+
* never started (the spawn's own error, `ENOENT` and the like). `code` is `no_status`, for a caller that loads the
|
|
121
|
+
* harness lazily. */
|
|
122
|
+
export class ClaudeLoginNoStatus extends Error {
|
|
123
|
+
code = "no_status";
|
|
124
|
+
constructor() {
|
|
125
|
+
super("the claude CLI gave no login status");
|
|
126
|
+
this.name = "ClaudeLoginNoStatus";
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** The name of a status check's own folder in the temporary folder, ahead of mkdtemp's six characters. */
|
|
130
|
+
const STATUS_FOLDER = "agentrun-claude-status-";
|
|
131
|
+
const STATUS_FOLDER_NAME = /^agentrun-claude-status-[A-Za-z0-9]{6}$/;
|
|
132
|
+
/** The file in a status check's folder that says when the check ends at the latest, in ms since the epoch: its start
|
|
133
|
+
* plus its own limit, the kill's grace and the wait for its pipe (claudeLoginStatus). */
|
|
134
|
+
const STATUS_ENDS_FILE = "ends";
|
|
135
|
+
/** How long past a check's end (STATUS_ENDS_FILE) its folder is left before a sweep takes it. */
|
|
136
|
+
const STATUS_SWEEP_MARGIN_MS = LOGIN_STATUS_MS;
|
|
137
|
+
/** When the status check that owns `folder` ends at the latest (its STATUS_ENDS_FILE), or undefined when that can't be
|
|
138
|
+
* read as a time. A check writes its end at its start, so an end before the file's own mtime is none a check wrote:
|
|
139
|
+
* empty or blank (a check between its create, wx, and its write: Number("") is 0), a partial write, a negative. */
|
|
140
|
+
async function checkEnds(folder) {
|
|
141
|
+
try {
|
|
142
|
+
const file = join(folder, STATUS_ENDS_FILE);
|
|
143
|
+
const stat = await lstat(file);
|
|
144
|
+
if (!stat.isFile() || stat.size > 32)
|
|
145
|
+
return undefined;
|
|
146
|
+
const ends = Number((await readFile(file, "utf8")).trim());
|
|
147
|
+
return Number.isSafeInteger(ends) && ends >= stat.mtimeMs ? ends : undefined;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** Removes what status checks cut off mid-way left: a server killed outright (SIGKILL) runs no `finally`, so its check's
|
|
154
|
+
* folder (claudeLoginStatus's `scratch`), with the copy of the account file in it, stays in the temporary folder. Takes
|
|
155
|
+
* each folder there named as a check's (the prefix and mkdtemp's six characters, nothing longer) that is this user's
|
|
156
|
+
* (`uid`, `process.getuid()` by default) and whose check has ended: more than STATUS_SWEEP_MARGIN_MS (15 s) before
|
|
157
|
+
* `now` by the end the check wrote in it (STATUS_ENDS_FILE), whatever limit its caller gave it, so a check another
|
|
158
|
+
* server on this host is running is never taken. A folder with no such end (its check was killed before writing it,
|
|
159
|
+
* or what the file holds is no time, or one before the file was written: checkEnds) is taken once it was last changed
|
|
160
|
+
* more than twice a check's limit (LOGIN_STATUS_MS) before `now`. Exactly at its margin, a folder stays by either
|
|
161
|
+
* rule. Another user's folder, a link or a file is never taken. `dir`: the temporary folder (`os.tmpdir()` by
|
|
162
|
+
* default). Nothing on Windows, which has no uid to tell whose a folder is. Never throws: a folder that can't be read or
|
|
163
|
+
* removed stays. Resolves to the folders it removed. The server runs it as it starts. */
|
|
164
|
+
export async function sweepClaudeStatusFolders(options = {}) {
|
|
165
|
+
const uid = options.uid ?? process.getuid?.();
|
|
166
|
+
if (uid === undefined)
|
|
167
|
+
return [];
|
|
168
|
+
const dir = options.dir ?? tmpdir();
|
|
169
|
+
const now = options.now ?? Date.now();
|
|
170
|
+
let names;
|
|
171
|
+
try {
|
|
172
|
+
names = await readdir(dir);
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return [];
|
|
176
|
+
}
|
|
177
|
+
const removed = [];
|
|
178
|
+
for (const name of names.filter((entry) => STATUS_FOLDER_NAME.test(entry)).sort()) {
|
|
179
|
+
const path = join(dir, name);
|
|
180
|
+
try {
|
|
181
|
+
const stat = await lstat(path);
|
|
182
|
+
if (!stat.isDirectory() || stat.uid !== uid)
|
|
183
|
+
continue;
|
|
184
|
+
const ends = await checkEnds(path);
|
|
185
|
+
// Kept while at most its margin past, by either rule.
|
|
186
|
+
if (ends === undefined ? stat.mtimeMs >= now - 2 * LOGIN_STATUS_MS : now <= ends + STATUS_SWEEP_MARGIN_MS)
|
|
187
|
+
continue;
|
|
188
|
+
await rm(path, { recursive: true, force: true });
|
|
189
|
+
removed.push(path);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// It stays.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return removed;
|
|
196
|
+
}
|
|
197
|
+
/** The account file (`.claude.json`) the CLI keeps for `login`: in the person's home on the CLI's default folder
|
|
198
|
+
* (`home`), else in the login's folder (their `CLAUDE_CONFIG_DIR`, or AgentRun's own, where `auth login` writes it). */
|
|
199
|
+
const accountFile = (login) => join(login.home ?? login.dir, ".claude.json");
|
|
85
200
|
/** The account file's fields that hold secrets, which its copy never gets: the API key an older CLI signed in with
|
|
86
201
|
* (`primaryApiKey`, the CLI's key when no other is set), the variables the CLI exports on start (`env`, which can hold
|
|
87
202
|
* `ANTHROPIC_API_KEY` or a token), and MCP servers, whose `env` and `headers` hold their tokens (`mcpServers`: the
|
|
@@ -119,68 +234,140 @@ function withoutSecrets(raw) {
|
|
|
119
234
|
}
|
|
120
235
|
return `${JSON.stringify(copy, null, 2)}\n`;
|
|
121
236
|
}
|
|
122
|
-
/**
|
|
123
|
-
* nothing
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
237
|
+
/** The largest account file a status check copies. The pinned CLI's own files are far smaller; a bigger one is copied
|
|
238
|
+
* as nothing, so no poll parses it. */
|
|
239
|
+
const ACCOUNT_MAX_BYTES = 32 * 1024 * 1024;
|
|
240
|
+
/** The bytes of the account file `from`, or undefined when there is none, or when it is no regular file of at most
|
|
241
|
+
* ACCOUNT_MAX_BYTES (a FIFO, a device, a folder, a bigger file): copied as nothing, as an unparsable one is. Read off
|
|
242
|
+
* the server's thread, and never past the size it had when opened. Opened with O_NONBLOCK, so a FIFO opens at once with
|
|
243
|
+
* no writer (rather than holding the open until one comes), and is then refused by its fstat. Links are followed (no
|
|
244
|
+
* O_NOFOLLOW): `~/.claude.json` is often a link a dotfiles manager keeps, and the fstat is of what the open reached, so a
|
|
245
|
+
* link to a device or a FIFO is refused as they are. Any other failure to open it (EACCES) throws, as before. */
|
|
246
|
+
async function accountBytes(from) {
|
|
247
|
+
let file;
|
|
127
248
|
try {
|
|
128
|
-
|
|
249
|
+
file = await open(from, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
|
|
129
250
|
}
|
|
130
251
|
catch (error) {
|
|
131
|
-
if (error.code
|
|
132
|
-
|
|
252
|
+
if (error.code === "ENOENT")
|
|
253
|
+
return undefined;
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
const stat = await file.stat();
|
|
258
|
+
if (!stat.isFile() || stat.size > ACCOUNT_MAX_BYTES)
|
|
259
|
+
return undefined;
|
|
260
|
+
// One byte past the size it said: a file that grew since is not read whole, and is copied as nothing.
|
|
261
|
+
const bytes = Buffer.alloc(stat.size + 1);
|
|
262
|
+
let length = 0;
|
|
263
|
+
while (length < bytes.length) {
|
|
264
|
+
const { bytesRead } = await file.read(bytes, length, bytes.length - length, length);
|
|
265
|
+
if (bytesRead === 0)
|
|
266
|
+
break;
|
|
267
|
+
length += bytesRead;
|
|
268
|
+
}
|
|
269
|
+
return length > stat.size ? undefined : bytes.subarray(0, length);
|
|
270
|
+
}
|
|
271
|
+
finally {
|
|
272
|
+
await file.close();
|
|
133
273
|
}
|
|
274
|
+
}
|
|
275
|
+
/** A new folder `to` (0700) holding a copy (0600) of the account file `from` without its secrets (withoutSecrets), or
|
|
276
|
+
* nothing when there is none, it is no regular file of at most ACCOUNT_MAX_BYTES (accountBytes) or no JSON object.
|
|
277
|
+
* `from` is only read. */
|
|
278
|
+
async function accountCopy(from, to) {
|
|
279
|
+
await mkdir(to, { mode: 0o700 });
|
|
280
|
+
const raw = await accountBytes(from);
|
|
134
281
|
const account = raw === undefined ? undefined : withoutSecrets(raw);
|
|
135
282
|
if (account !== undefined)
|
|
136
|
-
|
|
283
|
+
await writeFile(join(to, ".claude.json"), account, { mode: 0o600, flag: "wx" });
|
|
137
284
|
return to;
|
|
138
285
|
}
|
|
139
|
-
/** The home of the person whose CLI keeps `login
|
|
140
|
-
* the server's (`os.homedir()`)
|
|
141
|
-
*
|
|
142
|
-
|
|
286
|
+
/** The home of the person whose CLI keeps `login`, the one every use of the login reads: the login's `userHome`, else
|
|
287
|
+
* its `home` (the CLI's default folder), else the server's (`os.homedir()`), for a login made with neither. On macOS
|
|
288
|
+
* the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
|
|
289
|
+
* session's) it finds no keychain and reads signed out, whatever the variables. */
|
|
290
|
+
export const personHome = (login) => login.userHome ?? login.home ?? homedir();
|
|
143
291
|
/** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH and the login's
|
|
144
|
-
* variables beside it, in the person's home (personHome
|
|
292
|
+
* variables beside it, in the person's home (personHome) on every place and platform.
|
|
145
293
|
* The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
|
|
146
294
|
* 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
|
|
147
|
-
* runs it on
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
* throws), less its secrets (accountCopy), and the credentials dir is a run's (loginEnv): on macOS it names the
|
|
153
|
-
* Keychain item ahead of the config dir (empty: the item with no suffix, the default folder's; else hashed from the
|
|
154
|
-
* folder), so the copy never renames it.
|
|
295
|
+
* 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
|
|
296
|
+
* (accountFile: the default folder's in the home, else the login folder's) in a folder of its own (`scratch`, one per
|
|
297
|
+
* check, removed after it answers or throws), less its secrets (accountCopy), and the credentials dir is a run's
|
|
298
|
+
* (loginEnv): on macOS it names the Keychain item ahead of the config dir (empty: the item with no suffix, the default
|
|
299
|
+
* folder's; else hashed from the login's folder, as the sign-in there named it), so the copy never renames it.
|
|
155
300
|
* A status check is no session: nothing resumes in its config dir. `platform`: the one the CLI runs on, this host's.
|
|
156
|
-
* Throws when the CLI gives no answer that reads as one
|
|
301
|
+
* Asks once. Throws when the CLI gives no answer that reads as one: ClaudeLoginTimedOut when it was still running at
|
|
302
|
+
* the limit (`timeoutMs`, LOGIN_STATUS_MS by default) and was ended there, else ClaudeLoginNoStatus. A CLI that never
|
|
303
|
+
* 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 STATUS_DRAIN_MS more for its output, which a process it
|
|
305
|
+
* started may hold open. So a check settles within its limit and 2 s, whatever the CLI does. A `timeoutMs` that is no
|
|
306
|
+
* whole number of ms from 1 to 2^31 - 1 throws a RangeError before anything starts. */
|
|
157
307
|
export async function claudeLoginStatus(cli, login, options = {}) {
|
|
158
|
-
const
|
|
308
|
+
const limitMs = options.timeoutMs ?? LOGIN_STATUS_MS;
|
|
309
|
+
// 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
|
|
310
|
+
// of ms: a fractional one would leave a live check's folder to the sweep's mtime rule. setTimeout fires at once past
|
|
311
|
+
// 2^31 - 1.
|
|
312
|
+
if (!Number.isSafeInteger(limitMs) || limitMs < 1 || limitMs > MAX_TIMER_MS)
|
|
313
|
+
throw new RangeError(`timeoutMs must be a whole number of ms from 1 to ${MAX_TIMER_MS}, not ${limitMs}`);
|
|
314
|
+
const scratch = mkdtempSync(join(tmpdir(), STATUS_FOLDER));
|
|
159
315
|
try {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
const stdout = await new Promise((resolve, reject) => {
|
|
316
|
+
// When this check ends at the latest, so another server's sweep leaves its folder until then, whatever its limit.
|
|
317
|
+
await writeFile(join(scratch, STATUS_ENDS_FILE), String(Date.now() + limitMs + STATUS_KILL_MS + STATUS_DRAIN_MS), { mode: 0o600, flag: "wx" });
|
|
318
|
+
const HOME = personHome(login);
|
|
319
|
+
const where = { HOME, ...loginEnv(login, options.platform), CLAUDE_CONFIG_DIR: await accountCopy(accountFile(login), join(scratch, "config")) };
|
|
320
|
+
const { stdout, timedOut } = await new Promise((resolve, reject) => {
|
|
166
321
|
const child = spawn(cli, ["auth", "status", "--json"], {
|
|
167
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" },
|
|
168
323
|
stdio: ["ignore", "pipe", "ignore"],
|
|
169
|
-
timeout: options.timeoutMs ?? LOGIN_STATUS_MS,
|
|
170
324
|
});
|
|
171
325
|
let out = "";
|
|
326
|
+
let timedOut = false;
|
|
327
|
+
let settled = false;
|
|
328
|
+
let kill;
|
|
329
|
+
let drain;
|
|
330
|
+
const settle = (then) => {
|
|
331
|
+
if (settled)
|
|
332
|
+
return;
|
|
333
|
+
settled = true;
|
|
334
|
+
clearTimeout(limit);
|
|
335
|
+
clearTimeout(kill);
|
|
336
|
+
clearTimeout(drain);
|
|
337
|
+
then();
|
|
338
|
+
};
|
|
339
|
+
// The CLI exits 1 when signed out, its answer said all the same.
|
|
340
|
+
const done = () => settle(() => {
|
|
341
|
+
child.stdout.destroy();
|
|
342
|
+
resolve({ stdout: out, timedOut });
|
|
343
|
+
});
|
|
344
|
+
// Once the CLI has exited or was killed, its pipe gets a short while to close, and is then left.
|
|
345
|
+
const drainSoon = () => {
|
|
346
|
+
drain ??= setTimeout(done, STATUS_DRAIN_MS);
|
|
347
|
+
};
|
|
348
|
+
// The limit is kept here, not by spawn's `timeout`, so the check knows it ended the CLI, and kills a CLI that
|
|
349
|
+
// outlasts the TERM.
|
|
350
|
+
const limit = setTimeout(() => {
|
|
351
|
+
timedOut = true;
|
|
352
|
+
child.kill("SIGTERM");
|
|
353
|
+
kill = setTimeout(() => {
|
|
354
|
+
child.kill("SIGKILL");
|
|
355
|
+
drainSoon();
|
|
356
|
+
}, STATUS_KILL_MS);
|
|
357
|
+
}, limitMs);
|
|
172
358
|
child.stdout.setEncoding("utf8");
|
|
173
359
|
child.stdout.on("data", (chunk) => {
|
|
174
360
|
if (out.length < 64 * 1024)
|
|
175
361
|
out += chunk;
|
|
176
362
|
});
|
|
177
|
-
child.once("error", reject);
|
|
178
|
-
|
|
179
|
-
child.once("close",
|
|
363
|
+
child.once("error", (error) => settle(() => reject(error)));
|
|
364
|
+
child.once("exit", drainSoon);
|
|
365
|
+
child.once("close", done);
|
|
180
366
|
});
|
|
181
367
|
const status = parseLoginStatus(stdout.trim());
|
|
368
|
+
// A whole answer written just before the limit still counts.
|
|
182
369
|
if (!status)
|
|
183
|
-
throw new
|
|
370
|
+
throw timedOut ? new ClaudeLoginTimedOut(limitMs) : new ClaudeLoginNoStatus();
|
|
184
371
|
return status;
|
|
185
372
|
}
|
|
186
373
|
finally {
|
|
@@ -189,12 +376,41 @@ export async function claudeLoginStatus(cli, login, options = {}) {
|
|
|
189
376
|
}
|
|
190
377
|
/** How long the CLI's own sign-in waits for its browser before it is ended. */
|
|
191
378
|
export const SIGN_IN_MS = 10 * 60_000;
|
|
192
|
-
/** After asking an ending sign-in to stop, how long before it is killed.
|
|
379
|
+
/** After asking an ending sign-in to stop, how long before it is killed. Longer than SIGN_IN_TERM_GRACE_MS, the grace
|
|
380
|
+
* the sign-in asks of the parent-watch shim: under the shim this kill reaches the shim alone, which has killed a CLI
|
|
381
|
+
* that outlasted the TERM by then. */
|
|
193
382
|
const SIGN_IN_KILL_MS = 5_000;
|
|
383
|
+
/** Under the parent-watch shim, how long after passing the stop's TERM on the shim kills the CLI (parentWatched's
|
|
384
|
+
* `termGraceMs`). Shorter than SIGN_IN_KILL_MS, so the CLI is gone before the server's kill ends the shim. */
|
|
385
|
+
const SIGN_IN_TERM_GRACE_MS = 2_000;
|
|
386
|
+
/** 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 missing CLI only as its own exit code. A bare name is
|
|
388
|
+
* looked up on `path` (not on Windows, whose names take an extension; the watch's exit says it there). */
|
|
389
|
+
function startable(cli, path) {
|
|
390
|
+
if (/[\\/]/.test(cli))
|
|
391
|
+
return accessSync(cli, constants.X_OK);
|
|
392
|
+
if (process.platform === "win32")
|
|
393
|
+
return;
|
|
394
|
+
for (const dir of path.split(delimiter)) {
|
|
395
|
+
if (!dir)
|
|
396
|
+
continue;
|
|
397
|
+
try {
|
|
398
|
+
return accessSync(join(dir, cli), constants.X_OK);
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
// Not here.
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
throw Object.assign(new Error(`spawn ${cli} ENOENT`), { code: "ENOENT" });
|
|
405
|
+
}
|
|
194
406
|
/** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
|
|
195
|
-
* (
|
|
407
|
+
* (personHome) and desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
|
|
196
408
|
* Nothing of it is read here: its output goes nowhere. It is ended after `timeoutMs` (SIGN_IN_MS by default), which
|
|
197
|
-
* `ended` says apart from any other end.
|
|
409
|
+
* `ended` says apart from any other end.
|
|
410
|
+
* It dies with this process, as a session's CLI does: started under the kernel's parent watch (parentWatched; `watch`,
|
|
411
|
+
* by default what this machine supports), so a server that is SIGKILLed, and runs no stop or limit timer, leaves no CLI
|
|
412
|
+
* 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
|
|
413
|
+
* with the server as before, and nothing here kills a group, which would take a browser the CLI started with it. */
|
|
198
414
|
export function startClaudeLogin(cli, login, options = {}) {
|
|
199
415
|
// What a browser needs to open on this desktop, when the server has it.
|
|
200
416
|
const display = Object.fromEntries(["DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "BROWSER"].flatMap((name) => {
|
|
@@ -204,10 +420,13 @@ export function startClaudeLogin(cli, login, options = {}) {
|
|
|
204
420
|
let settle;
|
|
205
421
|
const ended = new Promise((resolve) => { settle = resolve; });
|
|
206
422
|
const failed = (error) => ({ end: "failed", message: String(error?.message ?? error).slice(0, 200) });
|
|
423
|
+
const path = options.path ?? process.env.PATH ?? "/usr/bin:/bin";
|
|
207
424
|
let child;
|
|
208
425
|
try {
|
|
209
|
-
|
|
210
|
-
|
|
426
|
+
startable(cli, path);
|
|
427
|
+
const run = parentWatched({ command: cli, args: ["auth", "login", "--claudeai"] }, options.watch, { termGraceMs: SIGN_IN_TERM_GRACE_MS });
|
|
428
|
+
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" },
|
|
211
430
|
stdio: "ignore",
|
|
212
431
|
});
|
|
213
432
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-harness-claude",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.57",
|
|
4
4
|
"description": "The Claude Agent SDK as an AgentRun harness: the host's tools as its only tools, its model behind a loopback proxy, durable in AgentRun's own store.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"test": "node --test --test-concurrency=8 'test/*.test.mjs'"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@parcha/agentrun-kernel": "0.1.0-beta.
|
|
51
|
+
"@parcha/agentrun-kernel": "0.1.0-beta.57"
|
|
52
52
|
},
|
|
53
53
|
"peerDependencies": {
|
|
54
54
|
"@anthropic-ai/claude-agent-sdk": "0.3.286",
|
|
@@ -77,6 +77,6 @@
|
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
79
|
"@anthropic-ai/claude-agent-sdk": "0.3.286",
|
|
80
|
-
"@parcha/agentrun-dsl": "0.1.0-beta.
|
|
80
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.57"
|
|
81
81
|
}
|
|
82
82
|
}
|