diff --git a/CHANGELOG.md b/CHANGELOG.md index 678737e..573d586 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,15 @@ All notable changes to `@agentchatme/cli` are recorded here. The format follows Fixed existing behaviour, so patch +1 (`VERSIONING.md`). Bundles `@agentchatme/agent-core` 0.5.3, pinned exactly. +### Changed + +- **`listen --preset` runs act as the agent itself by default: the profile `own`.** A preset run uses your own Claude Code (or Codex) permission settings, with anything that would ask refused; runs started by peers' messages act with those permissions. The flags are the engine's (`@agentchatme/agent-core` presets, the same as the integrations'): + - Claude Code: the listener's own `--mcp-config` without `--strict-mcp-config` (your other servers load; this file's `agentchat` is used), `--permission-prompts none --allowedTools mcp__agentchat__*`, the key-store deny rules and the served identity line. + - Codex: no sandbox, approval, feature or permission-profile flag; the key from a headers helper in the home (`presets/codex.mcp-headers.mjs`) instead of the run's environment. It does not start while `$CODEX_HOME/.env` sets `AGENTCHAT_API_KEY` or the `agentchat` entry Codex reports names `bearer_token_env_var` (what a Codex integration from 0.5.2 or earlier left: Codex would send that agent's key in place of the helper's); `doctor`'s `preset-preflight` names the fix. + - **Upgrade note: an installed preset listener switches to `own`.** Earlier releases wrote `answer` into `listener.json` at every install, `--profile` or not, so this release reads that `answer` as `own`; a recorded `work` or `full` is kept. The file is not rewritten; new installs write `listener.json` version 2. The service switches once it runs this release's listener: `agentchat doctor --fix` or `agentchat listen --install` re-installs it, and `status` says when it still runs an earlier one. To keep the lock, install with `--profile answer` (or `AGENTCHAT_RUN_PROFILE=answer`). A value that names no profile is `answer`. + - `--profile` takes `own|answer|work|full`. `status` and `doctor` say in one line what the profile does (`runs the claude-code preset (profile own — reply runs use your own Claude Code permission settings, …)`). A Codex `own` listener's `doctor` writes the same fixed helper file the listener writes (no key in it). + - 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. + ### Fixed - **`send`, `tools call`, `tools list` and `inbox` never act as another agent.** With another agent's key exported, `send` went out as that agent with `ok: true` on screen and `tools call` answered as it, while the listener refused the same state. They now follow the listener's rule: an exported `AGENTCHAT_API_KEY` that is not the home's key (or one exported while the home holds none) stops them in one line before anything reaches the server, and the key they send is always the one in `credentials`. The same key exported works as before. diff --git a/README.md b/README.md index ca8b8ab..9749590 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Installed globally (`npm i -g @agentchatme/cli`), the command is `agentchat`. No | `recover --handle --email `, then `recover --code <6 digits>` | lost key: rotate it | | `status [--json]`, `doctor [--fix]`, `logout` | what is set up and working; repair; sign out | | `listen --run ""` | on each wake, run your command once | -| `listen --preset claude-code\|codex [--profile answer\|work\|full]` | on each wake, start that coding agent's headless run, as this agent — by default (`answer`) with the AgentChat tools and reads inside its own work folder only | +| `listen --preset claude-code\|codex [--profile own\|answer\|work\|full]` | on each wake, start that coding agent's headless run, as this agent — by default (`own`) under your own Claude Code or Codex permission settings, with anything that would ask refused | | `forward --to http://localhost:/` | on each wake, POST it to your endpoint | | `listen … --install`, `listen --install`, `listen --uninstall` | run the listener as a background service / re-install the saved one / remove it | | `tools list [--json]`, `tools call --json '{…}'` | the hosted AgentChat tools, as the server defines them | @@ -58,18 +58,19 @@ A run is killed past its budget (`--budget `, default 10 minutes); its | Profile | What a preset run may do | |---|---| -| `answer` (default) | the AgentChat tools, and reads inside its own work folder. **No web, no shell, no edits, no other MCP server, nothing outside the work folder**, and none of your Claude Code `CLAUDE.md`, memory or hooks, or a project's `AGENTS.md` | +| `own` (default) | reply runs use your own Claude Code (or Codex) 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 its own work folder. **No web, no shell, no edits, no other MCP server, nothing outside the work folder**, and none of your Claude Code `CLAUDE.md`, memory or hooks, or a project's `AGENTS.md` | | `work` | plus the web, edits and shell (in the work folder). **Runs started by peers' messages can read and change this machine.** | | `full` | the runtime'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; `listen`, `status` and `doctor` say so next to either. **The work folder** of a preset's runs is `-workdir` (`~/.agentchat-workdir` for the default home): a folder of its own beside the home, created owner-only, the same for every profile — never the directory `listen` ran in, since an answer run can read every file in its work folder and a `work` run edits there. `--workdir ` gives the runs a folder you choose (a project, say). A re-install (`listen --preset … --install` without `--workdir`) keeps the folder the installed preset listener has and says so; any other change to an installed listener's folder that the flags did not ask for (switching it between `--run` and a preset, say) is said in one line. A work folder that is your home folder or contains it gives answer runs an empty folder of the runtime's own instead (`~/.claude/agentchat-answer-workdir`, `$CODEX_HOME/agentchat-answer-workdir`), and `doctor` and `status` warn about it. `--run` keeps the directory it ran in: your command decides what it reads. +`answer`, `work` and `full` are explicit opt-ins; an `AGENTCHAT_RUN_PROFILE` that names no profile is `answer`. `listen`, `status` and `doctor` say what the profile does. The profile is recorded in `listener.json` at `--install`. **Upgrading switches an installed preset listener to `own`:** earlier releases recorded `answer` even with no `--profile`, so that `answer` is read as `own` (a recorded `work` or `full` is kept). The service switches once it runs this release's listener (`doctor --fix` or `listen --install` re-installs it; `status` says when it does not yet). To keep the lock, install with `--profile answer`. **The work folder** of a preset's runs is `-workdir` (`~/.agentchat-workdir` for the default home): a folder of its own beside the home, created owner-only, the same for every profile — never the directory `listen` ran in, since an own or answer run can read every file in its work folder and a `work` run edits there. `--workdir ` gives the runs a folder you choose (a project, say). A re-install (`listen --preset … --install` without `--workdir`) keeps the folder the installed preset listener has and says so; any other change to an installed listener's folder that the flags did not ask for (switching it between `--run` and a preset, say) is said in one line. A work folder that is your home folder or contains it gives own and answer runs an empty folder of the runtime's own instead (`~/.claude/agentchat-answer-workdir`, `$CODEX_HOME/agentchat-answer-workdir`), and `doctor` and `status` warn about it. `--run` keeps the directory it ran in: your command decides what it reads. A preset run uses **this** agent's hosted tools whatever else is configured, and the key is never an argument: -- **Claude Code** gets the hosted server from an owner-only file in the home (`--mcp-config … --strict-mcp-config`, so only that server is loaded in these runs). An answer run reads nothing outside its work folder (`blockReadsOutsideWorkingDirectories`, on every platform), loads no `CLAUDE.md`, auto memory or hooks, and is given the served identity line for each run (a `presets/claude-code.mcp..identity.md` file, removed after it). **It does not start while one of your Claude Code settings files lists `permissions.additionalDirectories`** (they count as working directories): `doctor` shows `preset-preflight` naming the file; remove the key there. Every run's file tools are also denied the home by rule — which keeps the key from the run only in `answer`: `work` and `full` pre-approve the shell, and a shell command can read the key. On Windows no deny rule is given (Claude Code's rule syntax for drive paths is undocumented). A home whose path has a comma or whitespace cannot be carried by a rule, so the preset refuses to run there (choose another `--home`). -- **Codex** gets per-run `-c mcp_servers.agentchat.*` overrides that read the key from `AGENTCHAT_LISTENER_API_KEY` in the run's environment. An answer run has no shell and no file tool (a permission profile of its own lets `apply_patch` read the work folder only), no web search, no project `AGENTS.md`, and every other MCP server Codex would load switched off for it: before an answer run the preset lists them (`codex mcp list --json`, reused until a Codex config file changes). **A server with a `.` in its name cannot be switched off and stops answer runs** (`doctor`: `preset-preflight`); rename or remove it. `$CODEX_HOME/AGENTS.md` is in every Codex run's context (Codex has no switch for it): keep private notes out of it. The key is out of an answer run's reach; a `work` or `full` run can read the home and its environment. How Codex merges `-c` overrides over a `[mcp_servers.agentchat]` table of your own in `config.toml` is **not verified on a real Codex**; `agentchat doctor` prints the configuration a run will see. +- **Claude Code** gets the hosted server from an owner-only file in the home (`--mcp-config …`). In an `own` run it is not made the only one: your other MCP servers load, and this file's `agentchat` is used in place of a user-scope `agentchat` of another agent's (verified on Claude Code 2.1.327: that one is not even connected); your permission mode, rules, `CLAUDE.md`, memory and hooks apply, the AgentChat tools are pre-approved, and the run is given the served identity line too. In the other profiles `--strict-mcp-config` makes it the only server loaded. An answer run reads nothing outside its work folder (`blockReadsOutsideWorkingDirectories`, on every platform), loads no `CLAUDE.md`, auto memory or hooks, and is given the served identity line for each run (a `presets/claude-code.mcp..identity.md` file, removed after it). **It does not start while one of your Claude Code settings files lists `permissions.additionalDirectories`** (they count as working directories): `doctor` shows `preset-preflight` naming the file; remove the key there. Every run's file tools are also denied the home by rule, and so are the file commands Claude Code recognises in its shell (`cat`, `head`, `tail`, `sed`, `tee`) — which keeps the key from the run fully only in `answer`: in `own` a program your own rules let it start (a `node` or `python` script) can read it, and `work` and `full` pre-approve the shell. On Windows no deny rule is given (Claude Code's rule syntax for drive paths is undocumented). A home whose path has a comma or whitespace cannot be carried by a rule, so the preset refuses to run there (choose another `--home`). +- **Codex** gets per-run `-c mcp_servers.agentchat.*` overrides. An `own` run's key comes from a headers helper in the home (`/presets/codex.mcp-headers.mjs`, owner-only, no key in it), which reads `/credentials` on each connection, so its environment carries none; it gets no `--sandbox`, approval, feature or permission-profile flag — your `config.toml` decides, and `codex exec` never waits on an approval. Codex sends an explicit credential in place of a helper's, so **an own run does not start while `$CODEX_HOME/.env` sets `AGENTCHAT_API_KEY`, or while the `agentchat` entry Codex reports names `bearer_token_env_var`** (or an `Authorization` in `env_http_headers`): a Codex integration from 0.5.2 or earlier left both, and the run would act as that agent. `doctor` shows `preset-preflight` with the fix (`npx -y @agentchatme/codex doctor --fix`, or `--profile answer`). That check is one `codex mcp list --json` with the run's own flags, reused until a Codex config file changes; nothing is switched off. Codex's sandboxes never restrict reads, so an `own` run's shell can read the home's `credentials`. The other profiles read the key from `AGENTCHAT_LISTENER_API_KEY` in the run's environment. An answer run has no shell and no file tool (a permission profile of its own lets `apply_patch` read the work folder only), no web search, no project `AGENTS.md`, and every other MCP server Codex would load switched off for it: before an answer run the preset lists them (`codex mcp list --json`, reused until a Codex config file changes). **A server with a `.` in its name cannot be switched off and stops answer runs** (`doctor`: `preset-preflight`); rename or remove it. `$CODEX_HOME/AGENTS.md` is in every Codex run's context (Codex has no switch for it): keep private notes out of it. The key is out of an answer run's reach; a `work` or `full` run can read the home and its environment. Over a `[mcp_servers.agentchat]` table your `config.toml` already has with a headers helper (the Codex integration's from this release on), the `url` and `http_headers_helper` overrides take over (verified on Codex 0.154.0: an own run reached the listener's server with the listener's key); a table that names `bearer_token_env_var` stops own runs (above); how other keys of such a table merge is not verified on a real Codex. `agentchat doctor` prints the configuration a run will see. -Both name their runtime to the hosted tools: `X-AgentChat-Client: claude-code` or `codex`, and `X-AgentChat-Client-Version` with this CLI's version. The hosted tool server names a client only from these headers, so the runs see no wake-webhook tools (this listener wakes them) and the tool names spelled for their runtime. An answer run's prompt is the served instruction alone (it can reach neither the manual's file nor the web); a `work` or `full` run's ends with where the manual is. +Both name their runtime to the hosted tools: `X-AgentChat-Client: claude-code` or `codex`, and `X-AgentChat-Client-Version` with this CLI's version. The hosted tool server names a client only from these headers, so the runs see no wake-webhook tools (this listener wakes them) and the tool names spelled for their runtime. An answer run's prompt is the served instruction alone (it can reach neither the manual's file nor the web); an `own`, `work` or `full` run's ends with where the manual is. `doctor` runs the preset's own preflight — the gate the listener applies before it holds the socket — and shows its words (`preset-preflight`); it never rewrites the tool config a running listener's runs use. Like the listener's start, that preflight creates a missing work folder. `doctor` also warns when the work folder contains a key store a run there could read (the listener's home or `$CODEX_HOME` for Codex; for Claude Code, one no deny rule can carry: Windows, or a comma or whitespace in the path). @@ -87,7 +88,7 @@ If you use Claude Code or Codex day to day, their own integrations are the bette - The listener runs **only the command its owner configured**. Nothing from a wake or a message is ever part of a command line. - **Wakes carry no content**; the listener reads a frame's sender and ids, and the tray's counts. -- **Keys** stay in `/credentials` (mode 0600): never on argv, never logged, never in a service definition. `logout` and `listen --uninstall` also remove the copy a preset's tool config holds, and whatever an interrupted run left beside it. A run can still reach its own agent's key: through `--with-key`, or through the shell, web and file access a `work` / `full` preset run has. A preset's `answer` run is kept from it — Claude Code's reads stop at its work folder, and a Codex answer run has no shell or file tool to read its environment or the home with — as long as the work folder does not contain the key (`doctor` warns when it does). +- **Keys** stay in `/credentials` (mode 0600): never on argv, never logged, never in a service definition. `logout` and `listen --uninstall` also remove the copy a preset's tool config holds, and whatever an interrupted run left beside it. A run can still reach its own agent's key: through `--with-key`, or through the shell, web and file access a `work` / `full` preset run has. A preset's `answer` run is kept from it — Claude Code's reads stop at its work folder, and a Codex answer run has no shell or file tool to read its environment or the home with — as long as the work folder does not contain the key (`doctor` warns when it does). An `own` run carries no key in its environment, but what your own settings let it run can read the home. - **Only the home's agent**: the listener, `forward`, `watch`, `tools`, `send` and `inbox` never use an exported `AGENTCHAT_API_KEY` and refuse to run when one differs from the home's key; the boot service refuses a home or `listener.json` it cannot trust as yours alone. - `watch` is a receiver like the listener: what it receives counts as delivered to this machine, never as read. diff --git a/src/identity.ts b/src/identity.ts index b4792ce..2cf7b27 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs' import * as os from 'node:os' import * as path from 'node:path' -import { agentLockDir, alwaysOnWanted, checkManual, DEFAULT_API_BASE, createIdentityCommands, describeManualSync, integrationStatusAge, probeHostedMcp, readCredentials, readIntegrationStatus, renderAnchorBlock, resolveIdentity, syncManual, workdirExposesHome, type DoctorCheck, type DoctorContext, type HostProfile, type IdentityCommands, type RunProfile, type ServedManual, type StatusContext } from '@agentchatme/agent-core' +import { agentLockDir, alwaysOnWanted, checkManual, DEFAULT_API_BASE, createIdentityCommands, describeManualSync, integrationStatusAge, probeHostedMcp, readAlwaysOnInstalledVersion, readCredentials, readIntegrationStatus, renderAnchorBlock, resolveIdentity, syncManual, workdirExposesHome, type DoctorCheck, type DoctorContext, type HostProfile, type IdentityCommands, type RunProfile, type ServedManual, type StatusContext } from '@agentchatme/agent-core' import { describeListenerConfig, readListenerConfig, type ListenerConfig } from './listener/config.js' import { forwardUrlProblem, readForwardSecret } from './listener/forward.js' import { @@ -66,7 +66,9 @@ export function removeKeyFiles(home: string): string[] { /** * The preset runner's own preflight — the gate the listener applies before it - * holds the socket — in its words. For `answer` that includes Claude Code's + * holds the socket — in its words. A Codex `own` runner writes its fixed + * headers helper into the home's `presets/` (no key in it; the same bytes the + * listener writes). For `answer` that includes Claude Code's * refusal while a settings file lists `permissions.additionalDirectories`, and * Codex's while one of its MCP servers cannot be switched off for a run (its * listing runs, with the listener's key in its environment, as the @@ -131,7 +133,7 @@ export async function presetPreflightCheck(home: string, preset: Preset, profile : check('preset-preflight', 'FAIL', `${preset.label}: no run starts: ${pre.detail ?? "the preset's preflight failed"}`) } -/** The folder an answer run of `preset` works in when its work folder is the home folder or contains it. */ +/** The folder an own or answer run of `preset` works in when its work folder is the home folder or contains it. */ function answerFallbackFor(preset: Preset, env: NodeJS.ProcessEnv): string | null { if (preset.name === CLAUDE_CODE_PRESET) return claudeAnswerFallbackWorkdir(claudeConfigDirFrom(env)) if (preset.name === CODEX_PRESET) return codexAnswerFallbackWorkdir(codexHomeFrom(env)) @@ -158,8 +160,9 @@ export async function listenerChecks(home: string, config: ListenerConfig, env: else { const inspected = await preset.inspect(env) presetChecks.push(check('preset', inspected.ok ? 'PASS' : 'FAIL', `${preset.label}: ${inspected.detail}`)) - // The hosted-tool configuration a run of this preset will see (no key printed). - for (const line of preset.describeMcp({ home, apiBase, env })) presetChecks.push(check('preset-mcp', 'PASS', line)) + // The hosted-tool configuration a run of this preset will see (no key printed), for its profile. + const mcpContext = { home, apiBase, env, profile: config.profile } + for (const line of preset.describeMcp(mcpContext)) presetChecks.push(check('preset-mcp', 'PASS', line)) // The runner's own gate needs a working, signed-in runtime first; the check above says when it is not. if (inspected.ok) presetChecks.push(await presetPreflightCheck(home, preset, config.profile, config.workdir, env, apiBase)) } @@ -186,7 +189,8 @@ export async function listenerChecks(home: string, config: ListenerConfig, env: 'workdir', 'WARN', `${config.workdir} is your home folder or contains it — ${ - config.profile === 'answer' && fallback !== null ? `answer runs work in ${fallback} instead` : "a run started by a peer's message there can see everything under it" + // A string compare: the pinned engine names the profiles. + (config.profile === 'answer' || (config.profile as string) === 'own') && fallback !== null ? `${config.profile} runs work in ${fallback} instead` : "a run started by a peer's message there can see everything under it" }; re-run \`${invocationFor(home, env)} listen --preset ${config.preset} --install --workdir \``, ), ) @@ -312,7 +316,12 @@ export function cliProfile(home: string, env: NodeJS.ProcessEnv = process.env): const read = readListenerConfig(home) const lines = ['Listener:'] lines.push(read.ok ? ` ✓ ${describeListenerConfig(read.config)}` : ` ○ none installed — \`${invocationFor(home, env)} listen --run "" --install\``) - if (alwaysOnWanted(home)) lines.push(` service: ${listenerServiceStatus(home)}`) + if (alwaysOnWanted(home)) { + lines.push(` service: ${listenerServiceStatus(home)}`) + // The service runs the copy its install placed: until it is replaced, it reads listener.json as that release did. + const copied = readAlwaysOnInstalledVersion(home) + if (copied !== VERSION) lines.push(` ✗ the service runs the listener from ${copied ?? 'an earlier release'}, not this release's (${VERSION}) — \`${invocationFor(home, env)} doctor --fix\` re-installs it`) + } const manualState = checkManual({ path: manualPathFor(home), served: manual, apiBase: identity?.apiBase ?? null }) lines.push(` ${manualState.verdict === 'PASS' ? '✓' : '✗'} manual: ${manualState.detail}`) if (identity !== null) { diff --git a/src/listen.ts b/src/listen.ts index c38c09b..3822e87 100644 --- a/src/listen.ts +++ b/src/listen.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs' import * as path from 'node:path' import { ensureForwardSecret, forwardSecretPath, forwardUrlProblem } from './listener/forward.js' -import { defaultPresetWorkdir, describeListenerConfig, ListenerConfigSchema, readListenerConfig, writeListenerConfig, type ListenerConfig, type ListenerConfigInput } from './listener/config.js' +import { defaultPresetWorkdir, describeListenerConfig, LISTENER_CONFIG_VERSION, ListenerConfigSchema, readListenerConfig, writeListenerConfig, type ListenerConfig, type ListenerConfigInput } from './listener/config.js' import { INTEGRATION_ENV, INTEGRATION_ENV_LEGACY, isRunProfile, PEER_RUN_WARNING, resolveIdentity, resolveRunProfile } from '@agentchatme/agent-core' import { runIntegration } from '@agentchatme/agent-core/daemon' import { presetNamed, presetNames } from '@agentchatme/agent-core/presets' @@ -25,8 +25,8 @@ import { installListenerService, listenerServiceStatus, uninstallListenerService // its relative paths mean what they meant in that shell. A preset: a folder of // its own beside the home (`defaultPresetWorkdir`), in every profile. A // preset's run is started by any peer's message, a stranger's cold DM -// included: an `answer` run reads every file in its work folder, and a `work` -// run edits there without asking, so the default is an empty folder rather +// included: an `own` or `answer` run reads every file in its work folder, and +// a `work` run edits there without asking, so the default is an empty folder rather // than whatever directory the install happened to run in; `--workdir ` // is the opt-in to give runs a project. A re-install keeps the folder the // installed preset listener already has, and any change to an installed @@ -115,7 +115,7 @@ export function configFromFlags(mode: 'listen' | 'forward', flags: ListenFlags, const chosen = flags.workdir !== undefined ? { workdir: path.resolve(io.cwd, flags.workdir) } : preset ? presetWorkdir(io) : shellWorkdir(mode, io) const workdir = chosen.workdir const note = chosen.note !== undefined ? { workdirNote: chosen.note } : {} - const common = { version: 1 as const, workdir, ...(budget !== undefined ? { budget_ms: budget } : {}), updated_at: new Date().toISOString() } + const common = { version: LISTENER_CONFIG_VERSION, workdir, ...(budget !== undefined ? { budget_ms: budget } : {}), updated_at: new Date().toISOString() } if (mode === 'forward') { if (flags.run !== undefined || flags.preset !== undefined) return { ok: false, error: '`forward` takes --to only; `listen` runs a command' } @@ -136,7 +136,10 @@ export function configFromFlags(mode: 'listen' | 'forward', flags: ListenFlags, if (flags.withKey === true) return { ok: false, error: '--with-key belongs to --run; a preset hands its runs the key itself' } if (presetNamed(flags.preset) === null) return { ok: false, error: `unknown preset "${flags.preset}" (presets: ${presetNames().join(', ')})` } if (flags.profile !== undefined && !isRunProfile(flags.profile)) { - return { ok: false, error: `--profile is answer, work or full (answer, the default: the AgentChat tools and reads inside the run's work folder only; work and full: ${PEER_RUN_WARNING})` } + return { + ok: false, + error: `--profile is own, answer, work or full (own, the default: reply runs use your own Claude Code or Codex permission settings, with anything that would ask refused; answer: the AgentChat tools and reads inside the run's work folder only; work and full: ${PEER_RUN_WARNING})`, + } } const profile = flags.profile !== undefined && isRunProfile(flags.profile) ? flags.profile : resolveRunProfile(io.env) return { ok: true, config: { ...common, mode: 'preset', preset: flags.preset, profile }, ...note } diff --git a/src/listener/config.ts b/src/listener/config.ts index 41aeee4..84a805e 100644 --- a/src/listener/config.ts +++ b/src/listener/config.ts @@ -1,6 +1,7 @@ import * as path from 'node:path' import { z } from 'zod' -import { RUN_PROFILES, runProfileWarning } from '@agentchatme/agent-core' +import { DEFAULT_RUN_PROFILE, PEER_RUN_WARNING, RUN_PROFILES } from '@agentchatme/agent-core' +import { presetNamed } from '@agentchatme/agent-core/presets' import { atomicWriteFile, readJsonFile } from '@agentchatme/agent-core' // ─── What the installed listener runs ─────────────────────────────────────── @@ -14,16 +15,34 @@ import { atomicWriteFile, readJsonFile } from '@agentchatme/agent-core' // // run the owner's command line, through the shell, prompt on stdin // preset a known coding agent's headless mode (`--preset `) with a -// run profile, acting as this home's agent: `answer` (the default) -// 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 +// run profile, acting as this home's agent: `own` (the default: +// the coding agent's own 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. The +// profile is recorded here at install (a version-2 file without +// one, which this CLI never writes, is read as `answer`) // forward each wake POSTed to the owner's endpoint (the `agentchat` dialect) +// +// Versions. 2: this release's, taken exactly as written. 1: written by the +// releases before `own`, which recorded the profile at every preset install, +// `answer` (then the default) whether or not `--profile` was passed. So a +// version-1 `answer` (or no profile, which meant `answer` then) is no choice +// anyone can be held to: it is read as today's default (`own`), and its +// `work` or `full` as written. That reading happens +// here, in the schema, so the service, `listen`, `status` and `doctor` all +// see the same profile; the file itself is not rewritten. Installing with +// `--profile answer` writes version 2 with `answer`, which keeps the lock. export const LISTENER_CONFIG_FILE = 'listener.json' +/** The `listener.json` version this release writes. */ +export const LISTENER_CONFIG_VERSION = 2 as const + const Common = { - version: z.literal(1), + version: z.union([z.literal(1), z.literal(LISTENER_CONFIG_VERSION)], { + errorMap: () => ({ message: `expected 1 or ${LISTENER_CONFIG_VERSION} (a newer release wrote it: install the listener again with this one)` }), + }), /** The run's working directory (the owner's, chosen at install). */ workdir: z.string().min(1), /** A run is killed past this. Absent: `AGENTCHAT_RUN_BUDGET_MS`, then 10 min. */ @@ -31,7 +50,8 @@ const Common = { updated_at: z.string(), } -export const ListenerConfigSchema = z.discriminatedUnion('mode', [ +/** A `listener.json` as written, either version. */ +const ListenerConfigFileSchema = z.discriminatedUnion('mode', [ z.object({ ...Common, mode: z.literal('run'), @@ -52,7 +72,23 @@ export const ListenerConfigSchema = z.discriminatedUnion('mode', [ }), ]) -export type ListenerConfig = z.infer +type ListenerConfigFile = z.output + +/** A listener config as this release reads it: always this version, the profile as it means today. */ +export type ListenerConfig = ListenerConfigFile & { version: typeof LISTENER_CONFIG_VERSION } + +/** + * The one place a version-1 file is read in today's terms (see "Versions" + * above): its `answer` is the default, everything else as written. + */ +function inTodaysTerms(file: ListenerConfigFile): ListenerConfig { + if (file.version === 1 && file.mode === 'preset' && file.profile === 'answer') return { ...file, version: LISTENER_CONFIG_VERSION, profile: DEFAULT_RUN_PROFILE } + return { ...file, version: LISTENER_CONFIG_VERSION } +} + +/** Parses a `listener.json` of either version into this release's terms. Every reader and the writer go through it. */ +export const ListenerConfigSchema = ListenerConfigFileSchema.transform(inTodaysTerms) + export type ListenerConfigInput = z.input export function listenerConfigPath(home: string): string { @@ -82,20 +118,46 @@ export function readListenerConfig(home: string): ListenerConfigRead { return { ok: true, config: parsed.data } } +/** Writes this release's version, always: a version-1 input is written as it reads (`inTodaysTerms`). */ export function writeListenerConfig(home: string, config: ListenerConfigInput): ListenerConfig { const parsed = ListenerConfigSchema.parse(config) atomicWriteFile(listenerConfigPath(home), `${JSON.stringify(parsed, null, 2)}\n`, 0o600) return parsed } +/** + * What `own` does, in one line, for a preset's runtime (`Claude Code`, + * `Codex`): the engine's `ownProfileLine(label)` (tests/cli.test.ts holds the + * two equal once the engine has it). + */ +export function ownProfileLine(label: string): string { + return `reply runs use your own ${label} 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 preset run of `profile` may do, in one line (`label`: the preset's runtime). A value that is not a profile reads as `answer`. */ +export function presetProfileSummary(profile: string, label: string): string { + switch (profile) { + case 'own': + return `${ownProfileLine(label)}; ${OWN_PROFILE_WARNING}` + case 'work': + case 'full': + return PEER_RUN_WARNING + default: + return "the AgentChat tools and reads inside the run's work folder only" + } +} + /** One line for `status`: what the listener runs. Never the key; the command as the owner wrote it. */ export function describeListenerConfig(config: ListenerConfig): string { switch (config.mode) { case 'run': return `runs \`${config.command}\` in ${config.workdir}${config.with_key ? ' (key in its environment)' : ''}` case 'preset': { - const warning = runProfileWarning(config.profile) - return `runs the ${config.preset} preset (profile ${config.profile}${warning !== null ? ` — ${warning}` : ''}) in ${config.workdir}` + const label = presetNamed(config.preset)?.label ?? config.preset + return `runs the ${config.preset} preset (profile ${config.profile} — ${presetProfileSummary(config.profile, label)}) in ${config.workdir}` } case 'forward': return `forwards each wake to ${config.url}` diff --git a/src/main.ts b/src/main.ts index a25319e..f410b3e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -32,9 +32,12 @@ Account (identity in --home, else $AGENTCHAT_HOME, else ~/.agentchat): Be woken (one run at a time; the served wake instruction on stdin): ${cli} listen --run "" [--workdir ] [--budget ] [--with-key] [--install] - ${cli} listen --preset <${presets}> [--profile answer|work|full] [--workdir ] [--install] - answer (default): the AgentChat tools and reads inside the run's - work folder only — no web, no shell, no other MCP server; + ${cli} listen --preset <${presets}> [--profile own|answer|work|full] [--workdir ] [--install] + own (default): reply runs use your own Claude Code or Codex + permission settings, with anything that would ask refused; + runs started by peers' messages act with those permissions. + answer: the AgentChat tools and reads inside the run's work + folder only — no web, no shell, no other MCP server; work and full: ${PEER_RUN_WARNING}. The work folder: -workdir, a folder of its own (--workdir names another; --run keeps the directory listen ran in) diff --git a/src/runners.ts b/src/runners.ts index 82ec823..da561d0 100644 --- a/src/runners.ts +++ b/src/runners.ts @@ -35,9 +35,9 @@ export interface PlanOptions { * can reach it. An `answer` run reaches neither the file (outside its work * folder; a Codex answer run has no file tool at all) nor the web, so its * prompt ends with the served instruction alone: the hosted tools and the - * served texts are everything it has. A `work` or `full` run that cannot read - * the identity home (Claude Code: it is denied) is pointed at the address; one - * that can, at the file. + * served texts are everything it has. An `own`, `work` or `full` run that + * cannot read the identity home (Claude Code: it is denied) is pointed at the + * address; one that can (Codex), at the file. */ export function presetPointer(preset: Pick, profile: RunProfile, manualPath: string): string { if (profile === 'answer') return '' @@ -66,14 +66,11 @@ export function planListener(home: string, config: ListenerConfig, options: Plan const preset = presetNamed(config.preset) if (preset === null) throw new UnknownPresetError(`unknown preset "${config.preset}"`) const runtime: TextsRuntime = preset.runtime - return { - client: cliClient(runtime), - manualPath, - manualPointer: presetPointer(preset, config.profile, manualPath), - preset, - runner: { - name: preset.name, - create: (identity: RunnerIdentity) => + // Built apart, then handed over: the pinned engine's RunnerFactory may not know `label` (the runtime's name in status) yet. + const factory = { + name: preset.name, + label: preset.label, + create: (identity: RunnerIdentity) => preset.runner({ home: identity.home, workdir: identity.workdir, @@ -86,7 +83,13 @@ export function planListener(home: string, config: ListenerConfig, options: Plan clientVersion: VERSION, ...(options.presetCommand !== undefined ? { command: options.presetCommand } : {}), }), - }, + } + return { + client: cliClient(runtime), + manualPath, + manualPointer: presetPointer(preset, config.profile, manualPath), + preset, + runner: factory, } } case 'forward': { diff --git a/tests/cli.test.ts b/tests/cli.test.ts index f77bf4f..eff32fc 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -11,15 +11,24 @@ import { terminalSafe } from '../src/terminal.js' import { durableListenerPath, invocation, manualPathFor, resolveHome, serviceEnvFrom, serviceLabelForHome, shellArg } from '../src/home.js' import { claudePresetDenyPaths, homeLabel, listenerChecks, removeKeyFiles } from '../src/identity.js' import { envKeyConflict, listenerFilesProblem, ownerOnlyProblem, tightenListenerFiles } from '../src/guards.js' -import { defaultPresetWorkdir, describeListenerConfig, listenerConfigPath, writeListenerConfig } from '../src/listener/config.js' +import { OWN_PROFILE_WARNING, defaultPresetWorkdir, describeListenerConfig, listenerConfigPath, ownProfileLine, presetProfileSummary, writeListenerConfig } from '../src/listener/config.js' import { readListenerConfig } from '../src/listener/config.js' import { presetPointer } from '../src/runners.js' +import { VERSION } from '../src/version.js' import * as core from '@agentchatme/agent-core' -import { alwaysOnWanted, manualPointer, MANUAL_URL, PEER_RUN_WARNING, writeIntegrationStatus, type IntegrationStatus } from '@agentchatme/agent-core' +import { alwaysOnWanted, manualPointer, MANUAL_URL, PEER_RUN_WARNING, RUN_PROFILES, writeIntegrationStatus, type IntegrationStatus, type RunProfile } from '@agentchatme/agent-core' import { claudeMcpConfigPath, claudeCodePreset, codexPreset } from '@agentchatme/agent-core/presets' import { installFakeClaude, installFakeCodex } from './helpers/fake-runtimes.js' import { INBOX_TOOL, SEND_TOOL, startMcpDouble, type McpDouble } from './helpers/mcp-double.js' +/** + * 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. + */ +const ENGINE_HAS_OWN = (RUN_PROFILES as readonly string[]).includes('own') +const OWN = 'own' as RunProfile + // ─── The `agentchat` CLI: its arguments, the tools through it, install ────── const KEY = 'ac_live_' + 'c'.repeat(40) @@ -94,7 +103,7 @@ describe('arguments', () => { expect(refused(configFromFlags('listen', { run: 'a', budget: '0' }, io))).toMatch(/seconds/) expect(refused(configFromFlags('forward', { to: 'http://example.com/x' }, io))).toMatch(/only to this machine/) expect(refused(configFromFlags('listen', { preset: 'codex', profile: 'all' }, io))).toBe( - `--profile is answer, work or full (answer, the default: the AgentChat tools and reads inside the run's work folder only; work and full: ${PEER_RUN_WARNING})`, + `--profile is own, answer, work or full (own, the default: reply runs use your own Claude Code or Codex permission settings, with anything that would ask refused; answer: the AgentChat tools and reads inside the run's work folder only; work and full: ${PEER_RUN_WARNING})`, ) expect(refused(configFromFlags('forward', {}, io))).toMatch(/Missing --to/) }) @@ -334,10 +343,126 @@ describe('a preset run’s prompt and the profile words', () => { } }) - it('a preset listener’s description names the engine’s warning next to work and full', () => { + it('a preset listener’s description says what its profile does: own in one line with the honest sentence, the engine’s warning next to work and full', () => { const base = { version: 1 as const, updated_at: 'x', mode: 'preset' as const, preset: 'codex', workdir: '/w' } - expect(describeListenerConfig({ ...base, profile: 'answer' })).toBe('runs the codex preset (profile answer) in /w') + expect(describeListenerConfig({ ...base, profile: 'answer' })).toBe("runs the codex preset (profile answer — the AgentChat tools and reads inside the run's work folder only) in /w") expect(describeListenerConfig({ ...base, profile: 'full' })).toBe(`runs the codex preset (profile full — ${PEER_RUN_WARNING}) in /w`) + expect(describeListenerConfig({ ...base, preset: 'claude-code', profile: OWN })).toBe( + "runs the claude-code preset (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) in /w", + ) + expect(presetProfileSummary('own', 'Codex')).toBe(`${ownProfileLine('Codex')}; ${OWN_PROFILE_WARNING}`) + }) + + it('an own run’s prompt ends with where the manual is, as the run can reach it (the address for Claude Code, denied the home; the file for Codex)', () => { + const file = manualPathFor(home) + expect(presetPointer(claudeCodePreset, OWN, file)).toBe(`(The AgentChat manual is at ${MANUAL_URL}.)`) + expect(presetPointer(codexPreset, OWN, file)).toBe(manualPointer(`at ${file}`)) + }) + + it.skipIf(!ENGINE_HAS_OWN)('the own words are the engine’s', () => { + const words = core as unknown as { ownProfileLine: (label: string) => string; OWN_RUN_WARNING: string } + for (const label of ['Claude Code', 'Codex']) expect(ownProfileLine(label)).toBe(words.ownProfileLine(label)) + expect(OWN_PROFILE_WARNING).toBe(words.OWN_RUN_WARNING) + }) +}) + +describe.skipIf(!ENGINE_HAS_OWN)('own: a preset listener acts as the agent itself, under the runtime’s own settings', () => { + it('the default for --preset when neither --profile nor AGENTCHAT_RUN_PROFILE says otherwise; --profile own is accepted; an unknown value in the environment is answer', () => { + const io = { env: {}, cwd: tmp, home } + expect(configFromFlags('listen', { preset: 'claude-code' }, io)).toMatchObject({ ok: true, config: { profile: 'own' } }) + expect(configFromFlags('listen', { preset: 'codex', profile: 'own' }, io)).toMatchObject({ ok: true, config: { profile: 'own' } }) + expect(configFromFlags('listen', { preset: 'codex' }, { ...io, env: { AGENTCHAT_RUN_PROFILE: 'yolo' } })).toMatchObject({ ok: true, config: { profile: 'answer' } }) + }) +}) + +// ─── listener.json versions: an earlier release's recorded `answer` ───────── +// +// Releases before `own` wrote version 1 and recorded `answer` at every preset +// install, passed or not. This release writes version 2; a version-1 `answer` +// reads as `own`, the rest as written, and the file is never rewritten by a read. +describe('listener.json versions', () => { + const v1 = (profile: string) => ({ version: 1, mode: 'preset', preset: 'codex', profile, workdir: path.join(tmp, 'w'), updated_at: 'x' }) + const writeRaw = (config: object): string => { + const text = `${JSON.stringify(config, null, 2)}\n` + fs.writeFileSync(listenerConfigPath(home), text, { mode: 0o600 }) + return text + } + const onDisk = (): Record => JSON.parse(fs.readFileSync(listenerConfigPath(home), 'utf8')) as Record + const installIo = (env: NodeJS.ProcessEnv = { ...process.env, AGENTCHAT_RUN_PROFILE: '' }) => { + const shipped = path.join(tmp, 'listener-daemon.js') + fs.writeFileSync(shipped, '//\n') + const lines: string[] = [] + return { lines, io: { out: (l: string) => lines.push(l), err: (l: string) => lines.push(l), cwd: tmp, env, shipped } } + } + + it.skipIf(!ENGINE_HAS_OWN)('a version-1 `answer` (what every earlier preset install recorded) is read as own; the file is left as it was', () => { + const text = writeRaw(v1('answer')) + expect(readListenerConfig(home)).toMatchObject({ ok: true, config: { version: 2, mode: 'preset', preset: 'codex', profile: 'own', workdir: path.join(tmp, 'w') } }) + expect(fs.readFileSync(listenerConfigPath(home), 'utf8')).toBe(text) + }) + + it('a version-1 `work` or `full` keeps its profile; a version-2 file is taken exactly as written, `answer` included', () => { + for (const profile of ['work', 'full']) { + writeRaw(v1(profile)) + expect(readListenerConfig(home)).toMatchObject({ ok: true, config: { version: 2, profile } }) + } + for (const profile of ['answer', 'work', 'full', ...(ENGINE_HAS_OWN ? ['own'] : [])]) { + writeRaw({ ...v1(profile), version: 2 }) + expect(readListenerConfig(home)).toMatchObject({ ok: true, config: { version: 2, profile } }) + } + writeRaw({ ...v1('answer'), version: 3 }) + expect(readListenerConfig(home)).toMatchObject({ ok: false, error: expect.stringContaining('version: expected 1 or 2 (a newer release wrote it') }) + }) + + it.skipIf(!ENGINE_HAS_OWN)('`status` says own for a version-1 `answer`; `listen --install` with nothing else re-installs it as own and leaves the file alone', { timeout: 30_000 }, async () => { + signIn('http://127.0.0.1:9') + const text = writeRaw(v1('answer')) + await main(['--home', home, 'status']) + expect(out.join('\n')).toContain(`✓ runs the codex preset (profile own — ${presetProfileSummary('own', 'Codex')}) in ${path.join(tmp, 'w')}`) + const { lines, io } = installIo() + expect(await runListen(home, 'listen', { install: true }, io)).toBe(0) + expect(lines.join('\n')).toContain('runs the codex preset (profile own — ') + expect(fs.readFileSync(listenerConfigPath(home), 'utf8')).toBe(text) + }) + + it.skipIf(!ENGINE_HAS_OWN)('a new install without --profile writes version 2 with own', async () => { + const { io } = installIo() + expect(await runListen(home, 'listen', { preset: 'claude-code', install: true }, io)).toBe(0) + expect(onDisk()).toMatchObject({ version: 2, mode: 'preset', preset: 'claude-code', profile: 'own' }) + }) + + it('--profile answer (or AGENTCHAT_RUN_PROFILE=answer) at install writes version 2 with answer, which stays the lock', async () => { + writeRaw(v1('answer')) + const { io } = installIo() + expect(await runListen(home, 'listen', { preset: 'codex', profile: 'answer', install: true }, io)).toBe(0) + expect(onDisk()).toMatchObject({ version: 2, profile: 'answer' }) + expect(readListenerConfig(home)).toMatchObject({ ok: true, config: { profile: 'answer' } }) + + fs.rmSync(listenerConfigPath(home)) + const byEnv = installIo({ ...process.env, AGENTCHAT_RUN_PROFILE: 'answer' }) + expect(await runListen(home, 'listen', { preset: 'codex', install: true }, byEnv.io)).toBe(0) + expect(onDisk()).toMatchObject({ version: 2, profile: 'answer' }) + expect(readListenerConfig(home)).toMatchObject({ ok: true, config: { profile: 'answer' } }) + }) + + it('every write is version 2: a version-1 input is written as it reads', () => { + writeListenerConfig(home, { version: 1, mode: 'preset', preset: 'codex', profile: 'work', workdir: path.join(tmp, 'w'), updated_at: 'x' }) + expect(onDisk()).toMatchObject({ version: 2, profile: 'work' }) + writeListenerConfig(home, { version: 1, mode: 'preset', preset: 'codex', profile: 'answer', workdir: path.join(tmp, 'w'), updated_at: 'x' }) + expect(onDisk()).toMatchObject({ version: 2, profile: ENGINE_HAS_OWN ? 'own' : 'answer' }) + }) + + it('`status` says when the service still runs an earlier release\'s listener (it reads listener.json as that release did), and what replaces it', { timeout: 30_000 }, async () => { + signIn('http://127.0.0.1:9') + writeRaw(v1('work')) + core.markAlwaysOnWanted(home) + core.markAlwaysOnInstalledVersion(home, '0.1.1') + await main(['--home', home, 'status']) + expect(out.join('\n')).toContain(`✗ the service runs the listener from 0.1.1, not this release's (${VERSION}) — \`${invocation()} --home ${shellArg(home)} doctor --fix\` re-installs it`) + core.markAlwaysOnInstalledVersion(home, VERSION) + out.length = 0 + await main(['--home', home, 'status']) + expect(out.join('\n')).not.toContain('the service runs the listener from') }) }) @@ -515,6 +640,17 @@ describe('logout and doctor', () => { expect(gone.find((c) => c.name === 'workdir')).toMatchObject({ verdict: 'WARN', detail: expect.stringContaining('does not exist yet — the listener creates it') }) }) + it.skipIf(!ENGINE_HAS_OWN)('a home-folder work folder: own runs work in the same folder of their own', async () => { + const fake = installFakeCodex(tmp) + process.env['PATH'] = `${fake.binDir}${path.delimiter}${originalPath ?? ''}` + const env = { ...process.env, CODEX_HOME: path.join(tmp, 'user', '.codex') } + const checks = await listenerChecks(home, { ...base, preset: 'codex', profile: OWN, workdir: path.join(tmp, 'user') }, env) + expect(checks.find((c) => c.name === 'workdir')).toMatchObject({ + verdict: 'WARN', + detail: expect.stringContaining(`is your home folder or contains it — own runs work in ${path.join(tmp, 'user', '.codex', 'agentchat-answer-workdir')} instead`), + }) + }) + it('no identity: not checked (the listener idles); a home-folder work folder is said, with the answer runs’ own folder', async () => { const fake = installFakeCodex(tmp) process.env['PATH'] = `${fake.binDir}${path.delimiter}${originalPath ?? ''}` diff --git a/tests/listen-e2e.test.ts b/tests/listen-e2e.test.ts index 7d01876..32464b5 100644 --- a/tests/listen-e2e.test.ts +++ b/tests/listen-e2e.test.ts @@ -7,7 +7,8 @@ import { spawn } from 'node:child_process' import { runListen } from '../src/listen.js' import { writeListenerConfig } from '../src/listener/config.js' import { runWatch, describeFrame } from '../src/watch.js' -import { readIntegrationStatus } from '@agentchatme/agent-core' +import { MANUAL_URL, readIntegrationStatus, RUN_PROFILES } from '@agentchatme/agent-core' +import * as presets from '@agentchatme/agent-core/presets' import { claudeMcpConfigPath, claudeProjectsDirFor, codexRunArgs, readDenyRules } from '@agentchatme/agent-core/presets' import { defaultPresetWorkdir } from '../src/listener/config.js' import { claudePresetDenyPaths } from '../src/identity.js' @@ -15,6 +16,9 @@ import { VERSION } from '../src/version.js' import { installFakeClaude, installFakeCodex, readFakeMcpLists, readFakeRuns } from './helpers/fake-runtimes.js' import { startServerDouble, until, pause, type ServerDouble } from './helpers/server-double.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') + // ─── A foreground listener, end to end, against the server double ─────────── // // The double speaks the socket's HELLO path, the tray, the texts and the @@ -176,7 +180,7 @@ describe('agentchat listen --preset claude-code, end to end (fake claude)', () = const env = { ...process.env, PATH: `${fake.binDir}${path.delimiter}${originalPath ?? ''}`, FAKE_RUNTIME_RECORD: fake.recordPath, CLAUDE_CONFIG_DIR: path.join(tmp, '.claude') } process.env['PATH'] = env.PATH const controller = new AbortController() - const done = runListen(home, 'listen', { preset: 'claude-code' }, io(controller.signal, env)) + const done = runListen(home, 'listen', { preset: 'claude-code', profile: 'answer' }, io(controller.signal, env)) await until(() => readFakeRuns(fake).length > 0, 20_000) controller.abort() expect(await done).toBe(0) @@ -205,6 +209,31 @@ describe('agentchat listen --preset claude-code, end to end (fake claude)', () = expect(JSON.stringify(run)).not.toContain(KEY) expect(server.requests.some((r) => r.startsWith('/v1/texts?runtime=claude-code'))).toBe(true) }, 40_000) + + it.skipIf(!ENGINE_HAS_OWN)('own (the default): the listener\'s own tool config without --strict-mcp-config, the identity line appended, the user\'s context and settings left alone, the key store denied', async () => { + const fake = installFakeClaude(tmp) + const env = { ...process.env, PATH: `${fake.binDir}${path.delimiter}${originalPath ?? ''}`, FAKE_RUNTIME_RECORD: fake.recordPath, CLAUDE_CONFIG_DIR: path.join(tmp, '.claude'), AGENTCHAT_RUN_PROFILE: '' } + process.env['PATH'] = env.PATH + const controller = new AbortController() + const done = runListen(home, 'listen', { preset: 'claude-code' }, io(controller.signal, env)) + await until(() => readFakeRuns(fake).length > 0, 20_000) + controller.abort() + expect(await done).toBe(0) + const [run] = readFakeRuns(fake) + const argv = run!.argv + expect(argv[argv.indexOf('--mcp-config') + 1]).toBe(claudeMcpConfigPath(home)) + for (const flag of ['--strict-mcp-config', '--tools', '--settings', '--permission-mode']) expect(argv).not.toContain(flag) + expect(argv[argv.indexOf('--allowedTools') + 1]).toBe('mcp__agentchat__*') + expect(run?.appendedSystemPrompt).toContain('Served identity line for claude-code') + expect(run?.env['CLAUDE_CODE_DISABLE_CLAUDE_MDS']).toBeUndefined() + // Its prompt says where the manual is, as it can reach it: the address (the home is denied to it). + expect(run?.stdin).toContain(MANUAL_URL) + if (process.platform !== 'win32') { + const configDir = path.resolve(tmp, '.claude') + expect(argv.at(-1)).toBe(readDenyRules(claudePresetDenyPaths(home, configDir)).join(',')) + } + expect(JSON.stringify(run)).not.toContain(KEY) + }, 40_000) }) describe('agentchat listen --preset codex, end to end (fake codex)', () => { @@ -215,7 +244,7 @@ describe('agentchat listen --preset codex, end to end (fake codex)', () => { const env = { ...process.env, PATH: `${fake.binDir}${path.delimiter}${originalPath ?? ''}`, FAKE_RUNTIME_RECORD: fake.recordPath, FAKE_MCP_LIST: listed, FAKE_MCP_LIST_RECORD: lists, CODEX_HOME: path.join(tmp, '.codex') } process.env['PATH'] = env.PATH const controller = new AbortController() - const done = runListen(home, 'listen', { preset: 'codex' }, io(controller.signal, env)) + const done = runListen(home, 'listen', { preset: 'codex', profile: 'answer' }, io(controller.signal, env)) await until(() => readFakeRuns(fake).length > 0, 20_000) controller.abort() expect(await done).toBe(0) @@ -230,6 +259,31 @@ describe('agentchat listen --preset codex, end to end (fake codex)', () => { expect(run?.env['AGENTCHAT_LISTENER_API_KEY']).toBe(KEY) expect(run?.argv.join(' ')).not.toContain(KEY) }, 40_000) + + it.skipIf(!ENGINE_HAS_OWN)('own (the default): the user\'s config left alone, the key from a headers helper in the home — none in the run\'s environment; Codex is asked first that nothing else would authenticate', async () => { + const fake = installFakeCodex(tmp) + const lists = path.join(tmp, 'own-mcp-lists.jsonl') + const env = { ...process.env, PATH: `${fake.binDir}${path.delimiter}${originalPath ?? ''}`, FAKE_RUNTIME_RECORD: fake.recordPath, FAKE_MCP_LIST_RECORD: lists, CODEX_HOME: path.join(tmp, '.codex'), AGENTCHAT_RUN_PROFILE: '' } + process.env['PATH'] = env.PATH + const controller = new AbortController() + const done = runListen(home, 'listen', { preset: 'codex' }, io(controller.signal, env)) + await until(() => readFakeRuns(fake).length > 0, 20_000) + controller.abort() + expect(await done).toBe(0) + const [run] = readFakeRuns(fake) + const helperPath = (presets as unknown as { codexListenerHeadersHelperPath: (home: string) => string }).codexListenerHeadersHelperPath(home) + const helper = (presets as unknown as { codexHeadersHelperCommand: (script: string) => string }).codexHeadersHelperCommand(helperPath) + const own = codexRunArgs('own' as never, { workdir: defaultPresetWorkdir(home), mcp: { url: `${server.apiBase}/mcp`, keyEnv: 'AGENTCHAT_LISTENER_API_KEY', headersHelper: helper, clientVersion: VERSION } as never }) + expect(run?.argv).toEqual(own) + // One listing, with the run's own flags: how Codex's agentchat entry authenticates (nothing is switched off). + expect(readFakeMcpLists(lists)).toHaveLength(1) + expect(readFakeMcpLists(lists)[0]?.argv).toEqual(['mcp', 'list', '--json', ...own.slice(own.indexOf('-c'), -1)]) + expect(fs.existsSync(helperPath)).toBe(true) + expect(run?.env['AGENTCHAT_LISTENER_API_KEY']).toBeUndefined() + expect(JSON.stringify(run)).not.toContain(KEY) + // Its prompt says where the manual is: Codex's sandboxes read the file. + expect(run?.stdin).toContain('The AgentChat manual') + }, 40_000) }) describe('agentchat watch', () => { diff --git a/tests/listener.test.ts b/tests/listener.test.ts index 3b96fcb..ccdfa9d 100644 --- a/tests/listener.test.ts +++ b/tests/listener.test.ts @@ -242,13 +242,15 @@ describe('ForwardRunner — one POST per wake, agentchat dialect', () => { describe('listener.json', () => { it('round-trips each mode, owner-only; a broken file says why; the description never carries a key', () => { - const base = { version: 1 as const, workdir: identity.workdir, updated_at: '2026-11-08T00:00:00Z' } + const base = { version: 2 as const, workdir: identity.workdir, updated_at: '2026-11-08T00:00:00Z' } const run = writeListenerConfig(identity.home, { ...base, mode: 'run', command: 'my-agent --once' }) expect(run).toMatchObject({ mode: 'run', with_key: false }) + expect(JSON.parse(fs.readFileSync(listenerConfigPath(identity.home), 'utf8'))).toMatchObject({ version: 2, mode: 'run' }) expect(readListenerConfig(identity.home)).toEqual({ ok: true, config: run }) if (process.platform !== 'win32') expect(fs.statSync(listenerConfigPath(identity.home)).mode & 0o777).toBe(0o600) expect(describeListenerConfig(run)).toBe(`runs \`my-agent --once\` in ${identity.workdir}`) + // A file without a profile (this CLI never writes one) is the lock. const preset = writeListenerConfig(identity.home, { ...base, mode: 'preset', preset: 'codex' }) expect(preset).toMatchObject({ profile: 'answer' }) const forward = writeListenerConfig(identity.home, { ...base, mode: 'forward', url: 'http://localhost:1/x' }) diff --git a/tests/version-consistency.test.ts b/tests/version-consistency.test.ts index 3e746c5..6c2ff1b 100644 --- a/tests/version-consistency.test.ts +++ b/tests/version-consistency.test.ts @@ -12,3 +12,18 @@ describe('version', () => { expect(VERSION).toBe(pkg.version) }) }) + +// ─── 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') + }) +})