@parcha/agentrun-harness-claude 0.1.0-beta.57 → 0.1.0-beta.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/adapter.d.ts +7 -3
- package/dist/adapter.js +2 -2
- package/dist/env.d.ts +9 -1
- package/dist/env.js +12 -4
- package/dist/facts.d.ts +1 -0
- package/dist/facts.js +3 -0
- package/dist/harness.d.ts +9 -5
- package/dist/harness.js +34 -4
- package/dist/host/policy.d.ts +1 -3
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/login-refresh.d.ts +22 -0
- package/dist/login-refresh.js +45 -0
- package/dist/login.d.ts +21 -6
- package/dist/login.js +101 -24
- package/dist/store.d.ts +41 -5
- package/dist/store.js +85 -39
- package/dist/testing/fake-sdk.d.ts +11 -0
- package/dist/testing/fake-sdk.js +65 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.58 (2026-11-25)
|
|
6
|
+
|
|
7
|
+
- More follow-ups to the Claude login on this machine (Settings → Model keys), and to the server's probe of the harness offers. <!-- changes/claude-sign-in-followups-2.md -->
|
|
8
|
+
- A tool key's save or delete while the offers held are behind the inputs, and the probe out was made from the inputs read now (a turn-on of the login, say), waits for that probe's turn and starts no probe of its own while it lands. The turn ends when the probe lands or fails, or when a later probe overtakes it; the change then reads the inputs again: landed, it composes the capabilities; failed, it probes for itself; overtaken, it goes by the later probe. So it never answers `500` for another request's failed probe once its key is stored, never waits on a dropped probe, and its key always shows in the capabilities it answers after. Before, it started a probe that dropped the one out, so the save answered only after a whole probe of its own. The server logs `harness_offers_wait` as it waits.
|
|
9
|
+
- A probe of the offers that fails leaves no probe out when it was the latest one, so a later change back to the inputs the offers held were made from reuses them. Before, that change probed again.
|
|
10
|
+
- The Playground's "No model yet" bar is gone while the login is on and reads signed in, no agent is picked (no agents yet, or the agents still being read), and the server's default place is the runner, where a first agent on Claude Agent runs on the login. The bar's ChatGPT and key offer goes with it, whatever harness the first agent will use. On a server whose default place is a box, or before its places are read, the bar stays: a first agent there runs in the box on the model keys. Before, a Playground with no agents offered ChatGPT or a key though an agent on Claude Agent would run on the login.
|
|
11
|
+
- A run of an agent on Claude Agent in a box, refused for its model while the login is on, on a model the login runs (Anthropic's own, `anthropic/<id>`, or none named), says that the login runs agents on the runner only, names the box, and says that moving the agent to the runner runs it on the login. Its `409 agent_not_runnable` carries a new `details.login_on_runner: true` (additive), and the Playground offers "Move it to the runner" there, which saves the agent's definition with its computer set to none and its box-only tools dropped, as the agent's Computer step does, and names the tools it dropped. Which tools run only in a box is the capabilities' word: a move taken before they are read, or after their read failed, reads them itself, and while that read fails it saves nothing and says so. The Computer step, with no tools read, refuses a pick that puts the agent on the runner, in words, and changes nothing. Before, either saved the agent on the runner with bash still granted, and its next run was refused there. The offer is the refused agent's: it shows only while that agent is picked and moves only that agent. After the move, a revision picked in the Playground becomes the one the move saved, so the next request runs on the runner. An agent already on the runner is not saved again. The login still runs agents on the runner only. An agent on any other model (an OpenRouter one, Anthropic's through OpenRouter included) is offered no move: on the runner it still needs its provider's key, which its refusal names. Serve puts a run on the login and makes the offer by one rule.
|
|
12
|
+
- A run's check of the login takes the Settings view's signed-in answer from a runner in a process of its own on the same data folder (`agentrun-serve --no-runner` beside `agentrun-serve runner`). The answer is kept in the data folder's `claude-login-answers/`: one file per login (0600, in a 0700 folder), named by a hash of the machine's id and the login, holding only the time; a signed-out answer removes it. A run's check reads it only as a regular file of at most 32 bytes, never through a link, and a FIFO there is no answer rather than a held check. A note tightens a wider folder to 0700 and never writes through a link at its name. On disk, an answer outlives a server restart for up to its 10 minutes. Before, it was in the server process's memory, so such a runner refused a first run whose two checks timed out right after Settings read signed in.
|
|
13
|
+
- A sign-in whose CLI is a script naming an interpreter that is not there (`#!/path`, or `#!/usr/bin/env <program>` with the program on no folder of the sign-in's PATH) fails at its start, in words that name the interpreter. Before, the parent watch's exit 127 read as the CLI's own exit. The `#!` line is read as the kernel reads it, as bytes, so an interpreter under a folder whose name is not ASCII (a home folder named `José`, say) is found.
|
|
14
|
+
- `parentWatched` throws a `RangeError` at the call for a `termGraceMs` the parent-watch shim would refuse (anything but a whole number of ms from 1 to 2^31 - 1), whichever watch is asked for. Before, the shim exited 2 at spawn, which read as the child's own exit.
|
|
15
|
+
- The status check reads an answer that is already in the CLI's output when the drain's second ends, though the server's event loop was held up past that second. Before, the loop ran the drain's timer before its reads, and the check read `no_status`.
|
|
16
|
+
- Where each run is a user of its own (the image, `run_isolation: "uid"`), a claude-agent run now runs on Claude Code's login in AgentRun's own login folder instead of failing at its claim. The runner, as the server's user, reads the login's access token from that folder and hands the run's CLI that token alone, in `CLAUDE_CODE_OAUTH_TOKEN`: never the folder and never the refresh token, so the run's CLI never renews the login. The runner reads the folder again when the run starts and whenever Anthropic refuses the token mid-run, so a renewal your own Claude Code wrote there is picked up. The runner also renews the login itself, in the CLI's place, when a token has less than five minutes left and after Anthropic refuses one mid-run: it sends the pinned CLI's own refresh request, holds the CLI's own refresh lock on the folder, reads the file again under it (a renewal by the CLI or another runner is taken, and nothing is sent twice), and writes the answer back to that folder's `.credentials.json` alone, atomically at mode 0600, every other field kept. It holds the lock as the CLI does, by the directory it made and the mtime it set (to the microsecond; on a filesystem that keeps whole seconds alone, any mtime in that second, as the CLI reads its own lock there), so a lock another holder took over while the runner was paused is never touched or removed, and nothing is sent under it. Runners take the lock one at a time, a dead one included, through a short-lived `.takeover` directory beside it, so two runners never hold it at once, unless a runner stalls past the 60 s stale time inside a takeover or between its last check of the lock and its removal of it (every lock that expires has these gaps). The CLI does not see that directory: between a runner and the CLI the lock is as safe as the CLI's own, and where the CLI's second lock beside the login folder can be made, it keeps the two from both sending. If the write back fails, the runner keeps the new pair in memory: later asks get its token, send nothing (the old refresh token is spent and never sent again) and try the write again, under the same lock and after reading the file again, so a newer pair another holder wrote is kept; once that token has less than five minutes left and is still unsaved, the run fails in words that say the renewal could not be saved and what to fix. A held token Anthropic refuses is never handed again: the ask fails while its pair is unsaved, and once the pair is saved the runner renews from it. One ask sends at most one renewal and nothing retries it. A renewal that fails, a refresh token Anthropic refused included, fails the run at its start, and ends the turn mid-run, in words that say to open Claude Code once to renew the login; a token refused mid-run that the runner had no way to renew ends the turn in words that say to run the claude CLI once on this login to renew it. No token is in the runner's log or in any error, and each token handed is cut from the run's journal, messages and rows as the runner writes them. A command the run's CLI starts can read the token, as the run's own user can. Under per-run users, a run on this machine's own Claude Code login (`~/.claude`, or the `CLAUDE_CONFIG_DIR` AgentRun was started with) still fails at its claim. So does a login run while another runner on the same data folder runs its login runs under the server's user, and the error names that runner. A login kept in a form the runner does not read fails in words too. For each of these, set `AGENTRUN_RUN_USER=same` or give the run a `model_key`. `claudeAgentAdapter({ login })` in `@parcha/agentrun-harness-claude` also takes `{ token(), refused?(sent) }`, a host's reader of the login's access token: on the CLI's request for a newer token it tells the host which token was refused, then answers from `token()`. The pinned CLI's refresh request, lock and write back are exported as `CLAUDE_LOGIN_REFRESH` (and `loginRefresh` from `/facts`), and a test reads each of them in the installed CLI. <!-- changes/claude-login-per-run-users.md -->
|
|
17
|
+
- A host tool with replay `never` called early in a long message of parallel calls now runs. Such a tool waits until the transcript line that made its call is in the log, and the Agent SDK hands the log a message's lines only once the whole message has streamed, while the CLI starts each call as its block ends. The 10 s wait was counted from the call, so in a message of 12 calls streamed about 1.3 s apart the first calls were refused ("the transcript entry for tool call ... did not reach the log within 10000 ms") though nothing was wrong. The wait's clock now restarts on each stream event of the message that made the call (the main thread's, or a subagent's own), so it runs out 10 s after that message ends, or after its last event if the stream stalls; a call whose line never lands is still refused then. A message's end unties its calls from the stream, so the next message in the same stream (the main thread's next answer, say) never holds them open. A short message waits as before. <!-- changes/claude-barrier-message-end.md -->
|
|
18
|
+
A call the CLI refuses itself early in such a message is shown to the host again: its answer line comes with the rest of the message, and the wait for it had run out the same way, so the refusal was only logged ("a refused call is not shown").
|
|
19
|
+
|
|
5
20
|
## 0.1.0-beta.57 (2026-11-24)
|
|
6
21
|
|
|
7
22
|
**Breaking:**
|
package/dist/adapter.d.ts
CHANGED
|
@@ -2,8 +2,9 @@ import { skillProblems, type AgentAdapter, type HostSkill, type SessionSpec, typ
|
|
|
2
2
|
import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
|
|
3
3
|
import { ClaudeAgentNotInstalled, ClaudeAgentPinMismatch } from "./errors.js";
|
|
4
4
|
import { type ClaudeAgentSdk } from "./harness.js";
|
|
5
|
+
import { type BarrierTimers } from "./store.js";
|
|
5
6
|
import { type ConfineChild } from "./host/machine.js";
|
|
6
|
-
import type { ClaudeAgentLogin } from "./login.js";
|
|
7
|
+
import type { ClaudeAgentLogin, ClaudeLoginToken } from "./login.js";
|
|
7
8
|
import type { ToolServerModules } from "./host/tool-server.js";
|
|
8
9
|
export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
|
|
9
10
|
/** The pinned CLI's tools off by name in every session (WebSearch unless `webSearch`): those the copied harness leaves
|
|
@@ -47,8 +48,9 @@ export interface ClaudeAgentAdapterOptions {
|
|
|
47
48
|
provider?: ClaudeAgentProvider;
|
|
48
49
|
/** A person's own login on this machine (login.ts), which the CLI runs on in place of a provider: it calls Anthropic
|
|
49
50
|
* itself, with no proxy, no model URL and no key of the host's; each response is booked from its stream, billed to the
|
|
50
|
-
* person's plan (`price` is not read), and the session has no host port. The host
|
|
51
|
-
|
|
51
|
+
* person's plan (`price` is not read), and the session has no host port. The host says where the login is, or hands
|
|
52
|
+
* its access token alone (ClaudeLoginToken), asked at each start of the CLI and on a 401. */
|
|
53
|
+
login?: ClaudeAgentLogin | ClaudeLoginToken;
|
|
52
54
|
/** Start the CLI under the host's confinement (its own `confine()`, a `setpriv --no-new-privs` prefix, say). It may
|
|
53
55
|
* only add in front of the pinned binary and its arguments, and never touches its environment. */
|
|
54
56
|
confine?: ConfineChild;
|
|
@@ -95,6 +97,8 @@ export interface ClaudeAgentAdapterOptions {
|
|
|
95
97
|
standIn?: {
|
|
96
98
|
command: string;
|
|
97
99
|
};
|
|
100
|
+
/** For tests: the timers a host tool's wait for its call to reach the log runs on (a fake clock). Default the system's. */
|
|
101
|
+
barrierTimers?: BarrierTimers;
|
|
98
102
|
/** How hard the model thinks when a node names no level (its `thinking`, else its `effort`). Default medium; it is
|
|
99
103
|
* never off. */
|
|
100
104
|
thinking?: ClaudeAgentThinking;
|
package/dist/adapter.js
CHANGED
|
@@ -336,8 +336,7 @@ export function claudeAgentAdapter(options) {
|
|
|
336
336
|
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
337
337
|
...(provider.auth ? { auth: provider.auth } : {}),
|
|
338
338
|
...(provider.headers ? { headers: provider.headers } : {}),
|
|
339
|
-
//
|
|
340
|
-
// the run's zone. A session on a login has no proxy, and keeps the machine's date.
|
|
339
|
+
// The CLI's own date lines follow the clock (policy.ts `day`).
|
|
341
340
|
...(options.now ? { day: () => isoDay(options.now(), options.zone) } : {}),
|
|
342
341
|
...(options.log ? { log: options.log } : {}),
|
|
343
342
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
@@ -372,6 +371,7 @@ export function claudeAgentAdapter(options) {
|
|
|
372
371
|
...(options.log ? { log: options.log } : {}),
|
|
373
372
|
...(options.now ? { now: options.now } : {}),
|
|
374
373
|
...(options.zone ? { zone: options.zone } : {}),
|
|
374
|
+
...(options.barrierTimers ? { barrierTimers: options.barrierTimers } : {}),
|
|
375
375
|
// The host's gate, asked about each host-tool call and each WebSearch before it is written or run.
|
|
376
376
|
...(io.gate ? { gate: (call) => io.gate(call) } : {}),
|
|
377
377
|
});
|
package/dist/env.d.ts
CHANGED
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
* CLI's behavior; none reaches the child unless it is listed here.
|
|
9
9
|
*/
|
|
10
10
|
import { type ClaudeAgentLogin } from './login.js';
|
|
11
|
-
/** What never reaches a CLI that runs on a person's login: a model URL, key or token of
|
|
11
|
+
/** What never reaches a CLI that runs on a person's login from the app's own variables: a model URL, key or token of
|
|
12
|
+
* any kind, a refresh token or a token's file descriptor among them. A login handed as a token sets its own
|
|
13
|
+
* CLAUDE_CODE_OAUTH_TOKEN after. */
|
|
12
14
|
export declare const LOGIN_UNSET: readonly string[];
|
|
13
15
|
/** The `PATH` of the CLI and its commands in the VM: the image's, never the Function's. */
|
|
14
16
|
export declare const VM_PATH = "/usr/local/bin:/usr/bin:/bin";
|
|
@@ -36,6 +38,12 @@ export interface DurableEnvOptions {
|
|
|
36
38
|
* environment has no model URL or key at all (login.ts).
|
|
37
39
|
*/
|
|
38
40
|
login?: ClaudeAgentLogin;
|
|
41
|
+
/**
|
|
42
|
+
* The person's own login handed as its access token alone (login.ts ClaudeLoginToken, read by the host for this
|
|
43
|
+
* start), in place of the model port and of `login`: the CLI gets it as CLAUDE_CODE_OAUTH_TOKEN, with no refresh token
|
|
44
|
+
* and no login directory (its credentials directories are the session's own), and a 401 never parks it.
|
|
45
|
+
*/
|
|
46
|
+
oauthToken?: string;
|
|
39
47
|
/** The platform the CLI runs on, this host's by default. On macOS a CLI on a login runs in the person's home (`HOME`). */
|
|
40
48
|
platform?: NodeJS.Platform;
|
|
41
49
|
/** The model, as the CLI's main and alias models. */
|
package/dist/env.js
CHANGED
|
@@ -11,8 +11,10 @@
|
|
|
11
11
|
* CLI's behavior; none reaches the child unless it is listed here.
|
|
12
12
|
*/
|
|
13
13
|
import { loginEnv, personHome } from './login.js';
|
|
14
|
-
/** What never reaches a CLI that runs on a person's login: a model URL, key or token of
|
|
15
|
-
|
|
14
|
+
/** What never reaches a CLI that runs on a person's login from the app's own variables: a model URL, key or token of
|
|
15
|
+
* any kind, a refresh token or a token's file descriptor among them. A login handed as a token sets its own
|
|
16
|
+
* CLAUDE_CODE_OAUTH_TOKEN after. */
|
|
17
|
+
export const LOGIN_UNSET = Object.freeze(['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN', 'CLAUDE_CODE_OAUTH_REFRESH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR', 'ANTHROPIC_CUSTOM_HEADERS', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX']);
|
|
16
18
|
/** The `PATH` of the CLI and its commands in the VM: the image's, never the Function's. */
|
|
17
19
|
export const VM_PATH = '/usr/local/bin:/usr/bin:/bin';
|
|
18
20
|
/** Claude Code's default Bash timeout. */
|
|
@@ -44,7 +46,9 @@ export function durableEnv(options) {
|
|
|
44
46
|
const { home, model } = options;
|
|
45
47
|
const small = options.smallModel ?? model;
|
|
46
48
|
const env = { ...(options.extra ?? {}) };
|
|
47
|
-
if (options.login)
|
|
49
|
+
if (options.login && options.oauthToken !== undefined)
|
|
50
|
+
throw new Error('agentrun-harness-claude: the CLI takes a login by its directories or by its token, not both');
|
|
51
|
+
if (options.login || options.oauthToken !== undefined) {
|
|
48
52
|
// On a login, no model URL, key or token reaches the CLI, the app's own variables included: its login is its only one.
|
|
49
53
|
for (const name of Object.keys(env))
|
|
50
54
|
if (LOGIN_UNSET.includes(name))
|
|
@@ -53,6 +57,10 @@ export function durableEnv(options) {
|
|
|
53
57
|
else if (options.baseUrl === undefined || options.token === undefined) {
|
|
54
58
|
throw new Error('agentrun-harness-claude: the CLI needs its model port and key, or a login');
|
|
55
59
|
}
|
|
60
|
+
// A login by its token: the token alone, its credentials directories the session's own (so no app variable points
|
|
61
|
+
// them at a login), and no wait for a newer token on a 401: the host is asked for one at once (getOAuthToken). It
|
|
62
|
+
// reads no keychain, so its HOME stays the session's on every platform.
|
|
63
|
+
const byToken = options.oauthToken === undefined ? undefined : { CLAUDE_CODE_OAUTH_TOKEN: options.oauthToken, CLAUDE_CODE_OAUTH_401_WAIT_MS: '0', CLAUDE_SECURESTORAGE_CONFIG_DIR: options.configDir, ANTHROPIC_CONFIG_DIR: `${home}/.config/anthropic` };
|
|
56
64
|
const platform = options.platform ?? process.platform;
|
|
57
65
|
Object.assign(env, {
|
|
58
66
|
PATH: VM_PATH,
|
|
@@ -66,7 +74,7 @@ export function durableEnv(options) {
|
|
|
66
74
|
XDG_CACHE_HOME: options.cacheDir,
|
|
67
75
|
XDG_DATA_HOME: `${home}/.local/share`,
|
|
68
76
|
XDG_STATE_HOME: `${home}/.local/state`,
|
|
69
|
-
...(options.login ? loginEnv(options.login, platform) : { ANTHROPIC_BASE_URL: options.baseUrl, ANTHROPIC_AUTH_TOKEN: options.token }),
|
|
77
|
+
...(byToken ?? (options.login ? loginEnv(options.login, platform) : { ANTHROPIC_BASE_URL: options.baseUrl, ANTHROPIC_AUTH_TOKEN: options.token })),
|
|
70
78
|
ANTHROPIC_DEFAULT_OPUS_MODEL: model,
|
|
71
79
|
ANTHROPIC_DEFAULT_SONNET_MODEL: model,
|
|
72
80
|
ANTHROPIC_DEFAULT_HAIKU_MODEL: small,
|
package/dist/facts.d.ts
CHANGED
package/dist/facts.js
CHANGED
|
@@ -41,3 +41,6 @@ export const facts = Object.freeze({
|
|
|
41
41
|
schemaProblems: (tool, schema) => [...toolSchemaProblems(tool, schema), ...["anyOf", "allOf", "oneOf"].filter((key) => key in schema).map((key) => `/${key}: the Claude Agent CLI drops a tool whose root has ${key}`)],
|
|
42
42
|
policy: (options) => anthropicPolicy({ model: options.model, tools: options.tools, ...(options.auth ? { auth: options.auth } : {}), ...(options.webSearch === true ? { webSearch: true, ...(options.webSearchAllowance ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}), ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}) }),
|
|
43
43
|
});
|
|
44
|
+
// The pinned CLI's renewal of a login (login-refresh.ts), here too so a host that renews a login in the CLI's place
|
|
45
|
+
// reads it without loading the adapter and its SDK.
|
|
46
|
+
export { LOGIN_REFRESH as loginRefresh } from "./login-refresh.js";
|
package/dist/harness.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { type GateAnswer, type GateCall } from '@parcha/agentrun-kernel';
|
|
2
2
|
import { type DriveContext, type Harness, type HostTool, type ReplayPolicy, type SessionState, type Submission } from './host/kernel.js';
|
|
3
3
|
import { type GatewayHandler, type ProviderTool, type SessionMachine } from './host/process.js';
|
|
4
|
-
import { type ClaudeAgentLogin } from './login.js';
|
|
4
|
+
import { type ClaudeAgentLogin, type ClaudeLoginToken } from './login.js';
|
|
5
5
|
import type { ModelPort } from '@parcha/agentrun-kernel';
|
|
6
6
|
import { toolServer } from './host/tool-server.js';
|
|
7
|
-
import { JournalSessionStore } from './store.js';
|
|
7
|
+
import { JournalSessionStore, type BarrierTimers } from './store.js';
|
|
8
8
|
/**
|
|
9
9
|
* Claude Code on harness-world: a kernel `Harness` that drives the Claude
|
|
10
10
|
* Agent SDK's `query()` in the drive (in the Function), with the `claude` CLI
|
|
@@ -200,10 +200,11 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
200
200
|
/**
|
|
201
201
|
* The person's own login the CLI runs on (login.ts), in place of the model route: the drive asks its machine for no
|
|
202
202
|
* proxy, the CLI's environment holds no model URL, key or token, and each response is booked from the CLI's stream
|
|
203
|
-
* through `models`, billed to the plan. `credential` and `gatewayUrl` are not read.
|
|
203
|
+
* through `models`, billed to the plan. `credential` and `gatewayUrl` are not read. A login handed as a token
|
|
204
|
+
* (ClaudeLoginToken) is asked for its token at each drive, and again when the CLI asks for a newer one on a 401.
|
|
204
205
|
*/
|
|
205
206
|
login?: {
|
|
206
|
-
at: ClaudeAgentLogin;
|
|
207
|
+
at: ClaudeAgentLogin | ClaudeLoginToken;
|
|
207
208
|
models: Pick<ModelPort, 'beforeRequest' | 'afterRequest'>;
|
|
208
209
|
};
|
|
209
210
|
/** The CLI's path in the VM. Default `CLAUDE_VM_EXECUTABLE` (the base image's pinned build). Tests on the stand-in VM pass the host build. */
|
|
@@ -212,8 +213,11 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
212
213
|
name?: string;
|
|
213
214
|
/** The Agent SDK module. Default: `import('@anthropic-ai/claude-agent-sdk')` on the first drive, after its version is checked against the pin. */
|
|
214
215
|
sdk?: ClaudeAgentSdk;
|
|
215
|
-
/** How long a `never` tool waits for its call to reach the log before it is refused
|
|
216
|
+
/** How long a `never` tool waits for its call to reach the log before it is refused, from the last stream event of the
|
|
217
|
+
* message that made the call (the SDK mirrors a message's lines once it ends). Default 10 s. */
|
|
216
218
|
barrierMs?: number;
|
|
219
|
+
/** The timers that wait runs on. Default the system's; a test passes a fake clock. */
|
|
220
|
+
barrierTimers?: BarrierTimers;
|
|
217
221
|
/**
|
|
218
222
|
* Hold mirrored transcript lines this long so they share journal batches
|
|
219
223
|
* (fewer events per turn). A barrier or a turn's end sends them at once.
|
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, loginEnv } from './login.js';
|
|
13
|
+
import { LOGIN_TOKEN_REFUSED, loginBooking, loginByToken, 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';
|
|
@@ -234,7 +234,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
234
234
|
const { query } = await loadSdk();
|
|
235
235
|
const journal = new NativeJournal(ctx);
|
|
236
236
|
const records = await journal.read();
|
|
237
|
-
const store = new JournalSessionStore(journal, { records, coalesceMs: options.coalesceMs ?? 150 });
|
|
237
|
+
const store = new JournalSessionStore(journal, { records, coalesceMs: options.coalesceMs ?? 150, ...(options.barrierTimers ? { timers: options.barrierTimers } : {}) });
|
|
238
238
|
// The handler reads the credential per request, in the drive's async
|
|
239
239
|
// context: on a serverless function the OIDC token comes from the request
|
|
240
240
|
// that started the drive.
|
|
@@ -497,13 +497,17 @@ export function claudeCodeHarness(options = {}) {
|
|
|
497
497
|
},
|
|
498
498
|
],
|
|
499
499
|
};
|
|
500
|
+
// A login handed as a token: its token as the host reads it now, for this start of the CLI (a token the host
|
|
501
|
+
// refuses, one near its end say, fails the drive in the host's words before the CLI starts).
|
|
502
|
+
const byToken = login && loginByToken(login.at) ? login.at : undefined;
|
|
503
|
+
let sentToken = byToken ? await byToken.token() : undefined;
|
|
500
504
|
// The CLI's environment in the VM (the SDK gets it with the Function's config dir; `sandboxSpawn` swaps the VM's back in).
|
|
501
505
|
const vmEnv = durableEnv({
|
|
502
506
|
home: machine.dirs.home,
|
|
503
507
|
configDir: machine.dirs.config,
|
|
504
508
|
tmpDir: machine.dirs.tmp,
|
|
505
509
|
cacheDir: machine.dirs.cache,
|
|
506
|
-
...(login ? { login: login.at } : { baseUrl: machine.modelUrl, token: machine.modelKey }),
|
|
510
|
+
...(sentToken !== undefined ? { oauthToken: sentToken } : login ? { login: login.at } : { baseUrl: machine.modelUrl, token: machine.modelKey }),
|
|
507
511
|
model,
|
|
508
512
|
...(smallModel ? { smallModel } : {}),
|
|
509
513
|
...(sandbox.commandTimeoutMs ? { bashTimeoutMs: sandbox.commandTimeoutMs } : {}),
|
|
@@ -541,10 +545,33 @@ export function claudeCodeHarness(options = {}) {
|
|
|
541
545
|
const recordedDay = !store.hasSession ? dayOf(now(), options.zone) : undefined;
|
|
542
546
|
/** A message the CLI's transcript holds told the model `day`. */
|
|
543
547
|
const told = (day) => ctx.state().effectOrder.some((e) => e.name === DATE_EFFECT && e.input?.day === day && store.hasUser(e.key.slice(DATE_EFFECT.length + 1)));
|
|
548
|
+
// On a login handed as a token, the CLI's ask for a newer one when Anthropic refuses it (the SDK's
|
|
549
|
+
// `getOAuthToken`, answering the CLI's `oauth_token_refresh`; the pins test holds that the pinned SDK takes it,
|
|
550
|
+
// as its typings do not say): the host told which token was refused (`refused`, so a host that renews renews
|
|
551
|
+
// it), then its token read once more, answered when it is another than the one the CLI holds. Else null, and
|
|
552
|
+
// the drive halts in words (the host's, or LOGIN_TOKEN_REFUSED), so the CLI fails the request at once
|
|
553
|
+
// (CLAUDE_CODE_OAUTH_401_WAIT_MS=0) and the turn ends: never a wait.
|
|
554
|
+
const askToken = byToken
|
|
555
|
+
? async () => {
|
|
556
|
+
try {
|
|
557
|
+
if (sentToken !== undefined)
|
|
558
|
+
await byToken.refused?.(sentToken);
|
|
559
|
+
const next = await byToken.token();
|
|
560
|
+
if (next !== sentToken)
|
|
561
|
+
return (sentToken = next);
|
|
562
|
+
ctx.halt?.(new Error(LOGIN_TOKEN_REFUSED));
|
|
563
|
+
}
|
|
564
|
+
catch (error) {
|
|
565
|
+
ctx.halt?.(error instanceof Error ? error : new Error(String(error)));
|
|
566
|
+
}
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
: undefined;
|
|
544
570
|
const queryOptions = {
|
|
545
571
|
model,
|
|
546
572
|
cwd: machine.root,
|
|
547
573
|
env: sdkEnv,
|
|
574
|
+
...(askToken ? { getOAuthToken: askToken } : {}),
|
|
548
575
|
// Built-ins on: the allowed ones (less those whose state the log does not carry), each let through by
|
|
549
576
|
// the PreToolUse hook once its intent is in the log. Off: the bridged tools are the only ones. Either
|
|
550
577
|
// way nothing is asked of a user, and nothing else is permitted.
|
|
@@ -553,7 +580,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
553
580
|
...(skills ? { plugins: [{ type: 'local', path: skills.plugin }], skills: [...skills.names] } : {}),
|
|
554
581
|
disallowedTools: disallowed,
|
|
555
582
|
hooks,
|
|
556
|
-
...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network, login
|
|
583
|
+
...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network, login && !byToken ? login.at : undefined) } : {}),
|
|
557
584
|
...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
|
|
558
585
|
allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
|
|
559
586
|
permissionMode: 'dontAsk',
|
|
@@ -681,6 +708,9 @@ export function claudeCodeHarness(options = {}) {
|
|
|
681
708
|
ctx.halt?.(mirrorUnmapped('a batch the Agent SDK could not keep in the log'));
|
|
682
709
|
throw ctx.signal.reason ?? mirrorUnmapped('a batch the Agent SDK could not keep in the log');
|
|
683
710
|
}
|
|
711
|
+
// Each event of a message's stream restarts the barrier's clock for the calls made in it (the mirror sends a
|
|
712
|
+
// message's lines once the message ends).
|
|
713
|
+
store.heard(m);
|
|
684
714
|
booking?.observe(m);
|
|
685
715
|
const end = transcript.observe(m);
|
|
686
716
|
// A turn on a login ends once its responses are booked.
|
package/dist/host/policy.d.ts
CHANGED
|
@@ -52,9 +52,7 @@ 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
|
|
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. */
|
|
55
|
+
/** The day of the run's clock (YYYY-MM-DD) when the host set one; the CLI's date lines say it (`CLI_DATE`). */
|
|
58
56
|
day?: () => string;
|
|
59
57
|
}
|
|
60
58
|
/** `now`'s day in `zone` (default UTC) as YYYY-MM-DD, the form the CLI's date line takes. */
|
package/dist/index.d.ts
CHANGED
|
@@ -7,8 +7,9 @@ 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 { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
11
|
-
export type { ClaudeAgentLogin, ClaudeLoginStatus } from "./login.js";
|
|
10
|
+
export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, LOGIN_TOKEN_REFUSED as CLAUDE_LOGIN_TOKEN_REFUSED, loginByToken as claudeLoginByToken, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
11
|
+
export type { ClaudeAgentLogin, ClaudeLoginStatus, ClaudeLoginToken } from "./login.js";
|
|
12
|
+
export { LOGIN_REFRESH as CLAUDE_LOGIN_REFRESH } from "./login-refresh.js";
|
|
12
13
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
|
|
13
14
|
export type { ServedTool } from "./host/tool-server.js";
|
|
14
15
|
export { SIGN_IN_MS as CLAUDE_SIGN_IN_MS, signInEnv as claudeSignInEnv } from "./login.js";
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,7 @@ 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 { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
7
|
+
export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, LOGIN_TOKEN_REFUSED as CLAUDE_LOGIN_TOKEN_REFUSED, loginByToken as claudeLoginByToken, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
|
|
8
|
+
export { LOGIN_REFRESH as CLAUDE_LOGIN_REFRESH } from "./login-refresh.js";
|
|
8
9
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
|
|
9
10
|
export { SIGN_IN_MS as CLAUDE_SIGN_IN_MS, signInEnv as claudeSignInEnv } from "./login.js";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The pinned CLI's renewal of a login: where it posts, as which client, with which scopes when the login names none,
|
|
2
|
+
* and the lock it holds while it renews. */
|
|
3
|
+
export declare const LOGIN_REFRESH: Readonly<{
|
|
4
|
+
/** `TOKEN_URL:"https://platform.claude.com/v1/oauth/token"` in the CLI's production OAuth config (the one object that
|
|
5
|
+
* also holds its `CLIENT_ID`). */
|
|
6
|
+
tokenUrl: "https://platform.claude.com/v1/oauth/token";
|
|
7
|
+
/** `CLIENT_ID:"9d1c250a-e61b-44d9-88ed-5944d1962f5e"` in the same object: the CLI's public OAuth client, which it sends
|
|
8
|
+
* when the login names no `clientId` of its own (`client_id:s??cn().CLIENT_ID`). */
|
|
9
|
+
clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
|
|
10
|
+
/** The scopes it asks for when the login holds none: its list
|
|
11
|
+
* `[user:profile, user:inference, "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"]`, and
|
|
12
|
+
* `user:plugins` (its production config's `PLUGINS_SCOPE_REGISTERED:!0`). */
|
|
13
|
+
scopes: readonly ["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload", "user:plugins"];
|
|
14
|
+
/** The lock's directory in the credentials directory: `lockfilePath:<join>(e,".oauth_refresh.lock")`. */
|
|
15
|
+
lockName: ".oauth_refresh.lock";
|
|
16
|
+
/** The older lock's suffix, on the credentials directory's real path: `` `${await <realpath>(e)}.lock` ``. */
|
|
17
|
+
legacyLockSuffix: ".lock";
|
|
18
|
+
/** A lock older than this is a dead holder's, taken over: `stale:60000`. */
|
|
19
|
+
lockStaleMs: 60000;
|
|
20
|
+
/** How often a holder touches its lock: `update:5000`. */
|
|
21
|
+
lockUpdateMs: 5000;
|
|
22
|
+
}>;
|
|
@@ -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
|
@@ -17,11 +17,25 @@ export interface ClaudeAgentLogin {
|
|
|
17
17
|
/** With `secure`: the variable was set and empty, which on macOS names the Keychain item with no suffix, so it goes to
|
|
18
18
|
* the CLI empty there too. */
|
|
19
19
|
unsuffixed?: boolean;
|
|
20
|
-
/** The home of the person whose CLI keeps the login, read once by whoever makes the login (serve's
|
|
21
|
-
* server's `HOME` when
|
|
22
|
-
*
|
|
20
|
+
/** The home of the person whose CLI keeps the login, read once by whoever makes the login (serve's homeOf: the
|
|
21
|
+
* server's `HOME` when its user owns it, else that user's own home), so the status check, the sign-in and a run on
|
|
22
|
+
* macOS all run in that one home (personHome). With `home`, the same folder. */
|
|
23
23
|
userHome?: string;
|
|
24
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.";
|
|
25
39
|
/** The variables that point a session's CLI at `login`: never its config dir (`CLAUDE_CONFIG_DIR`), which the Agent SDK
|
|
26
40
|
* copies a credentials file out of when it resumes a session, so the credentials dir (`CLAUDE_SECURESTORAGE_CONFIG_DIR`)
|
|
27
41
|
* is always set. On macOS the CLI names its Keychain item from that dir (`-<sha256 of it>` after the name) unless it is
|
|
@@ -119,9 +133,10 @@ export declare const personHome: (login: ClaudeAgentLogin) => string;
|
|
|
119
133
|
* Asks once. Throws when the CLI gives no answer that reads as one: ClaudeLoginTimedOut when it was still running at
|
|
120
134
|
* the limit (`timeoutMs`, LOGIN_STATUS_MS by default) and was ended there, else ClaudeLoginNoStatus. A CLI that never
|
|
121
135
|
* started throws the spawn's own error. At the limit the CLI is asked to go (SIGTERM) and killed STATUS_KILL_MS later;
|
|
122
|
-
* once it has exited or was killed, the check waits at most
|
|
123
|
-
* started may hold open. So a check settles within its limit
|
|
124
|
-
* whole number of ms from 1 to 2^31 - 1 throws a RangeError
|
|
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. */
|
|
125
140
|
export declare function claudeLoginStatus(cli: string, login: ClaudeAgentLogin, options?: {
|
|
126
141
|
timeoutMs?: number;
|
|
127
142
|
path?: string;
|
package/dist/login.js
CHANGED
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
// A person's own Claude Code login on this machine, which a claude-agent session may run on in place of a model key.
|
|
2
2
|
// Written for AgentRun.
|
|
3
3
|
//
|
|
4
|
-
// The pinned CLI keeps the login where it always does, in its own files, and calls Anthropic with it itself.
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
4
|
+
// The pinned CLI keeps the login where it always does, in its own files, and calls Anthropic with it itself. A session
|
|
5
|
+
// either tells the CLI where its login is (two directories, by environment), and the host asks the CLI whether it is
|
|
6
|
+
// signed in (`claude auth status`), reading nothing but that answer; or, where the host keeps the login out of the CLI's
|
|
7
|
+
// reach (a run under a user of its own), it is handed the login's access token alone (ClaudeLoginToken), by
|
|
8
|
+
// environment, asked of the host again at each start and when Anthropic refuses it. The CLI never gets a refresh token
|
|
9
|
+
// then, and never renews the login itself: the host does, if anyone (told which token was refused: `refused`).
|
|
10
|
+
// The status check runs the CLI on a private copy of the login's account file (`.claude.json`), which the CLI rewrites on
|
|
8
11
|
// start, so the file (the person's own, or AgentRun's) is only ever opened to read. The copy leaves out the fields that
|
|
9
12
|
// hold secrets (an API key, exported variables, MCP servers' tokens) and lasts the check.
|
|
10
13
|
// The check runs in the person's own home, as does a run on macOS, where the CLI's tokens are in the login keychain.
|
|
11
14
|
import { spawn } from "node:child_process";
|
|
12
|
-
import { accessSync, constants, mkdtempSync, rmSync } from "node:fs";
|
|
15
|
+
import { accessSync, closeSync, constants, mkdtempSync, openSync, readSync, rmSync, statSync } from "node:fs";
|
|
13
16
|
import { lstat, mkdir, open, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
14
17
|
import { homedir, tmpdir } from "node:os";
|
|
15
18
|
import { delimiter, join } from "node:path";
|
|
16
19
|
import { parentWatched } from "@parcha/agentrun-kernel/host";
|
|
20
|
+
/** Whether `login` is handed as a token (ClaudeLoginToken), not as its directories. */
|
|
21
|
+
export const loginByToken = (login) => typeof login.token === "function";
|
|
22
|
+
/** The words a turn ends in when Anthropic refused the login's access token mid-turn and the host had no newer one. */
|
|
23
|
+
export const LOGIN_TOKEN_REFUSED = "Anthropic refused this machine's Claude login during the run, and no newer token was there: run the claude CLI once on this login to renew it, then start the run again.";
|
|
17
24
|
/** `login.secure` as the CLI's variable on `platform` (undefined when it is not set apart): empty on macOS where the
|
|
18
25
|
* person's own was set and empty. */
|
|
19
26
|
const secureVar = (login, platform) => (login.secure === undefined ? undefined : login.unsuffixed && platform === "darwin" ? "" : login.secure);
|
|
@@ -301,9 +308,10 @@ export const personHome = (login) => login.userHome ?? login.home ?? homedir();
|
|
|
301
308
|
* Asks once. Throws when the CLI gives no answer that reads as one: ClaudeLoginTimedOut when it was still running at
|
|
302
309
|
* the limit (`timeoutMs`, LOGIN_STATUS_MS by default) and was ended there, else ClaudeLoginNoStatus. A CLI that never
|
|
303
310
|
* started throws the spawn's own error. At the limit the CLI is asked to go (SIGTERM) and killed STATUS_KILL_MS later;
|
|
304
|
-
* once it has exited or was killed, the check waits at most
|
|
305
|
-
* started may hold open. So a check settles within its limit
|
|
306
|
-
* whole number of ms from 1 to 2^31 - 1 throws a RangeError
|
|
311
|
+
* once it has exited or was killed, the check waits STATUS_DRAIN_MS more at most for its output, which a process it
|
|
312
|
+
* 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
|
|
313
|
+
* that pass, whatever the CLI does. A `timeoutMs` that is no whole number of ms from 1 to 2^31 - 1 throws a RangeError
|
|
314
|
+
* before anything starts. */
|
|
307
315
|
export async function claudeLoginStatus(cli, login, options = {}) {
|
|
308
316
|
const limitMs = options.timeoutMs ?? LOGIN_STATUS_MS;
|
|
309
317
|
// 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
|
|
@@ -341,9 +349,11 @@ export async function claudeLoginStatus(cli, login, options = {}) {
|
|
|
341
349
|
child.stdout.destroy();
|
|
342
350
|
resolve({ stdout: out, timedOut });
|
|
343
351
|
});
|
|
344
|
-
// Once the CLI has exited or was killed, its pipe gets a short while to close, and is then left.
|
|
352
|
+
// Once the CLI has exited or was killed, its pipe gets a short while to close, and is then left. The timer gives up
|
|
353
|
+
// only after one more pass of the loop's reads (setImmediate runs after them): a loop held up past the drain, as on
|
|
354
|
+
// a busy server, runs its timers before its reads, and what the pipe already held would be dropped unread.
|
|
345
355
|
const drainSoon = () => {
|
|
346
|
-
drain ??= setTimeout(done, STATUS_DRAIN_MS);
|
|
356
|
+
drain ??= setTimeout(() => setImmediate(done), STATUS_DRAIN_MS);
|
|
347
357
|
};
|
|
348
358
|
// The limit is kept here, not by spawn's `timeout`, so the check knows it ended the CLI, and kills a CLI that
|
|
349
359
|
// outlasts the TERM.
|
|
@@ -383,25 +393,92 @@ const SIGN_IN_KILL_MS = 5_000;
|
|
|
383
393
|
/** Under the parent-watch shim, how long after passing the stop's TERM on the shim kills the CLI (parentWatched's
|
|
384
394
|
* `termGraceMs`). Shorter than SIGN_IN_KILL_MS, so the CLI is gone before the server's kill ends the shim. */
|
|
385
395
|
const SIGN_IN_TERM_GRACE_MS = 2_000;
|
|
396
|
+
/** Whether `file` is a regular file this process may execute. A Buffer is a path's own bytes, as the kernel takes them. */
|
|
397
|
+
function executable(file) {
|
|
398
|
+
try {
|
|
399
|
+
accessSync(file, constants.X_OK);
|
|
400
|
+
return statSync(file).isFile();
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/** The first program named `name` on `path`, or undefined. */
|
|
407
|
+
function onPath(name, path) {
|
|
408
|
+
for (const dir of path.split(delimiter))
|
|
409
|
+
if (dir && executable(join(dir, name)))
|
|
410
|
+
return join(dir, name);
|
|
411
|
+
return undefined;
|
|
412
|
+
}
|
|
413
|
+
/** Whether a program named by the bytes `name` is on a folder of `path` (the sign-in's PATH, which env searches). */
|
|
414
|
+
const onPathBytes = (name, path) => path.split(delimiter).some((dir) => dir !== "" && executable(Buffer.concat([Buffer.from(join(dir, "/")), name])));
|
|
415
|
+
/** The first line of `file` (at most 256 bytes) as its bytes, or undefined when it can't be read. */
|
|
416
|
+
function firstLine(file) {
|
|
417
|
+
let fd;
|
|
418
|
+
try {
|
|
419
|
+
fd = openSync(file, "r");
|
|
420
|
+
const head = Buffer.alloc(256);
|
|
421
|
+
const read = head.subarray(0, readSync(fd, head, 0, head.length, 0));
|
|
422
|
+
const end = read.indexOf(0x0a);
|
|
423
|
+
return end < 0 ? read : read.subarray(0, end);
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
return undefined;
|
|
427
|
+
}
|
|
428
|
+
finally {
|
|
429
|
+
if (fd !== undefined)
|
|
430
|
+
closeSync(fd);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
/** The words of a `#!` line after the `#!` (the interpreter, then its argument), as bytes: the kernel reads the line as
|
|
434
|
+
* bytes and splits it at blanks, so a path under a folder whose name is not ASCII is that name's bytes, never a decode
|
|
435
|
+
* of them. Blanks are ASCII ones only: in UTF-8 the byte 0xA0 is part of a character (`à` is C3 A0), not a space. */
|
|
436
|
+
function shebangWords(line) {
|
|
437
|
+
if (!line || line[0] !== 0x23 || line[1] !== 0x21)
|
|
438
|
+
return [];
|
|
439
|
+
const words = [];
|
|
440
|
+
let start = -1;
|
|
441
|
+
for (let i = 2; i <= line.length; i++) {
|
|
442
|
+
const blank = i === line.length || [0x20, 0x09, 0x0d, 0x0b, 0x0c, 0x00].includes(line[i]);
|
|
443
|
+
if (blank && start >= 0) {
|
|
444
|
+
words.push(line.subarray(start, i));
|
|
445
|
+
start = -1;
|
|
446
|
+
}
|
|
447
|
+
else if (!blank && start < 0)
|
|
448
|
+
start = i;
|
|
449
|
+
}
|
|
450
|
+
return words;
|
|
451
|
+
}
|
|
452
|
+
const notStartable = (cli, why = "") => Object.assign(new Error(`spawn ${cli} ENOENT${why}`), { code: "ENOENT" });
|
|
386
453
|
/** Throws, in the spawn's words, when `cli` is no program this host can start: the parent watch starts a program of its
|
|
387
|
-
* own first (setpriv, or node with its shim), which would tell a
|
|
388
|
-
*
|
|
454
|
+
* own first (setpriv, or node with its shim), which would tell a failed start only as its own exit code (127), and the
|
|
455
|
+
* sign-in's output is read by no one. So a script whose first line names an interpreter that is not there (`#!/path`,
|
|
456
|
+
* or `#!/usr/bin/env <program>` with the program on no folder of `path`) throws too, naming it. A bare name is looked up
|
|
457
|
+
* on `path`. Not on Windows, whose names take an extension and which reads no `#!` line: the watch's exit says it there. */
|
|
389
458
|
function startable(cli, path) {
|
|
459
|
+
if (process.platform === "win32") {
|
|
460
|
+
if (/[\\/]/.test(cli))
|
|
461
|
+
accessSync(cli, constants.X_OK);
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
let file = cli;
|
|
390
465
|
if (/[\\/]/.test(cli))
|
|
391
|
-
|
|
392
|
-
|
|
466
|
+
accessSync(cli, constants.X_OK);
|
|
467
|
+
else
|
|
468
|
+
file = onPath(cli, path) ?? "";
|
|
469
|
+
if (!file)
|
|
470
|
+
throw notStartable(cli);
|
|
471
|
+
// The interpreter and its argument are checked by their bytes (Buffer paths); the tests on their ASCII characters read
|
|
472
|
+
// them as Latin-1, which maps each byte to one character, so those tests see exactly the bytes. The words decode them.
|
|
473
|
+
const [interpreter, program] = shebangWords(firstLine(file));
|
|
474
|
+
if (!interpreter)
|
|
393
475
|
return;
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
}
|
|
400
|
-
catch {
|
|
401
|
-
// Not here.
|
|
402
|
-
}
|
|
476
|
+
if (!executable(interpreter))
|
|
477
|
+
throw notStartable(cli, `: the interpreter its first line names, ${interpreter.toString()}, is not there`);
|
|
478
|
+
// env runs the program it is given, looked up on the sign-in's PATH; an option or a variable is left to env.
|
|
479
|
+
if (/(^|\/)env$/.test(interpreter.toString("latin1")) && program && !/^-|=/.test(program.toString("latin1")) && !(program.includes(0x2f) ? executable(program) : onPathBytes(program, path))) {
|
|
480
|
+
throw notStartable(cli, `: the interpreter its first line names, ${program.toString()}, is on no folder of its PATH`);
|
|
403
481
|
}
|
|
404
|
-
throw Object.assign(new Error(`spawn ${cli} ENOENT`), { code: "ENOENT" });
|
|
405
482
|
}
|
|
406
483
|
/** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
|
|
407
484
|
* (personHome) and desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
|
package/dist/store.d.ts
CHANGED
|
@@ -37,9 +37,16 @@ export declare const subStream: (subpath: string) => string;
|
|
|
37
37
|
export declare function toolUseIds(entry: TranscriptLine | undefined): string[];
|
|
38
38
|
/** The `tool_use_id`s a user entry answers (its `tool_result` blocks). */
|
|
39
39
|
export declare function toolResultIds(entry: TranscriptLine | undefined): string[];
|
|
40
|
+
/** The timers a barrier's wait runs on (the system's by default; a test passes a fake clock). */
|
|
41
|
+
export interface BarrierTimers {
|
|
42
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
43
|
+
clearTimeout(timer: unknown): void;
|
|
44
|
+
}
|
|
40
45
|
export interface JournalSessionStoreOptions {
|
|
41
46
|
/** The journal's records as of the drive's start, blobs resolved (`journal.read()`). */
|
|
42
47
|
records: JournalRecord[];
|
|
48
|
+
/** The timers `barrier` and `resultBarrier` wait on. Default the system's. */
|
|
49
|
+
timers?: BarrierTimers;
|
|
43
50
|
/**
|
|
44
51
|
* Hold appended entries this long before they go to the journal, so the
|
|
45
52
|
* SDK's frames (one `append` per line with eager flushing) ride in fewer
|
|
@@ -60,7 +67,11 @@ export interface JournalSessionStoreOptions {
|
|
|
60
67
|
* from machine to machine) is ignored.
|
|
61
68
|
* - `barrier(toolUseId)` resolves once the assistant entry that made that
|
|
62
69
|
* call is committed: before a `replay: 'never'` tool runs, the call that
|
|
63
|
-
* asked for it is in the log.
|
|
70
|
+
* asked for it is in the log. The SDK mirrors a message's lines only once
|
|
71
|
+
* the message ends, while the CLI runs each call as its block ends, so the
|
|
72
|
+
* wait's clock restarts on each stream event of the message that made the
|
|
73
|
+
* call, up to its `message_stop` (`heard`): it runs out `timeoutMs` after
|
|
74
|
+
* that message's last event.
|
|
64
75
|
*/
|
|
65
76
|
export declare class JournalSessionStore {
|
|
66
77
|
private readonly journal;
|
|
@@ -71,9 +82,15 @@ export declare class JournalSessionStore {
|
|
|
71
82
|
private readonly waiters;
|
|
72
83
|
private readonly results;
|
|
73
84
|
private readonly resultWaiters;
|
|
85
|
+
/** The message stream each call was made in (its `parent_tool_use_id`, `''` for the main thread), from the SDK's live
|
|
86
|
+
* blocks, until its message's `message_stop`. */
|
|
87
|
+
private readonly callScopes;
|
|
88
|
+
/** The clocks of the waits on each call, by its id: each one restarts its wait. */
|
|
89
|
+
private readonly clocks;
|
|
74
90
|
private held;
|
|
75
91
|
private timer;
|
|
76
92
|
private readonly coalesceMs;
|
|
93
|
+
private readonly timers;
|
|
77
94
|
/** Entries this drive appended (for tests and diagnostics). */
|
|
78
95
|
appended: number;
|
|
79
96
|
constructor(journal: NativeJournal, options: JournalSessionStoreOptions);
|
|
@@ -118,16 +135,35 @@ export declare class JournalSessionStore {
|
|
|
118
135
|
}): Promise<string[]>;
|
|
119
136
|
/**
|
|
120
137
|
* Resolve once the assistant entry that made `toolUseId` is committed. The
|
|
121
|
-
* SDK delivers
|
|
122
|
-
* runs
|
|
123
|
-
* first. Rejects after `timeoutMs` (the caller does
|
|
138
|
+
* SDK delivers a message's entries once the CLI has written the whole
|
|
139
|
+
* message, and the tool runs once the CLI wrote its block, so this usually
|
|
140
|
+
* waits for the mirror first. Rejects after `timeoutMs` (the caller does
|
|
141
|
+
* not run the tool), counted from the last stream event of the message that
|
|
142
|
+
* made the call (`heard`), or from now if none is heard.
|
|
124
143
|
*/
|
|
125
144
|
barrier(toolUseId: string, timeoutMs: number): Promise<void>;
|
|
145
|
+
/**
|
|
146
|
+
* One message `query()` yielded. An `assistant` message names the calls its block made, in its stream (the main
|
|
147
|
+
* thread's, or a subagent's by its `parent_tool_use_id`); it and each `stream_event` of that stream restart the clock
|
|
148
|
+
* of every wait on a call made in it. A message's last event is its `message_stop`: it restarts those clocks one last
|
|
149
|
+
* time and unties the message's calls from the stream, whose next message reuses its `parent_tool_use_id`. So a call
|
|
150
|
+
* whose line never lands is refused `timeoutMs` after its message ended, whatever streams after it, and a stream that
|
|
151
|
+
* stalls, `timeoutMs` after its last event.
|
|
152
|
+
*/
|
|
153
|
+
heard(m: {
|
|
154
|
+
type: string;
|
|
155
|
+
parent_tool_use_id?: string | null;
|
|
156
|
+
message?: unknown;
|
|
157
|
+
event?: unknown;
|
|
158
|
+
}): void;
|
|
159
|
+
/** Wait for `note` to wake a waiter on `id` in `waiters`; reject with `error()` once the clock runs out (`heard` restarts it). */
|
|
160
|
+
private wait;
|
|
126
161
|
private note;
|
|
127
162
|
private user;
|
|
128
163
|
/**
|
|
129
164
|
* Resolve once the user entry that answers `toolUseId` (its `tool_result`) is committed: a call the CLI answered
|
|
130
|
-
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs
|
|
165
|
+
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs`, on the same
|
|
166
|
+
* clock as `barrier`: the answer is mirrored with the rest of its message, once that message ends.
|
|
131
167
|
*/
|
|
132
168
|
resultBarrier(toolUseId: string, timeoutMs: number): Promise<void>;
|
|
133
169
|
}
|
package/dist/store.js
CHANGED
|
@@ -21,6 +21,10 @@ export function toolResultIds(entry) {
|
|
|
21
21
|
return [];
|
|
22
22
|
return content.filter((c) => c?.type === 'tool_result' && typeof c.tool_use_id === 'string').map((c) => c.tool_use_id);
|
|
23
23
|
}
|
|
24
|
+
const SYSTEM_TIMERS = {
|
|
25
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
26
|
+
clearTimeout: (timer) => clearTimeout(timer),
|
|
27
|
+
};
|
|
24
28
|
/**
|
|
25
29
|
* A `SessionStore` (the SDK's `@alpha` mirror interface) whose storage is the
|
|
26
30
|
* drive's journal.
|
|
@@ -34,7 +38,11 @@ export function toolResultIds(entry) {
|
|
|
34
38
|
* from machine to machine) is ignored.
|
|
35
39
|
* - `barrier(toolUseId)` resolves once the assistant entry that made that
|
|
36
40
|
* call is committed: before a `replay: 'never'` tool runs, the call that
|
|
37
|
-
* asked for it is in the log.
|
|
41
|
+
* asked for it is in the log. The SDK mirrors a message's lines only once
|
|
42
|
+
* the message ends, while the CLI runs each call as its block ends, so the
|
|
43
|
+
* wait's clock restarts on each stream event of the message that made the
|
|
44
|
+
* call, up to its `message_stop` (`heard`): it runs out `timeoutMs` after
|
|
45
|
+
* that message's last event.
|
|
38
46
|
*/
|
|
39
47
|
export class JournalSessionStore {
|
|
40
48
|
journal;
|
|
@@ -45,14 +53,21 @@ export class JournalSessionStore {
|
|
|
45
53
|
waiters = new Map();
|
|
46
54
|
results = new Set();
|
|
47
55
|
resultWaiters = new Map();
|
|
56
|
+
/** The message stream each call was made in (its `parent_tool_use_id`, `''` for the main thread), from the SDK's live
|
|
57
|
+
* blocks, until its message's `message_stop`. */
|
|
58
|
+
callScopes = new Map();
|
|
59
|
+
/** The clocks of the waits on each call, by its id: each one restarts its wait. */
|
|
60
|
+
clocks = new Map();
|
|
48
61
|
held = [];
|
|
49
62
|
timer;
|
|
50
63
|
coalesceMs;
|
|
64
|
+
timers;
|
|
51
65
|
/** Entries this drive appended (for tests and diagnostics). */
|
|
52
66
|
appended = 0;
|
|
53
67
|
constructor(journal, options) {
|
|
54
68
|
this.journal = journal;
|
|
55
69
|
this.coalesceMs = options.coalesceMs ?? 0;
|
|
70
|
+
this.timers = options.timers ?? SYSTEM_TIMERS;
|
|
56
71
|
for (const r of options.records) {
|
|
57
72
|
if (r.stream !== CLAUDE_STREAM && !r.stream.startsWith(`${CLAUDE_STREAM}/`))
|
|
58
73
|
continue;
|
|
@@ -156,30 +171,75 @@ export class JournalSessionStore {
|
|
|
156
171
|
}
|
|
157
172
|
/**
|
|
158
173
|
* Resolve once the assistant entry that made `toolUseId` is committed. The
|
|
159
|
-
* SDK delivers
|
|
160
|
-
* runs
|
|
161
|
-
* first. Rejects after `timeoutMs` (the caller does
|
|
174
|
+
* SDK delivers a message's entries once the CLI has written the whole
|
|
175
|
+
* message, and the tool runs once the CLI wrote its block, so this usually
|
|
176
|
+
* waits for the mirror first. Rejects after `timeoutMs` (the caller does
|
|
177
|
+
* not run the tool), counted from the last stream event of the message that
|
|
178
|
+
* made the call (`heard`), or from now if none is heard.
|
|
162
179
|
*/
|
|
163
180
|
async barrier(toolUseId, timeoutMs) {
|
|
164
|
-
if (!this.calls.has(toolUseId))
|
|
165
|
-
await
|
|
166
|
-
const timer = setTimeout(() => {
|
|
167
|
-
const list = this.waiters.get(toolUseId)?.filter((w) => w !== done) ?? [];
|
|
168
|
-
if (list.length)
|
|
169
|
-
this.waiters.set(toolUseId, list);
|
|
170
|
-
else
|
|
171
|
-
this.waiters.delete(toolUseId);
|
|
172
|
-
reject(new Error(`the transcript entry for tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
173
|
-
}, timeoutMs);
|
|
174
|
-
const done = () => {
|
|
175
|
-
clearTimeout(timer);
|
|
176
|
-
resolve();
|
|
177
|
-
};
|
|
178
|
-
this.waiters.set(toolUseId, [...(this.waiters.get(toolUseId) ?? []), done]);
|
|
179
|
-
});
|
|
180
|
-
}
|
|
181
|
+
if (!this.calls.has(toolUseId))
|
|
182
|
+
await this.wait(toolUseId, timeoutMs, this.waiters, () => new Error(`the transcript entry for tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
181
183
|
await this.flush();
|
|
182
184
|
}
|
|
185
|
+
/**
|
|
186
|
+
* One message `query()` yielded. An `assistant` message names the calls its block made, in its stream (the main
|
|
187
|
+
* thread's, or a subagent's by its `parent_tool_use_id`); it and each `stream_event` of that stream restart the clock
|
|
188
|
+
* of every wait on a call made in it. A message's last event is its `message_stop`: it restarts those clocks one last
|
|
189
|
+
* time and unties the message's calls from the stream, whose next message reuses its `parent_tool_use_id`. So a call
|
|
190
|
+
* whose line never lands is refused `timeoutMs` after its message ended, whatever streams after it, and a stream that
|
|
191
|
+
* stalls, `timeoutMs` after its last event.
|
|
192
|
+
*/
|
|
193
|
+
heard(m) {
|
|
194
|
+
const scope = m.parent_tool_use_id ?? '';
|
|
195
|
+
if (m.type === 'assistant')
|
|
196
|
+
for (const id of toolUseIds(m))
|
|
197
|
+
this.callScopes.set(id, scope);
|
|
198
|
+
else if (m.type !== 'stream_event')
|
|
199
|
+
return;
|
|
200
|
+
for (const [id, restarts] of this.clocks)
|
|
201
|
+
if (this.callScopes.get(id) === scope)
|
|
202
|
+
for (const restart of [...restarts])
|
|
203
|
+
restart();
|
|
204
|
+
if (m.event?.type === 'message_stop')
|
|
205
|
+
for (const [id, of] of this.callScopes)
|
|
206
|
+
if (of === scope)
|
|
207
|
+
this.callScopes.delete(id);
|
|
208
|
+
}
|
|
209
|
+
/** Wait for `note` to wake a waiter on `id` in `waiters`; reject with `error()` once the clock runs out (`heard` restarts it). */
|
|
210
|
+
wait(id, timeoutMs, waiters, error) {
|
|
211
|
+
return new Promise((resolve, reject) => {
|
|
212
|
+
const clock = this.timers;
|
|
213
|
+
let timer;
|
|
214
|
+
const restart = () => {
|
|
215
|
+
clock.clearTimeout(timer);
|
|
216
|
+
timer = clock.setTimeout(expire, timeoutMs);
|
|
217
|
+
};
|
|
218
|
+
const stop = () => {
|
|
219
|
+
clock.clearTimeout(timer);
|
|
220
|
+
const restarts = this.clocks.get(id);
|
|
221
|
+
restarts?.delete(restart);
|
|
222
|
+
if (!restarts?.size)
|
|
223
|
+
this.clocks.delete(id);
|
|
224
|
+
};
|
|
225
|
+
const done = () => {
|
|
226
|
+
stop();
|
|
227
|
+
resolve();
|
|
228
|
+
};
|
|
229
|
+
const expire = () => {
|
|
230
|
+
stop();
|
|
231
|
+
const list = waiters.get(id)?.filter((w) => w !== done) ?? [];
|
|
232
|
+
if (list.length)
|
|
233
|
+
waiters.set(id, list);
|
|
234
|
+
else
|
|
235
|
+
waiters.delete(id);
|
|
236
|
+
reject(error());
|
|
237
|
+
};
|
|
238
|
+
waiters.set(id, [...(waiters.get(id) ?? []), done]);
|
|
239
|
+
this.clocks.set(id, (this.clocks.get(id) ?? new Set()).add(restart));
|
|
240
|
+
restart();
|
|
241
|
+
});
|
|
242
|
+
}
|
|
183
243
|
note(entry) {
|
|
184
244
|
if (entry.type === 'user' && entry.uuid)
|
|
185
245
|
this.user(entry.uuid);
|
|
@@ -207,26 +267,12 @@ export class JournalSessionStore {
|
|
|
207
267
|
}
|
|
208
268
|
/**
|
|
209
269
|
* Resolve once the user entry that answers `toolUseId` (its `tool_result`) is committed: a call the CLI answered
|
|
210
|
-
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs
|
|
270
|
+
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs`, on the same
|
|
271
|
+
* clock as `barrier`: the answer is mirrored with the rest of its message, once that message ends.
|
|
211
272
|
*/
|
|
212
273
|
async resultBarrier(toolUseId, timeoutMs) {
|
|
213
|
-
if (!this.results.has(toolUseId))
|
|
214
|
-
await
|
|
215
|
-
const timer = setTimeout(() => {
|
|
216
|
-
const list = this.resultWaiters.get(toolUseId)?.filter((w) => w !== done) ?? [];
|
|
217
|
-
if (list.length)
|
|
218
|
-
this.resultWaiters.set(toolUseId, list);
|
|
219
|
-
else
|
|
220
|
-
this.resultWaiters.delete(toolUseId);
|
|
221
|
-
reject(new Error(`the transcript entry answering tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
222
|
-
}, timeoutMs);
|
|
223
|
-
const done = () => {
|
|
224
|
-
clearTimeout(timer);
|
|
225
|
-
resolve();
|
|
226
|
-
};
|
|
227
|
-
this.resultWaiters.set(toolUseId, [...(this.resultWaiters.get(toolUseId) ?? []), done]);
|
|
228
|
-
});
|
|
229
|
-
}
|
|
274
|
+
if (!this.results.has(toolUseId))
|
|
275
|
+
await this.wait(toolUseId, timeoutMs, this.resultWaiters, () => new Error(`the transcript entry answering tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
|
|
230
276
|
await this.flush();
|
|
231
277
|
}
|
|
232
278
|
}
|
|
@@ -50,6 +50,17 @@ export interface FakeSdkOptions {
|
|
|
50
50
|
updatedInput?: Record<string, unknown>;
|
|
51
51
|
reason?: string;
|
|
52
52
|
}) => void;
|
|
53
|
+
/** The wait between a `batch` message's blocks. Default a real timer; a test on a fake clock passes its own. */
|
|
54
|
+
sleep?: (ms: number) => Promise<void>;
|
|
55
|
+
/** A `batch` call's handler returned: its block's place in the message (from 1), and what the tool server answered. */
|
|
56
|
+
onCallEnd?: (call: {
|
|
57
|
+
id: string;
|
|
58
|
+
index: number;
|
|
59
|
+
isError: boolean;
|
|
60
|
+
text: string;
|
|
61
|
+
}) => void;
|
|
62
|
+
/** A `batch` message's `message_stop` was taken: the consumer asked for what follows it, so it has heard the stop. */
|
|
63
|
+
onMessageEnd?: () => void;
|
|
53
64
|
}
|
|
54
65
|
export interface FakeSdk extends ClaudeAgentSdk {
|
|
55
66
|
queries: Record<string, any>[];
|
package/dist/testing/fake-sdk.js
CHANGED
|
@@ -387,6 +387,71 @@ export function fakeSdk(fake = {}) {
|
|
|
387
387
|
await mirror([{ type: 'last-prompt' }]);
|
|
388
388
|
continue;
|
|
389
389
|
}
|
|
390
|
+
const batching = /^batch (.*)$/s.exec(command);
|
|
391
|
+
if (batching) {
|
|
392
|
+
const spec = JSON.parse(batching[1]);
|
|
393
|
+
const sleep = fake.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
394
|
+
const event = (ev) => ({ type: 'stream_event', parent_tool_use_id: null, event: ev });
|
|
395
|
+
const tool = (await tools).get(spec.tool);
|
|
396
|
+
const lines = [];
|
|
397
|
+
const running = [];
|
|
398
|
+
yield event({ type: 'message_start', message: { id: `msg_${uuid().slice(0, 8)}`, role: 'assistant', content: [] } });
|
|
399
|
+
for (let index = 1; index <= spec.n; index++) {
|
|
400
|
+
const id = `toolu_${randomUUID().slice(0, 8)}_${++calls}`;
|
|
401
|
+
const block = { type: 'tool_use', id, name: `mcp__hands__${spec.tool}`, input: spec.args };
|
|
402
|
+
yield event({ type: 'content_block_start', index: index - 1, content_block: { ...block, input: {} } });
|
|
403
|
+
await sleep(spec.gapMs);
|
|
404
|
+
yield event({ type: 'content_block_delta', index: index - 1, delta: { type: 'input_json_delta', partial_json: JSON.stringify(spec.args) } });
|
|
405
|
+
yield event({ type: 'content_block_stop', index: index - 1 });
|
|
406
|
+
const a = entry('assistant', { message: { role: 'assistant', content: [block] } });
|
|
407
|
+
if (!spec.lost?.includes(index))
|
|
408
|
+
lines.push(a);
|
|
409
|
+
yield { type: 'assistant', parent_tool_use_id: null, uuid: a.uuid, session_id: sessionId, message: a.message };
|
|
410
|
+
if (spec.refused?.includes(index)) {
|
|
411
|
+
const r = entry('user', { message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, is_error: true, content: `<tool_use_error>Error: No such tool available: ${block.name}</tool_use_error>` }] } });
|
|
412
|
+
if (!spec.lost?.includes(index))
|
|
413
|
+
lines.push(r);
|
|
414
|
+
yield { type: 'user', parent_tool_use_id: null, message: r.message };
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
running.push((async () => {
|
|
418
|
+
const result = tool ? await tool.handler(spec.args, { _meta: { 'claudecode/toolUseId': id } }) : { content: [{ type: 'text', text: `no tool ${spec.tool}` }], isError: true };
|
|
419
|
+
fake.onCallEnd?.({ id, index, isError: !!result.isError, text: String(result.content[0]?.text ?? '') });
|
|
420
|
+
return { id, result };
|
|
421
|
+
})());
|
|
422
|
+
}
|
|
423
|
+
yield event({ type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: 12 } });
|
|
424
|
+
yield event({ type: 'message_stop' });
|
|
425
|
+
fake.onMessageEnd?.();
|
|
426
|
+
await mirror(lines);
|
|
427
|
+
const results = await Promise.all(running);
|
|
428
|
+
if (signal?.aborted)
|
|
429
|
+
return;
|
|
430
|
+
for (const { id, result } of results) {
|
|
431
|
+
const r = entry('user', { message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, is_error: !!result.isError, content: result.content[0]?.text }] } });
|
|
432
|
+
await mirror([r]);
|
|
433
|
+
yield { type: 'user', parent_tool_use_id: null, message: r.message };
|
|
434
|
+
}
|
|
435
|
+
const reply = `${spec.tool} ran ${results.filter(({ result }) => !result.isError).length} of ${spec.n}`;
|
|
436
|
+
if (spec.then) {
|
|
437
|
+
// The answer is a message of its own, in the same stream, streamed as the model writes it.
|
|
438
|
+
yield event({ type: 'message_start', message: { id: `msg_${uuid().slice(0, 8)}`, role: 'assistant', content: [] } });
|
|
439
|
+
yield event({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } });
|
|
440
|
+
for (let at = 0; at < spec.then.n; at++) {
|
|
441
|
+
await sleep(spec.then.gapMs);
|
|
442
|
+
yield event({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: at ? ' .' : reply } });
|
|
443
|
+
}
|
|
444
|
+
yield event({ type: 'content_block_stop', index: 0 });
|
|
445
|
+
yield event({ type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 12 } });
|
|
446
|
+
yield event({ type: 'message_stop' });
|
|
447
|
+
}
|
|
448
|
+
const b = entry('assistant', { message: { role: 'assistant', content: [{ type: 'text', text: reply }] } });
|
|
449
|
+
await mirror([b]);
|
|
450
|
+
yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: b.message };
|
|
451
|
+
yield { type: 'result', subtype: 'success', is_error: false, result: 'ok', session_id: sessionId, user_message_uuids: consumed, queued_turn_count: 0 };
|
|
452
|
+
await mirror([{ type: 'last-prompt' }]);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
390
455
|
const call = /^call (\S+) (.*)$/s.exec(command);
|
|
391
456
|
if (call) {
|
|
392
457
|
const id = `toolu_${randomUUID().slice(0, 8)}_${++calls}`;
|
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.58",
|
|
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.58"
|
|
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.58"
|
|
81
81
|
}
|
|
82
82
|
}
|