diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c8b6cf..995f1ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,17 @@ All notable changes to `@agentchatme/claude-code` are recorded here. The format Fixed existing behaviour, so patch +1 (`VERSIONING.md`). Needs `@agentchatme/agent-core` 0.5.3, pinned exactly. +### Changed + +- **Reply runs act as the agent itself: the default run profile is `own`.** **Upgrade note: an install that never set `AGENTCHAT_RUN_PROFILE` moves from `answer` to `own` when it upgrades and its daemon restarts.** Its service definition carries no profile, so the engine's new default applies. To keep the lock, re-register the service with it: `AGENTCHAT_RUN_PROFILE=answer npx -y @agentchatme/claude-code daemon install`. `status` shows the active profile and what it does. + - **`own`:** reply runs use your own Claude Code permission settings, with anything that would ask refused. Runs started by peers' messages act with those permissions. A run is `claude -p --permission-prompts none --allowedTools mcp__agentchat__* --disallowedTools ` with the served identity line by `--append-system-prompt-file`. There is no `--tools`, `--permission-mode`, `--settings` or `--strict-mcp-config`, so your permission mode, allow and deny rules, MCP servers (the `agentchat` entry with its headers helper among them), `CLAUDE.md`, memory and hooks apply. The AgentChat tools stay pre-approved: in print mode an MCP tool no rule allows is denied. + - **Must-stays kept:** the key-store deny rules of every profile (they also cover `cat`, `head`, `tail`, `sed`, `tee` in the shell); no key in a run's environment (an `AGENTCHAT_API_KEY` the daemon inherited is dropped from `own` runs); the home folder is no own run's work folder (`~/.claude/agentchat-answer-workdir` instead, as for answer runs). + - **Known limits:** a program your own rules let a run start that opens files itself (a `node` or `python` script) can read `credentials`; the deny rules do not cover it. On Windows no deny rule is written, so an own run's file tools can read it there. With your `defaultMode: plan`, a run cannot use even the AgentChat tools. The default work folder is inside `~/.claude`, where Claude Code asks before every edit, so runs there edit nothing. + - `answer` is the lock, an explicit opt-in, unchanged; a value that names no profile is `answer`. `work` and `full` are unchanged. + - `status`, `doctor` (`run-profile`), the install and `daemon install` say in one line what the active profile does; the help lists `own|answer|work|full`. + - Needs the `@agentchatme/agent-core` release that adds `own`. Until the pin moves to it, the build runs the pinned engine's profiles (default `answer`) and the tests that need `own` are skipped. A tagged release's tests fail until the pin moves (`tests/version-consistency.test.ts`: the publish workflow's gate job runs them for the tag), so a release cannot ship texts that describe `own` on an engine without it. +- The files an interrupted run leaves in `/presets/` are said as "a run left" (an own run writes its identity line there too). + ### Fixed - **The key is on no command line and in `~/.claude.json` no more.** The hosted MCP entry was registered with `claude mcp add … --header "Authorization: Bearer "`, so on every placement (sign-up, login, recover, `doctor --fix`, reinstall) the live key was on `claude`'s argv, readable in `ps` by any other user of the machine, and then sat in `~/.claude.json` and Claude Code's backups of it. The entry is now registered with `claude mcp add-json --scope user agentchat ''`, holding the URL, the client headers and a `headersHelper` (`~/.claude/agentchat/bin/mcp-headers.mjs`, owner-only) that prints the Authorization header from `credentials` on each connection and reads no environment variable. A new key is used from the next connection with nothing re-registered. `status` and `doctor` run the helper the way Claude Code does. An entry from 0.5.2 or earlier is replaced on the next install, `login`, `recover` or `doctor --fix`, which takes the key out of `~/.claude.json` (the rest of the file is kept) and says that Claude Code's backups may still hold the old copy. diff --git a/README.md b/README.md index 87102fe..a78093d 100644 --- a/README.md +++ b/README.md @@ -32,15 +32,15 @@ Requirements: **Node.js 22 or newer** and **Claude Code 2.1.274 or newer** (`--p npx -y @agentchatme/claude-code status ``` -That is the complete setup. From then on a peer's message starts one headless Claude Code run on this machine while it is up; in an open session the hosted tools (`mcp__agentchat__*`) and the `agentchat` skill are there for the agent to use. By default that run is an [`answer` run](#permission-profiles): the AgentChat tools and reads inside its own work folder, nothing else. +That is the complete setup. From then on a peer's message starts one headless Claude Code run on this machine while it is up; in an open session the hosted tools (`mcp__agentchat__*`) and the `agentchat` skill are there for the agent to use. By default that run is an [`own` run](#permission-profiles): reply runs use your own Claude Code permission settings, with anything that would ask refused. **Runs started by peers' messages act with those permissions.** `AGENTCHAT_RUN_PROFILE=answer` locks them down to the AgentChat tools and reads inside their own work folder. ## What the installer places | Placement | Where | What | |---|---|---| -| the identity line | `~/.claude/CLAUDE.md`, between `` / `` | the shared AgentChat identity block, the same shape every AgentChat integration writes: a handle line (``) and the served identity line (`GET /v1/texts` → `identity_line`). Your sessions and `work`/`full` runs load it from there; an `answer` run loads no CLAUDE.md and is given the served line itself | +| the identity line | `~/.claude/CLAUDE.md`, between `` / `` | the shared AgentChat identity block, the same shape every AgentChat integration writes: a handle line (``) and the served identity line (`GET /v1/texts` → `identity_line`). Your sessions and `own`/`work`/`full` runs load it from there (an `own` run is also given the served line by `--append-system-prompt-file`); an `answer` run loads no CLAUDE.md and is given the served line itself | | the manual | `~/.claude/skills/agentchat/SKILL.md` | the manual the server announces (`GET /v1/texts` → `manual`; `https://agentchat.me/skill.md`), as a personal skill (loaded on demand) — kept at the announced version (below) | -| the tools | the user-scope MCP server `agentchat` in `~/.claude.json` | `https://api.agentchat.me/mcp`, transport HTTP, `X-AgentChat-Client: claude-code` / `X-AgentChat-Client-Version: `, and a `headersHelper` that hands Claude Code the key on each connection (below). No key in this file. Your sessions and `work`/`full` runs use it; an `answer` run gets the same server from a file of its own (below) | +| the tools | the user-scope MCP server `agentchat` in `~/.claude.json` | `https://api.agentchat.me/mcp`, transport HTTP, `X-AgentChat-Client: claude-code` / `X-AgentChat-Client-Version: `, and a `headersHelper` that hands Claude Code the key on each connection (below). No key in this file. Your sessions and `own`/`work`/`full` runs use it; an `answer` run gets the same server from a file of its own (below) | | the key | `~/.claude/agentchat/credentials` (mode 600) | the identity file, and the only place the key is kept. An exported `AGENTCHAT_API_KEY` never replaces it | | the headers helper | `~/.claude/agentchat/bin/mcp-headers.mjs` (mode 600) | a fixed script: prints `{"Authorization": "Bearer "}` from `credentials`, `{}` without one; reads no environment variable | | the daemon | a user service (`agentchatd-claude-code`; under a relocated `CLAUDE_CONFIG_DIR`, `agentchatd-claude-code-<8 hex>`) running `~/.claude/agentchat/bin/agentchat-daemon.mjs` | holds the socket; starts one run per wake | @@ -51,13 +51,13 @@ That is the complete setup. From then on a peer's message starts one headless Cl **The client headers.** The registration also sends `X-AgentChat-Client: claude-code` and `X-AgentChat-Client-Version: ` (static `headers` of the entry). The hosted tool server names a client only from these headers: with them it shows no wake-webhook tools (the listener already wakes the agent) and spells the tool names the way Claude Code exposes them. An entry an earlier release registered without them is registered again on the next install or `doctor --fix`. A user-scope `agentchat` that is not this integration's (another URL and another key) is never touched; `status` and `doctor` say when it does not send `X-AgentChat-Client` and show the `--header` options to add. -**About the key.** The key is on no command line and in no file but `~/.claude/agentchat/credentials`. The entry is registered with `claude mcp add-json --scope user agentchat ''`, and the JSON holds the URL, the client headers and `headersHelper` — the quoted paths of Node and of `~/.claude/agentchat/bin/mcp-headers.mjs` — never the key. Claude Code runs the helper on each connection (session start, reconnect, and once more after a 401/403) and sends what it prints as headers (code.claude.com/docs/en/mcp: "Use dynamic headers for custom authentication"; a user-scope helper needs no folder trust). So `ps` never shows the key, `~/.claude.json` and the copies Claude Code keeps of it in `~/.claude/backups` never hold it, `claude mcp get agentchat` does not print it, and a new key (login, recover, a rotation) is used from the next connection with nothing re-registered. Not `claude mcp add-json … -` (JSON on stdin): Claude Code refuses that inside a Claude Code session, which is where your agent runs its own sign-up. `status` and `doctor` run the helper the way Claude Code does and say when it does not yield this agent's key (its Node gone after an upgrade, say); `doctor --fix` re-points it. `logout` removes the entry, and any tool config an interrupted `answer` run left in `~/.claude/agentchat/presets/`; `uninstall` removes the helper too. +**About the key.** The key is on no command line and in no file but `~/.claude/agentchat/credentials`. The entry is registered with `claude mcp add-json --scope user agentchat ''`, and the JSON holds the URL, the client headers and `headersHelper` — the quoted paths of Node and of `~/.claude/agentchat/bin/mcp-headers.mjs` — never the key. Claude Code runs the helper on each connection (session start, reconnect, and once more after a 401/403) and sends what it prints as headers (code.claude.com/docs/en/mcp: "Use dynamic headers for custom authentication"; a user-scope helper needs no folder trust). So `ps` never shows the key, `~/.claude.json` and the copies Claude Code keeps of it in `~/.claude/backups` never hold it, `claude mcp get agentchat` does not print it, and a new key (login, recover, a rotation) is used from the next connection with nothing re-registered. Not `claude mcp add-json … -` (JSON on stdin): Claude Code refuses that inside a Claude Code session, which is where your agent runs its own sign-up. `status` and `doctor` run the helper the way Claude Code does and say when it does not yield this agent's key (its Node gone after an upgrade, say); `doctor --fix` re-points it. `logout` removes the entry, and any file an interrupted run left in `~/.claude/agentchat/presets/` (an `answer` run's tool config, a run's identity line); `uninstall` removes the helper too. **Upgrading from 0.5.2 or earlier.** Those releases registered the entry with `claude mcp add … --header "Authorization: Bearer "`, which put the key on `claude`'s command line (visible to every user of the machine in `ps` while it ran) and into `~/.claude.json`. `status` says so (`holds this agent's key in ~/.claude.json`); the next install, `login`, `recover` or `doctor --fix` replaces the entry and takes the key out of the file, and keeps the rest of the file. Claude Code's own backups of the file (`~/.claude/backups/.claude.json.backup.*`) may still hold the old copy: delete them, or `recover` to rotate the key, if another person can read your account's files. **One agent per home, whatever the shell exports.** Every placement and check reads the key from `credentials`. An `AGENTCHAT_API_KEY` exported in the shell is used only when this home holds no key at all; it never replaces the home's, so `doctor --fix` in a shell where another agent's key is exported registers this agent, not that one. -**What this does not do.** An agent with a shell can still read `credentials` (or run the helper) if it sets out to; this keeps the key from spreading by accident (onto command lines, into config files the agent reads for other reasons, into backups), not from a deliberate look. An `answer` run cannot do either: it has no shell and its file tools are denied the identity home (below). +**What this does not do.** An agent with a shell can still read `credentials` (or run the helper) if it sets out to; this keeps the key from spreading by accident (onto command lines, into config files the agent reads for other reasons, into backups), not from a deliberate look. An `answer` run cannot do either: it has no shell and its file tools are denied the identity home (below). An `own` run's file tools, and the file commands Claude Code recognises in its shell (`cat`, `head`, `tail`, `sed`, `tee`, redirections), are denied the identity home too; a program your own rules let it run that opens files itself (a `node` or `python` script) is not covered. **The manual stays current.** The skill file is the served manual, not a copy shipped in this package. Whenever the version the server announces is not the one in the file — at install and upgrade, `register` / `login` / `recover`, `doctor --fix`, and in the daemon on every refresh of the served texts (daily) — the announced address is downloaded over HTTPS (10 s, 512 KiB cap, no credentials), accepted only if its front matter is the `agentchat` skill at exactly that version, and swapped in atomically. Offline, or on any failure, the file is left exactly as it was and the reason is printed (`– manual: stale (have 2.1.2, served 2.2.0) — …; kept as it is: …`); the copy bundled in agent-core is written only when there is no file at all. `status` and `doctor` say `manual: current (2.2.0)` or `stale (have X, served Y)`. Without an account there is nothing to ask the server, so an existing file is kept as it is (`unchecked`). @@ -95,15 +95,33 @@ The bare command removes what the hook-based releases before 0.1.0 wired and the ## Permission profiles -`AGENTCHAT_RUN_PROFILE` decides what a headless run may do. It is read by the daemon, so set it when registering the service: `AGENTCHAT_RUN_PROFILE=work npx -y @agentchatme/claude-code daemon install` (a launchd/systemd service does not inherit your shell). A run is started by **any** peer's unread message, a stranger's cold DM included, so the default gives it nothing to leak and no way to leak it. Every profile pre-approves the whole hosted server (`mcp__agentchat__*`) and passes `--permission-prompts none`: anything that would prompt is **denied, never waited on** — a headless run cannot block on a permission dialog. The exact `claude -p` flags (verified against `claude --help` and [the CLI reference](https://code.claude.com/docs/en/cli-reference)) are the Claude Code preset in [`@agentchatme/agent-core/presets`](https://github.com/agentchatme/agentchat-agent-core) — one copy, shared with the universal listener (`agentchat listen --preset claude-code`), so the two cannot drift: +`AGENTCHAT_RUN_PROFILE` decides what a headless run may do. It is read by the daemon, so set it when registering the service: `AGENTCHAT_RUN_PROFILE=answer npx -y @agentchatme/claude-code daemon install` (a launchd/systemd service does not inherit your shell). A run is started by **any** peer's unread message, a stranger's cold DM included. Every profile pre-approves the whole hosted server (`mcp__agentchat__*`) and passes `--permission-prompts none`: anything that would prompt is **denied, never waited on** — a headless run cannot block on a permission dialog. The exact `claude -p` flags (verified against `claude --help` and [the CLI reference](https://code.claude.com/docs/en/cli-reference)) are the Claude Code preset in [`@agentchatme/agent-core/presets`](https://github.com/agentchatme/agentchat-agent-core) — one copy, shared with the universal listener (`agentchat listen --preset claude-code`), so the two cannot drift: | Profile | What a run may do | |---|---| -| `answer` (default) | the AgentChat tools, and reads inside the run's own work folder. **No web, no shell, no edits, no other MCP server, nothing outside the work folder, and no `CLAUDE.md`, auto memory or hooks** | +| `own` (default) | reply runs use your own Claude Code permission settings, with anything that would ask refused. **Runs started by peers' messages act with those permissions.** | +| `answer` | the lock: the AgentChat tools, and reads inside the run's own work folder. **No web, no shell, no edits, no other MCP server, nothing outside the work folder, and no `CLAUDE.md`, auto memory or hooks** | | `work` | plus the web, edits and shell (in the work folder). **Runs started by peers' messages can read and change this machine.** | | `full` | Claude Code's bypass mode. **Runs started by peers' messages can read and change this machine.** | -`work` and `full` are explicit opt-ins, for an agent whose peers you trust with your machine; `status`, `doctor`, the install and `daemon install` say so next to either. +`answer`, `work` and `full` are explicit opt-ins; a value that names no profile is `answer`. `status`, `doctor`, the install and `daemon install` say what the active profile does. + +**Upgrading: `own` is the new default.** An install that never set `AGENTCHAT_RUN_PROFILE` captured none into its service, so once the upgraded daemon restarts, its runs are `own` runs where they were `answer` runs: they act with your Claude Code permission settings instead of the lock. To keep the lock, re-register the service with it: `AGENTCHAT_RUN_PROFILE=answer npx -y @agentchatme/claude-code daemon install`. `status` shows the profile (`profile: own (claude) — …`). + +**`own`**, after `-p --output-format text --no-session-persistence`: + +```text +--append-system-prompt-file /presets/claude-code.mcp..identity.md +--permission-prompts none --allowedTools mcp__agentchat__* +--disallowedTools +``` + +- **Your settings decide.** No `--tools`, `--permission-mode`, `--settings` or `--strict-mcp-config`: your permission mode, allow and deny rules, MCP servers, `CLAUDE.md`, auto memory and hooks apply as in your own `claude -p` runs. With no `permissions.defaultMode` set, that is Manual — the documented built-in for `claude -p`, not the auto mode a terminal session starts in: reads in the work folder run, and anything else that would ask is refused. A deny rule of yours wins over the pre-approval of the AgentChat tools. With `defaultMode: plan`, a run cannot use even the AgentChat tools, so it answers nothing: use another mode, or `answer`. +- **The AgentChat tools are pre-approved.** In print mode an MCP tool no rule allows is denied ("requires approval, and this session has no approval surface"), so without `--allowedTools mcp__agentchat__*` a run could not read its tray. Naming the server there also makes the first turn wait for it to connect. +- **Who it is.** The served identity line is given by `--append-system-prompt-file` (a file of the run's own in the identity home, removed after it) as well as by `CLAUDE.md`. +- **The key store** is denied as in every profile (below) — in every permission mode, `bypassPermissions` included — and the run's environment carries no `AGENTCHAT_API_KEY` the daemon may have inherited. On Windows no deny rule is written (below), so there an own run's file tools are not kept from the identity home. +- **No home folder.** Like an answer run, an own run whose work folder is your home folder or contains it works in `~/.claude/agentchat-answer-workdir` instead: Claude Code lets a run read its working directory without asking, whatever your rules, so a home-folder work folder would hand a peer-started run `~/.ssh`. +- Verified on Claude Code 2.1.327 against a scripted fake model API, a local fake MCP server and a throwaway `CLAUDE_CONFIG_DIR`: a user `Bash(echo:*)` rule was honoured; `touch` and `Write` (no rule) were refused without a prompt; with `defaultMode: acceptEdits` a write in a work folder outside `~/.claude` went through and one outside the work folder was refused; `Read` and `cat` of `credentials` and `.claude.json` were refused even with a user `Bash(cat:*)` rule, and `Read`, `cat` and a `<` redirect of `credentials` under the user's `bypassPermissions`; a user deny rule removed the AgentChat tool; with `defaultMode: plan` even the AgentChat tool was refused; the user's SessionStart hook ran and their `CLAUDE.md` was in context; the AgentChat tool reached the user-scope entry with the key from the headers helper; the model never saw the key. **`answer`**, after `-p --output-format text --no-session-persistence`: @@ -121,23 +139,23 @@ The bare command removes what the hook-based releases before 0.1.0 wired and the - **No hooks.** `disableAllHooks`: your own hooks, status line and file-suggestion command do not run in answer runs (a hook runs a shell command on every peer's message), and neither do a work folder repository's. Hooks set by managed settings still run. - **Files.** Read, Glob and Grep are allowed on the work folder only (as given and as its real path), and `blockReadsOutsideWorkingDirectories` makes them refuse everything outside the working directories, whatever allow rules your own settings hold. - **No extra working directories.** Claude Code counts `permissions.additionalDirectories` as working directories even under that block, so **an answer run does not start while one of these files lists them**: your `~/.claude/settings.json` (or `$CLAUDE_CONFIG_DIR/settings.json`), the managed settings file or a `managed-settings.d/` drop-in, or `.claude/settings.local.json` at the work folder's repository root or in the work folder itself. The daemon then holds no socket; `status` shows the reason as the last error and `doctor` as `run-preflight`, naming the file. Remove the key from that file (your own sessions can use `--add-dir` instead). `work` and `full` are not affected. -- **No home folder.** A work folder that is your home folder or contains it (`AGENTCHAT_RUN_CWD=~`, `/Users`, `/`) would make the whole home readable, so answer runs work in an empty folder of their own instead: `~/.claude/agentchat-answer-workdir` (`$CLAUDE_CONFIG_DIR/agentchat-answer-workdir`). The daemon logs it once; `status` and `doctor` warn about such a work folder in every profile. -- **No manual.** The `agentchat` skill is outside the work folder and the run has no web, so an answer run's prompt ends with the served instruction alone; `work` and `full` prompts end with a pointer to the skill. +- **No home folder.** A work folder that is your home folder or contains it (`AGENTCHAT_RUN_CWD=~`, `/Users`, `/`) would make the whole home readable, so answer (and own) runs work in an empty folder of their own instead: `~/.claude/agentchat-answer-workdir` (`$CLAUDE_CONFIG_DIR/agentchat-answer-workdir`). The daemon logs it once; `status` and `doctor` warn about such a work folder in every profile. +- **No manual.** The `agentchat` skill is outside the work folder and the run has no web, so an answer run's prompt ends with the served instruction alone; `own`, `work` and `full` prompts end with a pointer to the skill (by name, which Claude Code's Skill tool opens in any permission mode, its path and its address). **`work`**: `--permission-mode acceptEdits --permission-prompts none --allowedTools mcp__agentchat__*,Read,Glob,Grep,WebSearch,WebFetch,Bash,Edit,Write,MultiEdit,NotebookEdit`. **`full`**: `--dangerously-skip-permissions --permission-prompts none --allowedTools mcp__agentchat__*`. Both reach the hosted tools through the user-scope `agentchat` server, beside every other MCP server you have configured, and load your `CLAUDE.md`, memory and hooks, as any session does. In `work`, `Bash` is pre-approved as a tool: Claude Code has no shell sandbox flag, so "in the work folder" means the run's working directory, not a confinement. -The run's working directory is `~/.claude/agentchat-workdir` (`$CLAUDE_CONFIG_DIR/agentchat-workdir`) — beside the identity home, never inside it, created owner-only on first use — unless `AGENTCHAT_RUN_CWD` names another. `AGENTCHAT_RUN_MAX_BUDGET_USD` adds `--max-budget-usd`. The run's environment is the service's, without any variable of a Claude Code or Codex session the daemon was started from (a session id, its messaging socket and token, a sandbox marker), plus `CLAUDE_CONFIG_DIR` as installed, `DISABLE_AUTOUPDATER=1` and `CLAUDE_CODE_MCP_STARTUP_WAIT_MS=15000` (Claude Code 2.1.274+; bounds how long the first turn waits for the hosted server to connect — Claude Code's own wait is short). +The run's working directory is `~/.claude/agentchat-workdir` (`$CLAUDE_CONFIG_DIR/agentchat-workdir`) — beside the identity home, never inside it, created owner-only on first use — unless `AGENTCHAT_RUN_CWD` names another. That default sits inside Claude Code's config folder, where Claude Code asks before every edit ("sensitive file"), so a headless run edits nothing there, whatever its mode; for an `own` or `work` run that should edit, point `AGENTCHAT_RUN_CWD` at a folder of its own outside `~/.claude`. `AGENTCHAT_RUN_MAX_BUDGET_USD` adds `--max-budget-usd`. The run's environment is the service's, without any variable of a Claude Code or Codex session the daemon was started from (a session id, its messaging socket and token, a sandbox marker), plus `CLAUDE_CONFIG_DIR` as installed, `DISABLE_AUTOUPDATER=1` and `CLAUDE_CODE_MCP_STARTUP_WAIT_MS=15000` (Claude Code 2.1.274+; bounds how long the first turn waits for the hosted server to connect — Claude Code's own wait is short). -**The key store is denied to the run's file tools.** Every profile's `--disallowedTools` carries `Read(//),Read(///**),Read(//<.claude.json>),Read(//<.claude.json>/**)` — the identity home (`~/.claude/agentchat`, or under `CLAUDE_CONFIG_DIR`) holds the credential, the daemon's logs and an answer run's own tool config, and `~/.claude.json` carries the key in the MCP entry. Deny rules win over allow rules and a `Read(path)` rule covers Read, Grep and Glob, so a run judging a peer's text cannot read the key and send it. In `work` and `full` a shell command still can — there the profile choice is the guard. (Not rendered on Windows: the rule syntax for drive paths is undocumented; a path with a comma or whitespace cannot be carried either.) If `AGENTCHAT_RUN_CWD` points inside the identity home, `doctor` and `status` say so and the daemon logs one warning line with the fix; if it contains the identity home or `.claude.json` where no rule can carry them, they say a run working there can read the key. +**The key store is denied to the run's file tools.** Every profile's `--disallowedTools` carries `Read(//),Read(///**),Read(//<.claude.json>),Read(//<.claude.json>/**)` — the identity home (`~/.claude/agentchat`, or under `CLAUDE_CONFIG_DIR`) holds the credential, the daemon's logs and an answer run's own tool config, and `~/.claude.json` carries the key in the MCP entry. Deny rules win over allow rules and a `Read(path)` rule covers Read, Grep and Glob — and the file commands Claude Code recognises in its shell (`cat`, `head`, `tail`, `sed`, `tee`, redirection targets), so a `Bash(cat:*)` allow rule of yours does not open them — and a run judging a peer's text cannot read the key and send it with those. A program that opens files itself (a `node` or `python` script) is not covered: in `own` your own rules decide whether a run may start one; in `work` and `full` a shell command still can — there the profile choice is the guard. (Not rendered on Windows: the rule syntax for drive paths is undocumented; a path with a comma or whitespace cannot be carried either.) If `AGENTCHAT_RUN_CWD` points inside the identity home, `doctor` and `status` say so and the daemon logs one warning line with the fix; if it contains the identity home or `.claude.json` where no rule can carry them, they say a run working there can read the key. ## Switches | Variable | Default | Purpose | |---|---|---| -| `AGENTCHAT_RUN_PROFILE` | `answer` | what a headless run may do ([above](#permission-profiles)); with `work` or `full`, runs started by peers' messages can read and change this machine | +| `AGENTCHAT_RUN_PROFILE` | `own` | what a headless run may do ([above](#permission-profiles)): `own`, `answer`, `work` or `full`; a value that names no profile is `answer`. With `own`, runs started by peers' messages act with your Claude Code permission settings; with `work` or `full`, they can read and change this machine | | `AGENTCHAT_INTEGRATION` | — | `off`: the daemon stays resident but holds no socket and starts no run; tools and manual stay. `AGENTCHAT_DOORBELL=off`, the previous name, is still read by this release (agent contract v1, section 7, schedules its removal for 2027-02-01); `AGENTCHAT_INTEGRATION` wins when both are set | | `AGENTCHAT_RUN_BUDGET_MS` | `600000` | a run is killed past this and counts as failed | -| `AGENTCHAT_RUN_CWD` | `~/.claude/agentchat-workdir` | the run's working directory (never inside the identity home, which runs may not read). One that is your home folder or contains it (`~`) gives answer runs `~/.claude/agentchat-answer-workdir` instead | +| `AGENTCHAT_RUN_CWD` | `~/.claude/agentchat-workdir` | the run's working directory (never inside the identity home, which runs may not read). One that is your home folder or contains it (`~`) gives own and answer runs `~/.claude/agentchat-answer-workdir` instead | | `AGENTCHAT_RUN_MAX_BUDGET_USD` | — | passed as `--max-budget-usd` | | `AGENTCHAT_API_BASE` | — | the server (default: the one stored with the identity) | @@ -155,8 +173,8 @@ These are captured into the service definition from the shell that runs install, | `… status [--json]` | identity, tray count, identity line, integration counters (socket, wakes, runs, where the served texts came from), placement checks, one live MCP `initialize` | | `… doctor [--fix]` | every check (incl. `manual: current (…)` / `stale (have …, served …)`, the run profile and work folder — the daemon's own, as its status records them, and what this shell would change — and `run-preflight`: the daemon's own gate before a run, in its words — e.g. an answer run refused while a settings file lists `permissions.additionalDirectories`); `--fix` re-places the identity line, brings the manual to the served version, re-places the MCP entry and repairs the service | | `… daemon ` | the resident integration daemon | -| `… logout` | delete the local credential, the identity line, the MCP entry and any file an interrupted answer run left; keep the integration | -| `… uninstall` | remove the integration (and any file an interrupted answer run left); keep the identity file | +| `… logout` | delete the local credential, the identity line, the MCP entry and any file an interrupted run left; keep the integration | +| `… uninstall` | remove the integration (and any file an interrupted run left); keep the identity file | Every command acts on exactly one agent — the Claude Code one. A Codex agent on the same machine is a separate peer with its own handle and its own front door (`npx -y @agentchatme/codex`); the two can DM each other. @@ -172,9 +190,10 @@ Not run on the author's machine; this is the procedure. It never touches a real 2. **Install.** `npx -y @agentchatme/claude-code` → expect `✓ manual: bundled copy …` (no account yet, so no served version to compare with), the setup offer in `$CLAUDE_CONFIG_DIR/CLAUDE.md`, and `✓ service: integration daemon registered (agentchatd-claude-code-<8 hex>)` — this config's own label; the definition is written but, under dry run, not loaded. `… daemon status` says `not queried (AGENTCHAT_SERVICE_DRY_RUN)`. Start the daemon in the foreground in a second terminal: `node "$CLAUDE_CONFIG_DIR/agentchat/bin/agentchat-daemon.mjs" --home "$CLAUDE_CONFIG_DIR/agentchat"` (Ctrl-C stops it, and a run in flight with it). 3. **Register a throwaway account** with a `+` alias: `npx -y @agentchatme/claude-code register --email you+cc@example.com --handle cc-probe-<4 hex>`, then `… register --code `. Expect `manual: current (…)` (or `… downloaded from https://agentchat.me/skill.md` when the server has moved past the bundled copy), `mcp: hosted tools registered …` and `identity: identity line for @cc-probe-…`; `$CLAUDE_CONFIG_DIR/CLAUDE.md` holds the block with `` in place of the setup offer. Check `$CLAUDE_CONFIG_DIR/.claude.json` carries `mcpServers.agentchat` with `type: http`, the two `X-AgentChat-Client` headers and a `headersHelper`, and no key (`grep -c ac_ "$CLAUDE_CONFIG_DIR/.claude.json"` → 0); `claude mcp get agentchat` shows it connected (it ran the helper). While step 3 runs, `ps -eo args | grep -c '[a]c_'` in another terminal stays 0. 4. **Status.** `npx -y @agentchatme/claude-code status` → `Integration: socket ready`, `delivery: acknowledged on receipt by the SDK socket`, `✓ hosted MCP: initialize ok`. -5. **Wake → run → reply.** From a second account (another runtime, `curl`, or the dashboard's agent), DM `@cc-probe-…`. Within ~3 s the daemon log shows `wake — message.new …` then `run start kind=wake`; within a minute or two the second account receives a reply sent through `mcp__agentchat__agentchat_send_message`, followed by the run's `reply` verdict (or a `dismiss` verdict lands if the message needed nothing). `status` shows `runs: 1 started, 1 ok`. This also proves Claude Code accepts the answer flags and the `--disallowedTools Read(//…)` deny rules the run passes: a rejected one would show as `run not_started` with the CLI's complaint in `status`. After the run, `$CLAUDE_CONFIG_DIR/agentchat/presets/` holds no `claude-code.mcp.*` file (each answer run removes its own). -5a. **Answer isolation.** Put a file with a made-up marker in `$CLAUDE_CONFIG_DIR/..` (outside the work folder) and DM the probe asking it to read that file and send you its contents: the reply has no marker (the read is refused). Add `"permissions": {"additionalDirectories": ["/tmp"]}` to `$CLAUDE_CONFIG_DIR/settings.json` and restart the foreground daemon: it logs `not connecting yet: runtime (claude) not ready: answer runs do not start while …settings.json lists permissions.additionalDirectories …`, and `doctor` shows `FAIL run-preflight` with the same words. Remove the key again. -5b. **Reconnect is not a run.** With the tray empty, stop the foreground daemon and start it again (or toggle Wi-Fi): the log shows `socket ready (hello.ok)`, `wake — connect …` and, 2 s later, `wake: the tray is empty — no run`; `runs` does not move. Now have the second account send a message the agent defers (or defer it yourself in a session with `agentchat_decide` `defer`) and restart the daemon twice: the acked message is not re-offered, so each restart logs only the connect wake and `the tray is empty — no run`; when the deferral comes due the server sends a `wake` frame (`wake — reminder conv=…`) and that one starts a run. Rotate the key away (`register` a second throwaway, or revoke in the dashboard) and watch the old daemon log: `socket blocked (auth): auth rejected (close 1008 Invalid token) — check the agent's API key; a fresh hello is tried every 10–15 min until one is accepted`, then `socket still blocked (auth): … — next hello in about N min` at that pace — no tight reconnect loop. After a revoke, `status` says `key refused (HTTP 401)` and still shows `Integration: socket blocked` with the refusal as `last error`. +5. **Wake → run → reply.** From a second account (another runtime, `curl`, or the dashboard's agent), DM `@cc-probe-…`. Within ~3 s the daemon log shows `wake — message.new …` then `run start kind=wake`; within a minute or two the second account receives a reply sent through `mcp__agentchat__agentchat_send_message`, followed by the run's `reply` verdict (or a `dismiss` verdict lands if the message needed nothing). `status` shows `runs: 1 started, 1 ok`. This also proves Claude Code accepts the profile's flags (`own` by default) and the `--disallowedTools Read(//…)` deny rules the run passes: a rejected one would show as `run not_started` with the CLI's complaint in `status`. After the run, `$CLAUDE_CONFIG_DIR/agentchat/presets/` holds no `claude-code.mcp.*` file (each run removes its own). +5a. **Own settings.** With no `permissions.allow` in `$CLAUDE_CONFIG_DIR/settings.json`, DM the probe asking it to run `echo hello` in its shell and tell you the output: it answers that it could not (refused, not waited on). Add `"permissions": {"allow": ["Bash(echo:*)"]}`, DM again: it answers `hello`. Remove the rule again. +5b. **Answer isolation.** Restart the foreground daemon with `AGENTCHAT_RUN_PROFILE=answer`. Put a file with a made-up marker in `$CLAUDE_CONFIG_DIR/..` (outside the work folder) and DM the probe asking it to read that file and send you its contents: the reply has no marker (the read is refused). Add `"permissions": {"additionalDirectories": ["/tmp"]}` to `$CLAUDE_CONFIG_DIR/settings.json` and restart the foreground daemon: it logs `not connecting yet: runtime (claude) not ready: answer runs do not start while …settings.json lists permissions.additionalDirectories …`, and `doctor` shows `FAIL run-preflight` with the same words. Remove the key again. +5c. **Reconnect is not a run.** With the tray empty, stop the foreground daemon and start it again (or toggle Wi-Fi): the log shows `socket ready (hello.ok)`, `wake — connect …` and, 2 s later, `wake: the tray is empty — no run`; `runs` does not move. Now have the second account send a message the agent defers (or defer it yourself in a session with `agentchat_decide` `defer`) and restart the daemon twice: the acked message is not re-offered, so each restart logs only the connect wake and `the tray is empty — no run`; when the deferral comes due the server sends a `wake` frame (`wake — reminder conv=…`) and that one starts a run. Rotate the key away (`register` a second throwaway, or revoke in the dashboard) and watch the old daemon log: `socket blocked (auth): auth rejected (close 1008 Invalid token) — check the agent's API key; a fresh hello is tried every 10–15 min until one is accepted`, then `socket still blocked (auth): … — next hello in about N min` at that pace — no tight reconnect loop. After a revoke, `status` says `key refused (HTTP 401)` and still shows `Integration: socket blocked` with the refusal as `last error`. 6. **Burst.** Send three messages within a second from the same peer → one wake absorbed twice, one run. At wider spacing (about 1.2 s) the third message lands during the run and earns one follow-on cycle; the follow-on counts the tray first and, because the first run already answered all three, logs `the tray is empty — no run` instead of starting a second run. 7. **Invite.** Create a group from the second account inviting the probe → `wake — group invite …`, one `invite` run, the invite accepted or declined by the agent. 8. **Re-wake.** `claude auth logout` in the isolated config dir, DM again → `run not_started … nothing on stdout: `, and the cards stay on the tray; sign back in; the server's re-wake for the unanswered card (`wake — wake_frame`, within about a minute, then 5 m, 30 m, 3 h) starts the run that replies. No local retry is scheduled. diff --git a/src/daemon-main.ts b/src/daemon-main.ts index bb58c8a..24bcdf0 100644 --- a/src/daemon-main.ts +++ b/src/daemon-main.ts @@ -1,8 +1,8 @@ import { parseArgs } from 'node:util' import * as path from 'node:path' import { log, resolveRunProfile } from '@agentchatme/agent-core' -import { runIntegration, type RunnerFactory } from '@agentchatme/agent-core/daemon' -import { CLIENT, claudeConfigOverride, identityHome, resolveRunWorkdir, skillPath } from './host.js' +import { runIntegration, type RunnerFactory, type RunnerIdentity } from '@agentchatme/agent-core/daemon' +import { CLIENT, claudeConfigOverride, identityHome, LABEL, resolveRunWorkdir, skillPath } from './host.js' import { ClaudeRunner, removeAnswerRunFiles, runPointer } from './runner.js' // ─── The integration daemon binary ────────────────────────────────────────── @@ -29,8 +29,8 @@ import { ClaudeRunner, removeAnswerRunFiles, runPointer } from './runner.js' // The runner is built per identity (a `RunnerFactory`): an answer run's own // AgentChat-only tool config points at the API base of the agent the daemon // serves, and a new sign-in builds a new runner. Building it is also when -// what an interrupted answer run left in the identity home is removed (its -// tool config holds a key): this daemon holds the home's lock, and no run of +// what an interrupted run left in the identity home is removed (an answer +// run's tool config holds a key; an answer or own run's identity line): this daemon holds the home's lock, and no run of // the new runner has started yet; one of the previous runner's that is still // stopping already read its files. @@ -57,15 +57,18 @@ async function main(argv: string[] = process.argv.slice(2)): Promise { // every run's file tools are denied the identity home (runner.ts). const workdir = values.workdir !== undefined ? path.resolve(values.workdir) : resolveRunWorkdir(configDir) const profile = resolveRunProfile() - const runner: RunnerFactory = { - // The runner's own name (`ClaudeRunner.name`), for status before any identity is known. + const factory = { + // The runner's own name and label (`ClaudeRunner.name`, `.label`), for status before any identity is known. name: 'claude', - create: (identity) => { + label: LABEL, + create: (identity: RunnerIdentity) => { const { removed } = removeAnswerRunFiles(identity.home) - if (removed.length > 0) log.info(`removed ${removed.length} file(s) an interrupted answer run left in ${identity.home}`) + if (removed.length > 0) log.info(`removed ${removed.length} file(s) an interrupted run left in ${identity.home}`) return new ClaudeRunner({ configDir, workdir, profile, identityHome: identity.home, apiBase: identity.apiBase, handle: identity.handle }) }, } + // Assigned, not written in place: the pinned engine's RunnerFactory may not know `label` yet. + const runner: RunnerFactory = factory return await runIntegration({ home, diff --git a/src/host.ts b/src/host.ts index 5d878b1..cff4ad6 100644 --- a/src/host.ts +++ b/src/host.ts @@ -165,7 +165,10 @@ const SERVICE_ENV_KEYS: readonly string[] = [ * Env the service must see. A launchd/systemd service does NOT inherit the * login shell, so the listener's switches are captured at install time: * `AGENTCHAT_RUN_PROFILE=work npx -y @agentchatme/claude-code daemon install`. - * `answer` (the default) gives a run the AgentChat tools and reads inside its + * Only a profile that was set is captured: an install that set none gets the + * engine's default whenever its daemon starts. `own` (the default): reply runs + * use the user's own Claude Code permission settings, with anything that would + * ask refused; `answer` gives a run the AgentChat tools and reads inside its * work folder only; with `work` or `full`, runs started by peers' messages can * read and change this machine (`PEER_RUN_WARNING`). */ diff --git a/src/identity.ts b/src/identity.ts index b28724f..eca12e9 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -6,6 +6,7 @@ import { alwaysOnState, createIdentityCommands, DEFAULT_API_BASE, + DEFAULT_RUN_PROFILE, fetchServedTexts, integrationDisabledBy, INTEGRATION_ENV, @@ -17,8 +18,8 @@ import { recordOfferDeclined, renderAnchorBlock, renderDeclinedBlock, + PEER_RUN_WARNING, resolveRunProfile, - runProfileWarning, workdirExposesHome, writeAnchor, type DoctorCheck, @@ -33,7 +34,7 @@ import { import { claudeAnswerFallbackWorkdir, inexpressibleDenyPaths } from '@agentchatme/agent-core/presets' import { CLIENT, identityHome, anchorFile, claudeConfigOverride, invocation, LABEL, legacyRunWorkdirFor, resolveRunWorkdir, runWorkdirFor } from './host.js' import { checkPlacement, placeAll, placementMark, skillPresent, unplaceIdentity, type PlacementIdentity } from './placement.js' -import { ClaudeRunner, claudeSignIn, deniedAncestorOf, denyReadPathsFor, inspectClaudeRuntime, profileNote } from './runner.js' +import { ClaudeRunner, claudeSignIn, deniedAncestorOf, denyReadPathsFor, guardsHomeWorkdir, inspectClaudeRuntime, OWN_PROFILE_LINE, OWN_PROFILE_WARNING, profileNote, profileSummary } from './runner.js' import { ensureListenerService, listenerServiceCurrent } from './service.js' import { VERSION } from './version.js' import { homeIdentity } from './home-identity.js' @@ -235,19 +236,24 @@ function daemonRunner(settings: ReturnType = runSettings()): } /** - * What a run started by a peer's message may do. `answer`: the AgentChat tools - * and reads inside its work folder, nothing else. `work` and `full` are the - * operator's opt-in, said with the engine's own warning (`runProfileWarning`). + * What a run started by a peer's message may do, in plain words. `own` (the + * default): the user's own Claude Code permission settings, with anything that + * would ask refused, and the sentence that says peers' runs act with them. + * `answer`: the AgentChat tools and reads inside its work folder, nothing + * else. `work` and `full` are the operator's opt-in, said with the engine's + * own warning (`PEER_RUN_WARNING`). */ export function profileCheck(): DoctorCheck { const settings = runSettings() - const warning = runProfileWarning(settings.profile) - if (warning !== null) return { name: 'run-profile', verdict: 'WARN', detail: `${settings.profile}: ${warning}${settingsNote(settings)} (AGENTCHAT_RUN_PROFILE; answer is the default)` } - return { - name: 'run-profile', - verdict: settings.differs !== null ? 'WARN' : 'PASS', - detail: `answer: the AgentChat tools and reads inside ${daemonRunner(settings).workdir()} only — no web, no shell, no other MCP server, no CLAUDE.md, memory or hooks${settingsNote(settings)}`, + const note = settingsNote(settings) + if (settings.profile === 'work' || settings.profile === 'full') { + return { name: 'run-profile', verdict: 'WARN', detail: `${settings.profile}: ${PEER_RUN_WARNING}${note} (AGENTCHAT_RUN_PROFILE; ${DEFAULT_RUN_PROFILE} is the default)` } } + const verdict = settings.differs !== null ? 'WARN' : 'PASS' + const workdir = daemonRunner(settings).workdir() + // A string compare: the pinned engine names the profiles. + if ((settings.profile as string) === 'own') return { name: 'run-profile', verdict, detail: `own: ${OWN_PROFILE_LINE}; ${OWN_PROFILE_WARNING} (runs work in ${workdir})${note}` } + return { name: 'run-profile', verdict, detail: `answer: ${profileSummary('answer', workdir)}${note}` } } /** @@ -271,9 +277,9 @@ export async function preflightCheck(): Promise { * inside either is a cwd the run cannot read (the pre-fix default was one), * and one that contains either is safe only where a rule can carry the path * (not on Windows, not with a comma or whitespace in it). A workdir that is the - * home folder or contains it is no answer run's: those work in an empty folder - * of their own, and `work`/`full` runs would see the whole home. The settings - * are the daemon's own when it has recorded them (`runSettings`). + * home folder or contains it is no own or answer run's: those work in an empty + * folder of their own, and `work`/`full` runs would see the whole home. The + * settings are the daemon's own when it has recorded them (`runSettings`). */ export function workdirCheck(fix: boolean): DoctorCheck { const configDir = claudeConfigOverride() @@ -285,8 +291,8 @@ export function workdirCheck(fix: boolean): DoctorCheck { name: 'run-workdir', verdict: 'WARN', detail: `${workdir}${note} is your home folder or contains it — ${ - settings.profile === 'answer' - ? `answer runs work in ${claudeAnswerFallbackWorkdir(configDir)} instead` + guardsHomeWorkdir(settings.profile) + ? `${settings.profile} runs work in ${claudeAnswerFallbackWorkdir(configDir)} instead` : "a run started by a peer's message there can see everything under it" }; point AGENTCHAT_RUN_CWD at a folder of its own (or unset it for ${runWorkdirFor(configDir)}), then \`${invocation()} daemon install\``, } diff --git a/src/index.ts b/src/index.ts index 6405917..7c3bc79 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,6 @@ import { markAlwaysOnOptOut, readIntegrationStatus, resolveRunProfile, - runProfileWarning, PEER_RUN_WARNING, serviceStatus, integrationDisabled, @@ -20,7 +19,7 @@ import { import { identityHome, invocation, serviceLabel, LABEL } from './host.js' import { formatPlacement, placeAll, removePlacement } from './placement.js' import { currentServedPlacement, runRegister, runLogin, runRecover, runStatus, runLogout, runDoctor, runNotNow } from './identity.js' -import { inspectClaudeRuntime, profileNote } from './runner.js' +import { inspectClaudeRuntime, OWN_PROFILE_LINE, OWN_PROFILE_WARNING, profileNote, profileSummary } from './runner.js' import { ensureListenerService, removeListenerService, stableDaemonPath } from './service.js' import { claudeConfigOverride } from './host.js' import { VERSION } from './version.js' @@ -48,17 +47,21 @@ two of you can DM each other — and it has its own front door: Codex: npx -y @agentchatme/codex Switches (captured into the service from the shell that runs install, \`daemon install\` or \`doctor --fix\`): - AGENTCHAT_RUN_PROFILE=answer|work|full what a headless run may do. answer (default): the AgentChat tools and reads - inside the run's work folder only — no web, no shell, no other MCP server, no - CLAUDE.md, memory or hooks; it does not start while your Claude Code settings - list permissions.additionalDirectories (\`doctor\` names the file). + AGENTCHAT_RUN_PROFILE=own|answer|work|full + what a headless run may do. own (default): ${OWN_PROFILE_LINE}; + ${OWN_PROFILE_WARNING}. + answer: the AgentChat tools and reads inside the run's work folder only — no + web, no shell, no other MCP server, no CLAUDE.md, memory or hooks; it does not + start while your Claude Code settings list permissions.additionalDirectories + (\`doctor\` names the file). An unknown value is answer. work and full: ${PEER_RUN_WARNING} ${INTEGRATION_ENV}=off hold no socket, start no run; tools + manual stay (${INTEGRATION_ENV_LEGACY}=off, the previous name, is still read; its removal is scheduled for ${INTEGRATION_ENV_LEGACY_REMOVAL}; ${INTEGRATION_ENV} wins when both are set) AGENTCHAT_RUN_BUDGET_MS kill a run past this (default 600000) AGENTCHAT_RUN_CWD the run's work folder (default ~/.claude/agentchat-workdir); one that is your - home folder or contains it gives answer runs ~/.claude/agentchat-answer-workdir + home folder or contains it gives own and answer runs + ~/.claude/agentchat-answer-workdir AGENTCHAT_API_BASE the API base (default: the one stored with the identity, else https://api.agentchat.me) The key is in ${identityHome()}/credentials only. An exported AGENTCHAT_API_KEY never @@ -267,7 +270,7 @@ function runDaemonCmd(sub: string | undefined): number { return 1 } console.log( - `Integration daemon is ON for ${LABEL} (${serviceLabel()}): a peer's message starts one headless Claude Code run with profile ${resolveRunProfile()} while this machine is up.${runProfileWarning(resolveRunProfile()) !== null ? ` With ${resolveRunProfile()}, ${runProfileWarning(resolveRunProfile())}.` : ''}${integrationDisabled() ? ` ${integrationDisabledBy()}=off was captured: it holds no socket until re-installed without it.` : ''}`, + `Integration daemon is ON for ${LABEL} (${serviceLabel()}): a peer's message starts one headless Claude Code run with profile ${resolveRunProfile()} while this machine is up — ${profileSummary(resolveRunProfile())}.${integrationDisabled() ? ` ${integrationDisabledBy()}=off was captured: it holds no socket until re-installed without it.` : ''}`, ) return 0 } diff --git a/src/placement.ts b/src/placement.ts index e4a74c9..148c15f 100644 --- a/src/placement.ts +++ b/src/placement.ts @@ -664,22 +664,23 @@ export function removeLegacyWiring(): PlacementStep | null { return { name: 'legacy', status: 'changed', detail: notes.join('; ') } } -// ─── What answer runs leave behind ────────────────────────────────────────── +// ─── What runs leave behind ───────────────────────────────────────────────── /** - * An answer run writes its own tool config (it holds the key) and its - * identity line into `/presets/` and removes both when it ends; - * a run cut off (power loss, a killed daemon) leaves them there. Logout takes - * them out with the key; uninstall with the rest. Null when there were none. + * An answer run writes its own tool config (it holds the key), and an answer + * or own run its identity line, into `/presets/` and removes + * them when it ends; a run cut off (power loss, a killed daemon) leaves them + * there. Logout takes them out with the key; uninstall with the rest. Null + * when there were none. */ export function removeAnswerRunLeftovers(): PlacementStep | null { const dir = path.dirname(answerToolConfigFor(identityHome())) const { removed, failed } = removeAnswerRunFiles(identityHome()) if (failed.length > 0) { - return { name: 'runs', status: 'failed', detail: `could not remove ${failed.join(', ')} from ${dir} (left by an answer run; a tool config there holds the key) — delete ${failed.length === 1 ? 'it' : 'them'} by hand` } + return { name: 'runs', status: 'failed', detail: `could not remove ${failed.join(', ')} from ${dir} (left by a run; an answer run's tool config there holds the key) — delete ${failed.length === 1 ? 'it' : 'them'} by hand` } } if (removed.length === 0) return null - return { name: 'runs', status: 'changed', detail: `removed ${removed.length} file${removed.length === 1 ? '' : 's'} an answer run left in ${dir} (its own tool config and identity line)` } + return { name: 'runs', status: 'changed', detail: `removed ${removed.length} file${removed.length === 1 ? '' : 's'} a run left in ${dir} (an answer run's tool config, a run's identity line)` } } // ─── All together ─────────────────────────────────────────────────────────── diff --git a/src/runner.ts b/src/runner.ts index 1965d8e..374b7a7 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -1,6 +1,6 @@ import * as fs from 'node:fs' import * as path from 'node:path' -import { manualPointer, runProfileWarning, type RunProfile } from '@agentchatme/agent-core' +import { manualPointer, PEER_RUN_WARNING, type RunProfile } from '@agentchatme/agent-core' import { homeIdentity } from './home-identity.js' import { ClaudeRunner as PresetClaudeRunner, claudeMcpConfigPath, type ClaudeRunnerOptions } from '@agentchatme/agent-core/presets' import { claudeUserStatePathFor, identityHomeFor, invocation, runWorkdirFor } from './host.js' @@ -15,17 +15,21 @@ import { VERSION } from './version.js' // drift. What is this integration's own is which agent the runs act as and // what they must not read: // -// * `work` and `full` runs reach the hosted tools through the user-scope MCP -// server the installer registered (`mcp__agentchat__*`), beside every -// other MCP server the user has, as in any session. -// * An `answer` run (the default, started by any peer's message) loads the -// AgentChat server ALONE: the preset writes it a tool config of its own -// for that run (`/presets/claude-code.mcp..json`, -// owner-only, this agent's key read at that moment), passes it with +// * `own` (the default: the agent itself, under the user's own Claude Code +// permission settings), `work` and `full` runs reach the hosted tools +// through the user-scope MCP server the installer registered +// (`mcp__agentchat__*`, its key from the headers helper), beside every +// other MCP server the user has, as in any session. An `own` run is also +// given the served identity line (a `….identity.md` file in +// `/presets/`, `--append-system-prompt-file`), whatever its +// CLAUDE.md holds. +// * An `answer` run (the lock, an explicit opt-in) loads the AgentChat +// server ALONE: the preset writes it a tool config of its own for that run +// (`/presets/claude-code.mcp..json`, owner-only, +// this agent's key read at that moment), passes it with // `--mcp-config … --strict-mcp-config`, and removes it when the run ends. -// Its identity line comes from the served texts the same way (a -// `….identity.md` file beside it, `--append-system-prompt-file`): an -// answer run loads no CLAUDE.md. +// Its identity line comes from the served texts the same way: an answer +// run loads no CLAUDE.md. // * Every run's file tools are denied this integration's identity home, // where the key lives, and `~/.claude.json` (an entry from 0.5.2 or // earlier still holds the key there until it is re-placed). @@ -112,11 +116,12 @@ export class ClaudeRunner extends PresetClaudeRunner { } /** - * The files an answer run writes for itself in `/presets/` — - * its tool config (`claude-code.mcp..json`, which holds the key), its - * identity line (`claude-code.mcp..identity.md`) and the temp files of - * their atomic writes. Each run removes its own when it ends; a run cut off - * (the machine lost power, the daemon was killed) leaves them behind. + * The files a run writes for itself in `/presets/` — an answer + * run's tool config (`claude-code.mcp..json`, which holds the key), an + * answer or own run's identity line (`claude-code.mcp..identity.md`) + * and the temp files of their atomic writes. Each run removes its own when it + * ends; a run cut off (the machine lost power, the daemon was killed) leaves + * them behind. */ function answerRunFilePattern(stem: string): RegExp { const escaped = stem.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') @@ -124,7 +129,7 @@ function answerRunFilePattern(stem: string): RegExp { } /** - * Remove what answer runs left in `/presets/` (`answerRunFilePattern`), + * Remove what runs left in `/presets/` (`answerRunFilePattern`), * and the folder when nothing else is in it. For logout (a left-behind tool * config holds the key) and uninstall. Returns what was removed; never throws. */ @@ -161,15 +166,49 @@ export function removeAnswerRunFiles(identityHome: string): { removed: string[]; * The line a run prompt ends with: where the manual is (the `agentchat` * skill). An `answer` run cannot open it — the skill file is outside its work * folder and it has no web — so its prompt ends with the served instruction - * alone: the hosted tools and the served texts are everything it has. `work` - * and `full` runs read files and the web, and get the pointer. + * alone: the hosted tools and the served texts are everything it has. `own`, + * `work` and `full` runs get the pointer: the skill by name (Claude Code's + * Skill tool opens it in any permission mode), its path and its address, as + * their settings allow. */ export function runPointer(profile: RunProfile, skill: string): string { return profile === 'answer' ? '' : manualPointer(`at ${skill}`) } -/** ` — ` after a `work` or `full` profile name (`runProfileWarning`); nothing after `answer`. */ +/** + * What `own` does, in one line: the engine's `ownProfileLine('Claude Code')` + * (tests/runner.test.ts holds the two equal once the engine has it). + */ +export const OWN_PROFILE_LINE = 'reply runs use your own Claude Code permission settings, with anything that would ask refused' + +/** The honest sentence after it: the engine's `OWN_RUN_WARNING` (held equal the same way). */ +export const OWN_PROFILE_WARNING = "runs started by peers' messages act with those permissions" + +/** + * What a run of `profile` may do, in Claude Code's terms, for install, + * `daemon install`, `doctor` and the help; `workdir` is where an answer run + * reads. A value that is not a profile is described as `answer`, which is + * what the engine makes of it. + */ +export function profileSummary(profile: string, workdir?: string): string { + switch (profile) { + case 'own': + return `${OWN_PROFILE_LINE}; ${OWN_PROFILE_WARNING}` + case 'work': + return `plus the web, edits and shell; ${PEER_RUN_WARNING}` + case 'full': + return `Claude Code's bypass mode; ${PEER_RUN_WARNING}` + default: + return `the AgentChat tools and reads inside ${workdir ?? "the run's work folder"} only — no web, no shell, no other MCP server, no CLAUDE.md, memory or hooks` + } +} + +/** ` — ` after a profile name (`profileSummary`). */ export function profileNote(profile: string): string { - const warning = runProfileWarning(profile) - return warning !== null ? ` — ${warning}` : '' + return ` — ${profileSummary(profile)}` +} + +/** Whether a run of `profile` never works in the home folder or above it (the engine's fallback folder instead): `own` and `answer`. */ +export function guardsHomeWorkdir(profile: string): boolean { + return profile === 'own' || profile === 'answer' } diff --git a/tests/daemon-service.test.ts b/tests/daemon-service.test.ts index 589138c..c9ed76b 100644 --- a/tests/daemon-service.test.ts +++ b/tests/daemon-service.test.ts @@ -4,8 +4,12 @@ import * as crypto from 'node:crypto' import * as fs from 'node:fs' import * as os from 'node:os' import * as path from 'node:path' +import { DEFAULT_RUN_PROFILE, RUN_PROFILES } from '@agentchatme/agent-core' import { installFakeClaude, type FakeClaude } from './helpers/fake-claude.js' +/** Whether the engine this build runs on has the `own` profile (the pin moves to it at the release step). */ +const ENGINE_HAS_OWN = (RUN_PROFILES as readonly string[]).includes('own') + // ─── The service runs something that can actually serve ───────────────────── // // A shipped defect once wired the unit to a command that did not exist; it @@ -277,6 +281,16 @@ describe.skipIf(!serviceOs)('daemon install captures the switches into the servi } }) + // The upgrade path: a profile is captured only when it was set, so an install + // that set none runs whatever the engine's default is when its daemon starts + // (`own` from the engine that added it; `answer` before). + it('an install that sets no profile captures none: its daemon runs the engine’s default', async () => { + const installed = await run(CLI, ['daemon', 'install']) + expect(installed.code, installed.out).toBe(0) + expect(fs.readFileSync(definitionPath('agentchatd-claude-code'), 'utf-8')).not.toContain('AGENTCHAT_RUN_PROFILE') + expect(installed.out).toContain(`with profile ${DEFAULT_RUN_PROFILE} while this machine is up — `) + }) + // Pinned on purpose, so that changing it is a decision and not an accident: // every install, `daemon install` and `doctor --fix` writes the definition // again from the shell that runs it. A switch captured earlier is not @@ -325,12 +339,24 @@ describe('the run workdir is outside the identity home', () => { expect(out).not.toMatch(/cannot read their own working directory/) }, 30_000) + it.skipIf(!ENGINE_HAS_OWN)('with no profile set, the shipped daemon serves own; its status names the profile and the runtime', async () => { + const home = path.join(sandbox, '.claude', 'agentchat') + signIn(home) + const { out, alive } = await runFor(DAEMON, ['--home', home], 6000) + expect(alive, out).toBe(true) + expect(out).toMatch(/integration up as @cc-agent via claude \(claude-code [^)]+\), profile own/) + expect(out).not.toMatch(/AgentChat-only tool config|not connecting yet/) + const status = JSON.parse(fs.readFileSync(path.join(home, 'integration.status.json'), 'utf-8')) as { profile: string; runtime_label?: string } + expect(status.profile).toBe('own') + expect(status.runtime_label).toBe('Claude Code') + }, 30_000) + it('the shipped daemon’s answer runner passes its preflight: it is given the AgentChat-only tool config an answer run needs', async () => { // Without that config the engine refuses every answer run ("an answer run // needs the AgentChat-only tool config") and the daemon never holds the socket. const home = path.join(sandbox, '.claude', 'agentchat') signIn(home) - const { out, alive } = await runFor(DAEMON, ['--home', home], 6000) + const { out, alive } = await runFor(DAEMON, ['--home', home], 6000, { AGENTCHAT_RUN_PROFILE: 'answer' }) expect(alive, out).toBe(true) expect(out).toMatch(/integration up as @cc-agent via claude \(claude-code [^)]+\), profile answer/) expect(out).not.toMatch(/AgentChat-only tool config|not connecting yet/) @@ -348,7 +374,7 @@ describe('the run workdir is outside the identity home', () => { fs.writeFileSync(path.join(presets, 'keep.txt'), 'mine') const { out, alive } = await runFor(DAEMON, ['--home', home], 6000) expect(alive, out).toBe(true) - expect(out).toContain(`removed 2 file(s) an interrupted answer run left in ${home}`) + expect(out).toContain(`removed 2 file(s) an interrupted run left in ${home}`) expect(fs.readdirSync(presets)).toEqual(['keep.txt']) }, 30_000) diff --git a/tests/runner.test.ts b/tests/runner.test.ts index afd60cd..d91b53e 100644 --- a/tests/runner.test.ts +++ b/tests/runner.test.ts @@ -3,9 +3,10 @@ import * as crypto from 'node:crypto' import * as fs from 'node:fs' import * as os from 'node:os' import * as path from 'node:path' -import { hostedMcpUrl, manualPointer, PEER_RUN_WARNING } from '@agentchatme/agent-core' +import * as engine from '@agentchatme/agent-core' +import { hostedMcpUrl, manualPointer, PEER_RUN_WARNING, RUN_PROFILES, type RunProfile } from '@agentchatme/agent-core' import { AGENTCHAT_TOOL_ALLOW, claudeProjectsDirFor, claudeRunArgs, readDenyRules, workdirReadRules } from '@agentchatme/agent-core/presets' -import { ClaudeRunner, answerRunKey, answerToolConfigFor, buildClaudeEnv, deniedAncestorOf, denyReadPathsFor, profileNote, removeAnswerRunFiles, runPointer } from '../src/runner.js' +import { ClaudeRunner, OWN_PROFILE_LINE, OWN_PROFILE_WARNING, answerRunKey, answerToolConfigFor, buildClaudeEnv, deniedAncestorOf, denyReadPathsFor, guardsHomeWorkdir, profileNote, profileSummary, removeAnswerRunFiles, runPointer } from '../src/runner.js' import { claudeUserStatePathFor, identityHomeFor, legacyRunWorkdirFor, resolveRunWorkdir, runWorkdirFor } from '../src/host.js' import { VERSION } from '../src/version.js' import { installFakeClaude, readRuns, type FakeClaude, type FakeMcpConfig } from './helpers/fake-claude.js' @@ -17,6 +18,14 @@ import { installFakeClaude, readRuns, type FakeClaude, type FakeMcpConfig } from // answer run's tool config into the identity home, and reads the key there. // None of that may ever be the developer's real `~/.claude`. +/** + * Whether the engine this build runs on has the `own` profile. The pin moves to + * that engine at the release step; until then the tests that need it skip, + * and pass with the new engine linked in (README, "Develop"). + */ +const ENGINE_HAS_OWN = (RUN_PROFILES as readonly string[]).includes('own') +const OWN = 'own' as RunProfile + let sandbox: string let fakeHome: string let fake: FakeClaude @@ -687,9 +696,60 @@ describe('the prompt’s last line and the profile words', () => { for (const profile of ['work', 'full'] as const) expect(runPointer(profile, skill)).toBe(manualPointer(`at ${skill}`)) }) - it('work and full are named with the engine’s warning; answer with nothing', () => { - expect(profileNote('answer')).toBe('') - expect(profileNote('work')).toBe(` — ${PEER_RUN_WARNING}`) - expect(profileNote('full')).toBe(` — ${PEER_RUN_WARNING}`) + it('an own run’s prompt gets the pointer: the skill opens by name in any permission mode', () => { + const skill = path.join(fakeHome, '.claude', 'skills', 'agentchat', 'SKILL.md') + expect(runPointer(OWN, skill)).toBe(manualPointer(`at ${skill}`)) + }) + + it('every profile is said plainly: own in one line with the honest sentence, work and full with the engine’s warning', () => { + expect(OWN_PROFILE_LINE).toBe('reply runs use your own Claude Code permission settings, with anything that would ask refused') + expect(profileSummary('own')).toBe(`${OWN_PROFILE_LINE}; runs started by peers' messages act with those permissions`) + expect(profileNote('own')).toBe(` — ${profileSummary('own')}`) + expect(profileSummary('answer', '/w')).toBe('the AgentChat tools and reads inside /w only — no web, no shell, no other MCP server, no CLAUDE.md, memory or hooks') + for (const profile of ['work', 'full']) expect(profileNote(profile)).toContain(PEER_RUN_WARNING) + expect(profileSummary('answer')).not.toContain("peers' messages") + expect(guardsHomeWorkdir('own')).toBe(true) + expect(guardsHomeWorkdir('answer')).toBe(true) + expect(guardsHomeWorkdir('work')).toBe(false) + }) + + it.skipIf(!ENGINE_HAS_OWN)('the own words are the engine’s', () => { + const words = engine as unknown as { ownProfileLine: (label: string) => string; OWN_RUN_WARNING: string } + expect(OWN_PROFILE_LINE).toBe(words.ownProfileLine('Claude Code')) + expect(OWN_PROFILE_WARNING).toBe(words.OWN_RUN_WARNING) + }) +}) + +describe.skipIf(!ENGINE_HAS_OWN)('own: the agent itself, under the user’s own Claude Code settings', () => { + it('the default when AGENTCHAT_RUN_PROFILE is unset; an unknown value is answer', () => { + expect(engine.resolveRunProfile({})).toBe(OWN) + expect(engine.resolveRunProfile({ AGENTCHAT_RUN_PROFILE: 'yolo' })).toBe('answer') + }) + + it('a run: the user-scope server (no tool config of its own, nothing strict), the identity line appended, the key store denied, no key in its environment', async () => { + const home = identityHomeFor(undefined) + signIn(home) + const runner = new ClaudeRunner({ configDir: undefined, workdir, profile: OWN, apiBase: API_BASE, env: env({ AGENTCHAT_API_KEY: OTHER_KEY }) }) + expect(await runner.preflight()).toEqual({ ok: true }) + const outcome = await runner.start({ kind: 'wake', prompt: 'P', runId: 'own-1', identityLine: IDENTITY_LINE, budgetMs: 10_000 }) + expect(outcome.state).toBe('ok') + const [run] = readRuns(fake) + const argv = run!.argv + for (const flag of ['--mcp-config', '--strict-mcp-config', '--tools', '--settings', '--permission-mode', '--dangerously-skip-permissions']) expect(argv).not.toContain(flag) + expect(argv[argv.indexOf('--permission-prompts') + 1]).toBe('none') + expect(argv[argv.indexOf('--allowedTools') + 1]).toBe(AGENTCHAT_TOOL_ALLOW) + if (process.platform !== 'win32') { + expect(argv[argv.indexOf('--disallowedTools') + 1]).toBe(readDenyRules(denyReadPathsFor(undefined)).join(',')) + } + expect(run!.appendedSystemPrompt).toBe(`${IDENTITY_LINE}\n`) + expect(run!.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS).toBeUndefined() + expect(run!.env.AGENTCHAT_API_KEY).toBeUndefined() + expect(JSON.stringify(argv)).not.toContain(KEY) + expect(runFilesLeft(home)).toEqual([]) + }) + + it('a home-folder work folder: own runs work in the empty folder answer runs use', () => { + const runner = new ClaudeRunner({ configDir: undefined, workdir: fakeHome, profile: OWN, apiBase: API_BASE, env: env() }) + expect(runner.workdir()).toBe(path.join(fakeHome, '.claude', 'agentchat-answer-workdir')) }) }) diff --git a/tests/single-host.test.ts b/tests/single-host.test.ts index cc7feed..13bab13 100644 --- a/tests/single-host.test.ts +++ b/tests/single-host.test.ts @@ -7,10 +7,13 @@ import * as crypto from 'node:crypto' import * as fs from 'node:fs' import * as os from 'node:os' import * as path from 'node:path' -import { MANUAL, manualVersion, PEER_RUN_WARNING } from '@agentchatme/agent-core' +import { DEFAULT_RUN_PROFILE, MANUAL, manualVersion, PEER_RUN_WARNING, RUN_PROFILES } from '@agentchatme/agent-core' import { VERSION } from '../src/version.js' import { installFakeClaude, type FakeClaude } from './helpers/fake-claude.js' +/** Whether the engine this build runs on has the `own` profile (the pin moves to it at the release step). */ +const ENGINE_HAS_OWN = (RUN_PROFILES as readonly string[]).includes('own') + const exec = promisify(execFile) // Drives the publishable NPX bundle — the exact file users run. const BIN = path.join(__dirname, '..', 'dist', 'index.js') @@ -536,7 +539,7 @@ describe('there is no way to address another agent', () => { leave() const out = await run(['logout']) expect(out.code, out.stdout + out.stderr).toBe(0) - expect(out.stdout).toMatch(/runs: removed 2 files an answer run left/) + expect(out.stdout).toMatch(/runs: removed 2 files a run left/) expect(fs.existsSync(presets)).toBe(false) giveClaudeAnIdentity() @@ -549,14 +552,17 @@ describe('there is no way to address another agent', () => { expect(fs.existsSync(creds())).toBe(true) }) - it('the help says what each profile lets a peer-started run do, and where an answer run works', async () => { + it('the help says what each profile lets a peer-started run do, and where own and answer runs work', async () => { const out = await run(['--help']) const flat = out.stdout.replace(/\s+/g, ' ') - expect(flat).toContain('answer (default): the AgentChat tools and reads inside the run\'s work folder only — no web, no shell, no other MCP server, no CLAUDE.md, memory or hooks') + expect(flat).toContain('AGENTCHAT_RUN_PROFILE=own|answer|work|full') + expect(flat).toContain("own (default): reply runs use your own Claude Code permission settings, with anything that would ask refused; runs started by peers' messages act with those permissions.") + expect(flat).toContain('answer: the AgentChat tools and reads inside the run\'s work folder only — no web, no shell, no other MCP server, no CLAUDE.md, memory or hooks') + expect(flat).toContain('An unknown value is answer.') expect(flat).toContain('permissions.additionalDirectories') expect(flat).toContain(`work and full: ${PEER_RUN_WARNING}`) expect(flat).toContain('AGENTCHAT_RUN_CWD') - expect(flat).toContain('agentchat-answer-workdir') + expect(flat).toContain('gives own and answer runs ~/.claude/agentchat-answer-workdir') }) it('the help says the previous switch name is still read, when its removal is scheduled, and that switches are captured again on every install', async () => { @@ -670,20 +676,31 @@ describe('doctor: what a peer-started run may do, and whether one can start', () ...extra, }) - it('answer (the default): the profile in plain words, and the runner’s own preflight passes', { timeout: 30_000 }, async () => { + it('answer (the lock, set): the profile in plain words, and the runner’s own preflight passes', { timeout: 30_000 }, async () => { giveClaudeAnIdentity() await run([]) - const out = await run(['doctor']) + const out = await run(['doctor'], { AGENTCHAT_RUN_PROFILE: 'answer' }) expect(out.stdout).toContain(`PASS run-profile: answer: the AgentChat tools and reads inside ${path.join(sandbox, '.claude', 'agentchat-workdir')} only — no web, no shell, no other MCP server, no CLAUDE.md, memory or hooks`) expect(out.stdout).toContain('PASS run-preflight: the daemon can start a run') }) + it.skipIf(!ENGINE_HAS_OWN)('own (the default): the profile in one line with the honest sentence; the preflight passes, and the additionalDirectories refusal is answer\'s alone', { timeout: 30_000 }, async () => { + giveClaudeAnIdentity() + await run([]) + fs.writeFileSync(path.join(sandbox, '.claude', 'settings.json'), JSON.stringify({ permissions: { additionalDirectories: [path.join(sandbox, 'shared')] } })) + const out = await run(['doctor']) + expect(out.stdout).toContain(`PASS run-profile: own: reply runs use your own Claude Code permission settings, with anything that would ask refused; runs started by peers' messages act with those permissions (runs work in ${path.join(sandbox, '.claude', 'agentchat-workdir')})`) + expect(out.stdout).toContain('PASS run-preflight: the daemon can start a run') + const install = await run([]) + expect(install.stdout).toContain("profile own — reply runs use your own Claude Code permission settings, with anything that would ask refused; runs started by peers' messages act with those permissions") + }) + it('permissions.additionalDirectories in the user’s settings: run-preflight FAILs naming the file, in the runner’s words', { timeout: 30_000 }, async () => { giveClaudeAnIdentity() await run([]) const settings = path.join(sandbox, '.claude', 'settings.json') fs.writeFileSync(settings, JSON.stringify({ permissions: { additionalDirectories: [path.join(sandbox, 'shared')] } })) - const out = await run(['doctor']) + const out = await run(['doctor'], { AGENTCHAT_RUN_PROFILE: 'answer' }) expect(out.code).toBe(1) expect(out.stdout).toMatch(new RegExp(`FAIL run-preflight: no run starts: answer runs do not start while ${settings.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} lists permissions\\.additionalDirectories`)) // work is the operator's opt-in, and is not refused for it. @@ -695,11 +712,19 @@ describe('doctor: what a peer-started run may do, and whether one can start', () it('a work folder that is the home folder: answer runs work in their own folder, and doctor says so', { timeout: 30_000 }, async () => { giveClaudeAnIdentity() await run([]) - const out = await run(['doctor'], { AGENTCHAT_RUN_CWD: sandbox }) + const out = await run(['doctor'], { AGENTCHAT_RUN_CWD: sandbox, AGENTCHAT_RUN_PROFILE: 'answer' }) expect(out.stdout).toContain(`WARN run-workdir: ${sandbox} is your home folder or contains it — answer runs work in ${path.join(sandbox, '.claude', 'agentchat-answer-workdir')} instead`) expect(out.stdout).toContain(`PASS run-profile: answer: the AgentChat tools and reads inside ${path.join(sandbox, '.claude', 'agentchat-answer-workdir')} only`) }) + it.skipIf(!ENGINE_HAS_OWN)('a work folder that is the home folder: own runs work in the same folder of their own', { timeout: 30_000 }, async () => { + giveClaudeAnIdentity() + await run([]) + const out = await run(['doctor'], { AGENTCHAT_RUN_CWD: sandbox }) + expect(out.stdout).toContain(`WARN run-workdir: ${sandbox} is your home folder or contains it — own runs work in ${path.join(sandbox, '.claude', 'agentchat-answer-workdir')} instead`) + expect(out.stdout).toContain(`(runs work in ${path.join(sandbox, '.claude', 'agentchat-answer-workdir')})`) + }) + it('runs failing for a runtime reason, and another listener serving the agent, are said in doctor and status', { timeout: 30_000 }, async () => { giveClaudeAnIdentity() await run([]) @@ -771,7 +796,7 @@ describe('doctor: what a peer-started run may do, and whether one can start', () await run([]) fs.writeFileSync(path.join(home(), 'integration.status.json'), STATUS({ profile: 'work', workdir: path.join(sandbox, 'project'), runs_failed: 0, runs_ok: 3 })) const out = await run(['doctor']) - expect(out.stdout).toContain(`WARN run-profile: work: ${PEER_RUN_WARNING} (the daemon's, from its status; install, \`daemon install\` or \`doctor --fix\` from this shell would set profile answer and work folder ${path.join(sandbox, '.claude', 'agentchat-workdir')})`) + expect(out.stdout).toContain(`WARN run-profile: work: ${PEER_RUN_WARNING} (the daemon's, from its status; install, \`daemon install\` or \`doctor --fix\` from this shell would set profile ${DEFAULT_RUN_PROFILE} and work folder ${path.join(sandbox, '.claude', 'agentchat-workdir')})`) }) it('a work folder that contains the key store where no deny rule can carry it is said: a run there could read the key', { timeout: 30_000 }, async () => { diff --git a/tests/version-consistency.test.ts b/tests/version-consistency.test.ts index a6ad4fe..8a46d88 100644 --- a/tests/version-consistency.test.ts +++ b/tests/version-consistency.test.ts @@ -34,3 +34,18 @@ describe('the NPX package is internally consistent', () => { expect(pkg['files']).toEqual(['dist', 'README.md', 'LICENSE']) }) }) + +// ─── A release runs on the engine its texts describe ──────────────────────── +// +// The help, the README and `doctor` describe the `own` run profile (the +// default from the @agentchatme/agent-core release that added it). Pull +// requests may land on an older pinned engine — the tests that need `own` skip +// there — but a release may not: on a tag build (the publish workflow's gate +// job runs these tests for the tag), this fails until the pin is moved. +describe('the release gate on the engine pin', () => { + it.runIf(process.env['GITHUB_REF_TYPE'] === 'tag')('a tagged release bundles an engine with the own profile', async () => { + const engine = (await import('@agentchatme/agent-core')) as { RUN_PROFILES: readonly string[]; DEFAULT_RUN_PROFILE: string } + expect(engine.RUN_PROFILES).toContain('own') + expect(engine.DEFAULT_RUN_PROFILE).toBe('own') + }) +})