@parcha/agentrun-harness-claude 0.1.0-beta.56 → 0.1.0-beta.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,53 @@
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
+
20
+ ## 0.1.0-beta.57 (2026-11-24)
21
+
22
+ **Breaking:**
23
+
24
+ - The harness's Claude login (`ClaudeAgentLogin`) no longer has the `shared` flag 0.1.0-beta.56 gave it. Every status check now runs the CLI on a copy of the account file, as a check on a login marked `shared` did, so the flag has nothing left to choose. A host that set it drops it. TypeScript flags `shared` in a login written as an object literal as an unknown property; from JavaScript it is ignored. <!-- changes/claude-login-no-shared.md -->
25
+ - `startClaudeLogin` no longer takes a `home` option. A host that calls it with `{ home }` sets that home on the login as `userHome` instead (`startClaudeLogin(cli, { ...login, userHome: home })`); the status check and a run on macOS read the same field, so one home serves all three. TypeScript flags a `home` option as an unknown property; from JavaScript it is ignored, and the sign-in runs in the login's own `home`, else the OS's home. <!-- changes/claude-login-start-home.md -->
26
+ - `claudeLoginStatus` no longer takes a `home` option. A host that calls it with `{ home }` sets that home on the login as `userHome` instead (`claudeLoginStatus(cli, { ...login, userHome: home })`); the sign-in and a run on macOS read the same field, so one home serves all three. TypeScript flags a `home` option as an unknown property; from JavaScript it is ignored, and the check runs in the login's own `home`, else the OS's home. <!-- changes/claude-login-status-home.md -->
27
+
28
+ **Changes:**
29
+
30
+ - `web_search`'s default, `auto`, is now agentrun's own search on every harness: Parallel where the server holds a Parallel key, else keyless Firecrawl with keyless Exa behind it. Before, `auto` on codex was Codex's own live search, and on pi with a direct `anthropic/*` or `openai/*` model it was one request to that provider's hosted search. Both now go through agentrun's `web_search` instead. This changes what a codex or pi search costs and returns: Parallel's fee per search on the server's key, or keyless Firecrawl at no charge, in place of the provider's per-search fee, and those providers' results in place of Codex's or the model provider's. <!-- changes/web-search-auto-ours.md -->
31
+ `native` stays a provider you can pick, for an agent (`definition.tool_settings`) or the server (`PUT /settings/tools`). Picked, it still turns on Claude's WebSearch, Codex's live search or pi's hosted search, and it is unavailable where it was before (behind a gateway, on OpenRouter, under a spend cap). To keep the old behaviour on codex or pi, pick `native`. claude-agent's `auto` is unchanged.
32
+ The openapi document's `web_search` provider list is unchanged (`native` stays in it). Only `auto`'s description and capabilities' `resolves` and `why` change: on codex and pi, `resolves` reads `parallel` or `firecrawl-keyless` where it read `native`. A run that started before the upgrade keeps the plane it launched with, `native` included, for its life.
33
+ A claude-agent session now also names the claude CLI's WebFetch in its `disallowedTools` (`CLAUDE_AGENT_ALSO_OFF`), as it names WebSearch. WebFetch was already off three ways: the session's tools list is empty, the PreToolUse hook denies it, and the CLI's sandbox network is deny-all. Naming it keeps the host's `web_fetch` the session's only fetch even if one of those changes.
34
+ - A claude-agent run on a clock the host set (the adapter's `now`; in serve, a template eval case's `now:`) is now told that clock's day by the Claude CLI too. The CLI dates the session from the machine's clock in its own lines ("Today's date is 2026-11-24.", and "Today's date is now ..." on a later day), and has no setting for it. On a case clock set to another day, the model was told both days and went by the CLI's, so every date a grader checked against the case clock failed. The session's model proxy now rewrites those two lines to the clock's day in the run's zone (`zone`), in the CLI's own `system` message only, where the CLI puts them. The person's prompt, the model's replies, tool results and the app's system prompt are never rewritten, so a date someone wrote, quoted or read reaches the model as it was. A run with no `now`, which is every production run, is unchanged. <!-- changes/claude-agent-case-clock-date.md -->
35
+ A session on a person's Claude login has no model proxy, so there the CLI's lines keep the machine's date. Run clocked cases on the provider route (an API key or gateway).
36
+ - Settings → Model keys' login on this machine: fixes to the claude CLI's sign-in and to its status check. <!-- changes/claude-sign-in-followups.md -->
37
+ - The line shown for "this machine's" login on the CLI's default folder starts a CLI whose path holds `=` (a data folder such as `/data/a=b`): it still clears the CLI's folder variables with 0.1.0-beta.56's `env -u CLAUDE_CONFIG_DIR -u CLAUDE_SECURESTORAGE_CONFIG_DIR ...`, and such a path goes to `sh -c 'exec "$0" auth login'` as its `$0`. Before, env read that path as one more variable, and the CLI never started. The line runs alike pasted into sh, bash, zsh, fish or tcsh; env skips a `claude` alias or function of the person's shell.
38
+ - `PUT /v2/settings/claude-login` that moves the login to the other `place` ends a sign-in the server started that still waits, and answers once its CLI is gone; before, that CLI kept waiting to sign in at the old place. A `PUT` at the same place leaves it waiting. A move or a turn-off that lands while a sign-in is starting now waits for that start and then ends it, or comes first, and the sign-in starts on what it saved; before, the sign-in could start after it with the old setting, at the old place or for a login that was off.
39
+ - "This machine's" login honours `CLAUDE_SECURESTORAGE_CONFIG_DIR` in the server's environment, as the person's own claude CLI with that variable does: the status check, the sign-in, the shown line and a run keep the tokens in that folder (on macOS the Keychain item named from it). Set and empty, it means `~/.claude` and, on macOS, the Keychain item with no suffix, which the CLI gets as an empty value there. A relative value is not taken. The view says it as `machine.credentials`, and the console names it under the folder. Before, the server ignored it and read the tokens from the config folder, so a person whose CLI sets it read signed out. The harness's login takes `secure` and `unsuffixed` for it, and `claudeSignInEnv` and `claudeLoginCommand` take the platform, as `claudeLoginEnv` does. A run with the CLI's own sandbox on denies its commands reading that folder too, as it does the login's own folders; on macOS an empty value names a Keychain item, and adds nothing.
40
+ - The sign-in's CLI dies with the server that started it: `startClaudeLogin` starts it under the kernel's parent watch (`parentWatched`: the parent-death signal through `setpriv` on Linux, else the watching shim), as a session's CLI is. Before, a server killed outright (SIGKILL, the OOM killer) left `auth login` running with no limit, holding the browser's callback port. A CLI path that is no program still reads as never started, in the spawn's words. `startClaudeLogin` takes `watch` to choose the watch. A sign-in stopped or ended at its limit under the shim ends only once its CLI is gone, though the CLI ignores SIGTERM: the shim kills it 2 s after passing the TERM on, before the server's own kill 5 s after it, which reaches the shim alone.
41
+ - The login's setting names the machine it was turned on for by an id the server makes once in its data folder (`machine-id`, 0600) and reads back on every later start, in place of the hostname. Before, a laptop's hostname changed with its network, so a login turned on at home read "turned on for another machine" elsewhere, and its runs asked for a key. Two data folders are two machines.
42
+ - Settings → Model keys: Turn on says why it is grey while "Only I run agents on this server" is not ticked, beside it and as its description for a screen reader.
43
+ - The Playground's "No model yet" bar is gone for an agent on Claude Agent (`claude-agent`) while the login is on and reads signed in, since Claude Agent runs on it. Before, it offered ChatGPT or a key as if no model were there. An agent on another harness keeps the bar. The bar reads the revision picked in the Playground, which the run will use, and the agent's current one when none is picked; a picked revision whose definition the console does not hold keeps it. The bar stays for a run in a sandbox box, by the revision's own place or the server's default one, since only a run on the runner uses the login. It stays too for a revision that names a model the login does not serve: only Anthropic's own models (or none) run on it, and an OpenRouter model, Anthropic's included, still needs `OPENROUTER_API_KEY`. The console reads the login once, again on leaving Settings (where a sign-in finishes) and after a run starts, never on each move between pages, since each read runs `claude auth status` on the server.
44
+ - The status check copies the account file only when it is a regular file of at most 32 MiB, read without holding up the server: it opens the file without waiting (`O_NONBLOCK`) and checks what it opened before reading. Before, a FIFO in its place stopped the whole server until something wrote to it, and a device such as `/dev/zero` or a huge file was read whole into memory. A FIFO, a device, a folder or a bigger file is copied as nothing, as a file that doesn't parse is. A link is still followed, since dotfile managers often link `~/.claude.json`.
45
+ - Every status check runs the CLI on a copy of the account file in a folder of its own, AgentRun's own login folder included, never on the file itself, so a check never has the CLI rewrite the login's `.claude.json`. In 0.1.0-beta.56 the check on AgentRun's own folder, and on any harness login not marked `shared`, read the login's folder as its config dir, as that release's entry says; none does now. The harness login's `shared` flag is gone (see its breaking entry).
46
+ - A server sweeps the status checks' folders (`agentrun-claude-status-*` in the temporary folder) as it starts, when the Claude login is allowed on it: the ones this user owns whose check has ended: each check writes in its folder when it ends at the latest (its limit, whatever the caller gave, and 2 s), and the sweep takes the folder more than 15 s after that; a folder with no such end, or one that lies before its file was written (empty, a partial write, a negative), is taken once changed more than twice the status check's limit ago. `claudeLoginStatus` throws a `RangeError` for a `timeoutMs` that is no whole number of ms from 1 to 2^31 - 1, before it starts the CLI. A check that was killed mid-way (SIGKILL runs no clean-up) left its folder, with a copy of the account file in it, until the machine cleared its temporary folder. The harness exports `sweepClaudeStatusFolders`.
47
+ - The status check ends at its limit whatever the CLI does: it asks the CLI to go (SIGTERM), kills it (SIGKILL) 1 s later, and waits at most 1 s more for the CLI's output, then reads as timed out. Before, it sent one SIGTERM and waited for the output's pipe to close, so a CLI that ignored the TERM, or a process it started that held its output open, kept the check, and the run's claim behind it, waiting for ever.
48
+ - The person's home is read once, where the server makes the login (the server's `HOME` when it is an absolute path, else the OS's home), and the status check, the sign-in and a run on macOS all take it from the login's new `userHome`. Before, the sign-in took the server's `HOME` while the status check and a run took the OS's home, so a server started with another `HOME` signed in at one home and checked another. `claudeLoginStatus` and `startClaudeLogin` no longer take the `home` option 0.1.0-beta.56 gave them (see their breaking entries).
49
+ - A Claude-plan run no longer fails because the login's status check was slow. On a loaded machine the claude CLI could take longer than the check's 15 s, and the run was refused as "could not say whether its login is signed in" though the login was fine. Now a check that gives no answer (the CLI outlasts it, or answers nothing that reads as a status) is asked once more; if that one gives no answer either, the run goes on when the same login read signed in within the last 10 minutes on this server (at a run's check or in Settings), and is refused as before otherwise, in words that say why (a check that timed out says so, and after how long). Any other failure of the check, such as no CLI at its path, refuses the run at once in its own words, as before. A signed-out answer still refuses the run at once, and is never asked again. The harness's `claudeLoginStatus` throws `ClaudeLoginTimedOut` (`code: "timed_out"`) when the CLI outlasts its limit, and `ClaudeLoginNoStatus` (`code: "no_status"`) when it answers in time with no status.
50
+ - On macOS, a run on the login runs in the person's home, so the claude CLI writes its cache and logs under their `~/Library/Caches/claude-cli-nodejs`, where they stay after the run. Removing that folder is safe.
51
+
5
52
  ## 0.1.0-beta.56 (2026-11-24)
6
53
 
7
54
  - Settings → Model keys' "Open the CLI's sign-in here" signs the claude CLI in at the login's own folder, so the login reads signed in afterwards. The sign-in ran with a temporary config dir, where `auth login` wrote the account it signed in (`.claude.json`); that folder was removed when the sign-in ended, and the login's folder stayed without it, so AgentRun kept saying "not signed in" while running the shown command by hand worked. The sign-in, the shown command and the status check now take their variables from one function (`claudeSignInEnv`), and the status check reads the login's folder as its config dir. <!-- changes/claude-sign-in-folder.md -->
package/dist/adapter.d.ts CHANGED
@@ -2,11 +2,13 @@ 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
- /** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
10
+ /** The pinned CLI's tools off by name in every session (WebSearch unless `webSearch`): those the copied harness leaves
11
+ * undecided, and WebFetch, which fetches from the CLI's own process where the host's web_fetch is the session's. */
10
12
  export declare const CLAUDE_AGENT_ALSO_OFF: readonly string[];
11
13
  /** The local plugin the session's skills are served from: the model sees each as `agentrun:<name>`, and may load it by
12
14
  * that name or, unless the CLI has a command or skill of that name (`CLAUDE_AGENT_CLI_SKILL_NAMES`), by its bare one. */
@@ -46,8 +48,9 @@ export interface ClaudeAgentAdapterOptions {
46
48
  provider?: ClaudeAgentProvider;
47
49
  /** A person's own login on this machine (login.ts), which the CLI runs on in place of a provider: it calls Anthropic
48
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
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;
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;
51
54
  /** Start the CLI under the host's confinement (its own `confine()`, a `setpriv --no-new-privs` prefix, say). It may
52
55
  * only add in front of the pinned binary and its arguments, and never touches its environment. */
53
56
  confine?: ConfineChild;
@@ -94,12 +97,18 @@ export interface ClaudeAgentAdapterOptions {
94
97
  standIn?: {
95
98
  command: string;
96
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;
97
102
  /** How hard the model thinks when a node names no level (its `thinking`, else its `effort`). Default medium; it is
98
103
  * never off. */
99
104
  thinking?: ClaudeAgentThinking;
100
- /** For tests: the fetch the model proxy forwards with. */
105
+ /** The fetch the model proxy forwards with: the host's route for a model it translates onto this wire (a test's
106
+ * recorder, too); absent, the network. Forwarding it is the harness contract (HARNESS.md, the facts' `wire`). */
101
107
  fetch?: typeof fetch;
102
- /** For tests: the clock a user turn's day is read from (harness.ts dateLine). Default the system's. */
108
+ /** The run's clock, when the host sets one (serve: a template eval case's `now`): a user turn's day is read from it
109
+ * (harness.ts dateLine), and the CLI's own date lines, which it reads from the machine's clock, are made to say its
110
+ * day in `zone` at the session's model proxy (policy.ts `day`). A session on a login has no proxy: there the CLI's
111
+ * lines keep the machine's date. Default the system's clock, and the CLI's lines pass as written. */
103
112
  now?: () => Date;
104
113
  /** The IANA zone a user turn's day is read in (harness.ts dateLine), the one the host's environment line names. Default UTC. */
105
114
  zone?: string;
package/dist/adapter.js CHANGED
@@ -16,7 +16,7 @@ import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } f
16
16
  import { toolSchemaProblems } from "@parcha/agentrun-kernel";
17
17
  import { bridgeTool, NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
18
18
  import { checkedOnce, checkedOnceAsync, hostHeaderProblems, startModelProxy } from "@parcha/agentrun-kernel/host";
19
- import { anthropicPolicy, withWebSearches } from "./host/policy.js";
19
+ import { anthropicPolicy, isoDay, withWebSearches } from "./host/policy.js";
20
20
  import { findClaudeExecutable, platformSuffix } from "./binary.js";
21
21
  import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
22
22
  import { claudeCodeHarness, claudeToolSearch, lostPrompts } from "./harness.js";
@@ -25,8 +25,9 @@ import { localMachine } from "./host/machine.js";
25
25
  import { serialWriter } from "./serial.js";
26
26
  import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
27
27
  export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
28
- /** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
29
- export const CLAUDE_AGENT_ALSO_OFF = Object.freeze(["Skill", "WebSearch"]);
28
+ /** The pinned CLI's tools off by name in every session (WebSearch unless `webSearch`): those the copied harness leaves
29
+ * undecided, and WebFetch, which fetches from the CLI's own process where the host's web_fetch is the session's. */
30
+ export const CLAUDE_AGENT_ALSO_OFF = Object.freeze(["Skill", "WebSearch", "WebFetch"]);
30
31
  /** The local plugin the session's skills are served from: the model sees each as `agentrun:<name>`, and may load it by
31
32
  * that name or, unless the CLI has a command or skill of that name (`CLAUDE_AGENT_CLI_SKILL_NAMES`), by its bare one. */
32
33
  export const CLAUDE_AGENT_SKILLS_PLUGIN = "agentrun";
@@ -335,6 +336,8 @@ export function claudeAgentAdapter(options) {
335
336
  ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
336
337
  ...(provider.auth ? { auth: provider.auth } : {}),
337
338
  ...(provider.headers ? { headers: provider.headers } : {}),
339
+ // The CLI's own date lines follow the clock (policy.ts `day`).
340
+ ...(options.now ? { day: () => isoDay(options.now(), options.zone) } : {}),
338
341
  ...(options.log ? { log: options.log } : {}),
339
342
  ...(options.fetch ? { fetch: options.fetch } : {}),
340
343
  } } : {}),
@@ -368,6 +371,7 @@ export function claudeAgentAdapter(options) {
368
371
  ...(options.log ? { log: options.log } : {}),
369
372
  ...(options.now ? { now: options.now } : {}),
370
373
  ...(options.zone ? { zone: options.zone } : {}),
374
+ ...(options.barrierTimers ? { barrierTimers: options.barrierTimers } : {}),
371
375
  // The host's gate, asked about each host-tool call and each WebSearch before it is written or run.
372
376
  ...(io.gate ? { gate: (call) => io.gate(call) } : {}),
373
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 any kind. */
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 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']);
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
@@ -1,2 +1,3 @@
1
1
  import { type AdapterFacts } from "@parcha/agentrun-kernel";
2
2
  export declare const facts: AdapterFacts;
3
+ export { LOGIN_REFRESH as loginRefresh } from "./login-refresh.js";
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. Default 10 s. */
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.
@@ -308,8 +312,9 @@ export declare const CLAUDE_TOOL_SEARCH = "ToolSearch";
308
312
  export declare const claudeBuiltinReplay: (name: string) => ReplayPolicy;
309
313
  /** The `builtins` option, resolved: the `tools` option for `query()` (undefined: the preset, all of them). */
310
314
  export declare function builtinTools(builtins: ClaudeBuiltins | undefined): string[] | undefined;
311
- /** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16). */
312
- export declare function claudeSandboxSettings(machine: Pick<SessionMachine, 'root' | 'dirs'>, network: ClaudeSandboxNetwork, login?: ClaudeAgentLogin): NonNullable<QueryOptions['sandbox']>;
315
+ /** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16).
316
+ * `platform`: the one the CLI runs on, as loginEnv takes it. */
317
+ export declare function claudeSandboxSettings(machine: Pick<SessionMachine, 'root' | 'dirs'>, network: ClaudeSandboxNetwork, login?: ClaudeAgentLogin, platform?: NodeJS.Platform): NonNullable<QueryOptions['sandbox']>;
313
318
  /** Loopback, as names and literals a command could hand the sandbox's proxy for the model port. */
314
319
  export declare const LOOPBACK_NAMES: string[];
315
320
  export declare function claudeCodeHarness(options?: ClaudeCodeHarnessOptions): Harness;
package/dist/harness.js CHANGED
@@ -10,7 +10,7 @@ import { defersCatalog } from '@parcha/agentrun-kernel';
10
10
  import { Restart, Unavailable } from './host/kernel.js';
11
11
  import { askGate, BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, toolKey, waitForSubmissions, } from './host/process.js';
12
12
  import { durableEnv, nativeModelId } from './env.js';
13
- import { loginBooking } from './login.js';
13
+ import { 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';
@@ -144,16 +144,25 @@ export function builtinTools(builtins) {
144
144
  return undefined;
145
145
  throw new TypeError("agentrun-harness-claude: builtins takes true, a list of tool names, or { type: 'preset', preset: 'claude_code' }");
146
146
  }
147
- /** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16). */
148
- export function claudeSandboxSettings(machine, network, login) {
147
+ /** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16).
148
+ * `platform`: the one the CLI runs on, as loginEnv takes it. */
149
+ export function claudeSandboxSettings(machine, network, login, platform = process.platform) {
149
150
  const { dirs } = machine;
150
151
  const open = [dirs.tmp, dirs.home, dirs.cache];
152
+ const denyRead = [dirname(dirs.config), ...(login ? [login.dir, login.profiles] : [])];
153
+ // The folder the CLI reads the login's credentials from (loginEnv's own value), when the server's env sets it apart.
154
+ // Empty on macOS it names a Keychain item, no folder.
155
+ const secure = login ? loginEnv(login, platform).CLAUDE_SECURESTORAGE_CONFIG_DIR : '';
156
+ if (secure && !denyRead.includes(secure))
157
+ denyRead.push(secure);
151
158
  return {
152
159
  enabled: true,
153
160
  failIfUnavailable: true,
154
161
  allowUnsandboxedCommands: false,
155
- // A person's login 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 },
162
+ // A run on a person's login comes through claudeAgentAdapter, which passes builtins: false (the CLI has no Bash),
163
+ // and AgentRun's own tools never run on the server host. Where commands do run, denyRead keeps them from the login's
164
+ // files on Linux. On macOS the token is a Keychain item, which denyRead does not cover.
165
+ filesystem: { allowWrite: [machine.root, ...open], denyRead, allowRead: open },
157
166
  credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
158
167
  network: {
159
168
  ...(network === 'allow-all' ? { allowedDomains: ['*'] } : network === 'deny-all' ? { allowedDomains: [], strictAllowlist: true } : { allowedDomains: [...network.allow], strictAllowlist: true }),
@@ -225,7 +234,7 @@ export function claudeCodeHarness(options = {}) {
225
234
  const { query } = await loadSdk();
226
235
  const journal = new NativeJournal(ctx);
227
236
  const records = await journal.read();
228
- 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 } : {}) });
229
238
  // The handler reads the credential per request, in the drive's async
230
239
  // context: on a serverless function the OIDC token comes from the request
231
240
  // that started the drive.
@@ -488,13 +497,17 @@ export function claudeCodeHarness(options = {}) {
488
497
  },
489
498
  ],
490
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;
491
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).
492
505
  const vmEnv = durableEnv({
493
506
  home: machine.dirs.home,
494
507
  configDir: machine.dirs.config,
495
508
  tmpDir: machine.dirs.tmp,
496
509
  cacheDir: machine.dirs.cache,
497
- ...(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 }),
498
511
  model,
499
512
  ...(smallModel ? { smallModel } : {}),
500
513
  ...(sandbox.commandTimeoutMs ? { bashTimeoutMs: sandbox.commandTimeoutMs } : {}),
@@ -532,10 +545,33 @@ export function claudeCodeHarness(options = {}) {
532
545
  const recordedDay = !store.hasSession ? dayOf(now(), options.zone) : undefined;
533
546
  /** A message the CLI's transcript holds told the model `day`. */
534
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;
535
570
  const queryOptions = {
536
571
  model,
537
572
  cwd: machine.root,
538
573
  env: sdkEnv,
574
+ ...(askToken ? { getOAuthToken: askToken } : {}),
539
575
  // Built-ins on: the allowed ones (less those whose state the log does not carry), each let through by
540
576
  // the PreToolUse hook once its intent is in the log. Off: the bridged tools are the only ones. Either
541
577
  // way nothing is asked of a user, and nothing else is permitted.
@@ -544,7 +580,7 @@ export function claudeCodeHarness(options = {}) {
544
580
  ...(skills ? { plugins: [{ type: 'local', path: skills.plugin }], skills: [...skills.names] } : {}),
545
581
  disallowedTools: disallowed,
546
582
  hooks,
547
- ...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network, login?.at) } : {}),
583
+ ...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network, login && !byToken ? login.at : undefined) } : {}),
548
584
  ...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
549
585
  allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
550
586
  permissionMode: 'dontAsk',
@@ -672,6 +708,9 @@ export function claudeCodeHarness(options = {}) {
672
708
  ctx.halt?.(mirrorUnmapped('a batch the Agent SDK could not keep in the log'));
673
709
  throw ctx.signal.reason ?? mirrorUnmapped('a batch the Agent SDK could not keep in the log');
674
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);
675
714
  booking?.observe(m);
676
715
  const end = transcript.observe(m);
677
716
  // A turn on a login ends once its responses are booked.
@@ -37,6 +37,8 @@ export interface LocalMachineOptions {
37
37
  webSearchAllowance?: number;
38
38
  /** The CLI's own tool search is on: its beta, its tools and its tool references pass (anthropicPolicy). */
39
39
  toolSearch?: boolean;
40
+ /** The day of the run's clock, when the host set it: the CLI's date lines say it (anthropicPolicy `day`). */
41
+ day?: () => string;
40
42
  /** The tokens' price; each web search a response reports is added to it (`withWebSearches`). */
41
43
  price?: ModelProxyOptions["price"];
42
44
  maxOutputTokens?: number;
@@ -139,6 +139,7 @@ export function localMachine(options) {
139
139
  ...(po.webSearch ? { webSearch: true, ...(po.webSearchAllowance !== undefined ? { webSearchAllowance: po.webSearchAllowance } : {}) } : {}),
140
140
  ...(po.auth ? { auth: po.auth } : {}),
141
141
  ...(po.toolSearch ? { toolSearch: true } : {}),
142
+ ...(po.day ? { day: po.day } : {}),
142
143
  onThinkingDisabled: ({ model: main }) => po.log?.("claude-agent: thinking.disabled", { model: main }),
143
144
  }),
144
145
  hooks: po.hooks,
@@ -52,7 +52,11 @@ 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) when the host set one; the CLI's date lines say it (`CLI_DATE`). */
56
+ day?: () => string;
55
57
  }
