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

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,58 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.60 (2026-11-26)
6
+
7
+ - Sign out of Claude on this machine: `POST /v2/settings/claude-login/sign-out` (operation `signOutClaudeLogin`), and a Sign out button on Settings → Model keys' Claude login row. Before, the row had no way to sign out or switch accounts: Turn off kept the login as the CLI holds it, so Turn on read the same account again with no sign-in page. <!-- changes/claude-login-sign-out.md -->
8
+ - On AgentRun's own login (`<data>/claude-login`) the sign-out ends a sign-in that waits, turns the mode off, runs the pinned CLI's own `claude auth logout` there (its credentials file and, on macOS, its Keychain item for that folder), then removes the folder, the login's signed-in note and the runner's token reader whatever the CLI said. The next Turn on reads not signed in and offers the CLI's sign-in, for the same account or another. Each removal stands alone: one that fails is named in the answer, and the rest, the reader's drop and the server's reread of the keys still happen. `confirmed` false adds a `message` saying what may remain: the CLI didn't confirm its own sign-out, or its step failed (named), or a file could not be removed. A link found at `<data>/claude-login` is removed alone, with the login's signed-in note, no CLI run through it and nothing it leads to touched.
9
+ - This machine's own login (`place` `machine`, the person's `~/.claude` or `CLAUDE_CONFIG_DIR`) is never signed out: the route answers 403 in words that say to run `claude auth logout` in a terminal there, and the console offers no Sign out on it.
10
+ - Runs already going on the login are left as a turn-off leaves them: each fails saying the login is signed out at its next read of it. Where each run is a user of its own, a run claimed on the login and started while the mode is off is refused at its start ("turned off or moved to another folder since this run's claim"), as after a turn-off. The claim checks the login's folder, not its account: a run claimed before Sign out and started after a new sign-in may run on the new account.
11
+ - Not guaranteed for a run still going where runs stay in the runner's process: its CLI holds the refresh token and may write a renewed pair back into `<data>/claude-login` after the sign-out, and nothing removes it when the run ends. Once such runs end, a turn-on that reads signed in again means Sign out again.
12
+ - The harness exports `claudeLogout(cli, login, { timeoutMs, path, platform })`: the CLI's `auth logout` with the sign-in's variables in the person's home, true when it exited 0 within its limit (15 s), false otherwise; it never throws.
13
+ - On macOS, a native Claude runtime now finds the person's login when the server was started without `USER`, as a service launchd starts may be. The `claude` it starts for the sign-in check and for each turn names its Keychain item's account by `USER`, and without one it looked under `unknown`, read signed out and refused every turn. Where the server's environment has no `USER` or `LOGNAME`, or an empty one, they are now set to the user the server runs as; a `USER` it has is kept as it is. <!-- changes/claude-keychain-native-user.md -->
14
+
15
+ At AgentRun's own login folder, the Keychain item an earlier console sign-in left under the account `unknown` is now deleted once the item under the Mac user is there: after a sign-in from the console, or at the first status check that reads signed in. Items of this machine's own Claude login, and items under any other account, are never touched.
16
+
17
+ ## 0.1.0-beta.59 (2026-11-25)
18
+
19
+ **Breaking:**
20
+
21
+ - Ollama models run only on a harness that forwards the route, an output schema beside tools on Ollama is refused, and an ACP agent's permission requests for AgentRun's tools are no longer answered from their titles. What to change on upgrade: <!-- changes/b51-breaking.md -->
22
+ - A harness module on Messages or Responses that should keep running Ollama models must forward its model requests with the `fetch` its launch hands it (`ModuleLaunch.fetch`, given to `startModelProxy`'s `fetch`) and set `forwardsRoute: true` in its facts. Without the fact it is offered no Ollama model, and a run of it that names one is refused before it starts, in words that name these two steps.
23
+ - A claude-agent node with an output schema on an Ollama model now stops with a 400 `invalid_request_error`, since the claude-agent harness sends its tools on every turn and Ollama can't hold an answer to a format and also call tools. Drop the schema, or run the node on a model with a key.
24
+ - A recipe for an agent that asks permission before every tool call needs an `allowFile` in a form its agent reads, or the title tie (`quirks.permissionTie: "title"`). Without either, every request for an AgentRun tool goes to the host's gate as the agent's own call, and its runs stop there.
25
+ - An agent's `tool_call` title no longer names the AgentRun tool it calls. A recipe without `announces` (the new field where its agent's `tool_call` names the tool) has every call matched to its MCP call by its arguments alone, a call with no arguments included. A call announced with no input at all is matched to an MCP call that nothing else matches, the oldest first, until the agent reports it ended, so two such calls in flight can trade ids. Declare `announces` to tie each call to its own.
26
+ - Goose's offer promises `tool_gate: "config"` (was `"permission"`): its calls of AgentRun's tools are held by its permission file and the host's gate at the MCP call.
27
+ - `agentrun harness-check` fails `mcp_tool` for an agent that asks permission for `check_echo` on a recipe with neither field. A recipe whose check passed before can fail its next one.
28
+ - `examples/harness-recipe/antigravity.json` declares `announces` and the title tie (`quirks.permissionTie: "title"`), since agy asks permission for every MCP call: its requests for the AgentRun calls it announced are answered allow once, and the host's gate decides at the MCP call. A copy of the recipe made before this release has neither and needs both, or its runs stop at the gate.
29
+ - The exported test helper `fakeAgentRecipe` (`@parcha/agentrun-harness-acp/testing`) now gives its recipe an `allowFile` (style "goose", the default) or the title tie (style "cursor"), and each style's `announces`, as each shipped recipe does. The fake's style "cursor" now announces its MCP calls late, as Cursor 2026.11.13 does (`announce: "early"` for the old shape). A suite that relied on the fake asking for AgentRun's tools and being answered from the title gets neither by default.
30
+ - On macOS, signing in to Claude from the console now saves the login's Keychain item under the Mac user the server runs as, so `claude auth status` in that person's terminal reads it signed in, as AgentRun's badge does. Before, the claude CLI that AgentRun starts for the sign-in, the status check and a run got no `USER`, so the item's account was `unknown`. Those three now carry `USER` and `LOGNAME` set to the user the server runs as (`os.userInfo()`), even when the server itself was started without `USER` or with another user's. <!-- changes/claude-keychain-account-user.md -->
31
+
32
+ Who breaks: anyone who signed Claude in from the console on macOS before this release. That login reads signed out once the server is updated, since its item is under `unknown`. What to do: sign in again under Settings → Model keys. The old item stays in the Keychain under the account `unknown`; `@parcha/agentrun-serve`'s changelog for this version says how to delete it.
33
+
34
+ **Changes:**
35
+
36
+ - A model the runner's route translates onto a harness's wire (this machine's Ollama models on Anthropic's Messages and OpenAI's Responses) is offered only to a harness whose proxy forwards with the route's `fetch`, and the Messages translation no longer drops what it can't run. Before, any harness on the wire was offered those models, including a module that sends its requests to the network, where nothing answers. <!-- changes/b51-route-hints.md -->
37
+ - `AdapterFacts` gains `forwardsRoute`. claude-agent, Goose, codex and opencode set it, and so does every recipe that builds on Goose's facts. A harness without it is offered none of the route's models, takes none as its default, and its words say to add a key ("No model yet for <harness>: add an OpenRouter or Anthropic key"). A run that names one is refused before it starts.
38
+ - An output schema (`output_config.format` of type `json_schema`) on a Messages request with no tools now reaches Ollama as its `format`. Before, it was dropped and the answer came back unconstrained. Beside tools it is refused with a 400 `invalid_request_error` that says to drop the output schema or use a model route that takes tools with a format, because Ollama holds the whole answer to the format and leaves the model no way to call a tool.
39
+ - The Messages translation answers `POST /v1/messages` and `POST /v1/messages/count_tokens` alone. Any other method or path is a 404 `not_found_error` in Anthropic's error shape, and nothing reaches Ollama.
40
+ - `agentrun harness-check` on a model the route translates (`--model ollama/<tag>`) now reaches it. Its recorder wraps the route's own fetch, so the recipe's agent gets the same route a server's run gets and the check still sees every request. Before, every request went to the route's placeholder origin and `mcp_tool` failed.
41
+ - A run's trace no longer costs or carries what it should not. Under `agentrun-serve runner`, where each run is a process of its own, a run's end waited up to 3 s on the collector, since that process flushed its own spans before it exited: now it sends its trace to its runner, which exports it in the background, and a run's process never holds an `OTEL_*` setting at all. The runner reads that trace as untrusted: every string it carries (a provider, a host, a call id, a request's or turn's end, a failure) is cut of every secret the runner holds, or taken only from values the runner knows, and a call's id, its parent's or a route's name longer than 128 characters is kept as its SHA-256, so a run's process can't hold megabytes of ids open in its runner. A name the model wrote no longer reaches a span as written: a call the harness refused (a tool the session does not have; the kernel's `tool_start` event says `refused: true`, which claude-agent now sets) is `execute_tool` with `error.type=tool_refused` and no tool name, a model the run does not know (not a route's model, nor one its price table names by that same id) is named by its route's model, and every name is cut of every secret the runner holds and at 64 characters. Each value of `OTEL_EXPORTER_OTLP_HEADERS` and `OTEL_EXPORTER_OTLP_TRACES_HEADERS` of 8 characters or more is now a secret the server and the runner hold, under any header name, an unknown one too, but a `Content-Type`, `Accept`, `Content-Encoding` or `User-Agent` header's value, and a dataset or tenant header's (`x-honeycomb-dataset`, `x-axiom-dataset`, `x-scope-orgid`), which is only cut from the tracer's `[otel]` lines, so a dataset named `production` refuses no source capture. A credential is held without the word before it too, after a known auth scheme (`Bearer`, `Basic`, `Api-Key`, `Api-Token`, `Token`, `sentry`, `Splunk`, `GenieKey`) or under a credential-named header (`authorization`, `x-sentry-auth`, `x-api-key`); any other header's value is held whole, never its tail alone. So are an OTLP endpoint's user, password and each query parameter named like a credential: a word of its name is a credential word or ends in key, token, secret, password, auth, sig, signature or credential (`api_key`, `access_token`, `apiKey`, `accesstoken`, `writekey`; never `authority` or `keyspace`). A comma inside a header value must be written `%2C`. The tracer's own `[otel]` lines, where an exporter's error may quote a header it sent, are cut of each such value at any length, a short one too, and of what follows any header value's first word; everywhere else (the runner's logs, what a run writes, a served run, a source capture) a held value is still cut at 8 characters or more and a shorter header value is on no held list, on purpose, since a needle of a few characters would cut ordinary text, turn a served number such as `1` into `[redacted]`, or refuse a source capture of any project that holds it. <!-- changes/otel-trace-names-and-child-export.md -->
42
+ - The Claude login on this machine now uses the folders the server's env gives it only when they belong to the server's own user, as it already did for the home. Those folders are `CLAUDE_CONFIG_DIR`, `CLAUDE_SECURESTORAGE_CONFIG_DIR`, and `ANTHROPIC_CONFIG_DIR` or else `XDG_CONFIG_HOME`'s `anthropic`. Each one must be a folder that user owns, or a folder still to be made inside one it owns. The home and these folders are judged by one rule, so that no other user can change where the path leads after the check: <!-- changes/claude-login-config-dirs.md -->
43
+
44
+ - The path is walked as the system walks it, one name at a time, so a trailing slash, `.` or `..` hides nothing, and a `..` after a link goes up from where the link leads. Each link on the way, and each link in the chain it leads through, must be one that user or root made.
45
+ - Each folder above the real folder must be that user's or root's, and not one others may write in (anyone, or its group, unless that group is the user's private one), unless the sticky bit keeps each entry its maker's (as /tmp has it).
46
+ - The folder itself must be that user's and not open to others' writes by the same rule. So must the folder a still-to-make one is made in, sticky or not, so a folder still to make in /tmp is refused, root's included.
47
+ - The CLI gets the real path the check looked at (the home included), from the same look: each decision (a run, the sign-in, the Settings view's line and status check, a turn-on) walks the folders once and takes the login, or the refusal, from that walk, never the path as given. Where the folders are refused, the view's `command` is empty and its `folder` is the folder as the env names it. Where the env's path has a link on it, the shown sign-in line and the CLI now name the folder the link leads to. On macOS the CLI names its Keychain item after that folder, so a login the person's own Claude CLI keeps under a path with a link reads as signed out until it is signed in again from here.
48
+
49
+ A server started under a sudo that keeps the env (root, with the person's `CLAUDE_CONFIG_DIR`) no longer signs the Claude CLI in as root inside the person's folder. Where a folder fails the check, the turn-on and the sign-in at this machine's login are refused (403) in words that name the variable and the folder, and no run goes on the login. AgentRun's own login keeps its folders in the data folder, so the env's folders refuse nothing there, but the home rule above applies to both places. A login saved before on folders, the home's included, that fail the check is kept, not turned off: the start logs why it is not used, every read refuses it in those words, and it is back once the folder is mended (a chmod, or the server started as the right user). A chmod needs no restart: a run's check, a save's, a template's plan or apply, and capabilities look at the folders again, so the login is offered and runs again as soon as the view reads it signed in, and stops again once its folder is refused. Such a request asked while the server is still making the offers again from such a change, or from a turn-on or turn-off, waits for them, and the server logs `claude_login_wait` as it waits, with `why`: `queue` (behind a turn-on, turn-off or sign-in), `refresh` or `turn`. A sign-in, a turn-on or a turn-off never waits for those offers. The Settings view says such a login is `refused`, with why, and offers Turn off, which removes it; until then no API key is made. The refusal words now name the server's user (`uid 501 (svc)`, say), the home's refusal included. A folder that is the user's but open to others' writes is refused in words of its own, which name the open folder, its mode and the `chmod g-w,o-w` that closes it. A folder of this machine's login still to make is made by AgentRun at the turn-on and before the CLI's sign-in, 0700 whatever the umask, and checked again before the CLI gets it, so a login the CLI signs in there is not refused after.
50
+
51
+ Where the env's `HOME` is another user's and the login therefore uses the server's user's own home, the sign-in line the Settings view shows now carries `HOME=<that home>`. Before, it left `HOME` to the terminal, so the line run in the person's terminal signed in to their own home, which the server never reads. The harness's `ClaudeAgentLogin` has a new optional `homeApart` that asks for this.
52
+
53
+ A folder its group may write in is the user's alone where that group is the user's private one, as the local account files alone say: `/etc/nsswitch.conf` takes users and groups from those files only (`files` or `compat`), and the group is the user's primary group, which no other user has as theirs and which `/etc/group` lists with no other member. So a umask of 002 under such a group refuses nothing there. A switch that also asks another source (sssd, LDAP, NIS, winbind, or systemd's user records, as recent Ubuntu, Debian and Fedora installs do) can give the group members the files do not show, so there such a folder is refused.
54
+
55
+ Behaviour change: a login that ran before is refused, at either place, where the server's home is a folder anyone may write in, or its group where another user is in it, or is reached through one (a home on a volume whose group is set for a pod, 2775, say). So is a login on this machine's folders where one of these variables points at another user's folder, or reaches through another user's link or folder, or through such an open folder. A group shared with other users, a group that is not the user's primary one, one `/etc/group` does not list, account files that defer to a directory service (a `+` or `-` line), and any group where `/etc/nsswitch.conf` asks a source other than the files for users or groups, or is missing, all count as open: under a umask of 002 with such a group, a home, a `~/.config` or a `CLAUDE_CONFIG_DIR` folder made by hand is refused until it is `chmod g-w`. The setting stays. Start the server as the person whose Claude plan it is, with that person's variables, and make the folders on the way writable by their owner alone.
56
+
5
57
  ## 0.1.0-beta.58 (2026-11-25)
6
58
 
7
59
  - 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 -->
@@ -13,7 +65,7 @@
13
65
  - 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
66
  - `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
67
  - 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 -->
68
+ - Where each run is a user of its own (the image, `run_isolation: "uid"`), a claude-agent run now runs on the Claude 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 CLI 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 the Claude CLI 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 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
69
  - 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
70
  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
71
 
package/dist/adapter.js CHANGED
@@ -399,7 +399,7 @@ export function claudeAgentAdapter(options) {
399
399
  // A call the CLI refused itself (a tool the session doesn't have): shown as a call that failed, by the name the
400
400
  // model gave. The CLI's transcript, mirrored to the store, keeps the refusal.
401
401
  if (e?.type === "tool_refused" && typeof e.callId === "string" && typeof e.name === "string") {
402
- io.onEvent({ type: "tool_start", callId: e.callId, name: e.name, args: e.args ?? {} });
402
+ io.onEvent({ type: "tool_start", callId: e.callId, name: e.name, args: e.args ?? {}, refused: true });
403
403
  io.onEvent({ type: "tool_end", callId: e.callId, name: e.name, isError: true });
404
404
  options.log?.("claude-agent: the CLI turned down a call to a tool this session does not have", { name: e.name, reason: e.reason });
405
405
  }
package/dist/env.d.ts CHANGED
@@ -73,6 +73,8 @@ export interface DurableEnvOptions {
73
73
  * - `HOME`, `CLAUDE_CONFIG_DIR`, `TMPDIR` and the XDG dirs in the session's
74
74
  * cache dirs, which the relay wipes before every spawn (`/var/lib/dh/s`),
75
75
  * but `HOME` on macOS on a login: the person's (login.ts personHome);
76
+ * - on a login, `USER` and `LOGNAME`: the user this process runs as
77
+ * (login-user.ts loginUser), the account of the login's Keychain item on macOS;
76
78
  * - the projects key fixed (`CLAUDE_CODE_PROJECT_DIR_NAME`), so a transcript
77
79
  * resumes on any VM, whatever the cwd;
78
80
  * - the model through the VM's model port, with the attach's key; the
package/dist/env.js CHANGED
@@ -11,6 +11,7 @@
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
+ import { loginUser } from './login-user.js';
14
15
  /** 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
16
  * any kind, a refresh token or a token's file descriptor among them. A login handed as a token sets its own
16
17
  * CLAUDE_CODE_OAUTH_TOKEN after. */
@@ -25,6 +26,8 @@ export const PROJECT_DIR_NAME = 'session';
25
26
  * - `HOME`, `CLAUDE_CONFIG_DIR`, `TMPDIR` and the XDG dirs in the session's
26
27
  * cache dirs, which the relay wipes before every spawn (`/var/lib/dh/s`),
27
28
  * but `HOME` on macOS on a login: the person's (login.ts personHome);
29
+ * - on a login, `USER` and `LOGNAME`: the user this process runs as
30
+ * (login-user.ts loginUser), the account of the login's Keychain item on macOS;
28
31
  * - the projects key fixed (`CLAUDE_CODE_PROJECT_DIR_NAME`), so a transcript
29
32
  * resumes on any VM, whatever the cwd;
30
33
  * - the model through the VM's model port, with the attach's key; the
@@ -67,6 +70,9 @@ export function durableEnv(options) {
67
70
  // On macOS the CLI on a login reads its tokens from the login keychain, which is under the person's home: in the
68
71
  // session's it finds none and reads signed out. Its config, XDG and temporary dirs stay the session's.
69
72
  HOME: options.login && platform === 'darwin' ? personHome(options.login) : home,
73
+ // On a login, the user it is the login of: on macOS the CLI names the Keychain item's account by USER, and with
74
+ // none it reads the account "unknown", not the one the sign-in saved the tokens under (login-user.ts loginUser).
75
+ ...(options.login ? loginUser() : {}),
70
76
  TMPDIR: options.tmpDir,
71
77
  CLAUDE_CONFIG_DIR: options.configDir,
72
78
  CLAUDE_CODE_PROJECT_DIR_NAME: PROJECT_DIR_NAME,
package/dist/facts.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { type AdapterFacts } from "@parcha/agentrun-kernel";
2
2
  export declare const facts: AdapterFacts;
3
3
  export { LOGIN_REFRESH as loginRefresh } from "./login-refresh.js";
4
+ export { loginUser } from "./login-user.js";
package/dist/facts.js CHANGED
@@ -27,6 +27,8 @@ export const facts = Object.freeze({
27
27
  webSearch: "native",
28
28
  // Its model is Anthropic's, on its own settings, never the gateway's default for the other harnesses.
29
29
  ownModel: true,
30
+ // Its proxy forwards with the fetch it is handed: a model the route translates onto its wire runs on it.
31
+ forwardsRoute: true,
30
32
  // Anthropic's ids hold no dot; OpenRouter names the same models with dots (anthropic/claude-sonnet-5.5).
31
33
  normalizeModel: (model) => (model.provider === "anthropic" ? { ...model, modelId: model.modelId.replaceAll(".", "-") } : model),
32
34
  install: Object.freeze({ npmLine: CLAUDE_AGENT_SDK_INSTALL, spec: `@anthropic-ai/claude-agent-sdk@${CLAUDE_AGENT_SDK_VERSION}`, codes: Object.freeze({ install: "CLAUDE_AGENT_NOT_INSTALLED", pins: "CLAUDE_AGENT_PIN_MISMATCH" }) }),
@@ -44,3 +46,6 @@ export const facts = Object.freeze({
44
46
  // 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
47
  // reads it without loading the adapter and its SDK.
46
48
  export { LOGIN_REFRESH as loginRefresh } from "./login-refresh.js";
49
+ // The user a CLI on a login runs as (login-user.ts), here too so a host that starts the person's own `claude` gives it
50
+ // the USER its Keychain item is named by without loading the adapter and its SDK.
51
+ export { loginUser } from "./login-user.js";
package/dist/harness.js CHANGED
@@ -340,6 +340,8 @@ export function claudeCodeHarness(options = {}) {
340
340
  try {
341
341
  const result = await running;
342
342
  const images = (result.images ?? []).map((image) => ({ type: 'image', data: image.data, mimeType: image.mimeType }));
343
+ // The tool's structured content is not passed on: the pinned CLI replaces an MCP answer's content with
344
+ // JSON.stringify(structuredContent), so sending both would hide the tool's text from the model.
343
345
  return { content: [{ type: 'text', text: result.text }, ...images], ...(result.isError ? { isError: true } : {}) };
344
346
  }
345
347
  catch (err) {
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claude
7
7
  export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
8
8
  export type { AnthropicPolicyOptions, AnthropicUsage } from "./host/policy.js";
9
9
  export type { ChildCommand, ConfineChild } from "./host/machine.js";
10
- export { 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";
10
+ export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, claudeLogout, 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
11
  export type { ClaudeAgentLogin, ClaudeLoginStatus, ClaudeLoginToken } from "./login.js";
12
12
  export { LOGIN_REFRESH as CLAUDE_LOGIN_REFRESH } from "./login-refresh.js";
13
13
  export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch,
4
4
  export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_AGENT_BASE_INPUT_TOKENS, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
5
5
  export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
6
6
  export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
7
- export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, 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";
7
+ export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, claudeLogout, 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
8
  export { LOGIN_REFRESH as CLAUDE_LOGIN_REFRESH } from "./login-refresh.js";
9
9
  export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
10
10
  export { SIGN_IN_MS as CLAUDE_SIGN_IN_MS, signInEnv as claudeSignInEnv } from "./login.js";
@@ -0,0 +1,9 @@
1
+ /** `USER` and `LOGNAME` for a CLI started on a login, built from nothing (the status check, the sign-in this host starts,
2
+ * a run, the CLI's own sign-out): the user this process runs as, as the system has it (`os.userInfo()`, which reads
3
+ * the user database, never the server's own USER), the user whose home personHome is. On macOS the pinned CLI names
4
+ * its Keychain item's account by `$USER`, else by its runtime's `os.userInfo().username`; it is a Bun binary, whose
5
+ * userInfo reads `$USER` too and says "unknown" without it. So a CLI started with no USER saves and reads the login's
6
+ * tokens under the account "unknown", where the person's own `claude`, run in a terminal that has USER, never looks:
7
+ * it reads signed out while the badge reads signed in. A user the system cannot name (no entry in its user database)
8
+ * is the server's USER or LOGNAME, when it has one. */
9
+ export declare function loginUser(): Record<string, string>;
@@ -0,0 +1,24 @@
1
+ // The user a CLI started on a login runs as, for the account of its Keychain item on macOS. Written for AgentRun.
2
+ //
3
+ // Here alone, beside nothing else, so a host that starts the person's own `claude` (serve's native runtimes) reads it
4
+ // without loading the adapter and its SDK (facts.ts).
5
+ import { userInfo } from "node:os";
6
+ /** `USER` and `LOGNAME` for a CLI started on a login, built from nothing (the status check, the sign-in this host starts,
7
+ * a run, the CLI's own sign-out): the user this process runs as, as the system has it (`os.userInfo()`, which reads
8
+ * the user database, never the server's own USER), the user whose home personHome is. On macOS the pinned CLI names
9
+ * its Keychain item's account by `$USER`, else by its runtime's `os.userInfo().username`; it is a Bun binary, whose
10
+ * userInfo reads `$USER` too and says "unknown" without it. So a CLI started with no USER saves and reads the login's
11
+ * tokens under the account "unknown", where the person's own `claude`, run in a terminal that has USER, never looks:
12
+ * it reads signed out while the badge reads signed in. A user the system cannot name (no entry in its user database)
13
+ * is the server's USER or LOGNAME, when it has one. */
14
+ export function loginUser() {
15
+ let name;
16
+ try {
17
+ name = userInfo().username || undefined;
18
+ }
19
+ catch {
20
+ name = undefined;
21
+ }
22
+ name ??= process.env.USER || process.env.LOGNAME || undefined;
23
+ return name === undefined ? {} : { USER: name, LOGNAME: name };
24
+ }
package/dist/login.d.ts CHANGED
@@ -21,6 +21,13 @@ export interface ClaudeAgentLogin {
21
21
  * server's `HOME` when its user owns it, else that user's own home), so the status check, the sign-in and a run on
22
22
  * macOS all run in that one home (personHome). With `home`, the same folder. */
23
23
  userHome?: string;
24
+ /** Set where `userHome` is not the home a terminal with the server's env has (serve's homeOf: that env's `HOME` was
25
+ * another user's, so the server's user's own home was taken): the line a person runs (loginCommand) then carries
26
+ * `HOME`, so it signs in where the server reads, never in that terminal's own home. */
27
+ homeApart?: boolean;
28
+ /** Set only for AgentRun's own login folder (serve's place `agentrun`), which no CLI of the person's uses: the one
29
+ * place whose Keychain item left under the account "unknown" is deleted here (dropUnknownItem). */
30
+ own?: boolean;
24
31
  }
25
32
  /** A login handed to the CLI as its access token alone, by a host that holds the login itself. `token()` is asked at
26
33
  * each start of the CLI and when Anthropic refuses the token the CLI holds: it answers the login's access token as
@@ -68,7 +75,8 @@ export declare function signInEnv(login: ClaudeAgentLogin, platform?: NodeJS.Pla
68
75
  * holding '=' as one more variable, so a CLI path holding one (/data/a=b/claude) goes to `sh -c` as its `$0`, single
69
76
  * quoted, which every one of those shells reads alike too. What env skips: a `claude` alias or function of the
70
77
  * person's shell. Elsewhere nothing is cleared, and the line is the variables in front of the CLI, as a shell reads
71
- * them (sh, bash, zsh, fish 3.1 and later; not tcsh). `platform`: as signInEnv's. */
78
+ * them (sh, bash, zsh, fish 3.1 and later; not tcsh). A login whose home is not the terminal's (`homeApart`) carries
79
+ * `HOME` first (personHome), as the sign-in this host starts does. `platform`: as signInEnv's. */
72
80
  export declare const loginCommand: (login: ClaudeAgentLogin, cli?: string, platform?: NodeJS.Platform) => string;
73
81
  /** What the CLI says of its login: whether it is signed in, how, and the account's own words when it gives them. */
74
82
  export interface ClaudeLoginStatus {
@@ -120,8 +128,20 @@ export declare function sweepClaudeStatusFolders(options?: {
120
128
  * the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
121
129
  * session's) it finds no keychain and reads signed out, whatever the variables. */
122
130
  export declare const personHome: (login: ClaudeAgentLogin) => string;
123
- /** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH and the login's
124
- * variables beside it, in the person's home (personHome) on every place and platform.
131
+ /** On macOS, at AgentRun's own folder (`own`) alone, delete the login's Keychain item under the account "unknown", which
132
+ * a sign-in left there when the CLI was started with no USER (loginUser), and which nothing reads now: `security
133
+ * delete-generic-password -a unknown -s <the item's service>`, the service the CLI names from the folder (`Claude
134
+ * Code-credentials-<first 8 hex of the folder's sha256>`), in the person's home (personHome), whose login keychain holds
135
+ * it. Called once the item under the person's account is there (the sign-in exited 0, a status check read signed in).
136
+ * Never at the person's own CLI's places, whose "unknown" item may be theirs, never the item with no suffix, never an
137
+ * item of any other account, and never where the user this server runs as is named "unknown" itself. "Not found" is
138
+ * done, as is any other end: nothing is thrown, and it is asked once per item in this process. */
139
+ export declare function dropUnknownItem(login: ClaudeAgentLogin, options: {
140
+ path: string;
141
+ platform?: NodeJS.Platform;
142
+ }): Promise<void>;
143
+ /** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH, the user (loginUser)
144
+ * and the login's variables beside it, in the person's home (personHome) on every place and platform.
125
145
  * The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
126
146
  * own, and adds a settings file, a backup and a lock beside it the first time, all in its config dir, so the check never
127
147
  * runs it on the login's own file, whatever the caller says of the login: the config dir is a copy of the account file
@@ -165,19 +185,37 @@ export interface ClaudeSignIn {
165
185
  stop(): void;
166
186
  }
167
187
  /** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
168
- * (personHome) and desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
188
+ * (personHome), as that person (loginUser: the account the Keychain item is saved under on macOS, the one their own
189
+ * terminal's `claude` reads), and on their desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
169
190
  * Nothing of it is read here: its output goes nowhere. It is ended after `timeoutMs` (SIGN_IN_MS by default), which
170
191
  * `ended` says apart from any other end.
171
192
  * It dies with this process, as a session's CLI does: started under the kernel's parent watch (parentWatched; `watch`,
172
193
  * by default what this machine supports), so a server that is SIGKILLed, and runs no stop or limit timer, leaves no CLI
173
194
  * waiting on the browser's port. It is not detached: it stays in this process's group, so a terminal's Ctrl-C ends it
174
- * with the server as before, and nothing here kills a group, which would take a browser the CLI started with it. */
195
+ * with the server as before, and nothing here kills a group, which would take a browser the CLI started with it.
196
+ * A sign-in that exits 0 at AgentRun's own folder has the item a sign-in left there under "unknown" deleted before
197
+ * `ended` settles (dropUnknownItem). `platform`: the one the CLI runs on, this host's. */
175
198
  export declare function startClaudeLogin(cli: string, login: ClaudeAgentLogin, options?: {
176
199
  timeoutMs?: number;
177
200
  path?: string;
178
201
  display?: Readonly<Record<string, string | undefined>>;
179
202
  watch?: ParentWatch;
203
+ platform?: NodeJS.Platform;
180
204
  }): ClaudeSignIn;
205
+ /** The longest the CLI's own sign-out may take. */
206
+ export declare const LOGOUT_MS = 15000;
207
+ /** The CLI's own sign-out at `login` (`auth logout`), with the sign-in's variables (signInEnv) and user (loginUser) in
208
+ * the person's home (personHome), so it removes what that sign-in kept where it kept it: the credentials file in the
209
+ * login's credentials dir or, on macOS, the Keychain item named from it under that user's account, and the account in
210
+ * the config dir's `.claude.json`. Nothing of it
211
+ * is read but how it ended: true when it exited 0 within `timeoutMs` (LOGOUT_MS by default), false when it exited
212
+ * otherwise, never started, or was ended at the limit (SIGTERM, then SIGKILL a second later). Never throws.
213
+ * `platform`: as signInEnv's. */
214
+ export declare function claudeLogout(cli: string, login: ClaudeAgentLogin, options?: {
215
+ timeoutMs?: number;
216
+ path?: string;
217
+ platform?: NodeJS.Platform;
218
+ }): Promise<boolean>;
181
219
  /** How a session on a login books its requests: no proxy sees them, so each response the CLI streams is booked from its
182
220
  * own events, billed to the plan, at no price here. No proxy can hold a request back either, so a request is admitted
183
221
  * before the CLI can send it: when a message goes to the CLI (`sending`), and when a response stops for its tool calls,
package/dist/login.js CHANGED
@@ -12,11 +12,13 @@
12
12
  // hold secrets (an API key, exported variables, MCP servers' tokens) and lasts the check.
13
13
  // The check runs in the person's own home, as does a run on macOS, where the CLI's tokens are in the login keychain.
14
14
  import { spawn } from "node:child_process";
15
+ import { createHash } from "node:crypto";
15
16
  import { accessSync, closeSync, constants, mkdtempSync, openSync, readSync, rmSync, statSync } from "node:fs";
16
17
  import { lstat, mkdir, open, readdir, readFile, rm, writeFile } from "node:fs/promises";
17
18
  import { homedir, tmpdir } from "node:os";
18
19
  import { delimiter, join } from "node:path";
19
20
  import { parentWatched } from "@parcha/agentrun-kernel/host";
21
+ import { loginUser } from "./login-user.js";
20
22
  /** Whether `login` is handed as a token (ClaudeLoginToken), not as its directories. */
21
23
  export const loginByToken = (login) => typeof login.token === "function";
22
24
  /** The words a turn ends in when Anthropic refused the login's access token mid-turn and the host had no newer one. */
@@ -66,11 +68,12 @@ const FOLDER_VARS = ["CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"];
66
68
  * holding '=' as one more variable, so a CLI path holding one (/data/a=b/claude) goes to `sh -c` as its `$0`, single
67
69
  * quoted, which every one of those shells reads alike too. What env skips: a `claude` alias or function of the
68
70
  * person's shell. Elsewhere nothing is cleared, and the line is the variables in front of the CLI, as a shell reads
69
- * them (sh, bash, zsh, fish 3.1 and later; not tcsh). `platform`: as signInEnv's. */
71
+ * them (sh, bash, zsh, fish 3.1 and later; not tcsh). A login whose home is not the terminal's (`homeApart`) carries
72
+ * `HOME` first (personHome), as the sign-in this host starts does. `platform`: as signInEnv's. */
70
73
  export const loginCommand = (login, cli = "claude", platform = process.platform) => {
71
- const env = signInEnv(login, platform);
74
+ const env = login.homeApart ? { HOME: personHome(login), ...signInEnv(login, platform) } : signInEnv(login, platform);
72
75
  const cleared = FOLDER_VARS.filter((name) => !(name in env));
73
- const vars = Object.entries(env).filter(([name]) => name !== "HOME").map(([name, value]) => `${name}=${shellWord(value)}`);
76
+ const vars = Object.entries(env).filter(([name]) => name !== "HOME" || login.homeApart).map(([name, value]) => `${name}=${shellWord(value)}`);
74
77
  if (!cleared.length)
75
78
  return [...vars, commandWord(cli), "auth", "login"].join(" ");
76
79
  const run = cli.includes("=") ? ["sh", "-c", `'exec "$0" auth login'`, quoted(cli)] : [shellWord(cli), "auth", "login"];
@@ -295,8 +298,45 @@ async function accountCopy(from, to) {
295
298
  * the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
296
299
  * session's) it finds no keychain and reads signed out, whatever the variables. */
297
300
  export const personHome = (login) => login.userHome ?? login.home ?? homedir();
298
- /** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH and the login's
299
- * variables beside it, in the person's home (personHome) on every place and platform.
301
+ /** How long the delete of an "unknown" item may take before it is killed (SIGKILL, which a `security` or a wrapper on
302
+ * PATH cannot ignore, as it can SIGTERM) and left (dropUnknownItem): the sign-in's end and the status check wait on it. */
303
+ const DROP_MS = 5_000;
304
+ /** The items dropUnknownItem has dealt with in this process, by home and service: each is deleted once. */
305
+ const dropped = new Set();
306
+ /** On macOS, at AgentRun's own folder (`own`) alone, delete the login's Keychain item under the account "unknown", which
307
+ * a sign-in left there when the CLI was started with no USER (loginUser), and which nothing reads now: `security
308
+ * delete-generic-password -a unknown -s <the item's service>`, the service the CLI names from the folder (`Claude
309
+ * Code-credentials-<first 8 hex of the folder's sha256>`), in the person's home (personHome), whose login keychain holds
310
+ * it. Called once the item under the person's account is there (the sign-in exited 0, a status check read signed in).
311
+ * Never at the person's own CLI's places, whose "unknown" item may be theirs, never the item with no suffix, never an
312
+ * item of any other account, and never where the user this server runs as is named "unknown" itself. "Not found" is
313
+ * done, as is any other end: nothing is thrown, and it is asked once per item in this process. */
314
+ export async function dropUnknownItem(login, options) {
315
+ if ((options.platform ?? process.platform) !== "darwin" || login.own !== true)
316
+ return;
317
+ const folder = loginEnv(login, "darwin").CLAUDE_SECURESTORAGE_CONFIG_DIR;
318
+ const user = loginUser();
319
+ if (!folder || user.USER === undefined || user.USER === "unknown")
320
+ return;
321
+ const service = `Claude Code-credentials-${createHash("sha256").update(folder).digest("hex").slice(0, 8)}`;
322
+ const HOME = personHome(login);
323
+ const key = JSON.stringify([HOME, service]);
324
+ if (dropped.has(key))
325
+ return;
326
+ dropped.add(key);
327
+ await new Promise((resolve) => {
328
+ try {
329
+ const child = spawn("security", ["delete-generic-password", "-a", "unknown", "-s", service], { env: { PATH: options.path, HOME, ...user }, stdio: "ignore", timeout: DROP_MS, killSignal: "SIGKILL" });
330
+ child.once("error", () => resolve());
331
+ child.once("close", () => resolve());
332
+ }
333
+ catch {
334
+ resolve();
335
+ }
336
+ });
337
+ }
338
+ /** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH, the user (loginUser)
339
+ * and the login's variables beside it, in the person's home (personHome) on every place and platform.
300
340
  * The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
301
341
  * own, and adds a settings file, a backup and a lock beside it the first time, all in its config dir, so the check never
302
342
  * runs it on the login's own file, whatever the caller says of the login: the config dir is a copy of the account file
@@ -327,7 +367,7 @@ export async function claudeLoginStatus(cli, login, options = {}) {
327
367
  const where = { HOME, ...loginEnv(login, options.platform), CLAUDE_CONFIG_DIR: await accountCopy(accountFile(login), join(scratch, "config")) };
328
368
  const { stdout, timedOut } = await new Promise((resolve, reject) => {
329
369
  const child = spawn(cli, ["auth", "status", "--json"], {
330
- env: { PATH: options.path ?? process.env.PATH ?? "/usr/bin:/bin", ...where, DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" },
370
+ env: { PATH: options.path ?? process.env.PATH ?? "/usr/bin:/bin", ...loginUser(), ...where, DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" },
331
371
  stdio: ["ignore", "pipe", "ignore"],
332
372
  });
333
373
  let out = "";
@@ -378,6 +418,10 @@ export async function claudeLoginStatus(cli, login, options = {}) {
378
418
  // A whole answer written just before the limit still counts.
379
419
  if (!status)
380
420
  throw timedOut ? new ClaudeLoginTimedOut(limitMs) : new ClaudeLoginNoStatus();
421
+ // Signed in: the item under the person's account is there, so one a sign-in left under "unknown" goes (AgentRun's
422
+ // own folder alone).
423
+ if (status.signedIn)
424
+ await dropUnknownItem(login, { path: options.path ?? process.env.PATH ?? "/usr/bin:/bin", ...(options.platform ? { platform: options.platform } : {}) });
381
425
  return status;
382
426
  }
383
427
  finally {
@@ -481,13 +525,16 @@ function startable(cli, path) {
481
525
  }
482
526
  }
483
527
  /** Start the CLI's own sign-in at `login` (`auth login`), with the line's own variables (signInEnv) in the person's home
484
- * (personHome) and desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
528
+ * (personHome), as that person (loginUser: the account the Keychain item is saved under on macOS, the one their own
529
+ * terminal's `claude` reads), and on their desktop (`display`): it opens a browser on this machine and keeps what it gets in the login's folder.
485
530
  * Nothing of it is read here: its output goes nowhere. It is ended after `timeoutMs` (SIGN_IN_MS by default), which
486
531
  * `ended` says apart from any other end.
487
532
  * It dies with this process, as a session's CLI does: started under the kernel's parent watch (parentWatched; `watch`,
488
533
  * by default what this machine supports), so a server that is SIGKILLed, and runs no stop or limit timer, leaves no CLI
489
534
  * waiting on the browser's port. It is not detached: it stays in this process's group, so a terminal's Ctrl-C ends it
490
- * with the server as before, and nothing here kills a group, which would take a browser the CLI started with it. */
535
+ * with the server as before, and nothing here kills a group, which would take a browser the CLI started with it.
536
+ * A sign-in that exits 0 at AgentRun's own folder has the item a sign-in left there under "unknown" deleted before
537
+ * `ended` settles (dropUnknownItem). `platform`: the one the CLI runs on, this host's. */
491
538
  export function startClaudeLogin(cli, login, options = {}) {
492
539
  // What a browser needs to open on this desktop, when the server has it.
493
540
  const display = Object.fromEntries(["DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "BROWSER"].flatMap((name) => {
@@ -503,7 +550,7 @@ export function startClaudeLogin(cli, login, options = {}) {
503
550
  startable(cli, path);
504
551
  const run = parentWatched({ command: cli, args: ["auth", "login", "--claudeai"] }, options.watch, { termGraceMs: SIGN_IN_TERM_GRACE_MS });
505
552
  child = spawn(run.command, run.args, {
506
- env: { PATH: path, HOME: personHome(login), ...display, ...signInEnv(login), DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1" },
553
+ env: { PATH: path, HOME: personHome(login), ...loginUser(), ...display, ...signInEnv(login), DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1" },
507
554
  stdio: "ignore",
508
555
  });
509
556
  }
@@ -534,9 +581,54 @@ export function startClaudeLogin(cli, login, options = {}) {
534
581
  settle(result);
535
582
  };
536
583
  child.once("error", (error) => finish(ending ? { end: ending } : failed(error)));
537
- child.once("close", (code, signal) => finish(ending ? { end: ending } : { end: "exited", code, signal }));
584
+ child.once("close", (code, signal) => {
585
+ const result = ending ? { end: ending } : { end: "exited", code, signal };
586
+ // Signed in: the item under the person's account is there, so one a sign-in left under "unknown" goes first
587
+ // (AgentRun's own folder alone).
588
+ if (result.end === "exited" && code === 0)
589
+ void dropUnknownItem(login, { path, ...(options.platform ? { platform: options.platform } : {}) }).then(() => finish(result));
590
+ else
591
+ finish(result);
592
+ });
538
593
  return { ended, stop: () => end("stopped") };
539
594
  }
595
+ /** The longest the CLI's own sign-out may take. */
596
+ export const LOGOUT_MS = LOGIN_STATUS_MS;
597
+ /** The CLI's own sign-out at `login` (`auth logout`), with the sign-in's variables (signInEnv) and user (loginUser) in
598
+ * the person's home (personHome), so it removes what that sign-in kept where it kept it: the credentials file in the
599
+ * login's credentials dir or, on macOS, the Keychain item named from it under that user's account, and the account in
600
+ * the config dir's `.claude.json`. Nothing of it
601
+ * is read but how it ended: true when it exited 0 within `timeoutMs` (LOGOUT_MS by default), false when it exited
602
+ * otherwise, never started, or was ended at the limit (SIGTERM, then SIGKILL a second later). Never throws.
603
+ * `platform`: as signInEnv's. */
604
+ export function claudeLogout(cli, login, options = {}) {
605
+ return new Promise((resolve) => {
606
+ let child;
607
+ try {
608
+ child = spawn(cli, ["auth", "logout"], {
609
+ env: { PATH: options.path ?? process.env.PATH ?? "/usr/bin:/bin", HOME: personHome(login), ...loginUser(), ...signInEnv(login, options.platform), DISABLE_AUTOUPDATER: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1" },
610
+ stdio: "ignore",
611
+ });
612
+ }
613
+ catch {
614
+ return resolve(false);
615
+ }
616
+ let timedOut = false;
617
+ let kill;
618
+ const limit = setTimeout(() => {
619
+ timedOut = true;
620
+ child.kill("SIGTERM");
621
+ kill = setTimeout(() => child.kill("SIGKILL"), STATUS_KILL_MS);
622
+ }, options.timeoutMs ?? LOGOUT_MS);
623
+ const done = (confirmed) => {
624
+ clearTimeout(limit);
625
+ clearTimeout(kill);
626
+ resolve(confirmed);
627
+ };
628
+ child.once("error", () => done(false));
629
+ child.once("close", (code) => done(!timedOut && code === 0));
630
+ });
631
+ }
540
632
  const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
541
633
  /** How a session on a login books its requests: no proxy sees them, so each response the CLI streams is booked from its
542
634
  * own events, billed to the plan, at no price here. No proxy can hold a request back either, so a request is admitted
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-claude",
3
- "version": "0.1.0-beta.58",
3
+ "version": "0.1.0-beta.60",
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.58"
51
+ "@parcha/agentrun-kernel": "0.1.0-beta.60"
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.58"
80
+ "@parcha/agentrun-dsl": "0.1.0-beta.60"
81
81
  }
82
82
  }