@parcha/agentrun-harness-claude 0.1.0-beta.43 → 0.1.0-beta.45
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 +4 -0
- package/dist/adapter.d.ts +7 -1
- package/dist/adapter.js +28 -24
- package/dist/env.d.ts +12 -4
- package/dist/env.js +13 -2
- package/dist/harness.d.ts +12 -1
- package/dist/harness.js +23 -8
- package/dist/host/machine.d.ts +3 -2
- package/dist/host/machine.js +24 -20
- package/dist/host/process.d.ts +4 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/login.d.ts +61 -0
- package/dist/login.js +177 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.45 (2026-11-18)
|
|
6
|
+
|
|
7
|
+
- Claude Agent can run on the claude CLI's own login on the same machine instead of a model key. `claudeLoginStatus` asks the CLI `claude auth status` and returns what it said (signed in, method, email, plan), never a token. `claudeLoginEnv` gives the run's CLI the login's directories and no `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` or key. `claudeLoginCommand` and `startClaudeLogin` give or start the CLI's own `auth login`. A session on the login keeps its directory out of the sandbox's reads, never wipes it, and books its tokens with no dollars. <!-- changes/run-adapters-claude-agent.md -->
|
|
8
|
+
|
|
5
9
|
## 0.1.0-beta.41 (2026-11-16)
|
|
6
10
|
|
|
7
11
|
- A message sent to a working `claude-agent` run now steers it mid-turn. Before, it waited for the turn's end, and a run whose whole job is one turn read it only after the work was done. The model now reads it at its next step, after the tool calls in flight finish, in the same turn. `POST /v2/runs/{id}/messages` answers mode `steer` for a working claude-agent run (it answered `follow_up`), and `GET /v2/capabilities` lists `claude-agent` with `steer: true`.
|
package/dist/adapter.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ 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
5
|
import { type ConfineChild } from "./host/machine.js";
|
|
6
|
+
import type { ClaudeAgentLogin } from "./login.js";
|
|
6
7
|
import type { ToolServerModules } from "./host/tool-server.js";
|
|
7
8
|
export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
|
|
8
9
|
/** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
|
|
@@ -41,7 +42,12 @@ export interface ClaudeAgentAdapterOptions {
|
|
|
41
42
|
};
|
|
42
43
|
/** The model of the CLI's small background calls. Default: the session's model. */
|
|
43
44
|
smallModel?: string;
|
|
44
|
-
provider
|
|
45
|
+
/** Where the model's requests go, through the session's model proxy. Exactly one of `provider` and `login`. */
|
|
46
|
+
provider?: ClaudeAgentProvider;
|
|
47
|
+
/** A person's own login on this machine (login.ts), which the CLI runs on in place of a provider: it calls Anthropic
|
|
48
|
+
* itself, with no proxy, no model URL and no key of the host's; each response is booked from its stream, billed to the
|
|
49
|
+
* person's plan (`price` is not read), and the session has no host port. The host only says where the login is. */
|
|
50
|
+
login?: ClaudeAgentLogin;
|
|
45
51
|
/** Start the CLI under the host's confinement (its own `confine()`, a `setpriv --no-new-privs` prefix, say). It may
|
|
46
52
|
* only add in front of the pinned binary and its arguments, and never touches its environment. */
|
|
47
53
|
confine?: ConfineChild;
|
package/dist/adapter.js
CHANGED
|
@@ -262,7 +262,10 @@ export function claudeAgentAdapter(options) {
|
|
|
262
262
|
const skillsWrong = skillProblems(skills);
|
|
263
263
|
if (skillsWrong.length)
|
|
264
264
|
throw new Error(`agentrun-harness-claude: ${skillsWrong.join("; ")}`);
|
|
265
|
-
const
|
|
265
|
+
const { provider, login } = options;
|
|
266
|
+
if (!provider === !login)
|
|
267
|
+
throw new Error("agentrun-harness-claude: give the adapter a provider or a login, not both and not neither");
|
|
268
|
+
const headersWrong = hostHeaderProblems(provider?.headers);
|
|
266
269
|
if (headersWrong.length)
|
|
267
270
|
throw new Error(`agentrun-harness-claude: provider.headers: ${headersWrong.join("; ")}`);
|
|
268
271
|
// The SDK and its CLI are checked once, here: a mismatch is the host's to report, before any run starts.
|
|
@@ -320,20 +323,21 @@ export function claudeAgentAdapter(options) {
|
|
|
320
323
|
// The host's workspace, when it names one: the CLI works where the host's file tools write (io.cwd).
|
|
321
324
|
...(io.cwd ? { cwd: io.cwd } : {}),
|
|
322
325
|
...(options.confine ? { confine: options.confine } : {}),
|
|
323
|
-
proxy:
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
326
|
+
// On a login, no proxy: the CLI calls Anthropic itself.
|
|
327
|
+
...(provider ? { proxy: {
|
|
328
|
+
hooks: io.models,
|
|
329
|
+
tools: tools.map((t) => t.name),
|
|
330
|
+
...(builtins.length ? { builtins } : {}),
|
|
331
|
+
...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
|
|
332
|
+
// What the CLI sends with its own tool search on, which the harness turns on as this does (claudeToolSearch).
|
|
333
|
+
...(claudeToolSearch(tools.map((t) => t.name), spec.deferCatalog) === "true" ? { toolSearch: true } : {}),
|
|
334
|
+
...(options.price ? { price: options.price } : {}),
|
|
335
|
+
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
336
|
+
...(provider.auth ? { auth: provider.auth } : {}),
|
|
337
|
+
...(provider.headers ? { headers: provider.headers } : {}),
|
|
338
|
+
...(options.log ? { log: options.log } : {}),
|
|
339
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
340
|
+
} } : {}),
|
|
337
341
|
});
|
|
338
342
|
// The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
|
|
339
343
|
// the session's level.
|
|
@@ -357,8 +361,7 @@ export function claudeAgentAdapter(options) {
|
|
|
357
361
|
...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
|
|
358
362
|
...(options.smallModel ? { smallModel: options.smallModel } : {}),
|
|
359
363
|
...(spec.system.length ? { instructions: spec.system.join("\n\n") } : {}),
|
|
360
|
-
credential: async () =>
|
|
361
|
-
gatewayUrl: options.provider.origin,
|
|
364
|
+
...(provider ? { credential: async () => provider.credential(), gatewayUrl: provider.origin } : { login: { at: login, models: io.models } }),
|
|
362
365
|
executable,
|
|
363
366
|
sdk,
|
|
364
367
|
...(options.mcp ? { toolServerModules: options.mcp } : {}),
|
|
@@ -485,21 +488,22 @@ export function claudeAgentAdapter(options) {
|
|
|
485
488
|
// the CLI never holds its key. Its policy object is its own: anything a policy keeps per instance stays apart from the
|
|
486
489
|
// drive's, as a side call's should. Closed with the session, or when the host lets the session go (io.signal).
|
|
487
490
|
// Started once the session's drive is open, the last step that can fail: an open that fails leaves no listener.
|
|
488
|
-
|
|
491
|
+
// A session on a person's login has none: no request of the host's ever goes on that login.
|
|
492
|
+
const hostPort = !provider ? undefined : await startModelProxy({
|
|
489
493
|
policy: anthropicPolicy({
|
|
490
494
|
model: modelFor(spec),
|
|
491
495
|
...(options.smallModel ? { smallModel: options.smallModel } : {}),
|
|
492
496
|
tools: [],
|
|
493
497
|
...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
|
|
494
498
|
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
495
|
-
...(
|
|
499
|
+
...(provider.auth ? { auth: provider.auth } : {}),
|
|
496
500
|
}),
|
|
497
501
|
hooks: io.models,
|
|
498
502
|
model: modelFor(spec),
|
|
499
|
-
origin:
|
|
500
|
-
credential: async () => (await
|
|
503
|
+
origin: provider.origin,
|
|
504
|
+
credential: async () => (await provider.credential()) ?? "",
|
|
501
505
|
...(options.price ? { price: withWebSearches(options.price) } : {}),
|
|
502
|
-
...(
|
|
506
|
+
...(provider.headers ? { headers: provider.headers } : {}),
|
|
503
507
|
...(options.log ? { log: options.log } : {}),
|
|
504
508
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
505
509
|
}, randomBytes(32).toString("base64url"));
|
|
@@ -508,7 +512,7 @@ export function claudeAgentAdapter(options) {
|
|
|
508
512
|
if (hostClosed)
|
|
509
513
|
return;
|
|
510
514
|
hostClosed = true;
|
|
511
|
-
await hostPort
|
|
515
|
+
await hostPort?.close().catch(() => { });
|
|
512
516
|
};
|
|
513
517
|
io.signal.addEventListener("abort", () => void closeHost(), { once: true });
|
|
514
518
|
if (io.signal.aborted)
|
|
@@ -627,7 +631,7 @@ export function claudeAgentAdapter(options) {
|
|
|
627
631
|
},
|
|
628
632
|
// The session's one model route, for the host's own request beside the CLI's: the session's host port, which
|
|
629
633
|
// never restarts once closed.
|
|
630
|
-
port: (label) => (closed || hostClosed ? undefined : { url: hostPort.url, key: hostPort.sideKey(label), model: modelFor(spec), api: "anthropic-messages" }),
|
|
634
|
+
port: (label) => (closed || hostClosed || !hostPort ? undefined : { url: hostPort.url, key: hostPort.sideKey(label), model: modelFor(spec), api: "anthropic-messages" }),
|
|
631
635
|
};
|
|
632
636
|
},
|
|
633
637
|
};
|
package/dist/env.d.ts
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
* about 50 `CLAUDE_*`, `ANTHROPIC_*` and `MCP_*` variables that change the
|
|
8
8
|
* CLI's behavior; none reaches the child unless it is listed here.
|
|
9
9
|
*/
|
|
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 any kind. */
|
|
12
|
+
export declare const LOGIN_UNSET: readonly string[];
|
|
10
13
|
/** The `PATH` of the CLI and its commands in the VM: the image's, never the Function's. */
|
|
11
14
|
export declare const VM_PATH = "/usr/local/bin:/usr/bin:/bin";
|
|
12
15
|
/** The projects key both sides use (`CLAUDE_CODE_PROJECT_DIR_NAME`): the CLI's transcript is `projects/session/<id>.jsonl` wherever its cwd is. */
|
|
@@ -20,14 +23,19 @@ export interface DurableEnvOptions {
|
|
|
20
23
|
tmpDir: string;
|
|
21
24
|
/** The XDG cache in the VM (`dirs.cache`). */
|
|
22
25
|
cacheDir: string;
|
|
23
|
-
/** Where the CLI sends model requests: the VM's model port (`SessionMachine.modelUrl`). */
|
|
24
|
-
baseUrl
|
|
26
|
+
/** Where the CLI sends model requests: the VM's model port (`SessionMachine.modelUrl`). None with `login`. */
|
|
27
|
+
baseUrl?: string;
|
|
25
28
|
/**
|
|
26
29
|
* The key the CLI sends (`ANTHROPIC_AUTH_TOKEN`, so `authorization: Bearer
|
|
27
30
|
* <key>`): the attach's model key (`SessionMachine.modelKey`). The relay
|
|
28
|
-
* admits a model request only with it, from the CLI's own process.
|
|
31
|
+
* admits a model request only with it, from the CLI's own process. None with `login`.
|
|
29
32
|
*/
|
|
30
|
-
token
|
|
33
|
+
token?: string;
|
|
34
|
+
/**
|
|
35
|
+
* The person's own login the CLI runs on, in place of the model port: the CLI calls Anthropic itself with it, and the
|
|
36
|
+
* environment has no model URL or key at all (login.ts).
|
|
37
|
+
*/
|
|
38
|
+
login?: ClaudeAgentLogin;
|
|
31
39
|
/** The model, as the CLI's main and alias models. */
|
|
32
40
|
model: string;
|
|
33
41
|
/** The model for the CLI's small background calls (titles, summaries). Default `model`. */
|
package/dist/env.js
CHANGED
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
* about 50 `CLAUDE_*`, `ANTHROPIC_*` and `MCP_*` variables that change the
|
|
11
11
|
* CLI's behavior; none reaches the child unless it is listed here.
|
|
12
12
|
*/
|
|
13
|
+
import { loginEnv } from './login.js';
|
|
14
|
+
/** What never reaches a CLI that runs on a person's login: a model URL, key or token of any kind. */
|
|
15
|
+
export const LOGIN_UNSET = Object.freeze(['ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_CUSTOM_HEADERS', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX']);
|
|
13
16
|
/** The `PATH` of the CLI and its commands in the VM: the image's, never the Function's. */
|
|
14
17
|
export const VM_PATH = '/usr/local/bin:/usr/bin:/bin';
|
|
15
18
|
/** Claude Code's default Bash timeout. */
|
|
@@ -40,6 +43,15 @@ export function durableEnv(options) {
|
|
|
40
43
|
const { home, model } = options;
|
|
41
44
|
const small = options.smallModel ?? model;
|
|
42
45
|
const env = { ...(options.extra ?? {}) };
|
|
46
|
+
if (options.login) {
|
|
47
|
+
// On a login, no model URL, key or token reaches the CLI, the app's own variables included: its login is its only one.
|
|
48
|
+
for (const name of Object.keys(env))
|
|
49
|
+
if (LOGIN_UNSET.includes(name))
|
|
50
|
+
delete env[name];
|
|
51
|
+
}
|
|
52
|
+
else if (options.baseUrl === undefined || options.token === undefined) {
|
|
53
|
+
throw new Error('agentrun-harness-claude: the CLI needs its model port and key, or a login');
|
|
54
|
+
}
|
|
43
55
|
Object.assign(env, {
|
|
44
56
|
PATH: VM_PATH,
|
|
45
57
|
HOME: home,
|
|
@@ -50,8 +62,7 @@ export function durableEnv(options) {
|
|
|
50
62
|
XDG_CACHE_HOME: options.cacheDir,
|
|
51
63
|
XDG_DATA_HOME: `${home}/.local/share`,
|
|
52
64
|
XDG_STATE_HOME: `${home}/.local/state`,
|
|
53
|
-
ANTHROPIC_BASE_URL: options.baseUrl,
|
|
54
|
-
ANTHROPIC_AUTH_TOKEN: options.token,
|
|
65
|
+
...(options.login ? loginEnv(options.login) : { ANTHROPIC_BASE_URL: options.baseUrl, ANTHROPIC_AUTH_TOKEN: options.token }),
|
|
55
66
|
ANTHROPIC_DEFAULT_OPUS_MODEL: model,
|
|
56
67
|
ANTHROPIC_DEFAULT_SONNET_MODEL: model,
|
|
57
68
|
ANTHROPIC_DEFAULT_HAIKU_MODEL: small,
|
package/dist/harness.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
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';
|
|
5
|
+
import type { ModelPort } from '@parcha/agentrun-kernel';
|
|
4
6
|
import { toolServer } from './host/tool-server.js';
|
|
5
7
|
import { JournalSessionStore } from './store.js';
|
|
6
8
|
/**
|
|
@@ -195,6 +197,15 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
195
197
|
credential?: () => Promise<string>;
|
|
196
198
|
/** The Gateway's base URL. Default `gatewayUrl()`. */
|
|
197
199
|
gatewayUrl?: string;
|
|
200
|
+
/**
|
|
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
|
+
* 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.
|
|
204
|
+
*/
|
|
205
|
+
login?: {
|
|
206
|
+
at: ClaudeAgentLogin;
|
|
207
|
+
models: Pick<ModelPort, 'beforeRequest' | 'afterRequest'>;
|
|
208
|
+
};
|
|
198
209
|
/** 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. */
|
|
199
210
|
executable?: string;
|
|
200
211
|
/** The kernel name (its sessions' runs are `workflow//durable-harness@<version>//<name>`). Default `claude-code`. */
|
|
@@ -298,7 +309,7 @@ export declare const claudeBuiltinReplay: (name: string) => ReplayPolicy;
|
|
|
298
309
|
/** The `builtins` option, resolved: the `tools` option for `query()` (undefined: the preset, all of them). */
|
|
299
310
|
export declare function builtinTools(builtins: ClaudeBuiltins | undefined): string[] | undefined;
|
|
300
311
|
/** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16). */
|
|
301
|
-
export declare function claudeSandboxSettings(machine: Pick<SessionMachine, 'root' | 'dirs'>, network: ClaudeSandboxNetwork): NonNullable<QueryOptions['sandbox']>;
|
|
312
|
+
export declare function claudeSandboxSettings(machine: Pick<SessionMachine, 'root' | 'dirs'>, network: ClaudeSandboxNetwork, login?: ClaudeAgentLogin): NonNullable<QueryOptions['sandbox']>;
|
|
302
313
|
/** Loopback, as names and literals a command could hand the sandbox's proxy for the model port. */
|
|
303
314
|
export declare const LOOPBACK_NAMES: string[];
|
|
304
315
|
export declare function claudeCodeHarness(options?: ClaudeCodeHarnessOptions): Harness;
|
package/dist/harness.js
CHANGED
|
@@ -10,6 +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
14
|
import { uuidFrom } from './ids.js';
|
|
14
15
|
import { MessageQueue } from './inbox.js';
|
|
15
16
|
import { sandboxSpawn } from './spawn.js';
|
|
@@ -144,14 +145,15 @@ export function builtinTools(builtins) {
|
|
|
144
145
|
throw new TypeError("agentrun-harness-claude: builtins takes true, a list of tool names, or { type: 'preset', preset: 'claude_code' }");
|
|
145
146
|
}
|
|
146
147
|
/** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16). */
|
|
147
|
-
export function claudeSandboxSettings(machine, network) {
|
|
148
|
+
export function claudeSandboxSettings(machine, network, login) {
|
|
148
149
|
const { dirs } = machine;
|
|
149
150
|
const open = [dirs.tmp, dirs.home, dirs.cache];
|
|
150
151
|
return {
|
|
151
152
|
enabled: true,
|
|
152
153
|
failIfUnavailable: true,
|
|
153
154
|
allowUnsandboxedCommands: false,
|
|
154
|
-
|
|
155
|
+
// A person's login is the CLI's alone: no command it runs reads it.
|
|
156
|
+
filesystem: { allowWrite: [machine.root, ...open], denyRead: [dirname(dirs.config), ...(login ? [login.dir, login.profiles] : [])], allowRead: open },
|
|
155
157
|
credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
|
|
156
158
|
network: {
|
|
157
159
|
...(network === 'allow-all' ? { allowedDomains: ['*'] } : network === 'deny-all' ? { allowedDomains: [], strictAllowlist: true } : { allowedDomains: [...network.allow], strictAllowlist: true }),
|
|
@@ -232,7 +234,11 @@ export function claudeCodeHarness(options = {}) {
|
|
|
232
234
|
if (ctx.deadline === undefined)
|
|
233
235
|
log('claude-agent: the kernel gave no deadline; assuming a 300 s invocation', {});
|
|
234
236
|
const deadline = ctx.deadline ?? Date.now() + ASSUMED_INVOCATION_MS;
|
|
235
|
-
|
|
237
|
+
// On a person's login there is no model route: the CLI calls Anthropic itself, and its responses are booked from
|
|
238
|
+
// its stream (loginBooking).
|
|
239
|
+
const login = options.login;
|
|
240
|
+
const booking = login ? loginBooking(login.models, model, (error) => ctx.halt?.(error)) : undefined;
|
|
241
|
+
const handler = login ? undefined : gatewayHandler({
|
|
236
242
|
routes: CLAUDE_ROUTES,
|
|
237
243
|
models: { model, ...(smallModel ? { smallModel } : {}) },
|
|
238
244
|
providerTools,
|
|
@@ -251,7 +257,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
251
257
|
let held;
|
|
252
258
|
let configDir;
|
|
253
259
|
try {
|
|
254
|
-
const machine = (held = await sandbox.attach(ctx, { model: handler, deadline }));
|
|
260
|
+
const machine = (held = await sandbox.attach(ctx, { ...(handler ? { model: handler } : {}), deadline }));
|
|
255
261
|
if (!isBrandedMachine(machine))
|
|
256
262
|
throw sandboxRequired();
|
|
257
263
|
// The Function's side of the CLI's config dir: empty, 0700, this drive's.
|
|
@@ -488,8 +494,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
488
494
|
configDir: machine.dirs.config,
|
|
489
495
|
tmpDir: machine.dirs.tmp,
|
|
490
496
|
cacheDir: machine.dirs.cache,
|
|
491
|
-
baseUrl: machine.modelUrl,
|
|
492
|
-
token: machine.modelKey,
|
|
497
|
+
...(login ? { login: login.at } : { baseUrl: machine.modelUrl, token: machine.modelKey }),
|
|
493
498
|
model,
|
|
494
499
|
...(smallModel ? { smallModel } : {}),
|
|
495
500
|
...(sandbox.commandTimeoutMs ? { bashTimeoutMs: sandbox.commandTimeoutMs } : {}),
|
|
@@ -539,7 +544,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
539
544
|
...(skills ? { plugins: [{ type: 'local', path: skills.plugin }], skills: [...skills.names] } : {}),
|
|
540
545
|
disallowedTools: disallowed,
|
|
541
546
|
hooks,
|
|
542
|
-
...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network) } : {}),
|
|
547
|
+
...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network, login?.at) } : {}),
|
|
543
548
|
...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
|
|
544
549
|
allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
|
|
545
550
|
permissionMode: 'dontAsk',
|
|
@@ -614,6 +619,8 @@ export function claudeCodeHarness(options = {}) {
|
|
|
614
619
|
const carried = [...placed.map((p) => p.id), ...(how.covers ?? [])];
|
|
615
620
|
if (carried.length)
|
|
616
621
|
void store.whenUser(uuid).then(() => ctx.live({ type: 'message_taken', ids: carried }));
|
|
622
|
+
// On a login, the request this message makes is admitted before the CLI has it (loginBooking).
|
|
623
|
+
await booking?.sending();
|
|
617
624
|
outstanding.add(uuid);
|
|
618
625
|
input.push({
|
|
619
626
|
type: 'user',
|
|
@@ -665,9 +672,13 @@ export function claudeCodeHarness(options = {}) {
|
|
|
665
672
|
ctx.halt?.(mirrorUnmapped('a batch the Agent SDK could not keep in the log'));
|
|
666
673
|
throw ctx.signal.reason ?? mirrorUnmapped('a batch the Agent SDK could not keep in the log');
|
|
667
674
|
}
|
|
675
|
+
booking?.observe(m);
|
|
668
676
|
const end = transcript.observe(m);
|
|
669
|
-
|
|
677
|
+
// A turn on a login ends once its responses are booked.
|
|
678
|
+
if (end) {
|
|
679
|
+
await booking?.settle();
|
|
670
680
|
return end;
|
|
681
|
+
}
|
|
671
682
|
}
|
|
672
683
|
};
|
|
673
684
|
/** Steers that arrive while a turn runs go in at once, at priority `next`; the rest wait for the turn to end. */
|
|
@@ -791,6 +802,10 @@ export function claudeCodeHarness(options = {}) {
|
|
|
791
802
|
// window reach the log before the rebuilt drive reads it (bounded: a failing journal has halted the drive anyway).
|
|
792
803
|
if (!ctx.signal.aborted)
|
|
793
804
|
await Promise.race([Promise.allSettled([store.flush(), journal.flush()]), new Promise((r) => setTimeout(r, 2000).unref())]);
|
|
805
|
+
// On a login, a response the drive's end cut off is booked as it stands, and an admission no request took is closed
|
|
806
|
+
// (bounded the same way).
|
|
807
|
+
if (booking)
|
|
808
|
+
await Promise.race([booking.settle(true), new Promise((r) => setTimeout(r, 2000).unref())]);
|
|
794
809
|
// Nothing the model started outlives the drive: the session's processes in the VM are killed (the VM and the Drive stay).
|
|
795
810
|
if (held)
|
|
796
811
|
await held.close().catch(() => { });
|
package/dist/host/machine.d.ts
CHANGED
|
@@ -24,8 +24,9 @@ export interface LocalMachineOptions {
|
|
|
24
24
|
confine?: ConfineChild;
|
|
25
25
|
/** How a child is tied to this process (default what the machine supports; tests force the shim). */
|
|
26
26
|
parentWatch?: ParentWatch;
|
|
27
|
-
/** The model proxy: the runner's hooks, the provider's price, and the session's tools and limits.
|
|
28
|
-
|
|
27
|
+
/** The model proxy: the runner's hooks, the provider's price, and the session's tools and limits. None when the CLI
|
|
28
|
+
* runs on a person's own login (login.ts): the machine then starts no proxy, and holds no model URL or key. */
|
|
29
|
+
proxy?: {
|
|
29
30
|
hooks: ModelProxyHooks;
|
|
30
31
|
tools: readonly string[];
|
|
31
32
|
/** The CLI's own tools the session has (`Skill`, with skills; `WebSearch`), offered beside its tools. */
|
package/dist/host/machine.js
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
// - each child runs in its own process group, which kill() and close() end whole, and dies with this process: started
|
|
10
10
|
// with a watch on its parent (./host's parentWatched, inside the host's confinement), so a host that is SIGKILLed,
|
|
11
11
|
// and runs no close, leaves no CLI behind;
|
|
12
|
-
// - the model proxy (@parcha/agentrun-kernel/host, with the Anthropic policy) starts with the machine and stops with it
|
|
12
|
+
// - the model proxy (@parcha/agentrun-kernel/host, with the Anthropic policy) starts with the machine and stops with it;
|
|
13
|
+
// a machine whose CLI runs on a person's own login (login.ts) has none.
|
|
13
14
|
import { spawn as spawnChild } from "node:child_process";
|
|
14
15
|
import { randomBytes } from "node:crypto";
|
|
15
16
|
import { mkdirSync } from "node:fs";
|
|
@@ -104,8 +105,10 @@ const inside = (path, base) => path === base || path.startsWith(base + sep);
|
|
|
104
105
|
export function localMachine(options) {
|
|
105
106
|
const from = options.env ?? process.env;
|
|
106
107
|
return async ({ ctx, model }) => {
|
|
107
|
-
if (!model)
|
|
108
|
+
if (options.proxy && !model)
|
|
108
109
|
throw new Error("agentrun-harness-claude: the harness gave the machine no model route");
|
|
110
|
+
if (!options.proxy && model)
|
|
111
|
+
throw new Error("agentrun-harness-claude: a machine with no model proxy takes no model route");
|
|
109
112
|
const base = normalize(options.dir);
|
|
110
113
|
if (!isAbsolute(base))
|
|
111
114
|
throw new Error("agentrun-harness-claude: the session directory must be an absolute path");
|
|
@@ -118,41 +121,43 @@ export function localMachine(options) {
|
|
|
118
121
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
119
122
|
// git stops at the session's directory and, for a workspace outside it, at the workspace's parent.
|
|
120
123
|
const ceiling = [base, ...(inside(root, base) ? [] : [dirname(root)])].join(":");
|
|
121
|
-
const route = model.options;
|
|
122
124
|
const key = randomBytes(32).toString("base64url");
|
|
123
125
|
// What the provider does with a token count (a free route it may not serve), said once per session, a status only.
|
|
124
126
|
let counted = false;
|
|
125
127
|
// Whether the provider has refused the session's key (one paid 401): said once.
|
|
126
128
|
let refused = false;
|
|
127
|
-
const
|
|
129
|
+
const route = model?.options;
|
|
130
|
+
const po = options.proxy;
|
|
131
|
+
// No proxy on a person's own login: the CLI calls its provider itself.
|
|
132
|
+
const proxy = !po || !route ? undefined : await startModelProxy({
|
|
128
133
|
policy: anthropicPolicy({
|
|
129
134
|
model: route.models.model,
|
|
130
135
|
...(route.models.smallModel ? { smallModel: route.models.smallModel } : {}),
|
|
131
|
-
tools:
|
|
132
|
-
...(
|
|
133
|
-
...(
|
|
134
|
-
...(
|
|
135
|
-
...(
|
|
136
|
-
...(
|
|
137
|
-
onThinkingDisabled: ({ model: main }) =>
|
|
136
|
+
tools: po.tools,
|
|
137
|
+
...(po.builtins?.length ? { builtins: po.builtins } : {}),
|
|
138
|
+
...(po.maxOutputTokens ? { maxOutputTokens: po.maxOutputTokens } : {}),
|
|
139
|
+
...(po.webSearch ? { webSearch: true, ...(po.webSearchAllowance !== undefined ? { webSearchAllowance: po.webSearchAllowance } : {}) } : {}),
|
|
140
|
+
...(po.auth ? { auth: po.auth } : {}),
|
|
141
|
+
...(po.toolSearch ? { toolSearch: true } : {}),
|
|
142
|
+
onThinkingDisabled: ({ model: main }) => po.log?.("claude-agent: thinking.disabled", { model: main }),
|
|
138
143
|
}),
|
|
139
|
-
hooks:
|
|
144
|
+
hooks: po.hooks,
|
|
140
145
|
model: route.models.model,
|
|
141
146
|
origin: route.target,
|
|
142
147
|
credential: async () => (await route.credential()) ?? "",
|
|
143
|
-
...(
|
|
144
|
-
...(
|
|
145
|
-
...(
|
|
148
|
+
...(po.price ? { price: withWebSearches(po.price) } : {}),
|
|
149
|
+
...(po.headers ? { headers: po.headers } : {}),
|
|
150
|
+
...(po.log ? { log: po.log } : {}),
|
|
146
151
|
// The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
|
|
147
152
|
onFiltered: (message) => ctx.halt?.(new Error(message)),
|
|
148
153
|
onResponse: ({ path, status }) => {
|
|
149
154
|
if (path !== "/v1/messages/count_tokens" || counted)
|
|
150
155
|
return;
|
|
151
156
|
counted = true;
|
|
152
|
-
|
|
157
|
+
po.log?.("claude-agent: the provider answered count_tokens", { status });
|
|
153
158
|
},
|
|
154
159
|
fetch: async (input, init) => {
|
|
155
|
-
const answer = await (
|
|
160
|
+
const answer = await (po.fetch ?? fetch)(input, init);
|
|
156
161
|
// A paid request the provider answers 401 is the key refused: said to the harness once, with the provider's words
|
|
157
162
|
// (what of its body comes within REFUSAL_WAIT_MS, never waiting on one that does not end).
|
|
158
163
|
if (answer.status === 401 && route.onKeyRefused && !refused && new URL(String(input instanceof Request ? input.url : input)).pathname.endsWith("/v1/messages")) {
|
|
@@ -178,8 +183,7 @@ export function localMachine(options) {
|
|
|
178
183
|
root,
|
|
179
184
|
dirs,
|
|
180
185
|
signal: lost.signal,
|
|
181
|
-
modelUrl: proxy.url,
|
|
182
|
-
modelKey: key,
|
|
186
|
+
...(proxy ? { modelUrl: proxy.url, modelKey: key } : {}),
|
|
183
187
|
notes: [],
|
|
184
188
|
from,
|
|
185
189
|
start,
|
|
@@ -194,7 +198,7 @@ export function localMachine(options) {
|
|
|
194
198
|
proc.kill("SIGKILL");
|
|
195
199
|
await Promise.all([...children].map((p) => p.exited));
|
|
196
200
|
lost.abort();
|
|
197
|
-
await proxy
|
|
201
|
+
await proxy?.close();
|
|
198
202
|
},
|
|
199
203
|
};
|
|
200
204
|
return brandMachine(machine);
|
package/dist/host/process.d.ts
CHANGED
|
@@ -35,9 +35,10 @@ export interface SessionMachine {
|
|
|
35
35
|
readonly root: string;
|
|
36
36
|
readonly dirs: Readonly<Record<CacheDir, string>>;
|
|
37
37
|
readonly signal: AbortSignal;
|
|
38
|
-
/** The model proxy's base URL (loopback), and the per-session key it admits.
|
|
39
|
-
|
|
40
|
-
readonly
|
|
38
|
+
/** The model proxy's base URL (loopback), and the per-session key it admits. Neither on a machine with no proxy, whose
|
|
39
|
+
* CLI runs on a person's own login. */
|
|
40
|
+
readonly modelUrl?: string;
|
|
41
|
+
readonly modelKey?: string;
|
|
41
42
|
/** What the model must hear about this machine (none locally), and its acknowledgement key. */
|
|
42
43
|
readonly notes: readonly string[];
|
|
43
44
|
readonly notesKey?: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -7,5 +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";
|
|
11
|
+
export type { ClaudeAgentLogin, ClaudeLoginStatus } from "./login.js";
|
|
10
12
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
|
|
11
13
|
export type { ServedTool } from "./host/tool-server.js";
|
package/dist/index.js
CHANGED
|
@@ -4,4 +4,5 @@ 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
8
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
|
package/dist/login.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ModelPort } from "@parcha/agentrun-kernel";
|
|
2
|
+
/** Where the pinned CLI keeps a login: its credentials file's directory (`CLAUDE_SECURESTORAGE_CONFIG_DIR`) and its
|
|
3
|
+
* Anthropic profiles (`ANTHROPIC_CONFIG_DIR`). The CLI reads and writes both; nothing else does. */
|
|
4
|
+
export interface ClaudeAgentLogin {
|
|
5
|
+
/** The directory of the CLI's credentials file. */
|
|
6
|
+
dir: string;
|
|
7
|
+
/** The directory of the CLI's Anthropic profiles. */
|
|
8
|
+
profiles: string;
|
|
9
|
+
}
|
|
10
|
+
/** The variables that point the CLI at `login`: never its config dir (`CLAUDE_CONFIG_DIR`), which the Agent SDK copies
|
|
11
|
+
* a credentials file out of when it resumes a session. */
|
|
12
|
+
export declare function loginEnv(login: ClaudeAgentLogin): Record<string, string>;
|
|
13
|
+
/** The line a person runs to sign the CLI in at `login` (the CLI opens a browser itself). Its config dir is the login's
|
|
14
|
+
* too, so a CLI older than the credentials variable keeps the login there as well. */
|
|
15
|
+
export declare const loginCommand: (login: ClaudeAgentLogin, cli?: string) => string;
|
|
16
|
+
/** What the CLI says of its login: whether it is signed in, how, and the account's own words when it gives them. */
|
|
17
|
+
export interface ClaudeLoginStatus {
|
|
18
|
+
signedIn: boolean;
|
|
19
|
+
/** How the CLI signs in (`claude.ai`, `oauth_token`, `api_key`, ...). */
|
|
20
|
+
method?: string;
|
|
21
|
+
email?: string;
|
|
22
|
+
organization?: string;
|
|
23
|
+
/** The account's plan (`max`, `pro`, `team`, ...). */
|
|
24
|
+
plan?: string;
|
|
25
|
+
}
|
|
26
|
+
/** `claude auth status --json`'s answer, read for the fields above alone; undefined when it is no such answer. */
|
|
27
|
+
export declare function parseLoginStatus(stdout: string): ClaudeLoginStatus | undefined;
|
|
28
|
+
/** The longest a status check may take. */
|
|
29
|
+
export declare const LOGIN_STATUS_MS = 15000;
|
|
30
|
+
/** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, in an empty home and config dir of its
|
|
31
|
+
* own (removed after), with only PATH and the login's two variables beside them. Throws when the CLI gives no answer
|
|
32
|
+
* that reads as one. */
|
|
33
|
+
export declare function claudeLoginStatus(cli: string, login: ClaudeAgentLogin, options?: {
|
|
34
|
+
timeoutMs?: number;
|
|
35
|
+
path?: string;
|
|
36
|
+
}): Promise<ClaudeLoginStatus>;
|
|
37
|
+
/** Start the CLI's own sign-in at `login` (`auth login`): it opens a browser on this machine and keeps what it gets in its
|
|
38
|
+
* own files. Nothing of it is read here: its output goes nowhere, and it is ended after `timeoutMs`. */
|
|
39
|
+
export declare function startClaudeLogin(cli: string, login: ClaudeAgentLogin, options?: {
|
|
40
|
+
timeoutMs?: number;
|
|
41
|
+
path?: string;
|
|
42
|
+
home?: string;
|
|
43
|
+
display?: Readonly<Record<string, string | undefined>>;
|
|
44
|
+
}): void;
|
|
45
|
+
/** How a session on a login books its requests: no proxy sees them, so each response the CLI streams is booked from its
|
|
46
|
+
* own events, billed to the plan, at no price here. No proxy can hold a request back either, so a request is admitted
|
|
47
|
+
* before the CLI can send it: when a message goes to the CLI (`sending`), and when a response stops for its tool calls,
|
|
48
|
+
* whose results the CLI sends straight back. A refusal there (a turn limit, say) halts the drive while the CLI has yet to
|
|
49
|
+
* send. A response with no admission ahead of it (one the CLI sent on its own) is admitted at its `message_start`. Each
|
|
50
|
+
* is booked at its `message_stop`; one the turn's end leaves open is booked as it stands, and an admission no request
|
|
51
|
+
* took is closed as never sent when the drive ends (`settle(true)`). */
|
|
52
|
+
export declare function loginBooking(models: Pick<ModelPort, "beforeRequest" | "afterRequest">, model: string, halt: (error: Error) => void): {
|
|
53
|
+
/** A message is about to go to the CLI: admit the request it will make, and settle when it is admitted (a refusal
|
|
54
|
+
* rejects, the drive halted already), so the message goes only once its request may. */
|
|
55
|
+
sending(): Promise<void>;
|
|
56
|
+
/** One message of the SDK's stream. */
|
|
57
|
+
observe(message: unknown): void;
|
|
58
|
+
/** Book what is open and wait for every booking to be written. `ended`: the drive is over, so an admission no request
|
|
59
|
+
* took is closed as never sent. */
|
|
60
|
+
settle(ended?: boolean): Promise<void>;
|
|
61
|
+
};
|
package/dist/login.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
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
|
+
// Written for AgentRun.
|
|
3
|
+
//
|
|
4
|
+
// The pinned CLI keeps the login where it always does, in its own files, and calls Anthropic with it itself. AgentRun
|
|
5
|
+
// never reads, copies, stores or relays it: a session only tells the CLI where its login is (two directories, by
|
|
6
|
+
// environment), and the host asks the CLI whether it is signed in (`claude auth status`), reading nothing but that answer.
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
/** The variables that point the CLI at `login`: never its config dir (`CLAUDE_CONFIG_DIR`), which the Agent SDK copies
|
|
12
|
+
* a credentials file out of when it resumes a session. */
|
|
13
|
+
export function loginEnv(login) {
|
|
14
|
+
return { CLAUDE_SECURESTORAGE_CONFIG_DIR: login.dir, ANTHROPIC_CONFIG_DIR: login.profiles };
|
|
15
|
+
}
|
|
16
|
+
/** The line a person runs to sign the CLI in at `login` (the CLI opens a browser itself). Its config dir is the login's
|
|
17
|
+
* too, so a CLI older than the credentials variable keeps the login there as well. */
|
|
18
|
+
export const loginCommand = (login, cli = "claude") => `CLAUDE_CONFIG_DIR=${shellWord(login.dir)} CLAUDE_SECURESTORAGE_CONFIG_DIR=${shellWord(login.dir)} ANTHROPIC_CONFIG_DIR=${shellWord(login.profiles)} ${shellWord(cli)} auth login`;
|
|
19
|
+
const shellWord = (word) => (/^[A-Za-z0-9_./:@%+=-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`);
|
|
20
|
+
const text = (value) => (typeof value === "string" && value.trim() ? value.trim().slice(0, 200) : undefined);
|
|
21
|
+
/** `claude auth status --json`'s answer, read for the fields above alone; undefined when it is no such answer. */
|
|
22
|
+
export function parseLoginStatus(stdout) {
|
|
23
|
+
let body;
|
|
24
|
+
try {
|
|
25
|
+
const parsed = JSON.parse(stdout);
|
|
26
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
27
|
+
return undefined;
|
|
28
|
+
body = parsed;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
if (typeof body.loggedIn !== "boolean")
|
|
34
|
+
return undefined;
|
|
35
|
+
const method = text(body.authMethod);
|
|
36
|
+
const email = text(body.email);
|
|
37
|
+
const organization = text(body.orgName) ?? text(body.organization);
|
|
38
|
+
const plan = text(body.subscriptionType) ?? text(body.plan);
|
|
39
|
+
return { signedIn: body.loggedIn && method !== "none", ...(method ? { method } : {}), ...(email ? { email } : {}), ...(organization ? { organization } : {}), ...(plan ? { plan } : {}) };
|
|
40
|
+
}
|
|
41
|
+
/** The longest a status check may take. */
|
|
42
|
+
export const LOGIN_STATUS_MS = 15_000;
|
|
43
|
+
/** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, in an empty home and config dir of its
|
|
44
|
+
* own (removed after), with only PATH and the login's two variables beside them. Throws when the CLI gives no answer
|
|
45
|
+
* that reads as one. */
|
|
46
|
+
export async function claudeLoginStatus(cli, login, options = {}) {
|
|
47
|
+
const scratch = mkdtempSync(join(tmpdir(), "agentrun-claude-status-"));
|
|
48
|
+
try {
|
|
49
|
+
const stdout = await new Promise((resolve, reject) => {
|
|
50
|
+
const child = spawn(cli, ["auth", "status", "--json"], {
|
|
51
|
+
env: { PATH: options.path ?? process.env.PATH ?? "/usr/bin:/bin", HOME: scratch, CLAUDE_CONFIG_DIR: scratch, XDG_CONFIG_HOME: join(scratch, ".config"), ...loginEnv(login), DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" },
|
|
52
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
53
|
+
timeout: options.timeoutMs ?? LOGIN_STATUS_MS,
|
|
54
|
+
});
|
|
55
|
+
let out = "";
|
|
56
|
+
child.stdout.setEncoding("utf8");
|
|
57
|
+
child.stdout.on("data", (chunk) => {
|
|
58
|
+
if (out.length < 64 * 1024)
|
|
59
|
+
out += chunk;
|
|
60
|
+
});
|
|
61
|
+
child.once("error", reject);
|
|
62
|
+
// The CLI exits 1 when signed out, its answer said all the same.
|
|
63
|
+
child.once("close", () => resolve(out));
|
|
64
|
+
});
|
|
65
|
+
const status = parseLoginStatus(stdout.trim());
|
|
66
|
+
if (!status)
|
|
67
|
+
throw new Error("the claude CLI gave no login status");
|
|
68
|
+
return status;
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Start the CLI's own sign-in at `login` (`auth login`): it opens a browser on this machine and keeps what it gets in its
|
|
75
|
+
* own files. Nothing of it is read here: its output goes nowhere, and it is ended after `timeoutMs`. */
|
|
76
|
+
export function startClaudeLogin(cli, login, options = {}) {
|
|
77
|
+
const scratch = mkdtempSync(join(tmpdir(), "agentrun-claude-login-"));
|
|
78
|
+
// What a browser needs to open on this desktop, when the server has it.
|
|
79
|
+
const display = Object.fromEntries(["DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "BROWSER"].flatMap((name) => {
|
|
80
|
+
const value = options.display?.[name];
|
|
81
|
+
return typeof value === "string" ? [[name, value]] : [];
|
|
82
|
+
}));
|
|
83
|
+
const child = spawn(cli, ["auth", "login", "--claudeai"], {
|
|
84
|
+
env: { PATH: options.path ?? process.env.PATH ?? "/usr/bin:/bin", HOME: options.home ?? scratch, CLAUDE_CONFIG_DIR: scratch, ...display, ...loginEnv(login), DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1" },
|
|
85
|
+
stdio: "ignore",
|
|
86
|
+
timeout: options.timeoutMs ?? 10 * 60_000,
|
|
87
|
+
});
|
|
88
|
+
child.once("error", () => { });
|
|
89
|
+
child.once("close", () => rmSync(scratch, { recursive: true, force: true }));
|
|
90
|
+
}
|
|
91
|
+
const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
92
|
+
/** How a session on a login books its requests: no proxy sees them, so each response the CLI streams is booked from its
|
|
93
|
+
* own events, billed to the plan, at no price here. No proxy can hold a request back either, so a request is admitted
|
|
94
|
+
* before the CLI can send it: when a message goes to the CLI (`sending`), and when a response stops for its tool calls,
|
|
95
|
+
* whose results the CLI sends straight back. A refusal there (a turn limit, say) halts the drive while the CLI has yet to
|
|
96
|
+
* send. A response with no admission ahead of it (one the CLI sent on its own) is admitted at its `message_start`. Each
|
|
97
|
+
* is booked at its `message_stop`; one the turn's end leaves open is booked as it stands, and an admission no request
|
|
98
|
+
* took is closed as never sent when the drive ends (`settle(true)`). */
|
|
99
|
+
export function loginBooking(models, model, halt) {
|
|
100
|
+
let open;
|
|
101
|
+
let ahead;
|
|
102
|
+
let booked = Promise.resolve();
|
|
103
|
+
const refused = Symbol("refused");
|
|
104
|
+
const stopped = (error) => halt(error instanceof Error ? error : new Error(String(error)));
|
|
105
|
+
const admit = () => {
|
|
106
|
+
const ticket = (async () => models.beforeRequest({ model }))();
|
|
107
|
+
ticket.catch(stopped);
|
|
108
|
+
return ticket;
|
|
109
|
+
};
|
|
110
|
+
const admitAhead = () => {
|
|
111
|
+
ahead ??= admit();
|
|
112
|
+
};
|
|
113
|
+
const after = (ticket, usage, ended) => {
|
|
114
|
+
booked = booked.then(async () => {
|
|
115
|
+
const taken = await ticket.catch(() => refused);
|
|
116
|
+
// Refused at its admission: nothing to book (the drive is halted already).
|
|
117
|
+
if (taken === refused)
|
|
118
|
+
return;
|
|
119
|
+
await models.afterRequest(usage, taken, ended);
|
|
120
|
+
}).catch(stopped);
|
|
121
|
+
};
|
|
122
|
+
const book = () => {
|
|
123
|
+
const entry = open;
|
|
124
|
+
open = undefined;
|
|
125
|
+
if (!entry)
|
|
126
|
+
return;
|
|
127
|
+
after(entry.ticket, { ...entry.usage, usd: null, billing: "plan" }, { end: "answered", usd: null });
|
|
128
|
+
if (entry.tools)
|
|
129
|
+
admitAhead();
|
|
130
|
+
};
|
|
131
|
+
const take = (usage, given) => {
|
|
132
|
+
const input = count(given?.input_tokens);
|
|
133
|
+
const output = count(given?.output_tokens);
|
|
134
|
+
const cacheRead = count(given?.cache_read_input_tokens);
|
|
135
|
+
const cacheWrite = count(given?.cache_creation_input_tokens);
|
|
136
|
+
return { ...usage, ...(input === undefined ? {} : { input }), ...(output === undefined ? {} : { output }), ...(cacheRead === undefined ? {} : { cacheRead }), ...(cacheWrite === undefined ? {} : { cacheWrite }) };
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
/** A message is about to go to the CLI: admit the request it will make, and settle when it is admitted (a refusal
|
|
140
|
+
* rejects, the drive halted already), so the message goes only once its request may. */
|
|
141
|
+
async sending() {
|
|
142
|
+
admitAhead();
|
|
143
|
+
await ahead;
|
|
144
|
+
},
|
|
145
|
+
/** One message of the SDK's stream. */
|
|
146
|
+
observe(message) {
|
|
147
|
+
const m = message;
|
|
148
|
+
if (m?.type !== "stream_event" || !m.event)
|
|
149
|
+
return;
|
|
150
|
+
const event = m.event;
|
|
151
|
+
if (event.type === "message_start") {
|
|
152
|
+
book();
|
|
153
|
+
const ticket = ahead ?? admit();
|
|
154
|
+
ahead = undefined;
|
|
155
|
+
open = { ticket, usage: take({ input: 0, output: 0, billing: "plan" }, event.message?.usage), tools: false };
|
|
156
|
+
}
|
|
157
|
+
else if (event.type === "message_delta" && open) {
|
|
158
|
+
open.usage = take(open.usage, event.usage);
|
|
159
|
+
if (event.delta?.stop_reason === "tool_use")
|
|
160
|
+
open.tools = true;
|
|
161
|
+
}
|
|
162
|
+
else if (event.type === "message_stop") {
|
|
163
|
+
book();
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
/** Book what is open and wait for every booking to be written. `ended`: the drive is over, so an admission no request
|
|
167
|
+
* took is closed as never sent. */
|
|
168
|
+
async settle(ended = false) {
|
|
169
|
+
book();
|
|
170
|
+
if (ended && ahead) {
|
|
171
|
+
after(ahead, { input: 0, output: 0, usd: null, billing: "plan" }, { end: "nothing", label: "never_left" });
|
|
172
|
+
ahead = undefined;
|
|
173
|
+
}
|
|
174
|
+
await booked;
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
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.45",
|
|
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.45"
|
|
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.45"
|
|
81
81
|
}
|
|
82
82
|
}
|