58
+ /** `now`'s day in `zone` (default UTC) as YYYY-MM-DD, the form the CLI's date line takes. */
59
+ export declare function isoDay(now: Date, zone?: string): string;
56
60
  /** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
57
61
  export declare function thinks(body: Record<string, unknown>): boolean;
58
62
  /** The tokens a request keeps for its answer when its output is limited, and the least thinking budget the provider
@@ -67,6 +67,10 @@ export const CLAUDE_WEB_SEARCH_TOOL = "web_search_20250305";
67
67
  const WEB_SEARCH_KEYS = new Set(["type", "name", "max_uses", "allowed_domains", "blocked_domains"]);
68
68
  /** The most searches one request may ask the provider for: the pinned CLI's `max_uses`. */
69
69
  const WEB_SEARCH_MAX_USES = 8;
70
+ /** `now`'s day in `zone` (default UTC) as YYYY-MM-DD, the form the CLI's date line takes. */
71
+ export function isoDay(now, zone = "UTC") {
72
+ return new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
73
+ }
70
74
  /** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
71
75
  export function thinks(body) {
72
76
  const thinking = body.thinking;
@@ -115,6 +119,26 @@ function blocks(content, where, inResult = false, references) {
115
119
  blocks(block.content, "a tool result's content", true, references);
116
120
  }
117
121
  }
122
+ /** The pinned CLI's date lines, read from the machine's clock in its own local time: "Today's date is 2026-11-24.", and on
123
+ * a later day "Today's date is now 2026-11-25. ...". The CLI has no setting for its date (test/case-clock.test.mjs fails
124
+ * if a CLI bump words these differently, or moves them). */
125
+ const CLI_DATE = /\bToday's date is (now )?\d{4}-\d{2}-\d{2}\./g;
126
+ /** `text` with each of the CLI's date lines saying `day`. */
127
+ const onDay = (text, day) => text.replace(CLI_DATE, (_line, now) => `Today's date is ${now ?? ""}${day}.`);
128
+ /** A message with the CLI's date lines saying `day`, when it is one of the CLI's own: a `system` message among the
129
+ * messages, where the pinned CLI puts its environment note and the date at its end. Every other message (the person's
130
+ * words, the app's tool results, the model's replies) and the system prompt (the app's instructions) are never changed, so
131
+ * a date someone wrote, quoted or read reaches the model as it was. */
132
+ function messageOnDay(message, day) {
133
+ if (!isPlain(message) || message.role !== "system")
134
+ return message;
135
+ const content = message.content;
136
+ if (typeof content === "string")
137
+ return { ...message, content: onDay(content, day) };
138
+ if (!Array.isArray(content))
139
+ return message;
140
+ return { ...message, content: content.map((block) => (isPlain(block) && block.type === "text" && typeof block.text === "string" ? { ...block, text: onDay(block.text, day) } : block)) };
141
+ }
118
142
  /** A message with the CLI's note of its own image file left out of each tool result that holds the image itself: the
119
143
  * note names a path in the session's directory, which differs between a session and its resumption, and says nothing
120
144
  * the image doesn't. */
@@ -288,7 +312,11 @@ export function applyAnthropic(body, route, options, context = {}) {
288
312
  const small = options.smallModel ?? options.model;
289
313
  if (body.model !== options.model && body.model !== small)
290
314
  refuse(403, "the model is not this session's");
291
- const out = { ...body, messages: body.messages.map(withoutImageNotes), ...(tools === undefined ? {} : { tools }) };
315
+ // On a set clock, the CLI's date lines say its day, in its own system messages only (messageOnDay). The host's own side
316
+ // requests carry none of the CLI's lines, and are left as they are.
317
+ const day = context.host === undefined ? options.day?.() : undefined;
318
+ const messages = body.messages.map(withoutImageNotes);
319
+ const out = { ...body, messages: day === undefined ? messages : messages.map((m) => messageOnDay(m, day)), ...(tools === undefined ? {} : { tools }) };
292
320
  if (count)
293
321
  return out;
294
322
  // A main-model request that would not think is said, never passed silently (it is still forwarded: the CLI decides
package/dist/index.d.ts CHANGED
@@ -7,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 { claudeLoginStatus, 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 { claudeLoginStatus, 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
+ }>;